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