xref: /petsc/src/sys/objects/pinit.c (revision d54338ec4fdf48b56b5efdd9bf04ca9d50d6ab04)
1 
2 /*
3    This file defines the initialization of PETSc, including PetscInitialize()
4 */
5 #define PETSC_DESIRE_COMPLEX
6 #include <petscsys.h>        /*I  "petscsys.h"   I*/
7 
8 #if defined(PETSC_HAVE_CUDA)
9 #include <cublas.h>
10 #endif
11 
12 #include <petscthreadcomm.h>
13 
14 #if defined(PETSC_USE_LOG)
15 extern PetscErrorCode PetscLogBegin_Private(void);
16 #endif
17 extern PetscBool  PetscHMPIWorker;
18 
19 
20 #if defined(PETSC_SERIALIZE_FUNCTIONS)
21 PetscFPT  PetscFPTData = 0;
22 #endif
23 
24 /* -----------------------------------------------------------------------------------------*/
25 
26 extern FILE *petsc_history;
27 
28 extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
29 extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
30 extern PetscErrorCode PetscFunctionListDestroyAll(void);
31 extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
32 extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
33 extern PetscErrorCode PetscCloseHistoryFile(FILE **);
34 
35 /* user may set this BEFORE calling PetscInitialize() */
36 MPI_Comm PETSC_COMM_WORLD = MPI_COMM_NULL;
37 
38 PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
39 PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
40 PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;
41 
42 /*
43      Declare and set all the string names of the PETSc enums
44 */
45 const char *const PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
46 const char *const PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
47 const char *const PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
48                                       "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","OBJECT","FUNCTION","PetscDataType","PETSC_",0};
49 
50 PetscBool  PetscPreLoadingUsed = PETSC_FALSE;
51 PetscBool  PetscPreLoadingOn   = PETSC_FALSE;
52 
53 /* pthread_key for PetscStack */
54 #if defined(PETSC_HAVE_PTHREADCLASSES) && !defined(PETSC_PTHREAD_LOCAL)
55 pthread_key_t petscstack;
56 #endif
57 
58 /*
59        Checks the options database for initializations related to the
60     PETSc components
61 */
62 #undef __FUNCT__
63 #define __FUNCT__ "PetscOptionsCheckInitial_Components"
64 PetscErrorCode  PetscOptionsCheckInitial_Components(void)
65 {
66   PetscBool  flg1;
67   PetscErrorCode ierr;
68 
69   PetscFunctionBegin;
70   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg1);CHKERRQ(ierr);
71   if (flg1) {
72 #if defined (PETSC_USE_LOG)
73     MPI_Comm   comm = PETSC_COMM_WORLD;
74     ierr = (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");CHKERRQ(ierr);
75     ierr = (*PetscHelpPrintf)(comm," -log_summary_exclude: <vec,mat,pc.ksp,snes>\n");CHKERRQ(ierr);
76     ierr = (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");CHKERRQ(ierr);
77     ierr = (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");CHKERRQ(ierr);
78 #endif
79   }
80   PetscFunctionReturn(0);
81 }
82 
83 extern PetscBool PetscBeganMPI;
84 
85 #undef __FUNCT__
86 #define __FUNCT__ "PetscInitializeNoPointers"
87 /*
88       PetscInitializeNoPointers - Calls PetscInitialize() from C/C++ without the pointers to argc and args
89 
90    Collective
91 
92    Level: advanced
93 
94     Notes: this is called only by the PETSc MATLAB and Julia interface. Even though it might start MPI it sets the flag to
95      indicate that it did NOT start MPI so that the PetscFinalize() does not end MPI, thus allowing PetscInitialize() to
96      be called multiple times from MATLAB and Julia without the problem of trying to initialize MPI more than once.
97 
98      Turns off PETSc signal handling because that can interact with MATLAB's signal handling causing random crashes.
99 
100 .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
101 */
102 PetscErrorCode  PetscInitializeNoPointers(int argc,char **args,const char *filename,const char *help)
103 {
104   PetscErrorCode ierr;
105   int            myargc = argc;
106   char           **myargs = args;
107 
108   PetscFunctionBegin;
109   ierr = PetscInitialize(&myargc,&myargs,filename,help);CHKERRQ(ierr);
110   ierr = PetscPopSignalHandler();CHKERRQ(ierr);
111   PetscBeganMPI = PETSC_FALSE;
112   PetscFunctionReturn(ierr);
113 }
114 
115 #undef __FUNCT__
116 #define __FUNCT__ "PetscGetPETSC_COMM_SELF"
117 /*
118       Used by MATLAB and Julia interface to get communicator
119 */
120 PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
121 {
122   PetscFunctionBegin;
123   *comm = PETSC_COMM_SELF;
124   PetscFunctionReturn(0);
125 }
126 
127 #undef __FUNCT__
128 #define __FUNCT__ "PetscInitializeNoArguments"
129 /*@C
130       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
131         the command line arguments.
132 
133    Collective
134 
135    Level: advanced
136 
137 .seealso: PetscInitialize(), PetscInitializeFortran()
138 @*/
139 PetscErrorCode  PetscInitializeNoArguments(void)
140 {
141   PetscErrorCode ierr;
142   int            argc = 0;
143   char           **args = 0;
144 
145   PetscFunctionBegin;
146   ierr = PetscInitialize(&argc,&args,PETSC_NULL,PETSC_NULL);
147   PetscFunctionReturn(ierr);
148 }
149 
150 #undef __FUNCT__
151 #define __FUNCT__ "PetscInitialized"
152 /*@
153       PetscInitialized - Determine whether PETSc is initialized.
154 
155 7   Level: beginner
156 
157 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
158 @*/
159 PetscErrorCode  PetscInitialized(PetscBool  *isInitialized)
160 {
161   PetscFunctionBegin;
162   PetscValidPointer(isInitialized, 1);
163   *isInitialized = PetscInitializeCalled;
164   PetscFunctionReturn(0);
165 }
166 
167 #undef __FUNCT__
168 #define __FUNCT__ "PetscFinalized"
169 /*@
170       PetscFinalized - Determine whether PetscFinalize() has been called yet
171 
172    Level: developer
173 
174 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
175 @*/
176 PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
177 {
178   PetscFunctionBegin;
179   PetscValidPointer(isFinalized, 1);
180   *isFinalized = PetscFinalizeCalled;
181   PetscFunctionReturn(0);
182 }
183 
184 extern PetscErrorCode        PetscOptionsCheckInitial_Private(void);
185 extern PetscBool  PetscBeganMPI;
186 
187 /*
188        This function is the MPI reduction operation used to compute the sum of the
189    first half of the datatype and the max of the second half.
190 */
191 MPI_Op PetscMaxSum_Op = 0;
192 
193 EXTERN_C_BEGIN
194 #undef __FUNCT__
195 #define __FUNCT__ "PetscMaxSum_Local"
196 void  MPIAPI PetscMaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
197 {
198   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;
199 
200   PetscFunctionBegin;
201   if (*datatype != MPIU_2INT) {
202     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
203     MPI_Abort(MPI_COMM_WORLD,1);
204   }
205 
206   for (i=0; i<count; i++) {
207     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
208     xout[2*i+1] += xin[2*i+1];
209   }
210   PetscFunctionReturnVoid();
211 }
212 EXTERN_C_END
213 
214 /*
215     Returns the max of the first entry owned by this processor and the
216 sum of the second entry.
217 
218     The reason nprocs[2*i] contains lengths nprocs[2*i+1] contains flag of 1 if length is nonzero
219 is so that the PetscMaxSum_Op() can set TWO values, if we passed in only nprocs[i] with lengths
220 there would be no place to store the both needed results.
221 */
222 #undef __FUNCT__
223 #define __FUNCT__ "PetscMaxSum"
224 PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt nprocs[],PetscInt *max,PetscInt *sum)
225 {
226   PetscMPIInt    size,rank;
227   struct {PetscInt max,sum;} *work;
228   PetscErrorCode ierr;
229 
230   PetscFunctionBegin;
231   ierr   = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
232   ierr   = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
233   ierr   = PetscMalloc(size*sizeof(*work),&work);CHKERRQ(ierr);
234   ierr   = MPI_Allreduce((void*)nprocs,work,size,MPIU_2INT,PetscMaxSum_Op,comm);CHKERRQ(ierr);
235   *max   = work[rank].max;
236   *sum   = work[rank].sum;
237   ierr   = PetscFree(work);CHKERRQ(ierr);
238   PetscFunctionReturn(0);
239 }
240 
241 /* ----------------------------------------------------------------------------*/
242 MPI_Op  PetscADMax_Op = 0;
243 
244 EXTERN_C_BEGIN
245 #undef __FUNCT__
246 #define __FUNCT__ "PetscADMax_Local"
247 void  MPIAPI PetscADMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
248 {
249   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
250   PetscInt    i,count = *cnt;
251 
252   PetscFunctionBegin;
253   if (*datatype != MPIU_2SCALAR) {
254     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
255     MPI_Abort(MPI_COMM_WORLD,1);
256   }
257 
258   for (i=0; i<count; i++) {
259     if (PetscRealPart(xout[2*i]) < PetscRealPart(xin[2*i])) {
260       xout[2*i]   = xin[2*i];
261       xout[2*i+1] = xin[2*i+1];
262     }
263   }
264   PetscFunctionReturnVoid();
265 }
266 EXTERN_C_END
267 
268 MPI_Op  PetscADMin_Op = 0;
269 
270 EXTERN_C_BEGIN
271 #undef __FUNCT__
272 #define __FUNCT__ "PetscADMin_Local"
273 void  MPIAPI PetscADMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
274 {
275   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
276   PetscInt    i,count = *cnt;
277 
278   PetscFunctionBegin;
279   if (*datatype != MPIU_2SCALAR) {
280     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
281     MPI_Abort(MPI_COMM_WORLD,1);
282   }
283 
284   for (i=0; i<count; i++) {
285     if (PetscRealPart(xout[2*i]) > PetscRealPart(xin[2*i])) {
286       xout[2*i]   = xin[2*i];
287       xout[2*i+1] = xin[2*i+1];
288     }
289   }
290   PetscFunctionReturnVoid();
291 }
292 EXTERN_C_END
293 /* ---------------------------------------------------------------------------------------*/
294 
295 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
296 MPI_Op MPIU_SUM = 0;
297 
298 #undef __FUNCT__
299 #define __FUNCT__ "PetscSum_Local"
300 PETSC_EXTERN_C void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
301 {
302   PetscInt    i,count = *cnt;
303 
304   PetscFunctionBegin;
305   if (*datatype == MPIU_REAL) {
306     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
307     for (i=0; i<count; i++) {
308       xout[i] += xin[i];
309     }
310   }
311 #if defined(PETSC_HAVE_COMPLEX)
312   else if (*datatype == MPIU_COMPLEX) {
313     PetscComplex *xin = (PetscComplex *)in,*xout = (PetscComplex*)out;
314     for (i=0; i<count; i++) {
315       xout[i] += xin[i];
316     }
317   }
318 #endif
319   else {
320     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
321     MPI_Abort(MPI_COMM_WORLD,1);
322   }
323   PetscFunctionReturnVoid();
324 }
325 #endif
326 
327 #if defined(PETSC_USE_REAL___FLOAT128)
328 MPI_Op MPIU_MAX = 0;
329 MPI_Op MPIU_MIN = 0;
330 
331 #undef __FUNCT__
332 #define __FUNCT__ "PetscMax_Local"
333 PETSC_EXTERN_C void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
334 {
335   PetscInt    i,count = *cnt;
336 
337   PetscFunctionBegin;
338   if (*datatype == MPIU_REAL) {
339     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
340     for (i=0; i<count; i++) {
341       xout[i] = PetscMax(xout[i],xin[i]);
342     }
343   }
344 #if defined(PETSC_HAVE_COMPLEX)
345   else if (*datatype == MPIU_COMPLEX) {
346     PetscComplex *xin = (PetscComplex *)in,*xout = (PetscComplex*)out;
347     for (i=0; i<count; i++) {
348       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i])? xin[i]: xout[i];
349     }
350   }
351 #endif
352   else {
353     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
354     MPI_Abort(MPI_COMM_WORLD,1);
355   }
356   PetscFunctionReturnVoid();
357 }
358 
359 #undef __FUNCT__
360 #define __FUNCT__ "PetscMin_Local"
361 PETSC_EXTERN_C void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
362 {
363   PetscInt    i,count = *cnt;
364 
365   PetscFunctionBegin;
366   if (*datatype == MPIU_REAL) {
367     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
368     for (i=0; i<count; i++) {
369       xout[i] = PetscMin(xout[i],xin[i]);
370     }
371   }
372 #if defined(PETSC_HAVE_COMPLEX)
373   else if (*datatype == MPIU_COMPLEX) {
374     PetscComplex *xin = (PetscComplex *)in,*xout = (PetscComplex*)out;
375     for (i=0; i<count; i++) {
376       xout[i] = PetscRealPartComplex(xout[i])>PetscRealPartComplex(xin[i])? xin[i]: xout[i];
377     }
378   }
379 #endif
380   else {
381     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
382     MPI_Abort(MPI_COMM_WORLD,1);
383   }
384   PetscFunctionReturnVoid();
385 }
386 #endif
387 
388 EXTERN_C_BEGIN
389 #undef __FUNCT__
390 #define __FUNCT__ "Petsc_DelCounter"
391 /*
392    Private routine to delete internal tag/name counter storage when a communicator is freed.
393 
394    This is called by MPI, not by users. This is called by MPI_Comm_free() when the communicator that has this  data as an attribute is freed.
395 
396    Note: this is declared extern "C" because it is passed to MPI_Keyval_create()
397 
398 */
399 PetscMPIInt  MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
400 {
401   PetscErrorCode ierr;
402 
403   PetscFunctionBegin;
404   ierr = PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
405   ierr = PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
406   PetscFunctionReturn(MPI_SUCCESS);
407 }
408 EXTERN_C_END
409 
410 EXTERN_C_BEGIN
411 #undef __FUNCT__
412 #define __FUNCT__ "Petsc_DelComm"
413 /*
414   This does not actually free anything, it simply marks when a reference count to an internal or external MPI_Comm reaches zero and the
415   the external MPI_Comm drops its reference to the internal or external MPI_Comm
416 
417   This is called by MPI, not by users. This is called when MPI_Comm_free() is called on the communicator.
418 
419   Note: this is declared extern "C" because it is passed to MPI_Keyval_create()
420 
421 */
422 PetscMPIInt  MPIAPI Petsc_DelComm(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
423 {
424   PetscErrorCode   ierr;
425   PetscMPIInt      flg;
426   MPI_Comm         icomm;
427   void             *ptr;
428 
429   PetscFunctionBegin;
430   ierr  = MPI_Attr_get(comm,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
431   if (flg) {
432     /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
433     ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
434     ierr = MPI_Attr_get(icomm,Petsc_OuterComm_keyval,&ptr,&flg);CHKERRQ(ierr);
435     if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
436     ierr = MPI_Attr_delete(icomm,Petsc_OuterComm_keyval);CHKERRQ(ierr);
437     ierr = PetscInfo1(0,"User MPI_Comm m %ld is being freed, removing reference from inner PETSc comm to this outer comm\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
438   } else {
439     ierr = PetscInfo1(0,"Removing reference to PETSc communicator imbedded in a user MPI_Comm m %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
440   }
441   PetscFunctionReturn(MPI_SUCCESS);
442 }
443 EXTERN_C_END
444 
445 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
446 #if !defined(PETSC_WORDS_BIGENDIAN)
447 EXTERN_C_BEGIN
448 extern PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
449 extern PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
450 extern PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
451 EXTERN_C_END
452 #endif
453 #endif
454 
455 int  PetscGlobalArgc   = 0;
456 char **PetscGlobalArgs = 0;
457 
458 #undef __FUNCT__
459 #define __FUNCT__ "PetscGetArgs"
460 /*@C
461    PetscGetArgs - Allows you to access the raw command line arguments anywhere
462      after PetscInitialize() is called but before PetscFinalize().
463 
464    Not Collective
465 
466    Output Parameters:
467 +  argc - count of number of command line arguments
468 -  args - the command line arguments
469 
470    Level: intermediate
471 
472    Notes:
473       This is usually used to pass the command line arguments into other libraries
474    that are called internally deep in PETSc or the application.
475 
476       The first argument contains the program name as is normal for C arguments.
477 
478    Concepts: command line arguments
479 
480 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArguments()
481 
482 @*/
483 PetscErrorCode  PetscGetArgs(int *argc,char ***args)
484 {
485   PetscFunctionBegin;
486   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
487   *argc = PetscGlobalArgc;
488   *args = PetscGlobalArgs;
489   PetscFunctionReturn(0);
490 }
491 
492 #undef __FUNCT__
493 #define __FUNCT__ "PetscGetArguments"
494 /*@C
495    PetscGetArguments - Allows you to access the  command line arguments anywhere
496      after PetscInitialize() is called but before PetscFinalize().
497 
498    Not Collective
499 
500    Output Parameters:
501 .  args - the command line arguments
502 
503    Level: intermediate
504 
505    Notes:
506       This does NOT start with the program name and IS null terminated (final arg is void)
507 
508    Concepts: command line arguments
509 
510 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscFreeArguments()
511 
512 @*/
513 PetscErrorCode  PetscGetArguments(char ***args)
514 {
515   PetscInt       i,argc = PetscGlobalArgc;
516   PetscErrorCode ierr;
517 
518   PetscFunctionBegin;
519   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
520   if (!argc) {*args = 0; PetscFunctionReturn(0);}
521   ierr = PetscMalloc(argc*sizeof(char*),args);CHKERRQ(ierr);
522   for (i=0; i<argc-1; i++) {
523     ierr = PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);CHKERRQ(ierr);
524   }
525   (*args)[argc-1] = 0;
526   PetscFunctionReturn(0);
527 }
528 
529 #undef __FUNCT__
530 #define __FUNCT__ "PetscFreeArguments"
531 /*@C
532    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()
533 
534    Not Collective
535 
536    Output Parameters:
537 .  args - the command line arguments
538 
539    Level: intermediate
540 
541    Concepts: command line arguments
542 
543 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscGetArguments()
544 
545 @*/
546 PetscErrorCode  PetscFreeArguments(char **args)
547 {
548   PetscInt       i = 0;
549   PetscErrorCode ierr;
550 
551   PetscFunctionBegin;
552   if (!args) {PetscFunctionReturn(0);}
553   while (args[i]) {
554     ierr = PetscFree(args[i]);CHKERRQ(ierr);
555     i++;
556   }
557   ierr = PetscFree(args);CHKERRQ(ierr);
558   PetscFunctionReturn(0);
559 }
560 
561 #undef __FUNCT__
562 #define __FUNCT__ "PetscInitialize"
563 /*@C
564    PetscInitialize - Initializes the PETSc database and MPI.
565    PetscInitialize() calls MPI_Init() if that has yet to be called,
566    so this routine should always be called near the beginning of
567    your program -- usually the very first line!
568 
569    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set
570 
571    Input Parameters:
572 +  argc - count of number of command line arguments
573 .  args - the command line arguments
574 .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL to not check for
575           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
576 -  help - [optional] Help message to print, use PETSC_NULL for no message
577 
578    If you wish PETSc code to run ONLY on a subcommunicator of MPI_COMM_WORLD, create that
579    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize(). Thus if you are running a
580    four process job and two processes will run PETSc and have PetscInitialize() and PetscFinalize() and two process will not,
581    then do this. If ALL processes in the job are using PetscInitialize() and PetscFinalize() then you don't need to do this, even
582    if different subcommunicators of the job are doing different things with PETSc.
583 
584    Options Database Keys:
585 +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
586 .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
587 .  -on_error_emacs <machinename> causes emacsclient to jump to error file
588 .  -on_error_abort calls abort() when error detected (no traceback)
589 .  -on_error_mpiabort calls MPI_abort() when error detected
590 .  -error_output_stderr prints error messages to stderr instead of the default stdout
591 .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
592 .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
593 .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
594 .  -stop_for_debugger - Print message on how to attach debugger manually to
595                         process and wait (-debugger_pause) seconds for attachment
596 .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
597 .  -malloc no - Indicates not to use error-checking malloc
598 .  -malloc_debug - check for memory corruption at EVERY malloc or free
599 .  -malloc_test - like -malloc_dump -malloc_debug, but only active for debugging builds
600 .  -fp_trap - Stops on floating point exceptions (Note that on the
601               IBM RS6000 this slows code by at least a factor of 10.)
602 .  -no_signal_handler - Indicates not to trap error signals
603 .  -shared_tmp - indicates /tmp directory is shared by all processors
604 .  -not_shared_tmp - each processor has own /tmp
605 .  -tmp - alternative name of /tmp directory
606 .  -get_total_flops - returns total flops done by all processors
607 .  -memory_info - Print memory usage at end of run
608 -  -server <port> - start PETSc webserver (default port is 8080)
609 
610    Options Database Keys for Profiling:
611    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
612 +  -log_trace [filename] - Print traces of all PETSc calls
613         to the screen (useful to determine where a program
614         hangs without running in the debugger).  See PetscLogTraceBegin().
615 .  -info <optional filename> - Prints verbose information to the screen
616 -  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
617 
618    Environmental Variables:
619 +   PETSC_TMP - alternative tmp directory
620 .   PETSC_SHARED_TMP - tmp is shared by all processes
621 .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
622 .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
623 -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to
624 
625 
626    Level: beginner
627 
628    Notes:
629    If for some reason you must call MPI_Init() separately, call
630    it before PetscInitialize().
631 
632    Fortran Version:
633    In Fortran this routine has the format
634 $       call PetscInitialize(file,ierr)
635 
636 +   ierr - error return code
637 -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL_CHARACTER to not check for
638           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
639 
640    Important Fortran Note:
641    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
642    null character string; you CANNOT just use PETSC_NULL as
643    in the C version. See the <a href="../../docs/manual.pdf">users manual</a> for details.
644 
645    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
646    calling PetscInitialize().
647 
648    Concepts: initializing PETSc
649 
650 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()
651 
652 @*/
653 PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
654 {
655   PetscErrorCode ierr;
656   PetscMPIInt    flag, size;
657   PetscInt       nodesize;
658   PetscBool      flg;
659   char           hostname[256];
660 
661   PetscFunctionBegin;
662   if (PetscInitializeCalled) PetscFunctionReturn(0);
663 
664   /* these must be initialized in a routine, not as a constant declaration*/
665   PETSC_STDOUT = stdout;
666   PETSC_STDERR = stderr;
667 
668   ierr = PetscOptionsCreate();CHKERRQ(ierr);
669 
670   /*
671      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
672      it that it sets args[0] on all processors to be args[0] on the first processor.
673   */
674   if (argc && *argc) {
675     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
676   } else {
677     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
678   }
679 
680   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
681   if (!flag) {
682     if (PETSC_COMM_WORLD != MPI_COMM_NULL) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"You cannot set PETSC_COMM_WORLD if you have not initialized MPI first");
683 #if defined(PETSC_HAVE_MPI_INIT_THREAD)
684     {
685       PetscMPIInt provided;
686       ierr = MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);CHKERRQ(ierr);
687     }
688 #else
689     ierr = MPI_Init(argc,args);CHKERRQ(ierr);
690 #endif
691     PetscBeganMPI = PETSC_TRUE;
692   }
693   if (argc && args) {
694     PetscGlobalArgc = *argc;
695     PetscGlobalArgs = *args;
696   }
697   PetscFinalizeCalled   = PETSC_FALSE;
698 
699   if (PETSC_COMM_WORLD == MPI_COMM_NULL) {
700     PETSC_COMM_WORLD = MPI_COMM_WORLD;
701   }
702 #if defined(PETSC_HAVE_MPI_COMM_SET_ERRHANDLER)
703   ierr = MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
704 #else
705   ierr = MPI_Errhandler_set(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
706 #endif
707 
708   /* Done after init due to a bug in MPICH-GM? */
709   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
710 
711   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
712   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
713 
714   MPIU_BOOL = MPI_INT;
715   MPIU_ENUM = MPI_INT;
716 
717   /*
718      Initialized the global complex variable; this is because with
719      shared libraries the constructors for global variables
720      are not called; at least on IRIX.
721   */
722 #if defined(PETSC_HAVE_COMPLEX)
723   {
724 #if defined(PETSC_CLANGUAGE_CXX)
725     PetscComplex ic(0.0,1.0);
726     PETSC_i = ic;
727 #elif defined(PETSC_CLANGUAGE_C)
728     PETSC_i = _Complex_I;
729 #endif
730   }
731 
732 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
733   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
734   ierr = MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
735   ierr = MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);CHKERRQ(ierr);
736   ierr = MPI_Type_commit(&MPIU_C_COMPLEX);CHKERRQ(ierr);
737 #endif
738 #endif /* PETSC_HAVE_COMPLEX */
739 
740   /*
741      Create the PETSc MPI reduction operator that sums of the first
742      half of the entries and maxes the second half.
743   */
744   ierr = MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);CHKERRQ(ierr);
745 
746 #if defined(PETSC_USE_REAL___FLOAT128)
747   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);CHKERRQ(ierr);
748   ierr = MPI_Type_commit(&MPIU___FLOAT128);CHKERRQ(ierr);
749 #if defined(PETSC_HAVE_COMPLEX)
750   ierr = MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);CHKERRQ(ierr);
751   ierr = MPI_Type_commit(&MPIU___COMPLEX128);CHKERRQ(ierr);
752 #endif
753   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
754   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
755 #endif
756 
757 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
758   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
759 #endif
760 
761   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
762   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
763   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
764   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
765 
766 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
767   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
768   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
769 #endif
770 
771   /*
772      Attributes to be set on PETSc communicators
773   */
774   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
775   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
776   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
777 
778   /*
779      Build the options database
780   */
781   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
782 
783 
784   /*
785      Print main application help message
786   */
787   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg);CHKERRQ(ierr);
788   if (help && flg) {
789     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
790   }
791   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
792 
793   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
794 #if defined(PETSC_USE_LOG)
795   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
796 #endif
797 
798   /*
799      Load the dynamic libraries (on machines that support them), this registers all
800      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
801   */
802   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
803 
804   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
805   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
806   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
807   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
808 
809   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
810   /* Check the options database for options related to the options database itself */
811   ierr = PetscOptionsSetFromOptions();CHKERRQ(ierr);
812 
813 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
814   /*
815       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
816 
817       Currently not used because it is not supported by MPICH.
818   */
819 #if !defined(PETSC_WORDS_BIGENDIAN)
820   ierr = MPI_Register_datarep((char *)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,PETSC_NULL);CHKERRQ(ierr);
821 #endif
822 #endif
823 
824   ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
825   if (flg) {
826 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
827     ierr = PetscHMPISpawn((PetscMPIInt) nodesize);CHKERRQ(ierr); /* worker nodes never return from here; they go directly to PetscEnd() */
828 #else
829     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -hmpi_merge_size instead");
830 #endif
831   } else {
832     ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_merge_size",&nodesize,&flg);CHKERRQ(ierr);
833     if (flg) {
834       ierr = PetscHMPIMerge((PetscMPIInt) nodesize,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
835       if (PetscHMPIWorker) { /* if worker then never enter user code */
836         PetscInitializeCalled = PETSC_TRUE;
837         PetscEnd();
838       }
839     }
840   }
841 
842 #if defined(PETSC_HAVE_CUDA)
843   {
844     PetscMPIInt p;
845     for (p = 0; p < PetscGlobalSize; ++p) {
846       if (p == PetscGlobalRank) {cublasInit();}
847       ierr = MPI_Barrier(PETSC_COMM_WORLD);CHKERRQ(ierr);
848     }
849   }
850 #endif
851 
852 #if defined(PETSC_HAVE_AMS)
853   ierr = PetscOptionsHasName(PETSC_NULL,"-ams_publish_objects",&flg);CHKERRQ(ierr);
854   if (flg) {
855     PetscAMSPublishAll = PETSC_TRUE;
856   }
857 #endif
858 
859   ierr = PetscOptionsHasName(PETSC_NULL,"-python",&flg);CHKERRQ(ierr);
860   if (flg) {
861     PetscInitializeCalled = PETSC_TRUE;
862     ierr = PetscPythonInitialize(PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
863   }
864 
865   ierr = PetscThreadCommInitializePackage(PETSC_NULL);CHKERRQ(ierr);
866 
867 #if defined(PETSC_USE_DEBUG)
868   PetscThreadLocalRegister(&petscstack); /* Creates petscstack_key if needed */
869   ierr = PetscStackCreate();CHKERRQ(ierr);
870 #endif
871 
872 #if defined(PETSC_SERIALIZE_FUNCTIONS)
873   ierr = PetscFPTCreate(10000);CHKERRQ(ierr);
874 #endif
875 
876   /*
877       Once we are completedly initialized then we can set this variables
878   */
879   PetscInitializeCalled = PETSC_TRUE;
880   PetscFunctionReturn(0);
881 }
882 
883 extern PetscObject *PetscObjects;
884 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
885 
886 #undef __FUNCT__
887 #define __FUNCT__ "PetscFinalize"
888 /*@C
889    PetscFinalize - Checks for options to be called at the conclusion
890    of the program. MPI_Finalize() is called only if the user had not
891    called MPI_Init() before calling PetscInitialize().
892 
893    Collective on PETSC_COMM_WORLD
894 
895    Options Database Keys:
896 +  -options_table - Calls PetscOptionsView()
897 .  -options_left - Prints unused options that remain in the database
898 .  -objects_dump [all] - Prints list of objects allocated by the user that have not been freed, the option all cause all outstanding objects to be listed
899 .  -mpidump - Calls PetscMPIDump()
900 .  -malloc_dump - Calls PetscMallocDump()
901 .  -malloc_info - Prints total memory usage
902 -  -malloc_log - Prints summary of memory usage
903 
904    Options Database Keys for Profiling:
905    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
906 +  -log_summary [filename] - Prints summary of flop and timing
907         information to screen. If the filename is specified the
908         summary is written to the file.  See PetscLogView().
909 .  -log_summary_python [filename] - Prints data on of flop and timing usage to a file or screen.
910         See PetscLogPrintSViewPython().
911 .  -log_all [filename] - Logs extensive profiling information
912         See PetscLogDump().
913 .  -log [filename] - Logs basic profiline information  See PetscLogDump().
914 .  -log_sync - Log the synchronization in scatters, inner products
915         and norms
916 -  -log_mpe [filename] - Creates a logfile viewable by the
917       utility Upshot/Nupshot (in MPICH distribution)
918 
919    Level: beginner
920 
921    Note:
922    See PetscInitialize() for more general runtime options.
923 
924 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
925 @*/
926 PetscErrorCode  PetscFinalize(void)
927 {
928   PetscErrorCode ierr;
929   PetscMPIInt    rank;
930   PetscInt       nopt;
931   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
932 #if defined(PETSC_HAVE_AMS)
933   PetscBool      flg = PETSC_FALSE;
934 #endif
935 #if defined(PETSC_USE_LOG)
936   char           mname[PETSC_MAX_PATH_LEN];
937 #endif
938 
939   PetscFunctionBegin;
940   if (!PetscInitializeCalled) {
941     printf("PetscInitialize() must be called before PetscFinalize()\n");
942     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
943   }
944   ierr = PetscInfo(PETSC_NULL,"PetscFinalize() called\n");CHKERRQ(ierr);
945 
946 #if defined(PETSC_SERIALIZE_FUNCTIONS)
947   ierr = PetscFPTDestroy();CHKERRQ(ierr);
948 #endif
949 
950 
951 #if defined(PETSC_HAVE_AMS)
952   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_gui",&flg,PETSC_NULL);CHKERRQ(ierr);
953   if (flg) {
954     ierr = PetscOptionsAMSDestroy();CHKERRQ(ierr);
955   }
956 #endif
957 
958   ierr = PetscHMPIFinalize();CHKERRQ(ierr);
959 
960   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
961   ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
962   if (!flg2) {
963     flg2 = PETSC_FALSE;
964     ierr = PetscOptionsGetBool(PETSC_NULL,"-memory_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
965   }
966   if (flg2) {
967     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
968   }
969 
970 #if defined(PETSC_USE_LOG)
971   flg1 = PETSC_FALSE;
972   ierr = PetscOptionsGetBool(PETSC_NULL,"-get_total_flops",&flg1,PETSC_NULL);CHKERRQ(ierr);
973   if (flg1) {
974     PetscLogDouble flops = 0;
975     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
976     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
977   }
978 #endif
979 
980 
981 #if defined(PETSC_USE_LOG)
982 #if defined(PETSC_HAVE_MPE)
983   mname[0] = 0;
984   ierr = PetscOptionsGetString(PETSC_NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
985   if (flg1) {
986     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
987     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
988   }
989 #endif
990   mname[0] = 0;
991   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
992   if (flg1) {
993     PetscViewer viewer;
994     if (mname[0])  {
995       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
996       ierr = PetscLogView(viewer);CHKERRQ(ierr);
997       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
998     } else {
999       viewer = PETSC_VIEWER_STDOUT_WORLD;
1000       ierr = PetscLogView(viewer);CHKERRQ(ierr);
1001     }
1002   }
1003 
1004   mname[0] = 0;
1005   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary_python",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1006   if (flg1) {
1007     PetscViewer viewer;
1008     if (mname[0])  {
1009       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1010       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
1011       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1012     } else {
1013       viewer = PETSC_VIEWER_STDOUT_WORLD;
1014       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
1015     }
1016   }
1017 
1018   ierr = PetscOptionsGetString(PETSC_NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1019   if (flg1) {
1020     if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
1021     else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
1022   }
1023 
1024   mname[0] = 0;
1025   ierr = PetscOptionsGetString(PETSC_NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1026   ierr = PetscOptionsGetString(PETSC_NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
1027   if (flg1 || flg2) {
1028     if (mname[0]) PetscLogDump(mname);
1029     else          PetscLogDump(0);
1030   }
1031 #endif
1032 
1033   /*
1034      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1035   */
1036   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1037 
1038 #if defined(PETSC_USE_DEBUG)
1039   ierr = PetscStackDestroy();CHKERRQ(ierr);
1040 #endif
1041 
1042   flg1 = PETSC_FALSE;
1043   ierr = PetscOptionsGetBool(PETSC_NULL,"-no_signal_handler",&flg1,PETSC_NULL);CHKERRQ(ierr);
1044   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
1045   flg1 = PETSC_FALSE;
1046   ierr = PetscOptionsGetBool(PETSC_NULL,"-mpidump",&flg1,PETSC_NULL);CHKERRQ(ierr);
1047   if (flg1) {
1048     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1049   }
1050   flg1 = PETSC_FALSE;
1051   flg2 = PETSC_FALSE;
1052   /* preemptive call to avoid listing this option in options table as unused */
1053   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1054   ierr = PetscOptionsHasName(PETSC_NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1055   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_table",&flg2,PETSC_NULL);CHKERRQ(ierr);
1056 
1057   if (flg2) {
1058     PetscViewer viewer;
1059     ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1060     ierr = PetscOptionsView(viewer);CHKERRQ(ierr);
1061     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1062   }
1063 
1064   /* to prevent PETSc -options_left from warning */
1065   ierr = PetscOptionsHasName(PETSC_NULL,"-nox",&flg1);CHKERRQ(ierr);
1066   ierr = PetscOptionsHasName(PETSC_NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1067 
1068   if (!PetscHMPIWorker) { /* worker processes skip this because they do not usually process options */
1069     flg3 = PETSC_FALSE; /* default value is required */
1070     ierr = PetscOptionsGetBool(PETSC_NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1071     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
1072     if (flg3) {
1073       if (!flg2) { /* have not yet printed the options */
1074         PetscViewer viewer;
1075         ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1076         ierr = PetscOptionsView(viewer);CHKERRQ(ierr);
1077         ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1078       }
1079       if (!nopt) {
1080         ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1081       } else if (nopt == 1) {
1082         ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1083       } else {
1084         ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1085       }
1086     }
1087 #if defined(PETSC_USE_DEBUG)
1088     if (nopt && !flg3 && !flg1) {
1089       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1090       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1091       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1092     } else if (nopt && flg3) {
1093 #else
1094     if (nopt && flg3) {
1095 #endif
1096       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1097     }
1098   }
1099 
1100   /*
1101        List all objects the user may have forgot to free
1102   */
1103   ierr = PetscOptionsHasName(PETSC_NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1104   if (flg1) {
1105     MPI_Comm  local_comm;
1106     char      string[64];
1107 
1108     ierr = PetscOptionsGetString(PETSC_NULL,"-objects_dump",string,64,PETSC_NULL);CHKERRQ(ierr);
1109     ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1110     ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1111     ierr = PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);CHKERRQ(ierr);
1112     ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1113     ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1114   }
1115   PetscObjectsCounts    = 0;
1116   PetscObjectsMaxCounts = 0;
1117   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1118 
1119 
1120 #if defined(PETSC_USE_LOG)
1121   ierr = PetscLogDestroy();CHKERRQ(ierr);
1122 #endif
1123 
1124   /*
1125        Free all the registered create functions, such as KSPList, VecList, SNESList, etc
1126   */
1127   ierr = PetscFunctionListDestroyAll();CHKERRQ(ierr);
1128 
1129   /*
1130      Destroy any packages that registered a finalize
1131   */
1132   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1133 
1134   /*
1135      Destroy all the function registration lists created
1136   */
1137   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1138 
1139   if (petsc_history) {
1140     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1141     petsc_history = 0;
1142   }
1143 
1144   ierr = PetscInfoAllow(PETSC_FALSE,PETSC_NULL);CHKERRQ(ierr);
1145 
1146   {
1147     char fname[PETSC_MAX_PATH_LEN];
1148     FILE *fd;
1149     int  err;
1150 
1151     fname[0] = 0;
1152     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1153     flg2 = PETSC_FALSE;
1154     ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_test",&flg2,PETSC_NULL);CHKERRQ(ierr);
1155 #if defined(PETSC_USE_DEBUG)
1156     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1157 #else
1158     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1159 #endif
1160     if (flg1 && fname[0]) {
1161       char sname[PETSC_MAX_PATH_LEN];
1162 
1163       sprintf(sname,"%s_%d",fname,rank);
1164       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1165       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1166       err = fclose(fd);
1167       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1168     } else if (flg1 || flg2) {
1169       MPI_Comm local_comm;
1170 
1171       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1172       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1173         ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1174       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1175       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1176     }
1177   }
1178 
1179   {
1180     char fname[PETSC_MAX_PATH_LEN];
1181     FILE *fd = PETSC_NULL;
1182 
1183     fname[0] = 0;
1184     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1185     ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_log_threshold",&flg2);CHKERRQ(ierr);
1186     if (flg1 && fname[0]) {
1187       int  err;
1188 
1189       if (!rank) {
1190         fd = fopen(fname,"w");
1191         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1192       }
1193       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1194       if (fd) {
1195         err = fclose(fd);
1196         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1197       }
1198     } else if (flg1 || flg2) {
1199       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1200     }
1201   }
1202   /* Can be destroyed only after all the options are used */
1203   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
1204 
1205   PetscGlobalArgc = 0;
1206   PetscGlobalArgs = 0;
1207 
1208 #if defined(PETSC_USE_REAL___FLOAT128)
1209   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1210 #if defined(PETSC_HAVE_COMPLEX)
1211   ierr = MPI_Type_free(&MPIU___COMPLEX128);CHKERRQ(ierr);
1212 #endif
1213   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1214   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1215 #endif
1216 
1217 #if defined(PETSC_HAVE_COMPLEX)
1218 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1219   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1220   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1221 #endif
1222 #endif
1223 
1224 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1225   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1226 #endif
1227 
1228   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1229 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1230   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1231 #endif
1232   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
1233   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
1234   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
1235 
1236   /*
1237      Destroy any known inner MPI_Comm's and attributes pointing to them
1238      Note this will not destroy any new communicators the user has created.
1239 
1240      If all PETSc objects were not destroyed those left over objects will have hanging references to
1241      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1242  */
1243   {
1244     PetscCommCounter *counter;
1245     PetscMPIInt      flg;
1246     MPI_Comm         icomm;
1247     void             *ptr;
1248     ierr  = MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1249     if (flg) {
1250       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1251       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1252       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1253       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1254 
1255       ierr = MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1256       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1257       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1258     }
1259     ierr  = MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1260     if (flg) {
1261       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1262       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1263       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1264       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1265 
1266       ierr = MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1267       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1268       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1269     }
1270   }
1271 
1272   ierr = MPI_Keyval_free(&Petsc_Counter_keyval);CHKERRQ(ierr);
1273   ierr = MPI_Keyval_free(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1274   ierr = MPI_Keyval_free(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1275 
1276 #if defined(PETSC_HAVE_CUDA)
1277   {
1278     PetscInt p;
1279     for (p = 0; p < PetscGlobalSize; ++p) {
1280       if (p == PetscGlobalRank) {cublasShutdown();}
1281       ierr = MPI_Barrier(PETSC_COMM_WORLD);CHKERRQ(ierr);
1282     }
1283   }
1284 #endif
1285 
1286   if (PetscBeganMPI) {
1287 #if defined(PETSC_HAVE_MPI_FINALIZED)
1288     PetscMPIInt flag;
1289     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1290     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1291 #endif
1292     ierr = MPI_Finalize();CHKERRQ(ierr);
1293   }
1294 /*
1295 
1296      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1297    the communicator has some outstanding requests on it. Specifically if the
1298    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1299    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1300    is never freed as it should be. Thus one may obtain messages of the form
1301    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1302    memory was not freed.
1303 
1304 */
1305   ierr = PetscMallocClear();CHKERRQ(ierr);
1306   PetscInitializeCalled = PETSC_FALSE;
1307   PetscFinalizeCalled   = PETSC_TRUE;
1308   PetscFunctionReturn(ierr);
1309 }
1310 
1311 #if defined(PETSC_MISSING_LAPACK_lsame_)
1312 EXTERN_C_BEGIN
1313 int lsame_(char *a,char *b)
1314 {
1315   if (*a == *b) return 1;
1316   if (*a + 32 == *b) return 1;
1317   if (*a - 32 == *b) return 1;
1318   return 0;
1319 }
1320 EXTERN_C_END
1321 #endif
1322 
1323 #if defined(PETSC_MISSING_LAPACK_lsame)
1324 EXTERN_C_BEGIN
1325 int lsame(char *a,char *b)
1326 {
1327   if (*a == *b) return 1;
1328   if (*a + 32 == *b) return 1;
1329   if (*a - 32 == *b) return 1;
1330   return 0;
1331 }
1332 EXTERN_C_END
1333 #endif
1334