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