xref: /petsc/src/sys/objects/pinit.c (revision feff33ee0b5b037fa8f9f294dede656a2f85cc47)
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,tao,ts>\n");CHKERRQ(ierr);
75     ierr = (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,tao,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 and Dave A. May and Lois Curfman McInnes\n            and Richard Tran Mills and Todd Munson and Karl Rupp and Patrick Sanan\n            and Barry F. Smith and Stefano Zampini and Hong Zhang and Hong Zhang},\n  Title = {{PETS}c Users Manual},\n  Number = {ANL-95/11 - Revision 3.9},\n  Institution = {Argonne National Laboratory},\n  Year = {2018}\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 -  -check_pointer_intensity 0,1,2 - if pointers are checked for validity (debug version only), using 0 will result in faster code
670 
671     Only one of -log_trace, -log_view, -log_view, -log_all, -log, or -log_mpe may be used at a time
672 
673    Options Database Keys for SAWs:
674 +  -saws_port <portnumber> - port number to publish SAWs data, default is 8080
675 .  -saws_port_auto_select - have SAWs select a new unique port number where it publishes the data, the URL is printed to the screen
676                             this is useful when you are running many jobs that utilize SAWs at the same time
677 .  -saws_log <filename> - save a log of all SAWs communication
678 .  -saws_https <certificate file> - have SAWs use HTTPS instead of HTTP
679 -  -saws_root <directory> - allow SAWs to have access to the given directory to search for requested resources and files
680 
681    Environmental Variables:
682 +   PETSC_TMP - alternative tmp directory
683 .   PETSC_SHARED_TMP - tmp is shared by all processes
684 .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
685 .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
686 -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to
687 
688 
689    Level: beginner
690 
691    Notes:
692    If for some reason you must call MPI_Init() separately, call
693    it before PetscInitialize().
694 
695    Fortran Version:
696    In Fortran this routine has the format
697 $       call PetscInitialize(file,ierr)
698 
699 +   ierr - error return code
700 -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL_CHARACTER to not check for
701           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
702 
703    Important Fortran Note:
704    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
705    null character string; you CANNOT just use NULL as
706    in the C version. See Users-Manual: ch_fortran for details.
707 
708    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
709    calling PetscInitialize().
710 
711    Concepts: initializing PETSc
712 
713 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()
714 
715 @*/
716 PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
717 {
718   PetscErrorCode ierr;
719   PetscMPIInt    flag, size;
720   PetscBool      flg = PETSC_TRUE;
721   char           hostname[256];
722 #if defined(PETSC_HAVE_HWLOC)
723   PetscViewer    viewer;
724 #endif
725 
726   PetscFunctionBegin;
727   if (PetscInitializeCalled) PetscFunctionReturn(0);
728   /*
729       The checking over compatible runtime libraries is complicated by the MPI ABI initiative
730       https://wiki.mpich.org/mpich/index.php/ABI_Compatibility_Initiative which started with
731         MPICH v3.1 (Released Feburary 2014)
732         IBM MPI v2.1 (December 2014)
733         Intel® MPI Library v5.0 (2014)
734         Cray MPT v7.0.0 (June 2014)
735       As of July 31, 2017 the ABI number still appears to be 12, that is all of the versions
736       listed above and since that time are compatible.
737 
738       Unfortunately the MPI ABI initiative has not defined a way to determine the ABI number
739       at compile time or runtime. Thus we will need to systematically track the allowed versions
740       and how they are represented in the mpi.h and MPI_Get_library_version() output in order
741       to perform the checking.
742 
743       Currently we only check for pre MPI ABI versions (and packages that do not follow the MPI ABI).
744 
745       Questions:
746 
747         Should the checks for ABI incompatibility be only on the major version number below?
748         Presumably the output to stderr will be removed before a release.
749   */
750 
751 #if defined(PETSC_HAVE_MPI_GET_LIBRARY_VERSION)
752   {
753     char        mpilibraryversion[MPI_MAX_LIBRARY_VERSION_STRING];
754     PetscMPIInt mpilibraryversionlength;
755     ierr = MPI_Get_library_version(mpilibraryversion,&mpilibraryversionlength);if (ierr) return ierr;
756     /* check for MPICH versions before MPI ABI initiative */
757 #if defined(MPICH_VERSION)
758 #if MPICH_NUMVERSION < 30100000
759     {
760       char *ver,*lf;
761       flg = PETSC_FALSE;
762       ierr = PetscStrstr(mpilibraryversion,"MPICH Version:",&ver);if (ierr) return ierr;
763       if (ver) {
764         ierr = PetscStrchr(ver,'\n',&lf);if (ierr) return ierr;
765         if (lf) {
766           *lf = 0;
767           ierr = PetscStrendswith(ver,MPICH_VERSION,&flg);if (ierr) return ierr;
768         }
769       }
770       if (!flg) {
771         fprintf(stderr,"PETSc Error --- MPICH library version \n%s does not match what PETSc was compiled with %s, aborting\n",mpilibraryversion,MPICH_VERSION);
772         return PETSC_ERR_MPI_LIB_INCOMP;
773       }
774     }
775 #endif
776     /* check for OpenMPI version, it is not part of the MPI ABI initiative (is it part of another initiative that needs to be handled?) */
777 #elif defined(OMPI_MAJOR_VERSION)
778     {
779       char *ver,bs[32],*bsf;
780       flg = PETSC_FALSE;
781       ierr = PetscStrstr(mpilibraryversion,"Open MPI",&ver);if (ierr) return ierr;
782       if (ver) {
783         PetscSNPrintf(bs,32,"v%d.%d",OMPI_MAJOR_VERSION,OMPI_MINOR_VERSION);
784         ierr = PetscStrstr(ver,bs,&bsf);if (ierr) return ierr;
785         if (bsf) flg = PETSC_TRUE;
786       }
787       if (!flg) {
788         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);
789         return PETSC_ERR_MPI_LIB_INCOMP;
790       }
791     }
792 #endif
793   }
794 #endif
795 
796 
797   /* these must be initialized in a routine, not as a constant declaration*/
798   PETSC_STDOUT = stdout;
799   PETSC_STDERR = stderr;
800 
801   /* on Windows - set printf to default to printing 2 digit exponents */
802 #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
803   _set_output_format(_TWO_DIGIT_EXPONENT);
804 #endif
805 
806   ierr = PetscOptionsCreateDefault();CHKERRQ(ierr);
807 
808   /*
809      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
810      it that it sets args[0] on all processors to be args[0] on the first processor.
811   */
812   if (argc && *argc) {
813     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
814   } else {
815     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
816   }
817 
818   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
819   if (!flag) {
820     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");
821 #if defined(PETSC_HAVE_MPI_INIT_THREAD)
822     {
823       PetscMPIInt provided;
824       ierr = MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);CHKERRQ(ierr);
825     }
826 #else
827     ierr = MPI_Init(argc,args);CHKERRQ(ierr);
828 #endif
829     PetscBeganMPI = PETSC_TRUE;
830   }
831   if (argc && args) {
832     PetscGlobalArgc = *argc;
833     PetscGlobalArgs = *args;
834   }
835   PetscFinalizeCalled = PETSC_FALSE;
836   ierr = PetscSpinlockCreate(&PetscViewerASCIISpinLockOpen);CHKERRQ(ierr);
837   ierr = PetscSpinlockCreate(&PetscViewerASCIISpinLockStdout);CHKERRQ(ierr);
838   ierr = PetscSpinlockCreate(&PetscViewerASCIISpinLockStderr);CHKERRQ(ierr);
839   ierr = PetscSpinlockCreate(&PetscCommSpinLock);CHKERRQ(ierr);
840 
841   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
842   ierr = MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
843 
844   ierr = MPI_Add_error_class(&PETSC_MPI_ERROR_CLASS);CHKERRQ(ierr);
845   ierr = MPI_Add_error_code(PETSC_MPI_ERROR_CLASS,&PETSC_MPI_ERROR_CODE);CHKERRQ(ierr);
846 
847   /* Done after init due to a bug in MPICH-GM? */
848   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
849 
850   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
851   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
852 
853   MPIU_BOOL = MPI_INT;
854   MPIU_ENUM = MPI_INT;
855 
856   /*
857      Initialized the global complex variable; this is because with
858      shared libraries the constructors for global variables
859      are not called; at least on IRIX.
860   */
861 #if defined(PETSC_HAVE_COMPLEX)
862   {
863 #if defined(PETSC_CLANGUAGE_CXX) && !defined(PETSC_USE_REAL___FLOAT128)
864     PetscComplex ic(0.0,1.0);
865     PETSC_i = ic;
866 #else
867     PETSC_i = _Complex_I;
868 #endif
869   }
870 
871 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
872   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
873   ierr = MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
874   ierr = MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);CHKERRQ(ierr);
875   ierr = MPI_Type_commit(&MPIU_C_COMPLEX);CHKERRQ(ierr);
876 #endif
877 #endif /* PETSC_HAVE_COMPLEX */
878 
879   /*
880      Create the PETSc MPI reduction operator that sums of the first
881      half of the entries and maxes the second half.
882   */
883   ierr = MPI_Op_create(MPIU_MaxSum_Local,1,&MPIU_MAXSUM_OP);CHKERRQ(ierr);
884 
885 #if defined(PETSC_USE_REAL___FLOAT128)
886   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);CHKERRQ(ierr);
887   ierr = MPI_Type_commit(&MPIU___FLOAT128);CHKERRQ(ierr);
888 #if defined(PETSC_HAVE_COMPLEX)
889   ierr = MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);CHKERRQ(ierr);
890   ierr = MPI_Type_commit(&MPIU___COMPLEX128);CHKERRQ(ierr);
891 #endif
892   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
893   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
894 #elif defined(PETSC_USE_REAL___FP16)
895   ierr = MPI_Type_contiguous(2,MPI_CHAR,&MPIU___FP16);CHKERRQ(ierr);
896   ierr = MPI_Type_commit(&MPIU___FP16);CHKERRQ(ierr);
897   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
898   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
899 #endif
900 
901 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
902   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
903 #endif
904 
905   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
906   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
907 
908 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
909   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
910   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
911 #endif
912 
913 
914   /*
915      Attributes to be set on PETSc communicators
916   */
917   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
918   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
919   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
920   ierr = MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelShared,&Petsc_Shared_keyval,(void*)0);CHKERRQ(ierr);
921 
922   /*
923      Build the options database
924   */
925   ierr = PetscOptionsInsert(NULL,argc,args,file);CHKERRQ(ierr);
926 
927   /* call a second time so it can look in the options database */
928   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
929 
930   /*
931      Print main application help message
932   */
933   ierr = PetscOptionsHasName(NULL,NULL,"-help",&flg);CHKERRQ(ierr);
934   if (help && flg) {
935     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
936   }
937   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
938 
939   ierr = PetscCitationsInitialize();CHKERRQ(ierr);
940 
941 #if defined(PETSC_HAVE_SAWS)
942   ierr = PetscInitializeSAWs(help);CHKERRQ(ierr);
943 #endif
944 
945   /* Creates the logging data structures; this is enabled even if logging is not turned on */
946 #if defined(PETSC_USE_LOG)
947   ierr = PetscLogInitialize();CHKERRQ(ierr);
948 #endif
949 
950   /*
951      Load the dynamic libraries (on machines that support them), this registers all
952      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
953   */
954   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
955 
956   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
957   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
958   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
959   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
960 
961   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
962   /* Check the options database for options related to the options database itself */
963   ierr = PetscOptionsSetFromOptions(NULL);CHKERRQ(ierr);
964 
965 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
966   /*
967       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
968 
969       Currently not used because it is not supported by MPICH.
970   */
971 #if !defined(PETSC_WORDS_BIGENDIAN)
972   ierr = MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);CHKERRQ(ierr);
973 #endif
974 #endif
975 
976   ierr = PetscOptionsHasName(NULL,NULL,"-python",&flg);CHKERRQ(ierr);
977   if (flg) {
978     PetscInitializeCalled = PETSC_TRUE;
979     ierr = PetscPythonInitialize(NULL,NULL);CHKERRQ(ierr);
980   }
981 
982   /*
983       Setup building of stack frames for all function calls
984   */
985 #if defined(PETSC_USE_DEBUG) && !defined(PETSC_HAVE_THREADSAFETY)
986   ierr = PetscStackCreate();CHKERRQ(ierr);
987 #endif
988 
989 #if defined(PETSC_SERIALIZE_FUNCTIONS)
990   ierr = PetscFPTCreate(10000);CHKERRQ(ierr);
991 #endif
992 
993 #if defined(PETSC_HAVE_HWLOC)
994   ierr   = PetscOptionsGetViewer(PETSC_COMM_WORLD,NULL,"-process_view",&viewer,NULL,&flg);CHKERRQ(ierr);
995   if (flg) {
996     ierr = PetscProcessPlacementView(viewer);CHKERRQ(ierr);
997   }
998 #endif
999 
1000   /*
1001       Once we are completedly initialized then we can set this variables
1002   */
1003   PetscInitializeCalled = PETSC_TRUE;
1004   PetscFunctionReturn(0);
1005 }
1006 
1007 #if defined(PETSC_USE_LOG)
1008 extern PetscObject *PetscObjects;
1009 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
1010 extern PetscBool   PetscObjectsLog;
1011 #endif
1012 
1013 /*
1014     Frees all the MPI types and operations that PETSc may have created
1015 */
1016 PetscErrorCode  PetscFreeMPIResources(void)
1017 {
1018   PetscErrorCode ierr;
1019 
1020   PetscFunctionBegin;
1021 #if defined(PETSC_USE_REAL___FLOAT128)
1022   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1023 #if defined(PETSC_HAVE_COMPLEX)
1024   ierr = MPI_Type_free(&MPIU___COMPLEX128);CHKERRQ(ierr);
1025 #endif
1026   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1027   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1028 #elif defined(PETSC_USE_REAL___FP16)
1029   ierr = MPI_Type_free(&MPIU___FP16);CHKERRQ(ierr);
1030   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1031   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1032 #endif
1033 
1034 #if defined(PETSC_HAVE_COMPLEX)
1035 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1036   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1037   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1038 #endif
1039 #endif
1040 
1041 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
1042   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1043 #endif
1044 
1045   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1046 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1047   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1048 #endif
1049   ierr = MPI_Op_free(&MPIU_MAXSUM_OP);CHKERRQ(ierr);
1050   PetscFunctionReturn(0);
1051 }
1052 
1053 /*@C
1054    PetscFinalize - Checks for options to be called at the conclusion
1055    of the program. MPI_Finalize() is called only if the user had not
1056    called MPI_Init() before calling PetscInitialize().
1057 
1058    Collective on PETSC_COMM_WORLD
1059 
1060    Options Database Keys:
1061 +  -options_table - Calls PetscOptionsView()
1062 .  -options_left - Prints unused options that remain in the database
1063 .  -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
1064 .  -mpidump - Calls PetscMPIDump()
1065 .  -malloc_dump - Calls PetscMallocDump()
1066 .  -malloc_info - Prints total memory usage
1067 -  -malloc_log - Prints summary of memory usage
1068 
1069    Level: beginner
1070 
1071    Note:
1072    See PetscInitialize() for more general runtime options.
1073 
1074 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
1075 @*/
1076 PetscErrorCode  PetscFinalize(void)
1077 {
1078   PetscErrorCode ierr;
1079   PetscMPIInt    rank;
1080   PetscInt       nopt;
1081   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
1082   PetscBool      flg;
1083 #if defined(PETSC_USE_LOG)
1084   char           mname[PETSC_MAX_PATH_LEN];
1085 #endif
1086 
1087   if (!PetscInitializeCalled) {
1088     printf("PetscInitialize() must be called before PetscFinalize()\n");
1089     return(PETSC_ERR_ARG_WRONGSTATE);
1090   }
1091   PetscFunctionBegin;
1092   ierr = PetscInfo(NULL,"PetscFinalize() called\n");CHKERRQ(ierr);
1093 
1094   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1095 
1096   ierr = PetscOptionsHasName(NULL,NULL,"-citations",&flg);CHKERRQ(ierr);
1097   if (flg) {
1098     char  *cits, filename[PETSC_MAX_PATH_LEN];
1099     FILE  *fd = PETSC_STDOUT;
1100 
1101     ierr = PetscOptionsGetString(NULL,NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
1102     if (filename[0]) {
1103       ierr = PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);CHKERRQ(ierr);
1104     }
1105     ierr = PetscSegBufferGet(PetscCitationsList,1,&cits);CHKERRQ(ierr);
1106     cits[0] = 0;
1107     ierr = PetscSegBufferExtractAlloc(PetscCitationsList,&cits);CHKERRQ(ierr);
1108     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");CHKERRQ(ierr);
1109     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
1110     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);CHKERRQ(ierr);
1111     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
1112     ierr = PetscFClose(PETSC_COMM_WORLD,fd);CHKERRQ(ierr);
1113     ierr = PetscFree(cits);CHKERRQ(ierr);
1114   }
1115   ierr = PetscSegBufferDestroy(&PetscCitationsList);CHKERRQ(ierr);
1116 
1117 #if defined(PETSC_HAVE_SSL) && defined(PETSC_USE_SOCKET_VIEWER)
1118   /* TextBelt is run for testing purposes only, please do not use this feature often */
1119   {
1120     PetscInt nmax = 2;
1121     char     **buffs;
1122     ierr = PetscMalloc1(2,&buffs);CHKERRQ(ierr);
1123     ierr = PetscOptionsGetStringArray(NULL,NULL,"-textbelt",buffs,&nmax,&flg1);CHKERRQ(ierr);
1124     if (flg1) {
1125       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-textbelt requires either the phone number or number,\"message\"");
1126       if (nmax == 1) {
1127         ierr = PetscMalloc1(128,&buffs[1]);CHKERRQ(ierr);
1128         ierr = PetscGetProgramName(buffs[1],32);CHKERRQ(ierr);
1129         ierr = PetscStrcat(buffs[1]," has completed");CHKERRQ(ierr);
1130       }
1131       ierr = PetscTextBelt(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);CHKERRQ(ierr);
1132       ierr = PetscFree(buffs[0]);CHKERRQ(ierr);
1133       ierr = PetscFree(buffs[1]);CHKERRQ(ierr);
1134     }
1135     ierr = PetscFree(buffs);CHKERRQ(ierr);
1136   }
1137   {
1138     PetscInt nmax = 2;
1139     char     **buffs;
1140     ierr = PetscMalloc1(2,&buffs);CHKERRQ(ierr);
1141     ierr = PetscOptionsGetStringArray(NULL,NULL,"-tellmycell",buffs,&nmax,&flg1);CHKERRQ(ierr);
1142     if (flg1) {
1143       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-tellmycell requires either the phone number or number,\"message\"");
1144       if (nmax == 1) {
1145         ierr = PetscMalloc1(128,&buffs[1]);CHKERRQ(ierr);
1146         ierr = PetscGetProgramName(buffs[1],32);CHKERRQ(ierr);
1147         ierr = PetscStrcat(buffs[1]," has completed");CHKERRQ(ierr);
1148       }
1149       ierr = PetscTellMyCell(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);CHKERRQ(ierr);
1150       ierr = PetscFree(buffs[0]);CHKERRQ(ierr);
1151       ierr = PetscFree(buffs[1]);CHKERRQ(ierr);
1152     }
1153     ierr = PetscFree(buffs);CHKERRQ(ierr);
1154   }
1155 #endif
1156   /*
1157     It should be safe to cancel the options monitors, since we don't expect to be setting options
1158     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1159     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1160   */
1161   ierr = PetscOptionsMonitorCancel();CHKERRQ(ierr);
1162 
1163 #if defined(PETSC_SERIALIZE_FUNCTIONS)
1164   ierr = PetscFPTDestroy();CHKERRQ(ierr);
1165 #endif
1166 
1167 
1168 #if defined(PETSC_HAVE_SAWS)
1169   flg = PETSC_FALSE;
1170   ierr = PetscOptionsGetBool(NULL,NULL,"-saw_options",&flg,NULL);CHKERRQ(ierr);
1171   if (flg) {
1172     ierr = PetscOptionsSAWsDestroy();CHKERRQ(ierr);
1173   }
1174 #endif
1175 
1176 #if defined(PETSC_HAVE_X)
1177   flg1 = PETSC_FALSE;
1178   ierr = PetscOptionsGetBool(NULL,NULL,"-x_virtual",&flg1,NULL);CHKERRQ(ierr);
1179   if (flg1) {
1180     /*  this is a crude hack, but better than nothing */
1181     ierr = PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);CHKERRQ(ierr);
1182   }
1183 #endif
1184 
1185 #if !defined(PETSC_HAVE_THREADSAFETY)
1186   ierr = PetscOptionsGetBool(NULL,NULL,"-malloc_info",&flg2,NULL);CHKERRQ(ierr);
1187   if (!flg2) {
1188     flg2 = PETSC_FALSE;
1189     ierr = PetscOptionsGetBool(NULL,NULL,"-memory_view",&flg2,NULL);CHKERRQ(ierr);
1190   }
1191   if (flg2) {
1192     ierr = PetscMemoryView(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
1193   }
1194 #endif
1195 
1196 #if defined(PETSC_USE_LOG)
1197   flg1 = PETSC_FALSE;
1198   ierr = PetscOptionsGetBool(NULL,NULL,"-get_total_flops",&flg1,NULL);CHKERRQ(ierr);
1199   if (flg1) {
1200     PetscLogDouble flops = 0;
1201     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
1202     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
1203   }
1204 #endif
1205 
1206 
1207 #if defined(PETSC_USE_LOG)
1208 #if defined(PETSC_HAVE_MPE)
1209   mname[0] = 0;
1210   ierr = PetscOptionsGetString(NULL,NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1211   if (flg1) {
1212     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
1213     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
1214   }
1215 #endif
1216 #endif
1217 
1218   /*
1219      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1220   */
1221   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1222 
1223 #if defined(PETSC_USE_LOG)
1224   ierr = PetscLogViewFromOptions();CHKERRQ(ierr);
1225   mname[0] = 0;
1226   ierr = PetscOptionsGetString(NULL,NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1227   if (flg1) {
1228     PetscViewer viewer;
1229     ierr = (*PetscHelpPrintf)(PETSC_COMM_WORLD,"\n\n WARNING:   -log_summary is being deprecated; switch to -log_view\n\n\n");CHKERRQ(ierr);
1230     if (mname[0]) {
1231       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1232       ierr = PetscLogView(viewer);CHKERRQ(ierr);
1233       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1234     } else {
1235       viewer = PETSC_VIEWER_STDOUT_WORLD;
1236       ierr   = PetscViewerPushFormat(viewer,PETSC_VIEWER_DEFAULT);CHKERRQ(ierr);
1237       ierr   = PetscLogView(viewer);CHKERRQ(ierr);
1238       ierr   = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
1239     }
1240   }
1241 
1242   /*
1243      Free any objects created by the last block of code.
1244   */
1245   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1246 
1247   mname[0] = 0;
1248   ierr = PetscOptionsGetString(NULL,NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1249   ierr = PetscOptionsGetString(NULL,NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
1250   if (flg1 || flg2) {
1251     if (mname[0]) PetscLogDump(mname);
1252     else          PetscLogDump(0);
1253   }
1254 #endif
1255 
1256   ierr = PetscStackDestroy();CHKERRQ(ierr);
1257 
1258   flg1 = PETSC_FALSE;
1259   ierr = PetscOptionsGetBool(NULL,NULL,"-no_signal_handler",&flg1,NULL);CHKERRQ(ierr);
1260   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
1261   flg1 = PETSC_FALSE;
1262   ierr = PetscOptionsGetBool(NULL,NULL,"-mpidump",&flg1,NULL);CHKERRQ(ierr);
1263   if (flg1) {
1264     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1265   }
1266   flg1 = PETSC_FALSE;
1267   flg2 = PETSC_FALSE;
1268   /* preemptive call to avoid listing this option in options table as unused */
1269   ierr = PetscOptionsHasName(NULL,NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1270   ierr = PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1271   ierr = PetscOptionsGetBool(NULL,NULL,"-options_view",&flg2,NULL);CHKERRQ(ierr);
1272 
1273   if (flg2) {
1274     PetscViewer viewer;
1275     ierr = PetscViewerCreate(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1276     ierr = PetscViewerSetType(viewer,PETSCVIEWERASCII);CHKERRQ(ierr);
1277     ierr = PetscOptionsView(NULL,viewer);CHKERRQ(ierr);
1278     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1279   }
1280 
1281   /* to prevent PETSc -options_left from warning */
1282   ierr = PetscOptionsHasName(NULL,NULL,"-nox",&flg1);CHKERRQ(ierr);
1283   ierr = PetscOptionsHasName(NULL,NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1284 
1285   flg3 = PETSC_FALSE; /* default value is required */
1286   ierr = PetscOptionsGetBool(NULL,NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1287   ierr = PetscOptionsAllUsed(NULL,&nopt);CHKERRQ(ierr);
1288   if (flg3) {
1289     if (!flg2) { /* have not yet printed the options */
1290       PetscViewer viewer;
1291       ierr = PetscViewerCreate(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1292       ierr = PetscViewerSetType(viewer,PETSCVIEWERASCII);CHKERRQ(ierr);
1293       ierr = PetscOptionsView(NULL,viewer);CHKERRQ(ierr);
1294       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1295     }
1296     if (!nopt) {
1297       ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1298     } else if (nopt == 1) {
1299       ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1300     } else {
1301       ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1302     }
1303   }
1304 #if defined(PETSC_USE_DEBUG)
1305   if (nopt && !flg3 && !flg1) {
1306     ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1307     ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1308     ierr = PetscOptionsLeft(NULL);CHKERRQ(ierr);
1309   } else if (nopt && flg3) {
1310 #else
1311   if (nopt && flg3) {
1312 #endif
1313     ierr = PetscOptionsLeft(NULL);CHKERRQ(ierr);
1314   }
1315 
1316 #if defined(PETSC_HAVE_SAWS)
1317   if (!PetscGlobalRank) {
1318     ierr = PetscStackSAWsViewOff();CHKERRQ(ierr);
1319     PetscStackCallSAWs(SAWs_Finalize,());
1320   }
1321 #endif
1322 
1323 #if defined(PETSC_USE_LOG)
1324   /*
1325        List all objects the user may have forgot to free
1326   */
1327   if (PetscObjectsLog) {
1328     ierr = PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1329     if (flg1) {
1330       MPI_Comm local_comm;
1331       char     string[64];
1332 
1333       ierr = PetscOptionsGetString(NULL,NULL,"-objects_dump",string,64,NULL);CHKERRQ(ierr);
1334       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1335       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1336       ierr = PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);CHKERRQ(ierr);
1337       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1338       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1339     }
1340   }
1341 #endif
1342 
1343 #if defined(PETSC_USE_LOG)
1344   PetscObjectsCounts    = 0;
1345   PetscObjectsMaxCounts = 0;
1346   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1347 #endif
1348 
1349   /*
1350      Destroy any packages that registered a finalize
1351   */
1352   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1353 
1354 #if defined(PETSC_USE_LOG)
1355   ierr = PetscLogDestroy();CHKERRQ(ierr);
1356 #endif
1357 
1358   /*
1359      Print PetscFunctionLists that have not been properly freed
1360 
1361   ierr = PetscFunctionListPrintAll();CHKERRQ(ierr);
1362   */
1363 
1364   if (petsc_history) {
1365     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1366     petsc_history = 0;
1367   }
1368   ierr = PetscOptionsHelpPrintedDestroy(&PetscOptionsHelpPrintedSingleton);CHKERRQ(ierr);
1369 
1370   ierr = PetscInfoAllow(PETSC_FALSE,NULL);CHKERRQ(ierr);
1371 
1372 #if !defined(PETSC_HAVE_THREADSAFETY)
1373   {
1374     char fname[PETSC_MAX_PATH_LEN];
1375     FILE *fd;
1376     int  err;
1377 
1378     fname[0] = 0;
1379 
1380     ierr = PetscOptionsGetString(NULL,NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1381     flg2 = PETSC_FALSE;
1382     ierr = PetscOptionsGetBool(NULL,NULL,"-malloc_test",&flg2,NULL);CHKERRQ(ierr);
1383 #if defined(PETSC_USE_DEBUG)
1384     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1385 #else
1386     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1387 #endif
1388     if (flg1 && fname[0]) {
1389       char sname[PETSC_MAX_PATH_LEN];
1390 
1391       PetscSNPrintf(sname,PETSC_MAX_PATH_LEN,"%s_%d",fname,rank);
1392       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1393       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1394       err  = fclose(fd);
1395       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1396     } else if (flg1 || flg2) {
1397       MPI_Comm local_comm;
1398 
1399       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1400       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1401       ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1402       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1403       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1404     }
1405   }
1406 
1407   {
1408     char fname[PETSC_MAX_PATH_LEN];
1409     FILE *fd = NULL;
1410 
1411     fname[0] = 0;
1412 
1413     ierr = PetscOptionsGetString(NULL,NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1414     ierr = PetscOptionsHasName(NULL,NULL,"-malloc_log_threshold",&flg2);CHKERRQ(ierr);
1415     if (flg1 && fname[0]) {
1416       int err;
1417 
1418       if (!rank) {
1419         fd = fopen(fname,"w");
1420         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1421       }
1422       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1423       if (fd) {
1424         err = fclose(fd);
1425         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1426       }
1427     } else if (flg1 || flg2) {
1428       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1429     }
1430   }
1431 #endif
1432 
1433   /*
1434      Close any open dynamic libraries
1435   */
1436   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1437 
1438   /* Can be destroyed only after all the options are used */
1439   ierr = PetscOptionsDestroyDefault();CHKERRQ(ierr);
1440 
1441   PetscGlobalArgc = 0;
1442   PetscGlobalArgs = 0;
1443 
1444   ierr = PetscFreeMPIResources();CHKERRQ(ierr);
1445 
1446   /*
1447      Destroy any known inner MPI_Comm's and attributes pointing to them
1448      Note this will not destroy any new communicators the user has created.
1449 
1450      If all PETSc objects were not destroyed those left over objects will have hanging references to
1451      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1452  */
1453   {
1454     PetscCommCounter *counter;
1455     PetscMPIInt      flg;
1456     MPI_Comm         icomm;
1457     union {MPI_Comm comm; void *ptr;} ucomm;
1458     ierr = MPI_Comm_get_attr(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1459     if (flg) {
1460       icomm = ucomm.comm;
1461       ierr = MPI_Comm_get_attr(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1462       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1463 
1464       ierr = MPI_Comm_delete_attr(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1465       ierr = MPI_Comm_delete_attr(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1466       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1467     }
1468     ierr = MPI_Comm_get_attr(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1469     if (flg) {
1470       icomm = ucomm.comm;
1471       ierr = MPI_Comm_get_attr(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1472       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1473 
1474       ierr = MPI_Comm_delete_attr(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1475       ierr = MPI_Comm_delete_attr(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1476       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1477     }
1478   }
1479 
1480   ierr = MPI_Comm_free_keyval(&Petsc_Counter_keyval);CHKERRQ(ierr);
1481   ierr = MPI_Comm_free_keyval(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1482   ierr = MPI_Comm_free_keyval(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1483   ierr = MPI_Comm_free_keyval(&Petsc_Shared_keyval);CHKERRQ(ierr);
1484 
1485   ierr = PetscSpinlockDestroy(&PetscViewerASCIISpinLockOpen);CHKERRQ(ierr);
1486   ierr = PetscSpinlockDestroy(&PetscViewerASCIISpinLockStdout);CHKERRQ(ierr);
1487   ierr = PetscSpinlockDestroy(&PetscViewerASCIISpinLockStderr);CHKERRQ(ierr);
1488   ierr = PetscSpinlockDestroy(&PetscCommSpinLock);CHKERRQ(ierr);
1489 
1490   if (PetscBeganMPI) {
1491 #if defined(PETSC_HAVE_MPI_FINALIZED)
1492     PetscMPIInt flag;
1493     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1494     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1495 #endif
1496     ierr = MPI_Finalize();CHKERRQ(ierr);
1497   }
1498 /*
1499 
1500      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1501    the communicator has some outstanding requests on it. Specifically if the
1502    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1503    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1504    is never freed as it should be. Thus one may obtain messages of the form
1505    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1506    memory was not freed.
1507 
1508 */
1509   ierr = PetscMallocClear();CHKERRQ(ierr);
1510 
1511   PetscInitializeCalled = PETSC_FALSE;
1512   PetscFinalizeCalled   = PETSC_TRUE;
1513   PetscFunctionReturn(0);
1514 }
1515 
1516 #if defined(PETSC_MISSING_LAPACK_lsame_)
1517 PETSC_EXTERN int lsame_(char *a,char *b)
1518 {
1519   if (*a == *b) return 1;
1520   if (*a + 32 == *b) return 1;
1521   if (*a - 32 == *b) return 1;
1522   return 0;
1523 }
1524 #endif
1525 
1526 #if defined(PETSC_MISSING_LAPACK_lsame)
1527 PETSC_EXTERN int lsame(char *a,char *b)
1528 {
1529   if (*a == *b) return 1;
1530   if (*a + 32 == *b) return 1;
1531   if (*a - 32 == *b) return 1;
1532   return 0;
1533 }
1534 #endif
1535