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