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