xref: /petsc/src/sys/objects/pinit.c (revision e9689791c5a9366a4cc7df4c5c057bb347a999a0)
1 
2 /*
3    This file defines the initialization of PETSc, including PetscInitialize()
4 */
5 #include <petsc/private/petscimpl.h>        /*I  "petscsys.h"   I*/
6 #include <petscvalgrind.h>
7 #include <petscviewer.h>
8 
9 #if defined(PETSC_USE_LOG)
10 extern PetscErrorCode PetscLogInitialize(void);
11 #endif
12 
13 #if defined(PETSC_SERIALIZE_FUNCTIONS)
14 PetscFPT PetscFPTData = 0;
15 #endif
16 
17 #if defined(PETSC_HAVE_SAWS)
18 #include <petscviewersaws.h>
19 #endif
20 /* -----------------------------------------------------------------------------------------*/
21 
22 extern FILE *petsc_history;
23 
24 extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
25 extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
26 extern PetscErrorCode PetscFunctionListPrintAll(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 PetscMPIInt Petsc_Shared_keyval    = MPI_KEYVAL_INVALID;
38 
39 /*
40      Declare and set all the string names of the PETSc enums
41 */
42 const char *const PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
43 const char *const PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
44 const char *const PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
45                                       "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","OBJECT","FUNCTION","PetscDataType","PETSC_",0};
46 
47 PetscBool PetscPreLoadingUsed = PETSC_FALSE;
48 PetscBool PetscPreLoadingOn   = PETSC_FALSE;
49 
50 PetscInt PetscHotRegionDepth;
51 
52 #if defined(PETSC_HAVE_THREADSAFETY)
53 PetscSpinlock PetscViewerASCIISpinLockOpen;
54 PetscSpinlock PetscViewerASCIISpinLockStdout;
55 PetscSpinlock PetscViewerASCIISpinLockStderr;
56 PetscSpinlock PetscCommSpinLock;
57 #endif
58 
59 /*
60        Checks the options database for initializations related to the
61     PETSc components
62 */
63 PetscErrorCode  PetscOptionsCheckInitial_Components(void)
64 {
65   PetscBool      flg1;
66   PetscErrorCode ierr;
67 
68   PetscFunctionBegin;
69   ierr = PetscOptionsHasName(NULL,NULL,"-help",&flg1);CHKERRQ(ierr);
70   if (flg1) {
71 #if defined(PETSC_USE_LOG)
72     MPI_Comm comm = PETSC_COMM_WORLD;
73     ierr = (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");CHKERRQ(ierr);
74     ierr = (*PetscHelpPrintf)(comm," -log_exclude: <vec,mat,pc.ksp,snes>\n");CHKERRQ(ierr);
75     ierr = (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");CHKERRQ(ierr);
76     ierr = (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");CHKERRQ(ierr);
77 #endif
78   }
79   PetscFunctionReturn(0);
80 }
81 
82 /*
83       PetscInitializeNoPointers - Calls PetscInitialize() from C/C++ without the pointers to argc and args
84 
85    Collective
86 
87    Level: advanced
88 
89     Notes: this is called only by the PETSc MATLAB and Julia interface. Even though it might start MPI it sets the flag to
90      indicate that it did NOT start MPI so that the PetscFinalize() does not end MPI, thus allowing PetscInitialize() to
91      be called multiple times from MATLAB and Julia without the problem of trying to initialize MPI more than once.
92 
93      Turns off PETSc signal handling because that can interact with MATLAB's signal handling causing random crashes.
94 
95 .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
96 */
97 PetscErrorCode  PetscInitializeNoPointers(int argc,char **args,const char *filename,const char *help)
98 {
99   PetscErrorCode ierr;
100   int            myargc   = argc;
101   char           **myargs = args;
102 
103   PetscFunctionBegin;
104   ierr = PetscInitialize(&myargc,&myargs,filename,help);CHKERRQ(ierr);
105   ierr = PetscPopSignalHandler();CHKERRQ(ierr);
106   PetscBeganMPI = PETSC_FALSE;
107   PetscFunctionReturn(ierr);
108 }
109 
110 /*
111       Used by MATLAB and Julia interface to get communicator
112 */
113 PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
114 {
115   PetscFunctionBegin;
116   *comm = PETSC_COMM_SELF;
117   PetscFunctionReturn(0);
118 }
119 
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,NULL,NULL);
138   PetscFunctionReturn(ierr);
139 }
140 
141 /*@
142       PetscInitialized - Determine whether PETSc is initialized.
143 
144    Level: beginner
145 
146 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
147 @*/
148 PetscErrorCode PetscInitialized(PetscBool  *isInitialized)
149 {
150   *isInitialized = PetscInitializeCalled;
151   return 0;
152 }
153 
154 /*@
155       PetscFinalized - Determine whether PetscFinalize() has been called yet
156 
157    Level: developer
158 
159 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
160 @*/
161 PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
162 {
163   *isFinalized = PetscFinalizeCalled;
164   return 0;
165 }
166 
167 extern PetscErrorCode PetscOptionsCheckInitial_Private(void);
168 
169 /*
170        This function is the MPI reduction operation used to compute the sum of the
171    first half of the datatype and the max of the second half.
172 */
173 MPI_Op MPIU_MAXSUM_OP = 0;
174 
175 PETSC_INTERN void MPIAPI MPIU_MaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
176 {
177   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;
178 
179   PetscFunctionBegin;
180   if (*datatype != MPIU_2INT) {
181     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
182     MPI_Abort(MPI_COMM_WORLD,1);
183   }
184 
185   for (i=0; i<count; i++) {
186     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
187     xout[2*i+1] += xin[2*i+1];
188   }
189   PetscFunctionReturnVoid();
190 }
191 
192 /*
193     Returns the max of the first entry owned by this processor and the
194 sum of the second entry.
195 
196     The reason sizes[2*i] contains lengths sizes[2*i+1] contains flag of 1 if length is nonzero
197 is so that the MPIU_MAXSUM_OP() can set TWO values, if we passed in only sizes[i] with lengths
198 there would be no place to store the both needed results.
199 */
200 PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt sizes[],PetscInt *max,PetscInt *sum)
201 {
202   PetscErrorCode ierr;
203 
204   PetscFunctionBegin;
205 #if defined(PETSC_HAVE_MPI_REDUCE_SCATTER_BLOCK)
206   {
207     struct {PetscInt max,sum;} work;
208     ierr = MPI_Reduce_scatter_block((void*)sizes,&work,1,MPIU_2INT,MPIU_MAXSUM_OP,comm);CHKERRQ(ierr);
209     *max = work.max;
210     *sum = work.sum;
211   }
212 #else
213   {
214     PetscMPIInt    size,rank;
215     struct {PetscInt max,sum;} *work;
216     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
217     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
218     ierr = PetscMalloc1(size,&work);CHKERRQ(ierr);
219     ierr = MPIU_Allreduce((void*)sizes,work,size,MPIU_2INT,MPIU_MAXSUM_OP,comm);CHKERRQ(ierr);
220     *max = work[rank].max;
221     *sum = work[rank].sum;
222     ierr = PetscFree(work);CHKERRQ(ierr);
223   }
224 #endif
225   PetscFunctionReturn(0);
226 }
227 
228 /* ----------------------------------------------------------------------------*/
229 
230 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
231 MPI_Op MPIU_SUM = 0;
232 
233 PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
234 {
235   PetscInt i,count = *cnt;
236 
237   PetscFunctionBegin;
238   if (*datatype == MPIU_REAL) {
239     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
240     for (i=0; i<count; i++) xout[i] += xin[i];
241   }
242 #if defined(PETSC_HAVE_COMPLEX)
243   else if (*datatype == MPIU_COMPLEX) {
244     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
245     for (i=0; i<count; i++) xout[i] += xin[i];
246   }
247 #endif
248   else {
249     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
250     MPI_Abort(MPI_COMM_WORLD,1);
251   }
252   PetscFunctionReturnVoid();
253 }
254 #endif
255 
256 #if defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
257 MPI_Op MPIU_MAX = 0;
258 MPI_Op MPIU_MIN = 0;
259 
260 PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
261 {
262   PetscInt i,count = *cnt;
263 
264   PetscFunctionBegin;
265   if (*datatype == MPIU_REAL) {
266     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
267     for (i=0; i<count; i++) xout[i] = PetscMax(xout[i],xin[i]);
268   }
269 #if defined(PETSC_HAVE_COMPLEX)
270   else if (*datatype == MPIU_COMPLEX) {
271     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
272     for (i=0; i<count; i++) {
273       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
274     }
275   }
276 #endif
277   else {
278     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
279     MPI_Abort(MPI_COMM_WORLD,1);
280   }
281   PetscFunctionReturnVoid();
282 }
283 
284 PETSC_EXTERN void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
285 {
286   PetscInt    i,count = *cnt;
287 
288   PetscFunctionBegin;
289   if (*datatype == MPIU_REAL) {
290     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
291     for (i=0; i<count; i++) xout[i] = PetscMin(xout[i],xin[i]);
292   }
293 #if defined(PETSC_HAVE_COMPLEX)
294   else if (*datatype == MPIU_COMPLEX) {
295     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
296     for (i=0; i<count; i++) {
297       xout[i] = PetscRealPartComplex(xout[i])>PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
298     }
299   }
300 #endif
301   else {
302     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
303     MPI_Abort(MPI_COMM_WORLD,1);
304   }
305   PetscFunctionReturnVoid();
306 }
307 #endif
308 
309 /*
310    Private routine to delete internal tag/name counter storage when a communicator is freed.
311 
312    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.
313 
314    Note: this is declared extern "C" because it is passed to MPI_Comm_create_keyval()
315 
316 */
317 PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
318 {
319   PetscErrorCode ierr;
320 
321   PetscFunctionBegin;
322   ierr = PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);CHKERRMPI(ierr);
323   ierr = PetscFree(count_val);CHKERRMPI(ierr);
324   PetscFunctionReturn(MPI_SUCCESS);
325 }
326 
327 /*
328   This is invoked on the outer comm as a result of either PetscCommDestroy() (via MPI_Comm_delete_attr) or when the user
329   calls MPI_Comm_free().
330 
331   This is the only entry point for breaking the links between inner and outer comms.
332 
333   This is called by MPI, not by users. This is called when MPI_Comm_free() is called on the communicator.
334 
335   Note: this is declared extern "C" because it is passed to MPI_Comm_create_keyval()
336 
337 */
338 PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
339 {
340   PetscErrorCode                    ierr;
341   PetscMPIInt                       flg;
342   union {MPI_Comm comm; void *ptr;} icomm,ocomm;
343 
344   PetscFunctionBegin;
345   if (keyval != Petsc_InnerComm_keyval) SETERRMPI(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Unexpected keyval");
346   icomm.ptr = attr_val;
347 
348   ierr = MPI_Comm_get_attr(icomm.comm,Petsc_OuterComm_keyval,&ocomm,&flg);CHKERRMPI(ierr);
349   if (!flg) SETERRMPI(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
350   if (ocomm.comm != comm) SETERRMPI(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm has reference to non-matching outer comm");
351   ierr = MPI_Comm_delete_attr(icomm.comm,Petsc_OuterComm_keyval);CHKERRMPI(ierr);
352   ierr = PetscInfo1(0,"User MPI_Comm %ld is being freed after removing reference from inner PETSc comm to this outer comm\n",(long)comm);CHKERRMPI(ierr);
353   PetscFunctionReturn(MPI_SUCCESS);
354 }
355 
356 /*
357  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Comm_delete_attr.  It should not be reached any other way.
358  */
359 PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
360 {
361   PetscErrorCode ierr;
362 
363   PetscFunctionBegin;
364   ierr = PetscInfo1(0,"Removing reference to PETSc communicator embedded in a user MPI_Comm %ld\n",(long)comm);CHKERRMPI(ierr);
365   PetscFunctionReturn(MPI_SUCCESS);
366 }
367 
368 PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelShared(MPI_Comm,PetscMPIInt,void *,void *);
369 
370 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
371 #if !defined(PETSC_WORDS_BIGENDIAN)
372 PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
373 PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
374 PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
375 #endif
376 #endif
377 
378 PetscMPIInt PETSC_MPI_ERROR_CLASS,PETSC_MPI_ERROR_CODE;
379 
380 int  PetscGlobalArgc   = 0;
381 char **PetscGlobalArgs = 0;
382 PetscSegBuffer PetscCitationsList;
383 
384 PetscErrorCode PetscCitationsInitialize(void)
385 {
386   PetscErrorCode ierr;
387 
388   PetscFunctionBegin;
389   ierr = PetscSegBufferCreate(1,10000,&PetscCitationsList);CHKERRQ(ierr);
390   ierr = PetscCitationsRegister("@TechReport{petsc-user-ref,\n  Author = {Satish Balay and Shrirang Abhyankar and Mark F. Adams and Jed Brown and Peter Brune\n            and Kris Buschelman and Lisandro Dalcin and Victor Eijkhout and William D. Gropp\n            and Dinesh Kaushik and Matthew G. Knepley\n            and Lois Curfman McInnes and Karl Rupp and Barry F. Smith\n            and Stefano Zampini and Hong Zhang and Hong Zhang},\n  Title = {{PETS}c Users Manual},\n  Number = {ANL-95/11 - Revision 3.8},\n  Institution = {Argonne National Laboratory},\n  Year = {2017}\n}\n",NULL);CHKERRQ(ierr);
391   ierr = PetscCitationsRegister("@InProceedings{petsc-efficient,\n  Author = {Satish Balay and William D. Gropp and Lois Curfman McInnes and Barry F. Smith},\n  Title = {Efficient Management of Parallelism in Object Oriented Numerical Software Libraries},\n  Booktitle = {Modern Software Tools in Scientific Computing},\n  Editor = {E. Arge and A. M. Bruaset and H. P. Langtangen},\n  Pages = {163--202},\n  Publisher = {Birkh{\\\"{a}}user Press},\n  Year = {1997}\n}\n",NULL);CHKERRQ(ierr);
392   PetscFunctionReturn(0);
393 }
394 
395 /*@C
396    PetscGetArgs - Allows you to access the raw command line arguments anywhere
397      after PetscInitialize() is called but before PetscFinalize().
398 
399    Not Collective
400 
401    Output Parameters:
402 +  argc - count of number of command line arguments
403 -  args - the command line arguments
404 
405    Level: intermediate
406 
407    Notes:
408       This is usually used to pass the command line arguments into other libraries
409    that are called internally deep in PETSc or the application.
410 
411       The first argument contains the program name as is normal for C arguments.
412 
413    Concepts: command line arguments
414 
415 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArguments()
416 
417 @*/
418 PetscErrorCode  PetscGetArgs(int *argc,char ***args)
419 {
420   PetscFunctionBegin;
421   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
422   *argc = PetscGlobalArgc;
423   *args = PetscGlobalArgs;
424   PetscFunctionReturn(0);
425 }
426 
427 /*@C
428    PetscGetArguments - Allows you to access the  command line arguments anywhere
429      after PetscInitialize() is called but before PetscFinalize().
430 
431    Not Collective
432 
433    Output Parameters:
434 .  args - the command line arguments
435 
436    Level: intermediate
437 
438    Notes:
439       This does NOT start with the program name and IS null terminated (final arg is void)
440 
441    Concepts: command line arguments
442 
443 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscFreeArguments()
444 
445 @*/
446 PetscErrorCode  PetscGetArguments(char ***args)
447 {
448   PetscInt       i,argc = PetscGlobalArgc;
449   PetscErrorCode ierr;
450 
451   PetscFunctionBegin;
452   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
453   if (!argc) {*args = 0; PetscFunctionReturn(0);}
454   ierr = PetscMalloc1(argc,args);CHKERRQ(ierr);
455   for (i=0; i<argc-1; i++) {
456     ierr = PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);CHKERRQ(ierr);
457   }
458   (*args)[argc-1] = 0;
459   PetscFunctionReturn(0);
460 }
461 
462 /*@C
463    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()
464 
465    Not Collective
466 
467    Output Parameters:
468 .  args - the command line arguments
469 
470    Level: intermediate
471 
472    Concepts: command line arguments
473 
474 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscGetArguments()
475 
476 @*/
477 PetscErrorCode  PetscFreeArguments(char **args)
478 {
479   PetscInt       i = 0;
480   PetscErrorCode ierr;
481 
482   PetscFunctionBegin;
483   if (!args) PetscFunctionReturn(0);
484   while (args[i]) {
485     ierr = PetscFree(args[i]);CHKERRQ(ierr);
486     i++;
487   }
488   ierr = PetscFree(args);CHKERRQ(ierr);
489   PetscFunctionReturn(0);
490 }
491 
492 #if defined(PETSC_HAVE_SAWS)
493 #include <petscconfiginfo.h>
494 
495 PetscErrorCode  PetscInitializeSAWs(const char help[])
496 {
497   if (!PetscGlobalRank) {
498     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
499     int            port;
500     PetscBool      flg,rootlocal = PETSC_FALSE,flg2,selectport = PETSC_FALSE;
501     size_t         applinelen,introlen;
502     PetscErrorCode ierr;
503     char           sawsurl[256];
504 
505     ierr = PetscOptionsHasName(NULL,NULL,"-saws_log",&flg);CHKERRQ(ierr);
506     if (flg) {
507       char  sawslog[PETSC_MAX_PATH_LEN];
508 
509       ierr = PetscOptionsGetString(NULL,NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
510       if (sawslog[0]) {
511         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
512       } else {
513         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
514       }
515     }
516     ierr = PetscOptionsGetString(NULL,NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
517     if (flg) {
518       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
519     }
520     ierr = PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select",&selectport,NULL);CHKERRQ(ierr);
521     if (selectport) {
522         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
523         PetscStackCallSAWs(SAWs_Set_Port,(port));
524     } else {
525       ierr = PetscOptionsGetInt(NULL,NULL,"-saws_port",&port,&flg);CHKERRQ(ierr);
526       if (flg) {
527         PetscStackCallSAWs(SAWs_Set_Port,(port));
528       }
529     }
530     ierr = PetscOptionsGetString(NULL,NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
531     if (flg) {
532       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));CHKERRQ(ierr);
533       ierr = PetscStrcmp(root,".",&rootlocal);CHKERRQ(ierr);
534     } else {
535       ierr = PetscOptionsHasName(NULL,NULL,"-saws_options",&flg);CHKERRQ(ierr);
536       if (flg) {
537         ierr = PetscStrreplace(PETSC_COMM_WORLD,"${PETSC_DIR}/share/petsc/saws",root,PETSC_MAX_PATH_LEN);CHKERRQ(ierr);
538         PetscStackCallSAWs(SAWs_Set_Document_Root,(root));CHKERRQ(ierr);
539       }
540     }
541     ierr = PetscOptionsHasName(NULL,NULL,"-saws_local",&flg2);CHKERRQ(ierr);
542     if (flg2) {
543       char jsdir[PETSC_MAX_PATH_LEN];
544       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
545       ierr = PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);CHKERRQ(ierr);
546       ierr = PetscTestDirectory(jsdir,'r',&flg);CHKERRQ(ierr);
547       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
548       PetscStackCallSAWs(SAWs_Push_Local_Header,());CHKERRQ(ierr);
549     }
550     ierr = PetscGetProgramName(programname,64);CHKERRQ(ierr);
551     ierr = PetscStrlen(help,&applinelen);CHKERRQ(ierr);
552     introlen   = 4096 + applinelen;
553     applinelen += 1024;
554     ierr = PetscMalloc(applinelen,&appline);CHKERRQ(ierr);
555     ierr = PetscMalloc(introlen,&intro);CHKERRQ(ierr);
556 
557     if (rootlocal) {
558       ierr = PetscSNPrintf(appline,applinelen,"%s.c.html",programname);CHKERRQ(ierr);
559       ierr = PetscTestFile(appline,'r',&rootlocal);CHKERRQ(ierr);
560     }
561     ierr = PetscOptionsGetAll(NULL,&options);CHKERRQ(ierr);
562     if (rootlocal && help) {
563       ierr = PetscSNPrintf(appline,applinelen,"<center> Running <a href=\"%s.c.html\">%s</a> %s</center><br><center><pre>%s</pre></center><br>\n",programname,programname,options,help);
564     } else if (help) {
565       ierr = PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>",programname,options,help);
566     } else {
567       ierr = PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
568     }
569     ierr = PetscFree(options);CHKERRQ(ierr);
570     ierr = PetscGetVersion(version,sizeof(version));CHKERRQ(ierr);
571     ierr = PetscSNPrintf(intro,introlen,"<body>\n"
572                                     "<center><h2> <a href=\"http://www.mcs.anl.gov/petsc\">PETSc</a> Application Web server powered by <a href=\"https://bitbucket.org/saws/saws\">SAWs</a> </h2></center>\n"
573                                     "<center>This is the default PETSc application dashboard, from it you can access any published PETSc objects or logging data</center><br><center>%s configured with %s</center><br>\n"
574                                     "%s",version,petscconfigureoptions,appline);
575     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
576     ierr = PetscFree(intro);CHKERRQ(ierr);
577     ierr = PetscFree(appline);CHKERRQ(ierr);
578     if (selectport) {
579       PetscBool silent;
580 
581       ierr = SAWs_Initialize();
582       /* another process may have grabbed the port so keep trying */
583       while (ierr) {
584         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
585         PetscStackCallSAWs(SAWs_Set_Port,(port));
586         ierr = SAWs_Initialize();
587       }
588 
589       ierr = PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select_silent",&silent,NULL);CHKERRQ(ierr);
590       if (!silent) {
591         PetscStackCallSAWs(SAWs_Get_FullURL,(sizeof(sawsurl),sawsurl));
592         ierr = PetscPrintf(PETSC_COMM_WORLD,"Point your browser to %s for SAWs\n",sawsurl);CHKERRQ(ierr);
593       }
594     } else {
595       PetscStackCallSAWs(SAWs_Initialize,());
596     }
597     ierr = PetscCitationsRegister("@TechReport{ saws,\n"
598                                   "  Author = {Matt Otten and Jed Brown and Barry Smith},\n"
599                                   "  Title  = {Scientific Application Web Server (SAWs) Users Manual},\n"
600                                   "  Institution = {Argonne National Laboratory},\n"
601                                   "  Year   = 2013\n}\n",NULL);CHKERRQ(ierr);
602   }
603   PetscFunctionReturn(0);
604 }
605 #endif
606 
607 /*@C
608    PetscInitialize - Initializes the PETSc database and MPI.
609    PetscInitialize() calls MPI_Init() if that has yet to be called,
610    so this routine should always be called near the beginning of
611    your program -- usually the very first line!
612 
613    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set
614 
615    Input Parameters:
616 +  argc - count of number of command line arguments
617 .  args - the command line arguments
618 .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
619           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
620 -  help - [optional] Help message to print, use NULL for no message
621 
622    If you wish PETSc code to run ONLY on a subcommunicator of MPI_COMM_WORLD, create that
623    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize(). Thus if you are running a
624    four process job and two processes will run PETSc and have PetscInitialize() and PetscFinalize() and two process will not,
625    then do this. If ALL processes in the job are using PetscInitialize() and PetscFinalize() then you don't need to do this, even
626    if different subcommunicators of the job are doing different things with PETSc.
627 
628    Options Database Keys:
629 +  -help [intro] - prints help method for each option; if intro is given the program stops after printing the introductory help message
630 .  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
631 .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
632 .  -on_error_emacs <machinename> causes emacsclient to jump to error file
633 .  -on_error_abort calls abort() when error detected (no traceback)
634 .  -on_error_mpiabort calls MPI_abort() when error detected
635 .  -error_output_stderr prints error messages to stderr instead of the default stdout
636 .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
637 .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
638 .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
639 .  -stop_for_debugger - Print message on how to attach debugger manually to
640                         process and wait (-debugger_pause) seconds for attachment
641 .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
642 .  -malloc no - Indicates not to use error-checking malloc
643 .  -malloc_debug - check for memory corruption at EVERY malloc or free
644 .  -malloc_dump - prints a list of all unfreed memory at the end of the run
645 .  -malloc_test - like -malloc_dump -malloc_debug, but only active for debugging builds
646 .  -fp_trap - Stops on floating point exceptions (Note that on the
647               IBM RS6000 this slows code by at least a factor of 10.)
648 .  -no_signal_handler - Indicates not to trap error signals
649 .  -shared_tmp - indicates /tmp directory is shared by all processors
650 .  -not_shared_tmp - each processor has own /tmp
651 .  -tmp - alternative name of /tmp directory
652 .  -get_total_flops - returns total flops done by all processors
653 -  -memory_view - Print memory usage at end of run
654 
655    Options Database Keys for Profiling:
656    See Users-Manual: ch_profiling for details.
657 +  -info <optional filename> - Prints verbose information to the screen
658 .  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
659 .  -log_sync - Log the synchronization in scatters, inner products and norms
660 .  -log_trace [filename] - Print traces of all PETSc calls to the screen (useful to determine where a program
661         hangs without running in the debugger).  See PetscLogTraceBegin().
662 .  -log_view [:filename:format] - Prints summary of flop and timing information to screen or file, see PetscLogView().
663 .  -log_summary [filename] - (Deprecated, use -log_view) Prints summary of flop and timing information to screen. If the filename is specified the
664         summary is written to the file.  See PetscLogView().
665 .  -log_exclude: <vec,mat,pc.ksp,snes> - excludes subset of object classes from logging
666 .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
667 .  -log [filename] - Logs basic profiline information  See PetscLogDump().
668 -  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)
669 
670     Only one of -log_trace, -log_view, -log_view, -log_all, -log, or -log_mpe may be used at a time
671 
672    Options Database Keys for SAWs:
673 +  -saws_port <portnumber> - port number to publish SAWs data, default is 8080
674 .  -saws_port_auto_select - have SAWs select a new unique port number where it publishes the data, the URL is printed to the screen
675                             this is useful when you are running many jobs that utilize SAWs at the same time
676 .  -saws_log <filename> - save a log of all SAWs communication
677 .  -saws_https <certificate file> - have SAWs use HTTPS instead of HTTP
678 -  -saws_root <directory> - allow SAWs to have access to the given directory to search for requested resources and files
679 
680    Environmental Variables:
681 +   PETSC_TMP - alternative tmp directory
682 .   PETSC_SHARED_TMP - tmp is shared by all processes
683 .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
684 .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
685 -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to
686 
687 
688    Level: beginner
689 
690    Notes:
691    If for some reason you must call MPI_Init() separately, call
692    it before PetscInitialize().
693 
694    Fortran Version:
695    In Fortran this routine has the format
696 $       call PetscInitialize(file,ierr)
697 
698 +   ierr - error return code
699 -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL_CHARACTER to not check for
700           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
701 
702    Important Fortran Note:
703    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
704    null character string; you CANNOT just use NULL as
705    in the C version. See Users-Manual: ch_fortran for details.
706 
707    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
708    calling PetscInitialize().
709 
710    Concepts: initializing PETSc
711 
712 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()
713 
714 @*/
715 PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
716 {
717   PetscErrorCode ierr;
718   PetscMPIInt    flag, size;
719   PetscBool      flg = PETSC_TRUE;
720   char           hostname[256];
721 #if defined(PETSC_HAVE_HWLOC)
722   PetscViewer    viewer;
723 #endif
724 
725   PetscFunctionBegin;
726   if (PetscInitializeCalled) PetscFunctionReturn(0);
727   /*
728       The checking over compatible runtime libraries is complicated by the MPI ABI initiative
729       https://wiki.mpich.org/mpich/index.php/ABI_Compatibility_Initiative which started with
730         MPICH v3.1 (Released Feburary 2014)
731         IBM MPI v2.1 (December 2014)
732         Intel® MPI Library v5.0 (2014)
733         Cray MPT v7.0.0 (June 2014)
734       As of July 31, 2017 the ABI number still appears to be 12, that is all of the versions
735       listed above and since that time are compatible.
736 
737       Unfortunately the MPI ABI initiative has not defined a way to determine the ABI number
738       at compile time or runtime. Thus we will need to systematically track the allowed versions
739       and how they are represented in the mpi.h and MPI_Get_library_version() output in order
740       to perform the checking.
741 
742       Currently we only check for pre MPI ABI versions (and packages that do not follow the MPI ABI).
743 
744       Questions:
745 
746         Should the checks for ABI incompatibility be only on the major version number below?
747         Presumably the output to stderr will be removed before a release.
748   */
749 
750 #if defined(PETSC_HAVE_MPI_GET_LIBRARY_VERSION)
751   {
752     char        mpilibraryversion[MPI_MAX_LIBRARY_VERSION_STRING];
753     PetscMPIInt mpilibraryversionlength;
754     ierr = MPI_Get_library_version(mpilibraryversion,&mpilibraryversionlength);if (ierr) return ierr;
755     /* check for MPICH versions before MPI ABI initiative */
756 #if defined(MPICH_VERSION)
757 #if MPICH_NUMVERSION < 30100000
758     {
759       char *ver,*lf;
760       flg = PETSC_FALSE;
761       ierr = PetscStrstr(mpilibraryversion,"MPICH Version:",&ver);if (ierr) return ierr;
762       if (ver) {
763         ierr = PetscStrchr(ver,'\n',&lf);if (ierr) return ierr;
764         if (lf) {
765           *lf = 0;
766           ierr = PetscStrendswith(ver,MPICH_VERSION,&flg);if (ierr) return ierr;
767         }
768       }
769       if (!flg) {
770         fprintf(stderr,"PETSc Error --- MPICH library version \n%s does not match what PETSc was compiled with %s, aborting\n",mpilibraryversion,MPICH_VERSION);
771         return PETSC_ERR_MPI_LIB_INCOMP;
772       }
773     }
774 #endif
775     /* check for OpenMPI version, it is not part of the MPI ABI initiative (is it part of another initiative that needs to be handled?) */
776 #elif defined(OMPI_MAJOR_VERSION)
777     {
778       char *ver,bs[32],*bsf;
779       flg = PETSC_FALSE;
780       ierr = PetscStrstr(mpilibraryversion,"Open MPI",&ver);if (ierr) return ierr;
781       if (ver) {
782         sprintf(bs,"v%d.%d",OMPI_MAJOR_VERSION,OMPI_MINOR_VERSION);
783         ierr = PetscStrstr(ver,bs,&bsf);if (ierr) return ierr;
784         if (bsf) flg = PETSC_TRUE;
785       }
786       if (!flg) {
787         fprintf(stderr,"PETSc Error --- Open MPI library version \n%s does not match what PETSc was compiled with %d.%d, aborting\n",mpilibraryversion,OMPI_MAJOR_VERSION,OMPI_MINOR_VERSION);
788         return PETSC_ERR_MPI_LIB_INCOMP;
789       }
790     }
791 #endif
792   }
793 #endif
794 
795 
796   /* these must be initialized in a routine, not as a constant declaration*/
797   PETSC_STDOUT = stdout;
798   PETSC_STDERR = stderr;
799 
800   /* on Windows - set printf to default to printing 2 digit exponents */
801 #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
802   _set_output_format(_TWO_DIGIT_EXPONENT);
803 #endif
804 
805   ierr = PetscOptionsCreateDefault();CHKERRQ(ierr);
806 
807   /*
808      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
809      it that it sets args[0] on all processors to be args[0] on the first processor.
810   */
811   if (argc && *argc) {
812     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
813   } else {
814     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
815   }
816 
817   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
818   if (!flag) {
819     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");
820 #if defined(PETSC_HAVE_MPI_INIT_THREAD)
821     {
822       PetscMPIInt provided;
823       ierr = MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);CHKERRQ(ierr);
824     }
825 #else
826     ierr = MPI_Init(argc,args);CHKERRQ(ierr);
827 #endif
828     PetscBeganMPI = PETSC_TRUE;
829   }
830   if (argc && args) {
831     PetscGlobalArgc = *argc;
832     PetscGlobalArgs = *args;
833   }
834   PetscFinalizeCalled = PETSC_FALSE;
835   ierr = PetscSpinlockCreate(&PetscViewerASCIISpinLockOpen);CHKERRQ(ierr);
836   ierr = PetscSpinlockCreate(&PetscViewerASCIISpinLockStdout);CHKERRQ(ierr);
837   ierr = PetscSpinlockCreate(&PetscViewerASCIISpinLockStderr);CHKERRQ(ierr);
838   ierr = PetscSpinlockCreate(&PetscCommSpinLock);CHKERRQ(ierr);
839 
840   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
841   ierr = MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
842 
843   ierr = MPI_Add_error_class(&PETSC_MPI_ERROR_CLASS);CHKERRQ(ierr);
844   ierr = MPI_Add_error_code(PETSC_MPI_ERROR_CLASS,&PETSC_MPI_ERROR_CODE);CHKERRQ(ierr);
845 
846   /* Done after init due to a bug in MPICH-GM? */
847   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
848 
849   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
850   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
851 
852   MPIU_BOOL = MPI_INT;
853   MPIU_ENUM = MPI_INT;
854 
855   /*
856      Initialized the global complex variable; this is because with
857      shared libraries the constructors for global variables
858      are not called; at least on IRIX.
859   */
860 #if defined(PETSC_HAVE_COMPLEX)
861   {
862 #if defined(PETSC_CLANGUAGE_CXX) && !defined(PETSC_USE_REAL___FLOAT128)
863     PetscComplex ic(0.0,1.0);
864     PETSC_i = ic;
865 #else
866     PETSC_i = _Complex_I;
867 #endif
868   }
869 
870 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
871   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
872   ierr = MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
873   ierr = MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);CHKERRQ(ierr);
874   ierr = MPI_Type_commit(&MPIU_C_COMPLEX);CHKERRQ(ierr);
875 #endif
876 #endif /* PETSC_HAVE_COMPLEX */
877 
878   /*
879      Create the PETSc MPI reduction operator that sums of the first
880      half of the entries and maxes the second half.
881   */
882   ierr = MPI_Op_create(MPIU_MaxSum_Local,1,&MPIU_MAXSUM_OP);CHKERRQ(ierr);
883 
884 #if defined(PETSC_USE_REAL___FLOAT128)
885   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);CHKERRQ(ierr);
886   ierr = MPI_Type_commit(&MPIU___FLOAT128);CHKERRQ(ierr);
887 #if defined(PETSC_HAVE_COMPLEX)
888   ierr = MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);CHKERRQ(ierr);
889   ierr = MPI_Type_commit(&MPIU___COMPLEX128);CHKERRQ(ierr);
890 #endif
891   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
892   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
893 #elif defined(PETSC_USE_REAL___FP16)
894   ierr = MPI_Type_contiguous(2,MPI_CHAR,&MPIU___FP16);CHKERRQ(ierr);
895   ierr = MPI_Type_commit(&MPIU___FP16);CHKERRQ(ierr);
896   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
897   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
898 #endif
899 
900 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
901   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
902 #endif
903 
904   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
905   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
906 
907 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
908   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
909   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
910 #endif
911 
912 
913   /*
914      Attributes to be set on PETSc communicators
915   */
916   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
917   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
918   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
919   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelShared,&Petsc_Shared_keyval,(void*)0);CHKERRQ(ierr);
920 
921   /*
922      Build the options database
923   */
924   ierr = PetscOptionsInsert(NULL,argc,args,file);CHKERRQ(ierr);
925 
926 
927   /*
928      Print main application help message
929   */
930   ierr = PetscOptionsHasName(NULL,NULL,"-help",&flg);CHKERRQ(ierr);
931   if (help && flg) {
932     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
933   }
934   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
935 
936   ierr = PetscCitationsInitialize();CHKERRQ(ierr);
937 
938 #if defined(PETSC_HAVE_SAWS)
939   ierr = PetscInitializeSAWs(help);CHKERRQ(ierr);
940 #endif
941 
942   /* Creates the logging data structures; this is enabled even if logging is not turned on */
943 #if defined(PETSC_USE_LOG)
944   ierr = PetscLogInitialize();CHKERRQ(ierr);
945 #endif
946 
947   /*
948      Load the dynamic libraries (on machines that support them), this registers all
949      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
950   */
951   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
952 
953   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
954   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
955   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
956   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
957 
958   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
959   /* Check the options database for options related to the options database itself */
960   ierr = PetscOptionsSetFromOptions(NULL);CHKERRQ(ierr);
961 
962 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
963   /*
964       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
965 
966       Currently not used because it is not supported by MPICH.
967   */
968 #if !defined(PETSC_WORDS_BIGENDIAN)
969   ierr = MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);CHKERRQ(ierr);
970 #endif
971 #endif
972 
973   ierr = PetscOptionsHasName(NULL,NULL,"-python",&flg);CHKERRQ(ierr);
974   if (flg) {
975     PetscInitializeCalled = PETSC_TRUE;
976     ierr = PetscPythonInitialize(NULL,NULL);CHKERRQ(ierr);
977   }
978 
979   /*
980       Setup building of stack frames for all function calls
981   */
982 #if defined(PETSC_USE_DEBUG) && !defined(PETSC_HAVE_THREADSAFETY)
983   ierr = PetscStackCreate();CHKERRQ(ierr);
984 #endif
985 
986 #if defined(PETSC_SERIALIZE_FUNCTIONS)
987   ierr = PetscFPTCreate(10000);CHKERRQ(ierr);
988 #endif
989 
990 #if defined(PETSC_HAVE_HWLOC)
991   ierr   = PetscOptionsGetViewer(PETSC_COMM_WORLD,NULL,"-process_view",&viewer,NULL,&flg);CHKERRQ(ierr);
992   if (flg) {
993     ierr = PetscProcessPlacementView(viewer);CHKERRQ(ierr);
994   }
995 #endif
996 
997   /*
998       Once we are completedly initialized then we can set this variables
999   */
1000   PetscInitializeCalled = PETSC_TRUE;
1001   PetscFunctionReturn(0);
1002 }
1003 
1004 #if defined(PETSC_USE_LOG)
1005 extern PetscObject *PetscObjects;
1006 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
1007 extern PetscBool   PetscObjectsLog;
1008 #endif
1009 
1010 /*
1011     Frees all the MPI types and operations that PETSc may have created
1012 */
1013 PetscErrorCode  PetscFreeMPIResources(void)
1014 {
1015   PetscErrorCode ierr;
1016 
1017   PetscFunctionBegin;
1018 #if defined(PETSC_USE_REAL___FLOAT128)
1019   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1020 #if defined(PETSC_HAVE_COMPLEX)
1021   ierr = MPI_Type_free(&MPIU___COMPLEX128);CHKERRQ(ierr);
1022 #endif
1023   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1024   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1025 #elif defined(PETSC_USE_REAL___FP16)
1026   ierr = MPI_Type_free(&MPIU___FP16);CHKERRQ(ierr);
1027   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1028   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1029 #endif
1030 
1031 #if defined(PETSC_HAVE_COMPLEX)
1032 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1033   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1034   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1035 #endif
1036 #endif
1037 
1038 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
1039   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1040 #endif
1041 
1042   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1043 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1044   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1045 #endif
1046   ierr = MPI_Op_free(&MPIU_MAXSUM_OP);CHKERRQ(ierr);
1047   PetscFunctionReturn(0);
1048 }
1049 
1050 /*@C
1051    PetscFinalize - Checks for options to be called at the conclusion
1052    of the program. MPI_Finalize() is called only if the user had not
1053    called MPI_Init() before calling PetscInitialize().
1054 
1055    Collective on PETSC_COMM_WORLD
1056 
1057    Options Database Keys:
1058 +  -options_table - Calls PetscOptionsView()
1059 .  -options_left - Prints unused options that remain in the database
1060 .  -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
1061 .  -mpidump - Calls PetscMPIDump()
1062 .  -malloc_dump - Calls PetscMallocDump()
1063 .  -malloc_info - Prints total memory usage
1064 -  -malloc_log - Prints summary of memory usage
1065 
1066    Level: beginner
1067 
1068    Note:
1069    See PetscInitialize() for more general runtime options.
1070 
1071 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
1072 @*/
1073 PetscErrorCode  PetscFinalize(void)
1074 {
1075   PetscErrorCode ierr;
1076   PetscMPIInt    rank;
1077   PetscInt       nopt;
1078   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
1079   PetscBool      flg;
1080 #if defined(PETSC_USE_LOG)
1081   char           mname[PETSC_MAX_PATH_LEN];
1082 #endif
1083 
1084   if (!PetscInitializeCalled) {
1085     printf("PetscInitialize() must be called before PetscFinalize()\n");
1086     return(PETSC_ERR_ARG_WRONGSTATE);
1087   }
1088   PetscFunctionBegin;
1089   ierr = PetscInfo(NULL,"PetscFinalize() called\n");CHKERRQ(ierr);
1090 
1091   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1092 
1093   ierr = PetscOptionsHasName(NULL,NULL,"-citations",&flg);CHKERRQ(ierr);
1094   if (flg) {
1095     char  *cits, filename[PETSC_MAX_PATH_LEN];
1096     FILE  *fd = PETSC_STDOUT;
1097 
1098     ierr = PetscOptionsGetString(NULL,NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
1099     if (filename[0]) {
1100       ierr = PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);CHKERRQ(ierr);
1101     }
1102     ierr = PetscSegBufferGet(PetscCitationsList,1,&cits);CHKERRQ(ierr);
1103     cits[0] = 0;
1104     ierr = PetscSegBufferExtractAlloc(PetscCitationsList,&cits);CHKERRQ(ierr);
1105     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");CHKERRQ(ierr);
1106     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
1107     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);CHKERRQ(ierr);
1108     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
1109     ierr = PetscFClose(PETSC_COMM_WORLD,fd);CHKERRQ(ierr);
1110     ierr = PetscFree(cits);CHKERRQ(ierr);
1111   }
1112   ierr = PetscSegBufferDestroy(&PetscCitationsList);CHKERRQ(ierr);
1113 
1114 #if defined(PETSC_HAVE_SSL) && defined(PETSC_USE_SOCKET_VIEWER)
1115   /* TextBelt is run for testing purposes only, please do not use this feature often */
1116   {
1117     PetscInt nmax = 2;
1118     char     **buffs;
1119     ierr = PetscMalloc1(2,&buffs);CHKERRQ(ierr);
1120     ierr = PetscOptionsGetStringArray(NULL,NULL,"-textbelt",buffs,&nmax,&flg1);CHKERRQ(ierr);
1121     if (flg1) {
1122       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-textbelt requires either the phone number or number,\"message\"");
1123       if (nmax == 1) {
1124         ierr = PetscMalloc1(128,&buffs[1]);CHKERRQ(ierr);
1125         ierr = PetscGetProgramName(buffs[1],32);CHKERRQ(ierr);
1126         ierr = PetscStrcat(buffs[1]," has completed");CHKERRQ(ierr);
1127       }
1128       ierr = PetscTextBelt(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);CHKERRQ(ierr);
1129       ierr = PetscFree(buffs[0]);CHKERRQ(ierr);
1130       ierr = PetscFree(buffs[1]);CHKERRQ(ierr);
1131     }
1132     ierr = PetscFree(buffs);CHKERRQ(ierr);
1133   }
1134   {
1135     PetscInt nmax = 2;
1136     char     **buffs;
1137     ierr = PetscMalloc1(2,&buffs);CHKERRQ(ierr);
1138     ierr = PetscOptionsGetStringArray(NULL,NULL,"-tellmycell",buffs,&nmax,&flg1);CHKERRQ(ierr);
1139     if (flg1) {
1140       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-tellmycell requires either the phone number or number,\"message\"");
1141       if (nmax == 1) {
1142         ierr = PetscMalloc1(128,&buffs[1]);CHKERRQ(ierr);
1143         ierr = PetscGetProgramName(buffs[1],32);CHKERRQ(ierr);
1144         ierr = PetscStrcat(buffs[1]," has completed");CHKERRQ(ierr);
1145       }
1146       ierr = PetscTellMyCell(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);CHKERRQ(ierr);
1147       ierr = PetscFree(buffs[0]);CHKERRQ(ierr);
1148       ierr = PetscFree(buffs[1]);CHKERRQ(ierr);
1149     }
1150     ierr = PetscFree(buffs);CHKERRQ(ierr);
1151   }
1152 #endif
1153   /*
1154     It should be safe to cancel the options monitors, since we don't expect to be setting options
1155     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1156     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1157   */
1158   ierr = PetscOptionsMonitorCancel();CHKERRQ(ierr);
1159 
1160 #if defined(PETSC_SERIALIZE_FUNCTIONS)
1161   ierr = PetscFPTDestroy();CHKERRQ(ierr);
1162 #endif
1163 
1164 
1165 #if defined(PETSC_HAVE_SAWS)
1166   flg = PETSC_FALSE;
1167   ierr = PetscOptionsGetBool(NULL,NULL,"-saw_options",&flg,NULL);CHKERRQ(ierr);
1168   if (flg) {
1169     ierr = PetscOptionsSAWsDestroy();CHKERRQ(ierr);
1170   }
1171 #endif
1172 
1173 #if defined(PETSC_HAVE_X)
1174   flg1 = PETSC_FALSE;
1175   ierr = PetscOptionsGetBool(NULL,NULL,"-x_virtual",&flg1,NULL);CHKERRQ(ierr);
1176   if (flg1) {
1177     /*  this is a crude hack, but better than nothing */
1178     ierr = PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);CHKERRQ(ierr);
1179   }
1180 #endif
1181 
1182 #if !defined(PETSC_HAVE_THREADSAFETY)
1183   ierr = PetscOptionsGetBool(NULL,NULL,"-malloc_info",&flg2,NULL);CHKERRQ(ierr);
1184   if (!flg2) {
1185     flg2 = PETSC_FALSE;
1186     ierr = PetscOptionsGetBool(NULL,NULL,"-memory_view",&flg2,NULL);CHKERRQ(ierr);
1187   }
1188   if (flg2) {
1189     ierr = PetscMemoryView(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
1190   }
1191 #endif
1192 
1193 #if defined(PETSC_USE_LOG)
1194   flg1 = PETSC_FALSE;
1195   ierr = PetscOptionsGetBool(NULL,NULL,"-get_total_flops",&flg1,NULL);CHKERRQ(ierr);
1196   if (flg1) {
1197     PetscLogDouble flops = 0;
1198     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
1199     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
1200   }
1201 #endif
1202 
1203 
1204 #if defined(PETSC_USE_LOG)
1205 #if defined(PETSC_HAVE_MPE)
1206   mname[0] = 0;
1207   ierr = PetscOptionsGetString(NULL,NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1208   if (flg1) {
1209     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
1210     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
1211   }
1212 #endif
1213 #endif
1214 
1215   /*
1216      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1217   */
1218   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1219 
1220 #if defined(PETSC_USE_LOG)
1221   ierr = PetscLogViewFromOptions();CHKERRQ(ierr);
1222   mname[0] = 0;
1223   ierr = PetscOptionsGetString(NULL,NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1224   if (flg1) {
1225     PetscViewer viewer;
1226     ierr = (*PetscHelpPrintf)(PETSC_COMM_WORLD,"\n\n WARNING:   -log_summary is being deprecated; switch to -log_view\n\n\n");CHKERRQ(ierr);
1227     if (mname[0]) {
1228       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1229       ierr = PetscLogView(viewer);CHKERRQ(ierr);
1230       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1231     } else {
1232       viewer = PETSC_VIEWER_STDOUT_WORLD;
1233       ierr   = PetscViewerPushFormat(viewer,PETSC_VIEWER_DEFAULT);CHKERRQ(ierr);
1234       ierr   = PetscLogView(viewer);CHKERRQ(ierr);
1235       ierr   = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
1236     }
1237   }
1238 
1239   /*
1240      Free any objects created by the last block of code.
1241   */
1242   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1243 
1244   mname[0] = 0;
1245   ierr = PetscOptionsGetString(NULL,NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1246   ierr = PetscOptionsGetString(NULL,NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
1247   if (flg1 || flg2) {
1248     if (mname[0]) PetscLogDump(mname);
1249     else          PetscLogDump(0);
1250   }
1251 #endif
1252 
1253   ierr = PetscStackDestroy();CHKERRQ(ierr);
1254 
1255   flg1 = PETSC_FALSE;
1256   ierr = PetscOptionsGetBool(NULL,NULL,"-no_signal_handler",&flg1,NULL);CHKERRQ(ierr);
1257   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
1258   flg1 = PETSC_FALSE;
1259   ierr = PetscOptionsGetBool(NULL,NULL,"-mpidump",&flg1,NULL);CHKERRQ(ierr);
1260   if (flg1) {
1261     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1262   }
1263   flg1 = PETSC_FALSE;
1264   flg2 = PETSC_FALSE;
1265   /* preemptive call to avoid listing this option in options table as unused */
1266   ierr = PetscOptionsHasName(NULL,NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1267   ierr = PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1268   ierr = PetscOptionsGetBool(NULL,NULL,"-options_view",&flg2,NULL);CHKERRQ(ierr);
1269 
1270   if (flg2) {
1271     PetscViewer viewer;
1272     ierr = PetscViewerCreate(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1273     ierr = PetscViewerSetType(viewer,PETSCVIEWERASCII);CHKERRQ(ierr);
1274     ierr = PetscOptionsView(NULL,viewer);CHKERRQ(ierr);
1275     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1276   }
1277 
1278   /* to prevent PETSc -options_left from warning */
1279   ierr = PetscOptionsHasName(NULL,NULL,"-nox",&flg1);CHKERRQ(ierr);
1280   ierr = PetscOptionsHasName(NULL,NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1281 
1282   flg3 = PETSC_FALSE; /* default value is required */
1283   ierr = PetscOptionsGetBool(NULL,NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1284   ierr = PetscOptionsAllUsed(NULL,&nopt);CHKERRQ(ierr);
1285   if (flg3) {
1286     if (!flg2) { /* have not yet printed the options */
1287       PetscViewer viewer;
1288       ierr = PetscViewerCreate(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1289       ierr = PetscViewerSetType(viewer,PETSCVIEWERASCII);CHKERRQ(ierr);
1290       ierr = PetscOptionsView(NULL,viewer);CHKERRQ(ierr);
1291       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1292     }
1293     if (!nopt) {
1294       ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1295     } else if (nopt == 1) {
1296       ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1297     } else {
1298       ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1299     }
1300   }
1301 #if defined(PETSC_USE_DEBUG)
1302   if (nopt && !flg3 && !flg1) {
1303     ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1304     ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1305     ierr = PetscOptionsLeft(NULL);CHKERRQ(ierr);
1306   } else if (nopt && flg3) {
1307 #else
1308   if (nopt && flg3) {
1309 #endif
1310     ierr = PetscOptionsLeft(NULL);CHKERRQ(ierr);
1311   }
1312 
1313 #if defined(PETSC_HAVE_SAWS)
1314   if (!PetscGlobalRank) {
1315     ierr = PetscStackSAWsViewOff();CHKERRQ(ierr);
1316     PetscStackCallSAWs(SAWs_Finalize,());
1317   }
1318 #endif
1319 
1320 #if defined(PETSC_USE_LOG)
1321   /*
1322        List all objects the user may have forgot to free
1323   */
1324   if (PetscObjectsLog) {
1325     ierr = PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1326     if (flg1) {
1327       MPI_Comm local_comm;
1328       char     string[64];
1329 
1330       ierr = PetscOptionsGetString(NULL,NULL,"-objects_dump",string,64,NULL);CHKERRQ(ierr);
1331       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1332       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1333       ierr = PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);CHKERRQ(ierr);
1334       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1335       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1336     }
1337   }
1338 #endif
1339 
1340 #if defined(PETSC_USE_LOG)
1341   PetscObjectsCounts    = 0;
1342   PetscObjectsMaxCounts = 0;
1343   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1344 #endif
1345 
1346   /*
1347      Destroy any packages that registered a finalize
1348   */
1349   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1350 
1351 #if defined(PETSC_USE_LOG)
1352   ierr = PetscLogDestroy();CHKERRQ(ierr);
1353 #endif
1354 
1355   /*
1356      Print PetscFunctionLists that have not been properly freed
1357 
1358   ierr = PetscFunctionListPrintAll();CHKERRQ(ierr);
1359   */
1360 
1361   if (petsc_history) {
1362     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1363     petsc_history = 0;
1364   }
1365   ierr = PetscOptionsHelpPrintedDestroy(&PetscOptionsHelpPrintedSingleton);CHKERRQ(ierr);
1366 
1367   ierr = PetscInfoAllow(PETSC_FALSE,NULL);CHKERRQ(ierr);
1368 
1369 #if !defined(PETSC_HAVE_THREADSAFETY)
1370   {
1371     char fname[PETSC_MAX_PATH_LEN];
1372     FILE *fd;
1373     int  err;
1374 
1375     fname[0] = 0;
1376 
1377     ierr = PetscOptionsGetString(NULL,NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1378     flg2 = PETSC_FALSE;
1379     ierr = PetscOptionsGetBool(NULL,NULL,"-malloc_test",&flg2,NULL);CHKERRQ(ierr);
1380 #if defined(PETSC_USE_DEBUG)
1381     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1382 #else
1383     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1384 #endif
1385     if (flg1 && fname[0]) {
1386       char sname[PETSC_MAX_PATH_LEN];
1387 
1388       sprintf(sname,"%s_%d",fname,rank);
1389       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1390       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1391       err  = fclose(fd);
1392       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1393     } else if (flg1 || flg2) {
1394       MPI_Comm local_comm;
1395 
1396       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1397       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1398       ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1399       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1400       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1401     }
1402   }
1403 
1404   {
1405     char fname[PETSC_MAX_PATH_LEN];
1406     FILE *fd = NULL;
1407 
1408     fname[0] = 0;
1409 
1410     ierr = PetscOptionsGetString(NULL,NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1411     ierr = PetscOptionsHasName(NULL,NULL,"-malloc_log_threshold",&flg2);CHKERRQ(ierr);
1412     if (flg1 && fname[0]) {
1413       int err;
1414 
1415       if (!rank) {
1416         fd = fopen(fname,"w");
1417         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1418       }
1419       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1420       if (fd) {
1421         err = fclose(fd);
1422         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1423       }
1424     } else if (flg1 || flg2) {
1425       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1426     }
1427   }
1428 #endif
1429 
1430   /*
1431      Close any open dynamic libraries
1432   */
1433   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1434 
1435   /* Can be destroyed only after all the options are used */
1436   ierr = PetscOptionsDestroyDefault();CHKERRQ(ierr);
1437 
1438   PetscGlobalArgc = 0;
1439   PetscGlobalArgs = 0;
1440 
1441   ierr = PetscFreeMPIResources();CHKERRQ(ierr);
1442 
1443   /*
1444      Destroy any known inner MPI_Comm's and attributes pointing to them
1445      Note this will not destroy any new communicators the user has created.
1446 
1447      If all PETSc objects were not destroyed those left over objects will have hanging references to
1448      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1449  */
1450   {
1451     PetscCommCounter *counter;
1452     PetscMPIInt      flg;
1453     MPI_Comm         icomm;
1454     union {MPI_Comm comm; void *ptr;} ucomm;
1455     ierr = MPI_Comm_get_attr(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1456     if (flg) {
1457       icomm = ucomm.comm;
1458       ierr = MPI_Comm_get_attr(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1459       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1460 
1461       ierr = MPI_Comm_delete_attr(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1462       ierr = MPI_Comm_delete_attr(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1463       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1464     }
1465     ierr = MPI_Comm_get_attr(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1466     if (flg) {
1467       icomm = ucomm.comm;
1468       ierr = MPI_Comm_get_attr(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1469       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1470 
1471       ierr = MPI_Comm_delete_attr(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1472       ierr = MPI_Comm_delete_attr(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1473       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1474     }
1475   }
1476 
1477   ierr = MPI_Comm_free_keyval(&Petsc_Counter_keyval);CHKERRQ(ierr);
1478   ierr = MPI_Comm_free_keyval(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1479   ierr = MPI_Comm_free_keyval(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1480   ierr = MPI_Comm_free_keyval(&Petsc_Shared_keyval);CHKERRQ(ierr);
1481 
1482   ierr = PetscSpinlockDestroy(&PetscViewerASCIISpinLockOpen);CHKERRQ(ierr);
1483   ierr = PetscSpinlockDestroy(&PetscViewerASCIISpinLockStdout);CHKERRQ(ierr);
1484   ierr = PetscSpinlockDestroy(&PetscViewerASCIISpinLockStderr);CHKERRQ(ierr);
1485   ierr = PetscSpinlockDestroy(&PetscCommSpinLock);CHKERRQ(ierr);
1486 
1487   if (PetscBeganMPI) {
1488 #if defined(PETSC_HAVE_MPI_FINALIZED)
1489     PetscMPIInt flag;
1490     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1491     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1492 #endif
1493     ierr = MPI_Finalize();CHKERRQ(ierr);
1494   }
1495 /*
1496 
1497      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1498    the communicator has some outstanding requests on it. Specifically if the
1499    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1500    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1501    is never freed as it should be. Thus one may obtain messages of the form
1502    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1503    memory was not freed.
1504 
1505 */
1506   ierr = PetscMallocClear();CHKERRQ(ierr);
1507 
1508   PetscInitializeCalled = PETSC_FALSE;
1509   PetscFinalizeCalled   = PETSC_TRUE;
1510   PetscFunctionReturn(0);
1511 }
1512 
1513 #if defined(PETSC_MISSING_LAPACK_lsame_)
1514 PETSC_EXTERN int lsame_(char *a,char *b)
1515 {
1516   if (*a == *b) return 1;
1517   if (*a + 32 == *b) return 1;
1518   if (*a - 32 == *b) return 1;
1519   return 0;
1520 }
1521 #endif
1522 
1523 #if defined(PETSC_MISSING_LAPACK_lsame)
1524 PETSC_EXTERN int lsame(char *a,char *b)
1525 {
1526   if (*a == *b) return 1;
1527   if (*a + 32 == *b) return 1;
1528   if (*a - 32 == *b) return 1;
1529   return 0;
1530 }
1531 #endif
1532