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