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