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