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