xref: /petsc/src/sys/objects/pinit.c (revision 94c814016428b1cfd91bc30b5000327841e6cf0f)
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     ierr          = MPI_Init(argc,args);CHKERRQ(ierr);
669     PetscBeganMPI = PETSC_TRUE;
670   }
671   if (argc && args) {
672     PetscGlobalArgc = *argc;
673     PetscGlobalArgs = *args;
674   }
675   PetscFinalizeCalled   = PETSC_FALSE;
676 
677   if (PETSC_COMM_WORLD == MPI_COMM_NULL) {
678     PETSC_COMM_WORLD = MPI_COMM_WORLD;
679   }
680   ierr = MPI_Errhandler_set(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
681 
682   /* Done after init due to a bug in MPICH-GM? */
683   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
684 
685   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
686   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
687 
688 #if defined(PETSC_USE_COMPLEX)
689   /*
690      Initialized the global complex variable; this is because with
691      shared libraries the constructors for global variables
692      are not called; at least on IRIX.
693   */
694   {
695 #if defined(PETSC_CLANGUAGE_CXX)
696     PetscScalar ic(0.0,1.0);
697     PETSC_i = ic;
698 #else
699     PETSC_i = I;
700 #endif
701   }
702 
703 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
704   ierr = MPI_Type_contiguous(2,MPIU_REAL,&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
705   ierr = MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
706   ierr = MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);CHKERRQ(ierr);
707   ierr = MPI_Type_commit(&MPIU_C_COMPLEX);CHKERRQ(ierr);
708   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
709 #endif
710 #endif
711 
712   /*
713      Create the PETSc MPI reduction operator that sums of the first
714      half of the entries and maxes the second half.
715   */
716   ierr = MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);CHKERRQ(ierr);
717 
718 #if defined(PETSC_USE_REAL___FLOAT128)
719   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);CHKERRQ(ierr);
720   ierr = MPI_Type_commit(&MPIU___FLOAT128);CHKERRQ(ierr);
721   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
722   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
723   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
724 #endif
725 
726   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
727   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
728   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
729   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
730 
731   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
732   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
733 
734   /*
735      Attributes to be set on PETSc communicators
736   */
737   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
738   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
739   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
740 
741   /*
742      Build the options database
743   */
744   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
745 
746 
747   /*
748      Print main application help message
749   */
750   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg);CHKERRQ(ierr);
751   if (help && flg) {
752     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
753   }
754   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
755 
756   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
757 #if defined(PETSC_USE_LOG)
758   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
759 #endif
760 
761   /*
762      Load the dynamic libraries (on machines that support them), this registers all
763      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
764   */
765   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
766 
767   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
768   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
769   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
770   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
771 
772   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
773   /* Check the options database for options related to the options database itself */
774   ierr = PetscOptionsSetFromOptions();CHKERRQ(ierr);
775 
776 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
777   /*
778       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
779 
780       Currently not used because it is not supported by MPICH.
781   */
782 #if !defined(PETSC_WORDS_BIGENDIAN)
783   ierr = MPI_Register_datarep((char *)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,PETSC_NULL);CHKERRQ(ierr);
784 #endif
785 #endif
786 
787   ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
788   if (flg) {
789 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
790     ierr = PetscHMPISpawn((PetscMPIInt) nodesize);CHKERRQ(ierr); /* worker nodes never return from here; they go directly to PetscEnd() */
791 #else
792     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -hmpi_merge_size instead");
793 #endif
794   } else {
795     ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_merge_size",&nodesize,&flg);CHKERRQ(ierr);
796     if (flg) {
797       ierr = PetscHMPIMerge((PetscMPIInt) nodesize,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
798       if (PetscHMPIWorker) { /* if worker then never enter user code */
799         PetscInitializeCalled = PETSC_TRUE;
800         ierr = PetscEnd();
801       }
802     }
803   }
804 
805 #if defined(PETSC_HAVE_CUDA)
806   cublasInit();
807 #endif
808 
809 #if defined(PETSC_HAVE_AMS)
810   ierr = PetscOptionsHasName(PETSC_NULL,"-ams_publish_objects",&flg);CHKERRQ(ierr);
811   if (flg) {
812     PetscAMSPublishAll = PETSC_TRUE;
813   }
814 #endif
815 
816   ierr = PetscOptionsHasName(PETSC_NULL,"-python",&flg);CHKERRQ(ierr);
817   if (flg) {
818     PetscInitializeCalled = PETSC_TRUE;
819     ierr = PetscPythonInitialize(PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
820   }
821 
822   ierr = PetscThreadCommInitializePackage(PETSC_NULL);CHKERRQ(ierr);
823 
824   /*
825       Once we are completedly initialized then we can set this variables
826   */
827   PetscInitializeCalled = PETSC_TRUE;
828   PetscFunctionReturn(0);
829 }
830 
831 extern PetscObject *PetscObjects;
832 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
833 
834 #undef __FUNCT__
835 #define __FUNCT__ "PetscFinalize"
836 /*@C
837    PetscFinalize - Checks for options to be called at the conclusion
838    of the program. MPI_Finalize() is called only if the user had not
839    called MPI_Init() before calling PetscInitialize().
840 
841    Collective on PETSC_COMM_WORLD
842 
843    Options Database Keys:
844 +  -options_table - Calls PetscOptionsView()
845 .  -options_left - Prints unused options that remain in the database
846 .  -objects_left  - Prints list of all objects that have not been freed
847 .  -mpidump - Calls PetscMPIDump()
848 .  -malloc_dump - Calls PetscMallocDump()
849 .  -malloc_info - Prints total memory usage
850 -  -malloc_log - Prints summary of memory usage
851 
852    Options Database Keys for Profiling:
853    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
854 +  -log_summary [filename] - Prints summary of flop and timing
855         information to screen. If the filename is specified the
856         summary is written to the file.  See PetscLogView().
857 .  -log_summary_python [filename] - Prints data on of flop and timing usage to a file or screen.
858         See PetscLogPrintSViewPython().
859 .  -log_all [filename] - Logs extensive profiling information
860         See PetscLogDump().
861 .  -log [filename] - Logs basic profiline information  See PetscLogDump().
862 .  -log_sync - Log the synchronization in scatters, inner products
863         and norms
864 -  -log_mpe [filename] - Creates a logfile viewable by the
865       utility Upshot/Nupshot (in MPICH distribution)
866 
867    Level: beginner
868 
869    Note:
870    See PetscInitialize() for more general runtime options.
871 
872 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
873 @*/
874 PetscErrorCode  PetscFinalize(void)
875 {
876   PetscErrorCode ierr;
877   PetscMPIInt    rank;
878   PetscInt       i,nopt;
879   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE,objects_left = PETSC_FALSE;
880 #if defined(PETSC_HAVE_AMS)
881   PetscBool      flg = PETSC_FALSE;
882 #endif
883 #if defined(PETSC_USE_LOG)
884   char           mname[PETSC_MAX_PATH_LEN];
885 #endif
886 
887   PetscFunctionBegin;
888 
889   if (!PetscInitializeCalled) {
890     printf("PetscInitialize() must be called before PetscFinalize()\n");
891     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
892   }
893   ierr = PetscInfo(PETSC_NULL,"PetscFinalize() called\n");
894 
895 #if defined(PETSC_HAVE_AMS)
896   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_gui",&flg,PETSC_NULL);CHKERRQ(ierr);
897   if (flg) {
898     ierr = PetscOptionsAMSDestroy();CHKERRQ(ierr);
899   }
900 #endif
901 
902   ierr = PetscHMPIFinalize();CHKERRQ(ierr);
903 
904 #if defined(PETSC_HAVE_PTHREADCLASSES)
905   ierr = PetscThreadsFinalize();CHKERRQ(ierr);
906 #endif
907 
908   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
909   ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
910   if (!flg2) {
911     flg2 = PETSC_FALSE;
912     ierr = PetscOptionsGetBool(PETSC_NULL,"-memory_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
913   }
914   if (flg2) {
915     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
916   }
917 
918 #if defined(PETSC_USE_LOG)
919   flg1 = PETSC_FALSE;
920   ierr = PetscOptionsGetBool(PETSC_NULL,"-get_total_flops",&flg1,PETSC_NULL);CHKERRQ(ierr);
921   if (flg1) {
922     PetscLogDouble flops = 0;
923     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
924     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
925   }
926 #endif
927 
928 
929 #if defined(PETSC_USE_LOG)
930 #if defined(PETSC_HAVE_MPE)
931   mname[0] = 0;
932   ierr = PetscOptionsGetString(PETSC_NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
933   if (flg1){
934     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
935     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
936   }
937 #endif
938   mname[0] = 0;
939   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
940   if (flg1) {
941     PetscViewer viewer;
942     if (mname[0])  {
943       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
944       ierr = PetscLogView(viewer);CHKERRQ(ierr);
945       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
946     } else {
947       viewer = PETSC_VIEWER_STDOUT_WORLD;
948       ierr = PetscLogView(viewer);CHKERRQ(ierr);
949     }
950   }
951 
952   mname[0] = 0;
953   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary_python",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
954   if (flg1) {
955     PetscViewer viewer;
956     if (mname[0])  {
957       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
958       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
959       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
960     } else {
961       viewer = PETSC_VIEWER_STDOUT_WORLD;
962       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
963     }
964   }
965 
966   ierr = PetscOptionsGetString(PETSC_NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
967   if (flg1) {
968     if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
969     else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
970   }
971 
972   mname[0] = 0;
973   ierr = PetscOptionsGetString(PETSC_NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
974   ierr = PetscOptionsGetString(PETSC_NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
975   if (flg1 || flg2){
976     if (mname[0]) PetscLogDump(mname);
977     else          PetscLogDump(0);
978   }
979 #endif
980 
981 #if defined(PETSC_USE_DEBUG)
982   if (PetscStackActive) {
983     ierr = PetscStackDestroy();CHKERRQ(ierr);
984   }
985 #endif
986 
987   flg1 = PETSC_FALSE;
988   ierr = PetscOptionsGetBool(PETSC_NULL,"-no_signal_handler",&flg1,PETSC_NULL);CHKERRQ(ierr);
989   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
990   flg1 = PETSC_FALSE;
991   ierr = PetscOptionsGetBool(PETSC_NULL,"-mpidump",&flg1,PETSC_NULL);CHKERRQ(ierr);
992   if (flg1) {
993     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
994   }
995   flg1 = PETSC_FALSE;
996   flg2 = PETSC_FALSE;
997   /* preemptive call to avoid listing this option in options table as unused */
998   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
999   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_table",&flg2,PETSC_NULL);CHKERRQ(ierr);
1000 
1001   if (flg2) {
1002     ierr = PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
1003   }
1004 
1005   /* to prevent PETSc -options_left from warning */
1006   ierr = PetscOptionsHasName(PETSC_NULL,"-nox",&flg1);CHKERRQ(ierr);
1007   ierr = PetscOptionsHasName(PETSC_NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1008   ierr = PetscOptionsGetBool(PETSC_NULL,"-objects_left",&objects_left,PETSC_NULL);CHKERRQ(ierr);
1009 
1010   if (!PetscHMPIWorker) { /* worker processes skip this because they do not usually process options */
1011     flg3 = PETSC_FALSE; /* default value is required */
1012     ierr = PetscOptionsGetBool(PETSC_NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1013     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
1014     if (flg3) {
1015       if (!flg2) { /* have not yet printed the options */
1016 	ierr = PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
1017       }
1018       if (!nopt) {
1019 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1020       } else if (nopt == 1) {
1021 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1022       } else {
1023 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1024       }
1025     }
1026 #if defined(PETSC_USE_DEBUG)
1027     if (nopt && !flg3 && !flg1) {
1028       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1029       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1030       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1031     } else if (nopt && flg3) {
1032 #else
1033     if (nopt && flg3) {
1034 #endif
1035       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1036     }
1037   }
1038 
1039   /*
1040      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1041   */
1042   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1043 
1044   /*
1045        List all objects the user may have forgot to free
1046   */
1047   if (objects_left && PetscObjectsCounts) {
1048     ierr = PetscPrintf(PETSC_COMM_WORLD,"The following objects %D were never freed\n",PetscObjectsCounts);
1049   }
1050   for (i=0; i<PetscObjectsMaxCounts; i++) {
1051     if (PetscObjects[i]) {
1052       if (objects_left) {
1053         ierr = PetscPrintf(PETSC_COMM_WORLD,"  %s %s %s\n",PetscObjects[i]->class_name,PetscObjects[i]->type_name,PetscObjects[i]->name);CHKERRQ(ierr);
1054       }
1055     }
1056   }
1057   /* cannot actually destroy the left over objects, but destroy the list */
1058   PetscObjectsCounts    = 0;
1059   PetscObjectsMaxCounts = 0;
1060   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1061 
1062 
1063 #if defined(PETSC_USE_LOG)
1064   ierr = PetscLogDestroy();CHKERRQ(ierr);
1065 #endif
1066 
1067   /*
1068        Free all the registered create functions, such as KSPList, VecList, SNESList, etc
1069   */
1070   ierr = PetscFListDestroyAll();CHKERRQ(ierr);
1071 
1072   /*
1073        Free all the registered op functions, such as MatOpList, etc
1074   */
1075   ierr = PetscOpFListDestroyAll();CHKERRQ(ierr);
1076 
1077   /*
1078      Destroy any packages that registered a finalize
1079   */
1080   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1081 
1082   /*
1083      Destroy all the function registration lists created
1084   */
1085   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1086 
1087   if (petsc_history) {
1088     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1089     petsc_history = 0;
1090   }
1091 
1092   ierr = PetscInfoAllow(PETSC_FALSE,PETSC_NULL);CHKERRQ(ierr);
1093 
1094   {
1095     char fname[PETSC_MAX_PATH_LEN];
1096     FILE *fd;
1097     int  err;
1098 
1099     fname[0] = 0;
1100     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1101     flg2 = PETSC_FALSE;
1102     ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_test",&flg2,PETSC_NULL);CHKERRQ(ierr);
1103 #if defined(PETSC_USE_DEBUG)
1104     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1105 #else
1106     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1107 #endif
1108     if (flg1 && fname[0]) {
1109       char sname[PETSC_MAX_PATH_LEN];
1110 
1111       sprintf(sname,"%s_%d",fname,rank);
1112       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1113       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1114       err = fclose(fd);
1115       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1116     } else if (flg1 || flg2) {
1117       MPI_Comm local_comm;
1118 
1119       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1120       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1121         ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1122       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1123       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1124     }
1125   }
1126   {
1127     char fname[PETSC_MAX_PATH_LEN];
1128     FILE *fd;
1129 
1130     fname[0] = 0;
1131     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1132     if (flg1 && fname[0]) {
1133       char sname[PETSC_MAX_PATH_LEN];
1134       int  err;
1135 
1136       sprintf(sname,"%s_%d",fname,rank);
1137       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1138       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1139       err = fclose(fd);
1140       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1141     } else if (flg1) {
1142       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1143     }
1144   }
1145   /* Can be destroyed only after all the options are used */
1146   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
1147 
1148   PetscGlobalArgc = 0;
1149   PetscGlobalArgs = 0;
1150 
1151 #if defined(PETSC_USE_REAL___FLOAT128)
1152   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1153   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1154   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1155   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1156 #endif
1157 
1158 #if defined(PETSC_USE_COMPLEX)
1159 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1160   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1161   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1162   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1163 #endif
1164 #endif
1165   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1166   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1167   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
1168   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
1169   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
1170 
1171   /*
1172      Destroy any known inner MPI_Comm's and attributes pointing to them
1173      Note this will not destroy any new communicators the user has created.
1174 
1175      If all PETSc objects were not destroyed those left over objects will have hanging references to
1176      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1177  */
1178   {
1179     PetscCommCounter *counter;
1180     PetscMPIInt      flg;
1181     MPI_Comm         icomm;
1182     void             *ptr;
1183     ierr  = MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1184     if (flg) {
1185       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1186       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1187       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1188       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1189 
1190       ierr = MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1191       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1192       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1193     }
1194     ierr  = MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1195     if (flg) {
1196       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1197       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1198       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1199       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1200 
1201       ierr = MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1202       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1203       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1204     }
1205   }
1206 
1207   ierr = MPI_Keyval_free(&Petsc_Counter_keyval);CHKERRQ(ierr);
1208   ierr = MPI_Keyval_free(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1209   ierr = MPI_Keyval_free(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1210 
1211   ierr = PetscInfo(0,"PETSc successfully ended!\n");CHKERRQ(ierr);
1212   if (PetscBeganMPI) {
1213 #if defined(PETSC_HAVE_MPI_FINALIZED)
1214     PetscMPIInt flag;
1215     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1216     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1217 #endif
1218     ierr = MPI_Finalize();CHKERRQ(ierr);
1219   }
1220 
1221 #if defined(PETSC_HAVE_CUDA)
1222   cublasShutdown();
1223 #endif
1224 /*
1225 
1226      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1227    the communicator has some outstanding requests on it. Specifically if the
1228    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1229    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1230    is never freed as it should be. Thus one may obtain messages of the form
1231    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1232    memory was not freed.
1233 
1234 */
1235   ierr = PetscMallocClear();CHKERRQ(ierr);
1236   PetscInitializeCalled = PETSC_FALSE;
1237   PetscFinalizeCalled   = PETSC_TRUE;
1238   PetscFunctionReturn(ierr);
1239 }
1240 
1241 #if defined(PETSC_MISSING_LAPACK_lsame_)
1242 EXTERN_C_BEGIN
1243 int lsame_(char *a,char *b)
1244 {
1245   if (*a == *b) return 1;
1246   if (*a + 32 == *b) return 1;
1247   if (*a - 32 == *b) return 1;
1248   return 0;
1249 }
1250 EXTERN_C_END
1251 #endif
1252 
1253 #if defined(PETSC_MISSING_LAPACK_lsame)
1254 EXTERN_C_BEGIN
1255 int lsame(char *a,char *b)
1256 {
1257   if (*a == *b) return 1;
1258   if (*a + 32 == *b) return 1;
1259   if (*a - 32 == *b) return 1;
1260   return 0;
1261 }
1262 EXTERN_C_END
1263 #endif
1264