xref: /petsc/src/sys/objects/pinit.c (revision 0e9bae810fdaeb60e2713eaa8ddb89f42e079fd1) !
1 
2 /*
3    This file defines the initialization of PETSc, including PetscInitialize()
4 */
5 
6 #include <petscsys.h>        /*I  "petscsys.h"   I*/
7 
8 #if defined(PETSC_HAVE_CUSP)
9 #include <cublas.h>
10 #endif
11 
12 #include <petscthreadcomm.h>
13 
14 #if defined(PETSC_USE_LOG)
15 extern PetscErrorCode PetscLogBegin_Private(void);
16 #endif
17 extern PetscBool  PetscHMPIWorker;
18 
19 /* -----------------------------------------------------------------------------------------*/
20 
21 extern FILE *petsc_history;
22 
23 extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
24 extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
25 extern PetscErrorCode PetscFListDestroyAll(void);
26 extern PetscErrorCode PetscOpFListDestroyAll(void);
27 extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
28 extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
29 extern PetscErrorCode PetscCloseHistoryFile(FILE **);
30 
31 /* user may set this BEFORE calling PetscInitialize() */
32 MPI_Comm PETSC_COMM_WORLD = MPI_COMM_NULL;
33 
34 PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
35 PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
36 PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;
37 
38 /*
39      Declare and set all the string names of the PETSc enums
40 */
41 const char *const PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
42 const char *const PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
43 const char *const PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
44                                 "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","OBJECT","PetscDataType","PETSC_",0};
45 
46 PetscBool  PetscPreLoadingUsed = PETSC_FALSE;
47 PetscBool  PetscPreLoadingOn   = PETSC_FALSE;
48 
49 /*
50        Checks the options database for initializations related to the
51     PETSc components
52 */
53 #undef __FUNCT__
54 #define __FUNCT__ "PetscOptionsCheckInitial_Components"
55 PetscErrorCode  PetscOptionsCheckInitial_Components(void)
56 {
57   PetscBool  flg1;
58   PetscErrorCode ierr;
59 
60   PetscFunctionBegin;
61   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg1);CHKERRQ(ierr);
62   if (flg1) {
63 #if defined (PETSC_USE_LOG)
64     MPI_Comm   comm = PETSC_COMM_WORLD;
65     ierr = (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");CHKERRQ(ierr);
66     ierr = (*PetscHelpPrintf)(comm," -log_summary_exclude: <vec,mat,pc.ksp,snes>\n");CHKERRQ(ierr);
67     ierr = (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");CHKERRQ(ierr);
68     ierr = (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");CHKERRQ(ierr);
69 #endif
70   }
71   PetscFunctionReturn(0);
72 }
73 
74 extern PetscBool PetscBeganMPI;
75 
76 #undef __FUNCT__
77 #define __FUNCT__ "PetscInitializeNoPointers"
78 /*
79       PetscInitializeNoPointers - Calls PetscInitialize() from C/C++ without the pointers to argc and args
80 
81    Collective
82 
83    Level: advanced
84 
85     Notes: this is called only by the PETSc MATLAB and Julia interface. Even though it might start MPI it sets the flag to
86      indicate that it did NOT start MPI so that the PetscFinalize() does not end MPI, thus allowing PetscInitialize() to
87      be called multiple times from MATLAB and Julia without the problem of trying to initialize MPI more than once.
88 
89      Turns off PETSc signal handling because that can interact with MATLAB's signal handling causing random crashes.
90 
91 .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
92 */
93 PetscErrorCode  PetscInitializeNoPointers(int argc,char **args,const char *filename,const char *help)
94 {
95   PetscErrorCode ierr;
96   int            myargc = argc;
97   char           **myargs = args;
98 
99   PetscFunctionBegin;
100   ierr = PetscInitialize(&myargc,&myargs,filename,help);
101   ierr = PetscPopSignalHandler();CHKERRQ(ierr);
102   PetscBeganMPI = PETSC_FALSE;
103   PetscFunctionReturn(ierr);
104 }
105 
106 #undef __FUNCT__
107 #define __FUNCT__ "PetscGetPETSC_COMM_SELF"
108 /*
109       Used by MATLAB and Julia interface to get communicator
110 */
111 PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
112 {
113   PetscFunctionBegin;
114   *comm = PETSC_COMM_SELF;
115   PetscFunctionReturn(0);
116 }
117 
118 #undef __FUNCT__
119 #define __FUNCT__ "PetscInitializeNoArguments"
120 /*@C
121       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
122         the command line arguments.
123 
124    Collective
125 
126    Level: advanced
127 
128 .seealso: PetscInitialize(), PetscInitializeFortran()
129 @*/
130 PetscErrorCode  PetscInitializeNoArguments(void)
131 {
132   PetscErrorCode ierr;
133   int            argc = 0;
134   char           **args = 0;
135 
136   PetscFunctionBegin;
137   ierr = PetscInitialize(&argc,&args,PETSC_NULL,PETSC_NULL);
138   PetscFunctionReturn(ierr);
139 }
140 
141 #undef __FUNCT__
142 #define __FUNCT__ "PetscInitialized"
143 /*@
144       PetscInitialized - Determine whether PETSc is initialized.
145 
146 7   Level: beginner
147 
148 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
149 @*/
150 PetscErrorCode  PetscInitialized(PetscBool  *isInitialized)
151 {
152   PetscFunctionBegin;
153   PetscValidPointer(isInitialized, 1);
154   *isInitialized = PetscInitializeCalled;
155   PetscFunctionReturn(0);
156 }
157 
158 #undef __FUNCT__
159 #define __FUNCT__ "PetscFinalized"
160 /*@
161       PetscFinalized - Determine whether PetscFinalize() has been called yet
162 
163    Level: developer
164 
165 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
166 @*/
167 PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
168 {
169   PetscFunctionBegin;
170   PetscValidPointer(isFinalized, 1);
171   *isFinalized = PetscFinalizeCalled;
172   PetscFunctionReturn(0);
173 }
174 
175 extern PetscErrorCode        PetscOptionsCheckInitial_Private(void);
176 extern PetscBool  PetscBeganMPI;
177 
178 /*
179        This function is the MPI reduction operation used to compute the sum of the
180    first half of the datatype and the max of the second half.
181 */
182 MPI_Op PetscMaxSum_Op = 0;
183 
184 EXTERN_C_BEGIN
185 #undef __FUNCT__
186 #define __FUNCT__ "PetscMaxSum_Local"
187 void  MPIAPI PetscMaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
188 {
189   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;
190 
191   PetscFunctionBegin;
192   if (*datatype != MPIU_2INT) {
193     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
194     MPI_Abort(MPI_COMM_WORLD,1);
195   }
196 
197   for (i=0; i<count; i++) {
198     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
199     xout[2*i+1] += xin[2*i+1];
200   }
201   PetscFunctionReturnVoid();
202 }
203 EXTERN_C_END
204 
205 /*
206     Returns the max of the first entry owned by this processor and the
207 sum of the second entry.
208 
209     The reason nprocs[2*i] contains lengths nprocs[2*i+1] contains flag of 1 if length is nonzero
210 is so that the PetscMaxSum_Op() can set TWO values, if we passed in only nprocs[i] with lengths
211 there would be no place to store the both needed results.
212 */
213 #undef __FUNCT__
214 #define __FUNCT__ "PetscMaxSum"
215 PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt nprocs[],PetscInt *max,PetscInt *sum)
216 {
217   PetscMPIInt    size,rank;
218   PetscInt       *work;
219   PetscErrorCode ierr;
220 
221   PetscFunctionBegin;
222   ierr   = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
223   ierr   = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
224   ierr   = PetscMalloc(2*size*sizeof(PetscInt),&work);CHKERRQ(ierr);
225   ierr   = MPI_Allreduce((void*)nprocs,work,size,MPIU_2INT,PetscMaxSum_Op,comm);CHKERRQ(ierr);
226   *max   = work[2*rank];
227   *sum   = work[2*rank+1];
228   ierr   = PetscFree(work);CHKERRQ(ierr);
229   PetscFunctionReturn(0);
230 }
231 
232 /* ----------------------------------------------------------------------------*/
233 MPI_Op  PetscADMax_Op = 0;
234 
235 EXTERN_C_BEGIN
236 #undef __FUNCT__
237 #define __FUNCT__ "PetscADMax_Local"
238 void  MPIAPI PetscADMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
239 {
240   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
241   PetscInt    i,count = *cnt;
242 
243   PetscFunctionBegin;
244   if (*datatype != MPIU_2SCALAR) {
245     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
246     MPI_Abort(MPI_COMM_WORLD,1);
247   }
248 
249   for (i=0; i<count; i++) {
250     if (PetscRealPart(xout[2*i]) < PetscRealPart(xin[2*i])) {
251       xout[2*i]   = xin[2*i];
252       xout[2*i+1] = xin[2*i+1];
253     }
254   }
255   PetscFunctionReturnVoid();
256 }
257 EXTERN_C_END
258 
259 MPI_Op  PetscADMin_Op = 0;
260 
261 EXTERN_C_BEGIN
262 #undef __FUNCT__
263 #define __FUNCT__ "PetscADMin_Local"
264 void  MPIAPI PetscADMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
265 {
266   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
267   PetscInt    i,count = *cnt;
268 
269   PetscFunctionBegin;
270   if (*datatype != MPIU_2SCALAR) {
271     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
272     MPI_Abort(MPI_COMM_WORLD,1);
273   }
274 
275   for (i=0; i<count; i++) {
276     if (PetscRealPart(xout[2*i]) > PetscRealPart(xin[2*i])) {
277       xout[2*i]   = xin[2*i];
278       xout[2*i+1] = xin[2*i+1];
279     }
280   }
281   PetscFunctionReturnVoid();
282 }
283 EXTERN_C_END
284 /* ---------------------------------------------------------------------------------------*/
285 
286 #if (defined(PETSC_USE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
287 MPI_Op MPIU_SUM = 0;
288 
289 EXTERN_C_BEGIN
290 #undef __FUNCT__
291 #define __FUNCT__ "PetscSum_Local"
292 void  PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
293 {
294   PetscInt    i,count = *cnt;
295 
296   PetscFunctionBegin;
297   if (*datatype == MPIU_SCALAR) {
298     PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
299     for (i=0; i<count; i++) {
300       xout[i] += xin[i];
301     }
302   } else if (*datatype == MPIU_REAL) {
303     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
304     for (i=0; i<count; i++) {
305       xout[i] += xin[i];
306     }
307   } else {
308     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
309     MPI_Abort(MPI_COMM_WORLD,1);
310   }
311   PetscFunctionReturnVoid();
312 }
313 EXTERN_C_END
314 #endif
315 
316 #if defined(PETSC_USE_REAL___FLOAT128)
317 MPI_Op MPIU_MAX = 0;
318 MPI_Op MPIU_MIN = 0;
319 
320 EXTERN_C_BEGIN
321 #undef __FUNCT__
322 #define __FUNCT__ "PetscMax_Local"
323 void  PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
324 {
325   PetscInt    i,count = *cnt;
326 
327   PetscFunctionBegin;
328   if (*datatype == MPIU_SCALAR) {
329     PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
330     for (i=0; i<count; i++) {
331       xout[i] = PetscRealPart(xout[i])<PetscRealPart(xin[i])? xin[i]: xout[i];
332     }
333   } else if (*datatype == MPIU_REAL) {
334     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
335     for (i=0; i<count; i++) {
336       xout[i] = PetscMax(xout[i],xin[i]);
337     }
338   } else {
339     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
340     MPI_Abort(MPI_COMM_WORLD,1);
341   }
342   PetscFunctionReturnVoid();
343 }
344 EXTERN_C_END
345 
346 EXTERN_C_BEGIN
347 #undef __FUNCT__
348 #define __FUNCT__ "PetscMin_Local"
349 void  PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
350 {
351   PetscInt    i,count = *cnt;
352 
353   PetscFunctionBegin;
354   if (*datatype == MPIU_SCALAR) {
355     PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
356     for (i=0; i<count; i++) {
357       xout[i] = PetscRealPart(xout[i])>PetscRealPart(xin[i])? xin[i]: xout[i];
358     }
359   } else if (*datatype == MPIU_REAL) {
360     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
361     for (i=0; i<count; i++) {
362       xout[i] = PetscMin(xout[i],xin[i]);
363     }
364   } else {
365     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
366     MPI_Abort(MPI_COMM_WORLD,1);
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 #if defined(PETSC_USE_COMPLEX)
729   ierr = MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);CHKERRQ(ierr);
730   ierr = MPI_Type_commit(&MPIU___COMPLEX128);CHKERRQ(ierr);
731 #endif
732   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
733   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
734   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
735 #endif
736 
737   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
738   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
739   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
740   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
741 
742   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
743   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
744 
745   /*
746      Attributes to be set on PETSc communicators
747   */
748   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
749   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
750   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
751 
752   /*
753      Build the options database
754   */
755   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
756 
757 
758   /*
759      Print main application help message
760   */
761   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg);CHKERRQ(ierr);
762   if (help && flg) {
763     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
764   }
765   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
766 
767   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
768 #if defined(PETSC_USE_LOG)
769   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
770 #endif
771 
772   /*
773      Load the dynamic libraries (on machines that support them), this registers all
774      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
775   */
776   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
777 
778   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
779   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
780   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
781   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
782 
783   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
784   /* Check the options database for options related to the options database itself */
785   ierr = PetscOptionsSetFromOptions();CHKERRQ(ierr);
786 
787 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
788   /*
789       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
790 
791       Currently not used because it is not supported by MPICH.
792   */
793 #if !defined(PETSC_WORDS_BIGENDIAN)
794   ierr = MPI_Register_datarep((char *)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,PETSC_NULL);CHKERRQ(ierr);
795 #endif
796 #endif
797 
798   ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
799   if (flg) {
800 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
801     ierr = PetscHMPISpawn((PetscMPIInt) nodesize);CHKERRQ(ierr); /* worker nodes never return from here; they go directly to PetscEnd() */
802 #else
803     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -hmpi_merge_size instead");
804 #endif
805   } else {
806     ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_merge_size",&nodesize,&flg);CHKERRQ(ierr);
807     if (flg) {
808       ierr = PetscHMPIMerge((PetscMPIInt) nodesize,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
809       if (PetscHMPIWorker) { /* if worker then never enter user code */
810         PetscInitializeCalled = PETSC_TRUE;
811         ierr = PetscEnd();
812       }
813     }
814   }
815 
816 #if defined(PETSC_HAVE_CUDA)
817   cublasInit();
818 #endif
819 
820 #if defined(PETSC_HAVE_AMS)
821   ierr = PetscOptionsHasName(PETSC_NULL,"-ams_publish_objects",&flg);CHKERRQ(ierr);
822   if (flg) {
823     PetscAMSPublishAll = PETSC_TRUE;
824   }
825 #endif
826 
827   ierr = PetscOptionsHasName(PETSC_NULL,"-python",&flg);CHKERRQ(ierr);
828   if (flg) {
829     PetscInitializeCalled = PETSC_TRUE;
830     ierr = PetscPythonInitialize(PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
831   }
832 
833   ierr = PetscThreadCommInitializePackage(PETSC_NULL);CHKERRQ(ierr);
834 
835   /*
836       Once we are completedly initialized then we can set this variables
837   */
838   PetscInitializeCalled = PETSC_TRUE;
839   PetscFunctionReturn(0);
840 }
841 
842 extern PetscObject *PetscObjects;
843 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
844 
845 #undef __FUNCT__
846 #define __FUNCT__ "PetscFinalize"
847 /*@C
848    PetscFinalize - Checks for options to be called at the conclusion
849    of the program. MPI_Finalize() is called only if the user had not
850    called MPI_Init() before calling PetscInitialize().
851 
852    Collective on PETSC_COMM_WORLD
853 
854    Options Database Keys:
855 +  -options_table - Calls PetscOptionsView()
856 .  -options_left - Prints unused options that remain in the database
857 .  -objects_left  - Prints list of all objects that have not been freed
858 .  -mpidump - Calls PetscMPIDump()
859 .  -malloc_dump - Calls PetscMallocDump()
860 .  -malloc_info - Prints total memory usage
861 -  -malloc_log - Prints summary of memory usage
862 
863    Options Database Keys for Profiling:
864    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
865 +  -log_summary [filename] - Prints summary of flop and timing
866         information to screen. If the filename is specified the
867         summary is written to the file.  See PetscLogView().
868 .  -log_summary_python [filename] - Prints data on of flop and timing usage to a file or screen.
869         See PetscLogPrintSViewPython().
870 .  -log_all [filename] - Logs extensive profiling information
871         See PetscLogDump().
872 .  -log [filename] - Logs basic profiline information  See PetscLogDump().
873 .  -log_sync - Log the synchronization in scatters, inner products
874         and norms
875 -  -log_mpe [filename] - Creates a logfile viewable by the
876       utility Upshot/Nupshot (in MPICH distribution)
877 
878    Level: beginner
879 
880    Note:
881    See PetscInitialize() for more general runtime options.
882 
883 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
884 @*/
885 PetscErrorCode  PetscFinalize(void)
886 {
887   PetscErrorCode ierr;
888   PetscMPIInt    rank;
889   PetscInt       i,nopt;
890   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE,objects_left = PETSC_FALSE;
891 #if defined(PETSC_HAVE_AMS)
892   PetscBool      flg = PETSC_FALSE;
893 #endif
894 #if defined(PETSC_USE_LOG)
895   char           mname[PETSC_MAX_PATH_LEN];
896 #endif
897 
898   PetscFunctionBegin;
899 
900   if (!PetscInitializeCalled) {
901     printf("PetscInitialize() must be called before PetscFinalize()\n");
902     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
903   }
904   ierr = PetscInfo(PETSC_NULL,"PetscFinalize() called\n");
905 
906 #if defined(PETSC_HAVE_AMS)
907   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_gui",&flg,PETSC_NULL);CHKERRQ(ierr);
908   if (flg) {
909     ierr = PetscOptionsAMSDestroy();CHKERRQ(ierr);
910   }
911 #endif
912 
913   ierr = PetscHMPIFinalize();CHKERRQ(ierr);
914 
915   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
916   ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
917   if (!flg2) {
918     flg2 = PETSC_FALSE;
919     ierr = PetscOptionsGetBool(PETSC_NULL,"-memory_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
920   }
921   if (flg2) {
922     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
923   }
924 
925 #if defined(PETSC_USE_LOG)
926   flg1 = PETSC_FALSE;
927   ierr = PetscOptionsGetBool(PETSC_NULL,"-get_total_flops",&flg1,PETSC_NULL);CHKERRQ(ierr);
928   if (flg1) {
929     PetscLogDouble flops = 0;
930     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
931     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
932   }
933 #endif
934 
935 
936 #if defined(PETSC_USE_LOG)
937 #if defined(PETSC_HAVE_MPE)
938   mname[0] = 0;
939   ierr = PetscOptionsGetString(PETSC_NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
940   if (flg1){
941     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
942     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
943   }
944 #endif
945   mname[0] = 0;
946   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
947   if (flg1) {
948     PetscViewer viewer;
949     if (mname[0])  {
950       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
951       ierr = PetscLogView(viewer);CHKERRQ(ierr);
952       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
953     } else {
954       viewer = PETSC_VIEWER_STDOUT_WORLD;
955       ierr = PetscLogView(viewer);CHKERRQ(ierr);
956     }
957   }
958 
959   mname[0] = 0;
960   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary_python",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
961   if (flg1) {
962     PetscViewer viewer;
963     if (mname[0])  {
964       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
965       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
966       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
967     } else {
968       viewer = PETSC_VIEWER_STDOUT_WORLD;
969       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
970     }
971   }
972 
973   ierr = PetscOptionsGetString(PETSC_NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
974   if (flg1) {
975     if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
976     else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
977   }
978 
979   mname[0] = 0;
980   ierr = PetscOptionsGetString(PETSC_NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
981   ierr = PetscOptionsGetString(PETSC_NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
982   if (flg1 || flg2){
983     if (mname[0]) PetscLogDump(mname);
984     else          PetscLogDump(0);
985   }
986 #endif
987 
988 #if defined(PETSC_USE_DEBUG)
989   if (PetscStackActive) {
990     ierr = PetscStackDestroy();CHKERRQ(ierr);
991   }
992 #endif
993 
994   flg1 = PETSC_FALSE;
995   ierr = PetscOptionsGetBool(PETSC_NULL,"-no_signal_handler",&flg1,PETSC_NULL);CHKERRQ(ierr);
996   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
997   flg1 = PETSC_FALSE;
998   ierr = PetscOptionsGetBool(PETSC_NULL,"-mpidump",&flg1,PETSC_NULL);CHKERRQ(ierr);
999   if (flg1) {
1000     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1001   }
1002   flg1 = PETSC_FALSE;
1003   flg2 = PETSC_FALSE;
1004   /* preemptive call to avoid listing this option in options table as unused */
1005   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1006   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_table",&flg2,PETSC_NULL);CHKERRQ(ierr);
1007 
1008   if (flg2) {
1009     ierr = PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
1010   }
1011 
1012   /* to prevent PETSc -options_left from warning */
1013   ierr = PetscOptionsHasName(PETSC_NULL,"-nox",&flg1);CHKERRQ(ierr);
1014   ierr = PetscOptionsHasName(PETSC_NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1015   ierr = PetscOptionsGetBool(PETSC_NULL,"-objects_left",&objects_left,PETSC_NULL);CHKERRQ(ierr);
1016 
1017   if (!PetscHMPIWorker) { /* worker processes skip this because they do not usually process options */
1018     flg3 = PETSC_FALSE; /* default value is required */
1019     ierr = PetscOptionsGetBool(PETSC_NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1020     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
1021     if (flg3) {
1022       if (!flg2) { /* have not yet printed the options */
1023 	ierr = PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
1024       }
1025       if (!nopt) {
1026 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1027       } else if (nopt == 1) {
1028 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1029       } else {
1030 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1031       }
1032     }
1033 #if defined(PETSC_USE_DEBUG)
1034     if (nopt && !flg3 && !flg1) {
1035       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1036       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1037       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1038     } else if (nopt && flg3) {
1039 #else
1040     if (nopt && flg3) {
1041 #endif
1042       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1043     }
1044   }
1045 
1046   /*
1047      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1048   */
1049   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1050 
1051   /*
1052        List all objects the user may have forgot to free
1053   */
1054   if (objects_left && PetscObjectsCounts) {
1055     ierr = PetscPrintf(PETSC_COMM_WORLD,"The following objects %D were never freed\n",PetscObjectsCounts);
1056   }
1057   for (i=0; i<PetscObjectsMaxCounts; i++) {
1058     if (PetscObjects[i]) {
1059       if (objects_left) {
1060         ierr = PetscPrintf(PETSC_COMM_WORLD,"  %s %s %s\n",PetscObjects[i]->class_name,PetscObjects[i]->type_name,PetscObjects[i]->name);CHKERRQ(ierr);
1061       }
1062     }
1063   }
1064   /* cannot actually destroy the left over objects, but destroy the list */
1065   PetscObjectsCounts    = 0;
1066   PetscObjectsMaxCounts = 0;
1067   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1068 
1069 
1070 #if defined(PETSC_USE_LOG)
1071   ierr = PetscLogDestroy();CHKERRQ(ierr);
1072 #endif
1073 
1074   /*
1075        Free all the registered create functions, such as KSPList, VecList, SNESList, etc
1076   */
1077   ierr = PetscFListDestroyAll();CHKERRQ(ierr);
1078 
1079   /*
1080        Free all the registered op functions, such as MatOpList, etc
1081   */
1082   ierr = PetscOpFListDestroyAll();CHKERRQ(ierr);
1083 
1084   /*
1085      Destroy any packages that registered a finalize
1086   */
1087   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1088 
1089   /*
1090      Destroy all the function registration lists created
1091   */
1092   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1093 
1094   if (petsc_history) {
1095     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1096     petsc_history = 0;
1097   }
1098 
1099   ierr = PetscInfoAllow(PETSC_FALSE,PETSC_NULL);CHKERRQ(ierr);
1100 
1101   {
1102     char fname[PETSC_MAX_PATH_LEN];
1103     FILE *fd;
1104     int  err;
1105 
1106     fname[0] = 0;
1107     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1108     flg2 = PETSC_FALSE;
1109     ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_test",&flg2,PETSC_NULL);CHKERRQ(ierr);
1110 #if defined(PETSC_USE_DEBUG)
1111     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1112 #else
1113     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1114 #endif
1115     if (flg1 && fname[0]) {
1116       char sname[PETSC_MAX_PATH_LEN];
1117 
1118       sprintf(sname,"%s_%d",fname,rank);
1119       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1120       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1121       err = fclose(fd);
1122       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1123     } else if (flg1 || flg2) {
1124       MPI_Comm local_comm;
1125 
1126       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1127       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1128         ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1129       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1130       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1131     }
1132   }
1133   {
1134     char fname[PETSC_MAX_PATH_LEN];
1135     FILE *fd = PETSC_NULL;
1136 
1137     fname[0] = 0;
1138     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1139     ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_log_threshold",&flg2);CHKERRQ(ierr);
1140     if (flg1 && fname[0]) {
1141       int  err;
1142 
1143       if (!rank) {
1144         fd = fopen(fname,"w");
1145         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1146       }
1147       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1148       if (fd) {
1149         err = fclose(fd);
1150         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1151       }
1152     } else if (flg1 || flg2) {
1153       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1154     }
1155   }
1156   /* Can be destroyed only after all the options are used */
1157   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
1158 
1159   PetscGlobalArgc = 0;
1160   PetscGlobalArgs = 0;
1161 
1162 #if defined(PETSC_USE_REAL___FLOAT128)
1163   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1164 #if defined(PETSC_USE_COMPLEX)
1165   ierr = MPI_Type_free(&MPIU___COMPLEX128);CHKERRQ(ierr);
1166 #endif
1167   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1168   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1169   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1170 #endif
1171 
1172 #if defined(PETSC_USE_COMPLEX)
1173 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1174   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1175   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1176   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1177 #endif
1178 #endif
1179   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1180   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1181   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
1182   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
1183   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
1184 
1185   /*
1186      Destroy any known inner MPI_Comm's and attributes pointing to them
1187      Note this will not destroy any new communicators the user has created.
1188 
1189      If all PETSc objects were not destroyed those left over objects will have hanging references to
1190      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1191  */
1192   {
1193     PetscCommCounter *counter;
1194     PetscMPIInt      flg;
1195     MPI_Comm         icomm;
1196     void             *ptr;
1197     ierr  = MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1198     if (flg) {
1199       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1200       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1201       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1202       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1203 
1204       ierr = MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1205       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1206       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1207     }
1208     ierr  = MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1209     if (flg) {
1210       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1211       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1212       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1213       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1214 
1215       ierr = MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1216       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1217       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1218     }
1219   }
1220 
1221   ierr = MPI_Keyval_free(&Petsc_Counter_keyval);CHKERRQ(ierr);
1222   ierr = MPI_Keyval_free(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1223   ierr = MPI_Keyval_free(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1224 
1225   ierr = PetscInfo(0,"PETSc successfully ended!\n");CHKERRQ(ierr);
1226   if (PetscBeganMPI) {
1227 #if defined(PETSC_HAVE_MPI_FINALIZED)
1228     PetscMPIInt flag;
1229     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1230     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1231 #endif
1232     ierr = MPI_Finalize();CHKERRQ(ierr);
1233   }
1234 
1235 #if defined(PETSC_HAVE_CUDA)
1236   cublasShutdown();
1237 #endif
1238 /*
1239 
1240      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1241    the communicator has some outstanding requests on it. Specifically if the
1242    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1243    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1244    is never freed as it should be. Thus one may obtain messages of the form
1245    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1246    memory was not freed.
1247 
1248 */
1249   ierr = PetscMallocClear();CHKERRQ(ierr);
1250   PetscInitializeCalled = PETSC_FALSE;
1251   PetscFinalizeCalled   = PETSC_TRUE;
1252   PetscFunctionReturn(ierr);
1253 }
1254 
1255 #if defined(PETSC_MISSING_LAPACK_lsame_)
1256 EXTERN_C_BEGIN
1257 int lsame_(char *a,char *b)
1258 {
1259   if (*a == *b) return 1;
1260   if (*a + 32 == *b) return 1;
1261   if (*a - 32 == *b) return 1;
1262   return 0;
1263 }
1264 EXTERN_C_END
1265 #endif
1266 
1267 #if defined(PETSC_MISSING_LAPACK_lsame)
1268 EXTERN_C_BEGIN
1269 int lsame(char *a,char *b)
1270 {
1271   if (*a == *b) return 1;
1272   if (*a + 32 == *b) return 1;
1273   if (*a - 32 == *b) return 1;
1274   return 0;
1275 }
1276 EXTERN_C_END
1277 #endif
1278