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