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