xref: /petsc/src/sys/objects/pinit.c (revision 9c1e0ce8770ab6d4884a7bf923ea63b737ed5291)
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 #if defined(PETSC_HAVE_SAWS)
25 #include <petscviewersaws.h>
26 #endif
27 /* -----------------------------------------------------------------------------------------*/
28 
29 extern FILE *petsc_history;
30 
31 extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
32 extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
33 extern PetscErrorCode PetscFunctionListPrintAll(void);
34 extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
35 extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
36 extern PetscErrorCode PetscCloseHistoryFile(FILE**);
37 
38 /* user may set this BEFORE calling PetscInitialize() */
39 MPI_Comm PETSC_COMM_WORLD = MPI_COMM_NULL;
40 
41 PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
42 PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
43 PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;
44 
45 /*
46      Declare and set all the string names of the PETSc enums
47 */
48 const char *const PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
49 const char *const PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
50 const char *const PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
51                                       "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","OBJECT","FUNCTION","PetscDataType","PETSC_",0};
52 
53 PetscBool PetscPreLoadingUsed = PETSC_FALSE;
54 PetscBool PetscPreLoadingOn   = PETSC_FALSE;
55 
56 PetscInt PetscHotRegionDepth;
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 = PetscMalloc1(size,&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 = PetscMalloc1(argc,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 #if defined(PETSC_HAVE_SAWS)
561 #include <petscconfiginfo.h>
562 
563 #undef __FUNCT__
564 #define __FUNCT__ "PetscInitializeSAWs"
565 PetscErrorCode  PetscInitializeSAWs(const char help[])
566 {
567   if (!PetscGlobalRank) {
568     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
569     int            port;
570     PetscBool      flg,rootlocal = PETSC_FALSE,flg2;
571     size_t         applinelen,introlen;
572     PetscErrorCode ierr;
573 
574     ierr = PetscOptionsHasName(NULL,"-saws_log",&flg);CHKERRQ(ierr);
575     if (flg) {
576       char  sawslog[PETSC_MAX_PATH_LEN];
577 
578       ierr = PetscOptionsGetString(NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
579       if (sawslog[0]) {
580         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
581       } else {
582         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
583       }
584     }
585     ierr = PetscOptionsGetString(NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
586     if (flg) {
587       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
588     }
589     ierr = PetscOptionsGetInt(NULL,"-saws_port",&port,&flg);CHKERRQ(ierr);
590     if (flg) {
591       PetscStackCallSAWs(SAWs_Set_Port,(port));
592     }
593     ierr = PetscOptionsGetString(NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
594     if (flg) {
595       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));CHKERRQ(ierr);
596       ierr = PetscStrcmp(root,".",&rootlocal);CHKERRQ(ierr);
597     } else {
598       ierr = PetscOptionsHasName(NULL,"-saws_options",&flg);CHKERRQ(ierr);
599       if (flg) {
600         ierr = PetscStrreplace(PETSC_COMM_WORLD,"${PETSC_DIR}/saws",root,PETSC_MAX_PATH_LEN);CHKERRQ(ierr);
601         PetscStackCallSAWs(SAWs_Set_Document_Root,(root));CHKERRQ(ierr);
602       }
603     }
604     ierr = PetscOptionsHasName(NULL,"-saws_local",&flg2);CHKERRQ(ierr);
605     if (flg2) {
606       char jsdir[PETSC_MAX_PATH_LEN];
607       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
608       ierr = PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);CHKERRQ(ierr);
609       ierr = PetscTestDirectory(jsdir,'r',&flg);CHKERRQ(ierr);
610       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
611       PetscStackCallSAWs(SAWs_Push_Local_Header,());CHKERRQ(ierr);
612     }
613     ierr = PetscGetProgramName(programname,64);CHKERRQ(ierr);
614     ierr = PetscStrlen(help,&applinelen);CHKERRQ(ierr);
615     introlen   = 4096 + applinelen;
616     applinelen += 256;
617     ierr = PetscMalloc(applinelen,&appline);CHKERRQ(ierr);
618     ierr = PetscMalloc(introlen,&intro);CHKERRQ(ierr);
619 
620     if (rootlocal) {
621       ierr = PetscSNPrintf(appline,applinelen,"%s.c.html",programname);CHKERRQ(ierr);
622       ierr = PetscTestFile(appline,'r',&rootlocal);CHKERRQ(ierr);
623     }
624     ierr = PetscOptionsGetAll(&options);CHKERRQ(ierr);
625     if (rootlocal && help) {
626       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);
627     } else if (help) {
628       ierr = PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>\n",programname,options,help);
629     } else {
630       ierr = PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
631     }
632     ierr = PetscFree(options);CHKERRQ(ierr);
633     ierr = PetscGetVersion(version,sizeof(version));CHKERRQ(ierr);
634     ierr = PetscSNPrintf(intro,introlen,"<body>\n"
635                                     "<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"
636                                     "<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 at %s with %s</center><br>\n"
637                          "%s",version,petscconfigureruntime,petscconfigureoptions,appline);
638     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
639     ierr = PetscFree(intro);CHKERRQ(ierr);
640     ierr = PetscFree(appline);CHKERRQ(ierr);
641     PetscStackCallSAWs(SAWs_Initialize,());
642     ierr = PetscCitationsRegister("@TechReport{ saws,"
643                                   "Author = {Matt Otten and Jed Brown and Barry Smith},"
644                                   "Title  = {Scientific Application Web Server (SAWs) Users Manual},"
645                                   "Institution = {Argonne National Laboratory},"
646                                   "Year   = 2013}",NULL);CHKERRQ(ierr);
647   }
648   PetscFunctionReturn(0);
649 }
650 #endif
651 
652 #undef __FUNCT__
653 #define __FUNCT__ "PetscInitialize"
654 /*@C
655    PetscInitialize - Initializes the PETSc database and MPI.
656    PetscInitialize() calls MPI_Init() if that has yet to be called,
657    so this routine should always be called near the beginning of
658    your program -- usually the very first line!
659 
660    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set
661 
662    Input Parameters:
663 +  argc - count of number of command line arguments
664 .  args - the command line arguments
665 .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
666           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
667 -  help - [optional] Help message to print, use NULL for no message
668 
669    If you wish PETSc code to run ONLY on a subcommunicator of MPI_COMM_WORLD, create that
670    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize(). Thus if you are running a
671    four process job and two processes will run PETSc and have PetscInitialize() and PetscFinalize() and two process will not,
672    then do this. If ALL processes in the job are using PetscInitialize() and PetscFinalize() then you don't need to do this, even
673    if different subcommunicators of the job are doing different things with PETSc.
674 
675    Options Database Keys:
676 +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
677 .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
678 .  -on_error_emacs <machinename> causes emacsclient to jump to error file
679 .  -on_error_abort calls abort() when error detected (no traceback)
680 .  -on_error_mpiabort calls MPI_abort() when error detected
681 .  -error_output_stderr prints error messages to stderr instead of the default stdout
682 .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
683 .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
684 .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
685 .  -stop_for_debugger - Print message on how to attach debugger manually to
686                         process and wait (-debugger_pause) seconds for attachment
687 .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
688 .  -malloc no - Indicates not to use error-checking malloc
689 .  -malloc_debug - check for memory corruption at EVERY malloc or free
690 .  -malloc_dump - prints a list of all unfreed memory at the end of the run
691 .  -malloc_test - like -malloc_dump -malloc_debug, but only active for debugging builds
692 .  -fp_trap - Stops on floating point exceptions (Note that on the
693               IBM RS6000 this slows code by at least a factor of 10.)
694 .  -no_signal_handler - Indicates not to trap error signals
695 .  -shared_tmp - indicates /tmp directory is shared by all processors
696 .  -not_shared_tmp - each processor has own /tmp
697 .  -tmp - alternative name of /tmp directory
698 .  -get_total_flops - returns total flops done by all processors
699 -  -memory_info - Print memory usage at end of run
700 
701    Options Database Keys for Profiling:
702    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
703 +  -info <optional filename> - Prints verbose information to the screen
704 .  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
705 .  -log_sync - Log the synchronization in scatters, inner products and norms
706 .  -log_trace [filename] - Print traces of all PETSc calls to the screen (useful to determine where a program
707         hangs without running in the debugger).  See PetscLogTraceBegin().
708 .  -log_summary [filename] - Prints summary of flop and timing information to screen. If the filename is specified the
709         summary is written to the file.  See PetscLogView().
710 .  -log_summary_python [filename] - Prints data on of flop and timing usage to a file or screen. See PetscLogPrintSViewPython().
711 .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
712 .  -log [filename] - Logs basic profiline information  See PetscLogDump().
713 -  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)
714 
715     Only one of -log_trace, -log_summary, -log_all, -log, or -log_mpe may be used at a time
716 
717    Environmental Variables:
718 +   PETSC_TMP - alternative tmp directory
719 .   PETSC_SHARED_TMP - tmp is shared by all processes
720 .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
721 .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
722 -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to
723 
724 
725    Level: beginner
726 
727    Notes:
728    If for some reason you must call MPI_Init() separately, call
729    it before PetscInitialize().
730 
731    Fortran Version:
732    In Fortran this routine has the format
733 $       call PetscInitialize(file,ierr)
734 
735 +   ierr - error return code
736 -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL_CHARACTER to not check for
737           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
738 
739    Important Fortran Note:
740    In Fortran, you MUST use NULL_CHARACTER to indicate a
741    null character string; you CANNOT just use NULL as
742    in the C version. See the <a href="../../docs/manual.pdf">users manual</a> for details.
743 
744    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
745    calling PetscInitialize().
746 
747    Concepts: initializing PETSc
748 
749 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()
750 
751 @*/
752 PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
753 {
754   PetscErrorCode ierr;
755   PetscMPIInt    flag, size;
756   PetscInt       nodesize;
757   PetscBool      flg;
758   char           hostname[256];
759 
760   PetscFunctionBegin;
761   if (PetscInitializeCalled) PetscFunctionReturn(0);
762 
763   /* these must be initialized in a routine, not as a constant declaration*/
764   PETSC_STDOUT = stdout;
765   PETSC_STDERR = stderr;
766 
767   ierr = PetscOptionsCreate();CHKERRQ(ierr);
768 
769   /*
770      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
771      it that it sets args[0] on all processors to be args[0] on the first processor.
772   */
773   if (argc && *argc) {
774     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
775   } else {
776     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
777   }
778 
779   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
780   if (!flag) {
781     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");
782 #if defined(PETSC_HAVE_MPI_INIT_THREAD)
783     {
784       PetscMPIInt provided;
785       ierr = MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);CHKERRQ(ierr);
786     }
787 #else
788     ierr = MPI_Init(argc,args);CHKERRQ(ierr);
789 #endif
790     PetscBeganMPI = PETSC_TRUE;
791   }
792   if (argc && args) {
793     PetscGlobalArgc = *argc;
794     PetscGlobalArgs = *args;
795   }
796   PetscFinalizeCalled = PETSC_FALSE;
797 
798   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
799   ierr = MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
800 
801   /* Done after init due to a bug in MPICH-GM? */
802   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
803 
804   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
805   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
806 
807   MPIU_BOOL = MPI_INT;
808   MPIU_ENUM = MPI_INT;
809 
810   /*
811      Initialized the global complex variable; this is because with
812      shared libraries the constructors for global variables
813      are not called; at least on IRIX.
814   */
815 #if defined(PETSC_HAVE_COMPLEX)
816   {
817 #if defined(PETSC_CLANGUAGE_CXX)
818     PetscComplex ic(0.0,1.0);
819     PETSC_i = ic;
820 #elif defined(PETSC_CLANGUAGE_C)
821     PETSC_i = _Complex_I;
822 #endif
823   }
824 
825 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
826   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
827   ierr = MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
828   ierr = MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);CHKERRQ(ierr);
829   ierr = MPI_Type_commit(&MPIU_C_COMPLEX);CHKERRQ(ierr);
830 #endif
831 #endif /* PETSC_HAVE_COMPLEX */
832 
833   /*
834      Create the PETSc MPI reduction operator that sums of the first
835      half of the entries and maxes the second half.
836   */
837   ierr = MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);CHKERRQ(ierr);
838 
839 #if defined(PETSC_USE_REAL___FLOAT128)
840   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);CHKERRQ(ierr);
841   ierr = MPI_Type_commit(&MPIU___FLOAT128);CHKERRQ(ierr);
842 #if defined(PETSC_HAVE_COMPLEX)
843   ierr = MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);CHKERRQ(ierr);
844   ierr = MPI_Type_commit(&MPIU___COMPLEX128);CHKERRQ(ierr);
845 #endif
846   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
847   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
848 #endif
849 
850 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
851   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
852 #endif
853 
854   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
855   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
856   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
857   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
858 
859 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
860   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
861   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
862 #endif
863 
864 
865   /*
866      Attributes to be set on PETSc communicators
867   */
868   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
869   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
870   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
871 
872   /*
873      Build the options database
874   */
875   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
876 
877 
878   /*
879      Print main application help message
880   */
881   ierr = PetscOptionsHasName(NULL,"-help",&flg);CHKERRQ(ierr);
882   if (help && flg) {
883     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
884   }
885   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
886 
887   ierr = PetscCitationsInitialize();CHKERRQ(ierr);
888 
889 #if defined(PETSC_HAVE_SAWS)
890   ierr = PetscInitializeSAWs(help);CHKERRQ(ierr);
891 #endif
892 
893   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
894 #if defined(PETSC_USE_LOG)
895   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
896 #endif
897 
898   /*
899      Load the dynamic libraries (on machines that support them), this registers all
900      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
901   */
902   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
903 
904   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
905   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
906   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
907   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
908 
909   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
910   /* Check the options database for options related to the options database itself */
911   ierr = PetscOptionsSetFromOptions();CHKERRQ(ierr);
912 
913 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
914   /*
915       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
916 
917       Currently not used because it is not supported by MPICH.
918   */
919 #if !defined(PETSC_WORDS_BIGENDIAN)
920   ierr = MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);CHKERRQ(ierr);
921 #endif
922 #endif
923 
924   ierr = PetscOptionsGetInt(NULL,"-hmpi_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
925   if (flg) {
926 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
927     ierr = PetscHMPISpawn((PetscMPIInt) nodesize);CHKERRQ(ierr); /* worker nodes never return from here; they go directly to PetscEnd() */
928 #else
929     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -hmpi_merge_size instead");
930 #endif
931   } else {
932     ierr = PetscOptionsGetInt(NULL,"-hmpi_merge_size",&nodesize,&flg);CHKERRQ(ierr);
933     if (flg) {
934       ierr = PetscHMPIMerge((PetscMPIInt) nodesize,NULL,NULL);CHKERRQ(ierr);
935       if (PetscHMPIWorker) { /* if worker then never enter user code */
936         PetscInitializeCalled = PETSC_TRUE;
937         PetscEnd();
938       }
939     }
940   }
941 
942 #if defined(PETSC_HAVE_CUDA)
943   flg  = PETSC_TRUE;
944   ierr = PetscOptionsGetBool(NULL,"-cublas",&flg,NULL);CHKERRQ(ierr);
945   if (flg) {
946     PetscMPIInt p;
947     for (p = 0; p < PetscGlobalSize; ++p) {
948       if (p == PetscGlobalRank) cublasInit();
949       ierr = MPI_Barrier(PETSC_COMM_WORLD);CHKERRQ(ierr);
950     }
951   }
952 #endif
953 
954   ierr = PetscOptionsHasName(NULL,"-python",&flg);CHKERRQ(ierr);
955   if (flg) {
956     PetscInitializeCalled = PETSC_TRUE;
957     ierr = PetscPythonInitialize(NULL,NULL);CHKERRQ(ierr);
958   }
959 
960   ierr = PetscThreadCommInitializePackage();CHKERRQ(ierr);
961 
962   /*
963       Setup building of stack frames for all function calls
964   */
965   PetscThreadLocalRegister((PetscThreadKey*)&petscstack); /* Creates pthread_key */
966 #if defined(PETSC_USE_DEBUG)
967   ierr = PetscStackCreate();CHKERRQ(ierr);
968 #endif
969 
970 #if defined(PETSC_SERIALIZE_FUNCTIONS)
971   ierr = PetscFPTCreate(10000);CHKERRQ(ierr);
972 #endif
973 
974 
975   /*
976       Once we are completedly initialized then we can set this variables
977   */
978   PetscInitializeCalled = PETSC_TRUE;
979   PetscFunctionReturn(0);
980 }
981 
982 #if defined(PETSC_USE_LOG)
983 extern PetscObject *PetscObjects;
984 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
985 #endif
986 
987 #undef __FUNCT__
988 #define __FUNCT__ "PetscFinalize"
989 /*@C
990    PetscFinalize - Checks for options to be called at the conclusion
991    of the program. MPI_Finalize() is called only if the user had not
992    called MPI_Init() before calling PetscInitialize().
993 
994    Collective on PETSC_COMM_WORLD
995 
996    Options Database Keys:
997 +  -options_table - Calls PetscOptionsView()
998 .  -options_left - Prints unused options that remain in the database
999 .  -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
1000 .  -mpidump - Calls PetscMPIDump()
1001 .  -malloc_dump - Calls PetscMallocDump()
1002 .  -malloc_info - Prints total memory usage
1003 -  -malloc_log - Prints summary of memory usage
1004 
1005    Level: beginner
1006 
1007    Note:
1008    See PetscInitialize() for more general runtime options.
1009 
1010 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
1011 @*/
1012 PetscErrorCode  PetscFinalize(void)
1013 {
1014   PetscErrorCode ierr;
1015   PetscMPIInt    rank;
1016   PetscInt       nopt;
1017   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
1018   PetscBool      flg;
1019 #if defined(PETSC_USE_LOG)
1020   char           mname[PETSC_MAX_PATH_LEN];
1021 #endif
1022 
1023   PetscFunctionBegin;
1024   if (!PetscInitializeCalled) {
1025     printf("PetscInitialize() must be called before PetscFinalize()\n");
1026     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
1027   }
1028   ierr = PetscInfo(NULL,"PetscFinalize() called\n");CHKERRQ(ierr);
1029 
1030   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1031 
1032   ierr = PetscOptionsHasName(NULL,"-citations",&flg);CHKERRQ(ierr);
1033   if (flg) {
1034     char  *cits, filename[PETSC_MAX_PATH_LEN];
1035     FILE  *fd = PETSC_STDOUT;
1036 
1037     ierr = PetscOptionsGetString(NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
1038     if (filename[0]) {
1039       ierr = PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);CHKERRQ(ierr);
1040     }
1041     ierr = PetscSegBufferGet(PetscCitationsList,1,&cits);CHKERRQ(ierr);
1042     cits[0] = 0;
1043     ierr = PetscSegBufferExtractAlloc(PetscCitationsList,&cits);CHKERRQ(ierr);
1044     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");CHKERRQ(ierr);
1045     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
1046     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);CHKERRQ(ierr);
1047     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
1048     ierr = PetscFClose(PETSC_COMM_WORLD,fd);CHKERRQ(ierr);
1049     ierr = PetscFree(cits);CHKERRQ(ierr);
1050   }
1051   ierr = PetscSegBufferDestroy(&PetscCitationsList);CHKERRQ(ierr);
1052 
1053 #if defined(PETSC_SERIALIZE_FUNCTIONS)
1054   ierr = PetscFPTDestroy();CHKERRQ(ierr);
1055 #endif
1056 
1057 
1058 #if defined(PETSC_HAVE_SAWS)
1059   flg = PETSC_FALSE;
1060   ierr = PetscOptionsGetBool(NULL,"-saw_options",&flg,NULL);CHKERRQ(ierr);
1061   if (flg) {
1062     ierr = PetscOptionsSAWsDestroy();CHKERRQ(ierr);
1063   }
1064 #endif
1065 
1066 #if defined(PETSC_HAVE_X)
1067   flg1 = PETSC_FALSE;
1068   ierr = PetscOptionsGetBool(NULL,"-x_virtual",&flg1,NULL);CHKERRQ(ierr);
1069   if (flg1) {
1070     /*  this is a crude hack, but better than nothing */
1071     ierr = PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);CHKERRQ(ierr);
1072   }
1073 #endif
1074 
1075   ierr = PetscHMPIFinalize();CHKERRQ(ierr);
1076 
1077   ierr = PetscOptionsGetBool(NULL,"-malloc_info",&flg2,NULL);CHKERRQ(ierr);
1078   if (!flg2) {
1079     flg2 = PETSC_FALSE;
1080     ierr = PetscOptionsGetBool(NULL,"-memory_info",&flg2,NULL);CHKERRQ(ierr);
1081   }
1082   if (flg2) {
1083     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
1084   }
1085 
1086 #if defined(PETSC_USE_LOG)
1087   flg1 = PETSC_FALSE;
1088   ierr = PetscOptionsGetBool(NULL,"-get_total_flops",&flg1,NULL);CHKERRQ(ierr);
1089   if (flg1) {
1090     PetscLogDouble flops = 0;
1091     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
1092     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
1093   }
1094 #endif
1095 
1096 
1097 #if defined(PETSC_USE_LOG)
1098 #if defined(PETSC_HAVE_MPE)
1099   mname[0] = 0;
1100 
1101   ierr = PetscOptionsGetString(NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1102   if (flg1) {
1103     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
1104     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
1105   }
1106 #endif
1107   mname[0] = 0;
1108 
1109   ierr = PetscOptionsGetString(NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1110   if (flg1) {
1111     PetscViewer viewer;
1112     if (mname[0]) {
1113       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1114       ierr = PetscLogView(viewer);CHKERRQ(ierr);
1115       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1116     } else {
1117       viewer = PETSC_VIEWER_STDOUT_WORLD;
1118       ierr   = PetscLogView(viewer);CHKERRQ(ierr);
1119     }
1120   }
1121 
1122   mname[0] = 0;
1123 
1124   ierr = PetscOptionsGetString(NULL,"-log_summary_python",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1125   if (flg1) {
1126     PetscViewer viewer;
1127     if (mname[0]) {
1128       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1129       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
1130       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1131     } else {
1132       viewer = PETSC_VIEWER_STDOUT_WORLD;
1133       ierr   = PetscLogViewPython(viewer);CHKERRQ(ierr);
1134     }
1135   }
1136 
1137   ierr = PetscOptionsGetString(NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1138   if (flg1) {
1139     if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
1140     else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
1141   }
1142 
1143   mname[0] = 0;
1144 
1145   ierr = PetscOptionsGetString(NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1146   ierr = PetscOptionsGetString(NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
1147   if (flg1 || flg2) {
1148     if (mname[0]) PetscLogDump(mname);
1149     else          PetscLogDump(0);
1150   }
1151 #endif
1152 
1153   /*
1154      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1155   */
1156   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1157 
1158   ierr = PetscStackDestroy();CHKERRQ(ierr);
1159   PetscThreadLocalDestroy((PetscThreadKey)petscstack); /* Deletes pthread_key */
1160 
1161   flg1 = PETSC_FALSE;
1162   ierr = PetscOptionsGetBool(NULL,"-no_signal_handler",&flg1,NULL);CHKERRQ(ierr);
1163   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
1164   flg1 = PETSC_FALSE;
1165   ierr = PetscOptionsGetBool(NULL,"-mpidump",&flg1,NULL);CHKERRQ(ierr);
1166   if (flg1) {
1167     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1168   }
1169   flg1 = PETSC_FALSE;
1170   flg2 = PETSC_FALSE;
1171   /* preemptive call to avoid listing this option in options table as unused */
1172   ierr = PetscOptionsHasName(NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1173   ierr = PetscOptionsHasName(NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1174   ierr = PetscOptionsGetBool(NULL,"-options_table",&flg2,NULL);CHKERRQ(ierr);
1175 
1176   if (flg2) {
1177     PetscViewer viewer;
1178     ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1179     ierr = PetscOptionsView(viewer);CHKERRQ(ierr);
1180     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1181   }
1182 
1183   /* to prevent PETSc -options_left from warning */
1184   ierr = PetscOptionsHasName(NULL,"-nox",&flg1);CHKERRQ(ierr);
1185   ierr = PetscOptionsHasName(NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1186 
1187   if (!PetscHMPIWorker) { /* worker processes skip this because they do not usually process options */
1188     flg3 = PETSC_FALSE; /* default value is required */
1189     ierr = PetscOptionsGetBool(NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1190     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
1191     if (flg3) {
1192       if (!flg2) { /* have not yet printed the options */
1193         PetscViewer viewer;
1194         ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1195         ierr = PetscOptionsView(viewer);CHKERRQ(ierr);
1196         ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1197       }
1198       if (!nopt) {
1199         ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1200       } else if (nopt == 1) {
1201         ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1202       } else {
1203         ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1204       }
1205     }
1206 #if defined(PETSC_USE_DEBUG)
1207     if (nopt && !flg3 && !flg1) {
1208       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1209       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1210       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1211     } else if (nopt && flg3) {
1212 #else
1213     if (nopt && flg3) {
1214 #endif
1215       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1216     }
1217   }
1218 
1219 #if defined(PETSC_HAVE_SAWS)
1220   if (!PetscGlobalRank) {
1221     ierr = PetscStackSAWsViewOff();CHKERRQ(ierr);
1222     PetscStackCallSAWs(SAWs_Finalize,());
1223   }
1224 #endif
1225 
1226   {
1227     PetscThreadComm tcomm_world;
1228     ierr = PetscGetThreadCommWorld(&tcomm_world);CHKERRQ(ierr);
1229     /* Free global thread communicator */
1230     ierr = PetscThreadCommDestroy(&tcomm_world);CHKERRQ(ierr);
1231   }
1232 
1233 #if defined(PETSC_USE_LOG)
1234   /*
1235        List all objects the user may have forgot to free
1236   */
1237   ierr = PetscOptionsHasName(NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1238   if (flg1) {
1239     MPI_Comm local_comm;
1240     char     string[64];
1241 
1242     ierr = PetscOptionsGetString(NULL,"-objects_dump",string,64,NULL);CHKERRQ(ierr);
1243     ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1244     ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1245     ierr = PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);CHKERRQ(ierr);
1246     ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1247     ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1248   }
1249 #endif
1250 
1251 #if defined(PETSC_USE_LOG)
1252   PetscObjectsCounts    = 0;
1253   PetscObjectsMaxCounts = 0;
1254   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1255 #endif
1256 
1257 #if defined(PETSC_USE_LOG)
1258   ierr = PetscLogDestroy();CHKERRQ(ierr);
1259 #endif
1260 
1261   /*
1262      Destroy any packages that registered a finalize
1263   */
1264   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1265 
1266   /*
1267      Destroy all the function registration lists created
1268   */
1269   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1270 
1271   /*
1272      Print PetscFunctionLists that have not been properly freed
1273 
1274   ierr = PetscFunctionListPrintAll();CHKERRQ(ierr);
1275   */
1276 
1277   if (petsc_history) {
1278     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1279     petsc_history = 0;
1280   }
1281 
1282   ierr = PetscInfoAllow(PETSC_FALSE,NULL);CHKERRQ(ierr);
1283 
1284   {
1285     char fname[PETSC_MAX_PATH_LEN];
1286     FILE *fd;
1287     int  err;
1288 
1289     fname[0] = 0;
1290 
1291     ierr = PetscOptionsGetString(NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1292     flg2 = PETSC_FALSE;
1293     ierr = PetscOptionsGetBool(NULL,"-malloc_test",&flg2,NULL);CHKERRQ(ierr);
1294 #if defined(PETSC_USE_DEBUG)
1295     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1296 #else
1297     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1298 #endif
1299     if (flg1 && fname[0]) {
1300       char sname[PETSC_MAX_PATH_LEN];
1301 
1302       sprintf(sname,"%s_%d",fname,rank);
1303       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1304       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1305       err  = fclose(fd);
1306       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1307     } else if (flg1 || flg2) {
1308       MPI_Comm local_comm;
1309 
1310       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1311       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1312       ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1313       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1314       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1315     }
1316   }
1317 
1318   {
1319     char fname[PETSC_MAX_PATH_LEN];
1320     FILE *fd = NULL;
1321 
1322     fname[0] = 0;
1323 
1324     ierr = PetscOptionsGetString(NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1325     ierr = PetscOptionsHasName(NULL,"-malloc_log_threshold",&flg2);CHKERRQ(ierr);
1326     if (flg1 && fname[0]) {
1327       int err;
1328 
1329       if (!rank) {
1330         fd = fopen(fname,"w");
1331         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1332       }
1333       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1334       if (fd) {
1335         err = fclose(fd);
1336         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1337       }
1338     } else if (flg1 || flg2) {
1339       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1340     }
1341   }
1342 
1343 #if defined(PETSC_HAVE_CUDA)
1344   flg  = PETSC_TRUE;
1345   ierr = PetscOptionsGetBool(NULL,"-cublas",&flg,NULL);CHKERRQ(ierr);
1346   if (flg) {
1347     PetscInt p;
1348     for (p = 0; p < PetscGlobalSize; ++p) {
1349       if (p == PetscGlobalRank) cublasShutdown();
1350       ierr = MPI_Barrier(PETSC_COMM_WORLD);CHKERRQ(ierr);
1351     }
1352   }
1353 #endif
1354 
1355   /* Can be destroyed only after all the options are used */
1356   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
1357 
1358   PetscGlobalArgc = 0;
1359   PetscGlobalArgs = 0;
1360 
1361 #if defined(PETSC_USE_REAL___FLOAT128)
1362   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1363 #if defined(PETSC_HAVE_COMPLEX)
1364   ierr = MPI_Type_free(&MPIU___COMPLEX128);CHKERRQ(ierr);
1365 #endif
1366   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1367   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1368 #endif
1369 
1370 #if defined(PETSC_HAVE_COMPLEX)
1371 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1372   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1373   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1374 #endif
1375 #endif
1376 
1377 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1378   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1379 #endif
1380 
1381   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1382 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1383   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1384 #endif
1385   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
1386   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
1387   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
1388 
1389   /*
1390      Destroy any known inner MPI_Comm's and attributes pointing to them
1391      Note this will not destroy any new communicators the user has created.
1392 
1393      If all PETSc objects were not destroyed those left over objects will have hanging references to
1394      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1395  */
1396   {
1397     PetscCommCounter *counter;
1398     PetscMPIInt      flg;
1399     MPI_Comm         icomm;
1400     union {MPI_Comm comm; void *ptr;} ucomm;
1401     ierr = MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1402     if (flg) {
1403       icomm = ucomm.comm;
1404       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1405       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1406 
1407       ierr = MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1408       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1409       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1410     }
1411     ierr = MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1412     if (flg) {
1413       icomm = ucomm.comm;
1414       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1415       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1416 
1417       ierr = MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1418       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1419       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1420     }
1421   }
1422 
1423   ierr = MPI_Keyval_free(&Petsc_Counter_keyval);CHKERRQ(ierr);
1424   ierr = MPI_Keyval_free(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1425   ierr = MPI_Keyval_free(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1426 
1427   if (PetscBeganMPI) {
1428 #if defined(PETSC_HAVE_MPI_FINALIZED)
1429     PetscMPIInt flag;
1430     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1431     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1432 #endif
1433     ierr = MPI_Finalize();CHKERRQ(ierr);
1434   }
1435 /*
1436 
1437      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1438    the communicator has some outstanding requests on it. Specifically if the
1439    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1440    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1441    is never freed as it should be. Thus one may obtain messages of the form
1442    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1443    memory was not freed.
1444 
1445 */
1446   ierr = PetscMallocClear();CHKERRQ(ierr);
1447 
1448   PetscInitializeCalled = PETSC_FALSE;
1449   PetscFinalizeCalled   = PETSC_TRUE;
1450   PetscFunctionReturn(ierr);
1451 }
1452 
1453 #if defined(PETSC_MISSING_LAPACK_lsame_)
1454 PETSC_EXTERN int lsame_(char *a,char *b)
1455 {
1456   if (*a == *b) return 1;
1457   if (*a + 32 == *b) return 1;
1458   if (*a - 32 == *b) return 1;
1459   return 0;
1460 }
1461 #endif
1462 
1463 #if defined(PETSC_MISSING_LAPACK_lsame)
1464 PETSC_EXTERN int lsame(char *a,char *b)
1465 {
1466   if (*a == *b) return 1;
1467   if (*a + 32 == *b) return 1;
1468   if (*a - 32 == *b) return 1;
1469   return 0;
1470 }
1471 #endif
1472