xref: /petsc/src/sys/objects/pinit.c (revision 37bef68685c1f05064f72c911cffeeaba9b107d9)
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   ierr = SAWs_Add_Directory(SAWs_ROOT_DIRECTORY,"PETSc",&PETSC_SAWs_ROOT_DIRECTORY);CHKERRQ(ierr);
803   ierr = SAWs_Add_Directory(PETSC_SAWs_ROOT_DIRECTORY,"Objects",&PETSC_OBJECTS_SAWs_ROOT_DIRECTORY);CHKERRQ(ierr);
804 #endif
805 
806   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
807 #if defined(PETSC_USE_LOG)
808   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
809 #endif
810 
811   /*
812      Load the dynamic libraries (on machines that support them), this registers all
813      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
814   */
815   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
816 
817   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
818   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
819   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
820   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
821 
822   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
823   /* Check the options database for options related to the options database itself */
824   ierr = PetscOptionsSetFromOptions();CHKERRQ(ierr);
825 
826 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
827   /*
828       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
829 
830       Currently not used because it is not supported by MPICH.
831   */
832 #if !defined(PETSC_WORDS_BIGENDIAN)
833   ierr = MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);CHKERRQ(ierr);
834 #endif
835 #endif
836 
837   ierr = PetscOptionsGetInt(NULL,"-hmpi_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
838   if (flg) {
839 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
840     ierr = PetscHMPISpawn((PetscMPIInt) nodesize);CHKERRQ(ierr); /* worker nodes never return from here; they go directly to PetscEnd() */
841 #else
842     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -hmpi_merge_size instead");
843 #endif
844   } else {
845     ierr = PetscOptionsGetInt(NULL,"-hmpi_merge_size",&nodesize,&flg);CHKERRQ(ierr);
846     if (flg) {
847       ierr = PetscHMPIMerge((PetscMPIInt) nodesize,NULL,NULL);CHKERRQ(ierr);
848       if (PetscHMPIWorker) { /* if worker then never enter user code */
849         PetscInitializeCalled = PETSC_TRUE;
850         PetscEnd();
851       }
852     }
853   }
854 
855 #if defined(PETSC_HAVE_CUDA)
856   {
857     PetscMPIInt p;
858     for (p = 0; p < PetscGlobalSize; ++p) {
859       if (p == PetscGlobalRank) cublasInit();
860       ierr = MPI_Barrier(PETSC_COMM_WORLD);CHKERRQ(ierr);
861     }
862   }
863 #endif
864 
865   ierr = PetscOptionsHasName(NULL,"-python",&flg);CHKERRQ(ierr);
866   if (flg) {
867     PetscInitializeCalled = PETSC_TRUE;
868     ierr = PetscPythonInitialize(NULL,NULL);CHKERRQ(ierr);
869   }
870 
871   ierr = PetscThreadCommInitializePackage();CHKERRQ(ierr);
872 
873   /*
874       Setup building of stack frames for all function calls
875   */
876 #if defined(PETSC_USE_DEBUG)
877   PetscThreadLocalRegister((PetscThreadKey*)&petscstack); /* Creates petscstack_key if needed */
878   ierr = PetscStackCreate();CHKERRQ(ierr);
879 #endif
880 
881 #if defined(PETSC_SERIALIZE_FUNCTIONS)
882   ierr = PetscFPTCreate(10000);CHKERRQ(ierr);
883 #endif
884 
885   ierr = PetscCitationsInitialize();CHKERRQ(ierr);
886 
887   /*
888       Once we are completedly initialized then we can set this variables
889   */
890   PetscInitializeCalled = PETSC_TRUE;
891   PetscFunctionReturn(0);
892 }
893 
894 extern PetscObject *PetscObjects;
895 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
896 
897 #undef __FUNCT__
898 #define __FUNCT__ "PetscFinalize"
899 /*@C
900    PetscFinalize - Checks for options to be called at the conclusion
901    of the program. MPI_Finalize() is called only if the user had not
902    called MPI_Init() before calling PetscInitialize().
903 
904    Collective on PETSC_COMM_WORLD
905 
906    Options Database Keys:
907 +  -options_table - Calls PetscOptionsView()
908 .  -options_left - Prints unused options that remain in the database
909 .  -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
910 .  -mpidump - Calls PetscMPIDump()
911 .  -malloc_dump - Calls PetscMallocDump()
912 .  -malloc_info - Prints total memory usage
913 -  -malloc_log - Prints summary of memory usage
914 
915    Level: beginner
916 
917    Note:
918    See PetscInitialize() for more general runtime options.
919 
920 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
921 @*/
922 PetscErrorCode  PetscFinalize(void)
923 {
924   PetscErrorCode ierr;
925   PetscMPIInt    rank;
926   PetscInt       nopt;
927   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
928   PetscBool      flg;
929 #if defined(PETSC_USE_LOG)
930   char           mname[PETSC_MAX_PATH_LEN];
931 #endif
932 
933   PetscFunctionBegin;
934   if (!PetscInitializeCalled) {
935     printf("PetscInitialize() must be called before PetscFinalize()\n");
936     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
937   }
938   ierr = PetscInfo(NULL,"PetscFinalize() called\n");CHKERRQ(ierr);
939 
940   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
941 
942   ierr = PetscOptionsHasName(NULL,"-citations",&flg);CHKERRQ(ierr);
943   if (flg) {
944     char  *cits, filename[PETSC_MAX_PATH_LEN];
945     FILE  *fd = PETSC_STDOUT;
946 
947     ierr = PetscOptionsGetString(NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
948     if (filename[0]) {
949       ierr = PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);CHKERRQ(ierr);
950     }
951     ierr = PetscSegBufferGet(PetscCitationsList,1,&cits);CHKERRQ(ierr);
952     cits[0] = 0;
953     ierr = PetscSegBufferExtractAlloc(PetscCitationsList,&cits);CHKERRQ(ierr);
954     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");CHKERRQ(ierr);
955     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
956     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);CHKERRQ(ierr);
957     ierr = PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");CHKERRQ(ierr);
958     ierr = PetscFClose(PETSC_COMM_WORLD,fd);CHKERRQ(ierr);
959     ierr = PetscFree(cits);CHKERRQ(ierr);
960   }
961   ierr = PetscSegBufferDestroy(&PetscCitationsList);CHKERRQ(ierr);
962 
963 #if defined(PETSC_SERIALIZE_FUNCTIONS)
964   ierr = PetscFPTDestroy();CHKERRQ(ierr);
965 #endif
966 
967 
968 #if defined(PETSC_HAVE_SAWS)
969   flg = PETSC_FALSE;
970   ierr = PetscOptionsGetBool(NULL,"-options_gui",&flg,NULL);CHKERRQ(ierr);
971   if (flg) {
972     ierr = PetscOptionsSAWsDestroy();CHKERRQ(ierr);
973   }
974 #endif
975 
976 #if defined(PETSC_HAVE_SERVER)
977   flg1 = PETSC_FALSE;
978   ierr = PetscOptionsGetBool(NULL,"-server",&flg1,NULL);CHKERRQ(ierr);
979   if (flg1) {
980     /*  this is a crude hack, but better than nothing */
981     ierr = PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 petscwebserver","r",NULL);CHKERRQ(ierr);
982   }
983 #endif
984 
985 #if defined(PETSC_HAVE_X)
986   flg1 = PETSC_FALSE;
987   ierr = PetscOptionsGetBool(NULL,"-x_virtual",&flg1,NULL);CHKERRQ(ierr);
988   if (flg1) {
989     /*  this is a crude hack, but better than nothing */
990     ierr = PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);CHKERRQ(ierr);
991   }
992 #endif
993 
994   ierr = PetscHMPIFinalize();CHKERRQ(ierr);
995 
996   ierr = PetscOptionsGetBool(NULL,"-malloc_info",&flg2,NULL);CHKERRQ(ierr);
997   if (!flg2) {
998     flg2 = PETSC_FALSE;
999     ierr = PetscOptionsGetBool(NULL,"-memory_info",&flg2,NULL);CHKERRQ(ierr);
1000   }
1001   if (flg2) {
1002     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
1003   }
1004 
1005 #if defined(PETSC_USE_LOG)
1006   flg1 = PETSC_FALSE;
1007   ierr = PetscOptionsGetBool(NULL,"-get_total_flops",&flg1,NULL);CHKERRQ(ierr);
1008   if (flg1) {
1009     PetscLogDouble flops = 0;
1010     ierr = MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
1011     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
1012   }
1013 #endif
1014 
1015 
1016 #if defined(PETSC_USE_LOG)
1017 #if defined(PETSC_HAVE_MPE)
1018   mname[0] = 0;
1019 
1020   ierr = PetscOptionsGetString(NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1021   if (flg1) {
1022     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
1023     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
1024   }
1025 #endif
1026   mname[0] = 0;
1027 
1028   ierr = PetscOptionsGetString(NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1029   if (flg1) {
1030     PetscViewer viewer;
1031     if (mname[0]) {
1032       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1033       ierr = PetscLogView(viewer);CHKERRQ(ierr);
1034       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1035     } else {
1036       viewer = PETSC_VIEWER_STDOUT_WORLD;
1037       ierr   = PetscLogView(viewer);CHKERRQ(ierr);
1038     }
1039   }
1040 
1041   mname[0] = 0;
1042 
1043   ierr = PetscOptionsGetString(NULL,"-log_summary_python",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1044   if (flg1) {
1045     PetscViewer viewer;
1046     if (mname[0]) {
1047       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
1048       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
1049       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1050     } else {
1051       viewer = PETSC_VIEWER_STDOUT_WORLD;
1052       ierr   = PetscLogViewPython(viewer);CHKERRQ(ierr);
1053     }
1054   }
1055 
1056   ierr = PetscOptionsGetString(NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1057   if (flg1) {
1058     if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
1059     else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
1060   }
1061 
1062   mname[0] = 0;
1063 
1064   ierr = PetscOptionsGetString(NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1065   ierr = PetscOptionsGetString(NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
1066   if (flg1 || flg2) {
1067     if (mname[0]) PetscLogDump(mname);
1068     else          PetscLogDump(0);
1069   }
1070 #endif
1071 
1072   /*
1073      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1074   */
1075   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1076 
1077   ierr = PetscStackDestroy();CHKERRQ(ierr);
1078 
1079   flg1 = PETSC_FALSE;
1080   ierr = PetscOptionsGetBool(NULL,"-no_signal_handler",&flg1,NULL);CHKERRQ(ierr);
1081   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
1082   flg1 = PETSC_FALSE;
1083   ierr = PetscOptionsGetBool(NULL,"-mpidump",&flg1,NULL);CHKERRQ(ierr);
1084   if (flg1) {
1085     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1086   }
1087   flg1 = PETSC_FALSE;
1088   flg2 = PETSC_FALSE;
1089   /* preemptive call to avoid listing this option in options table as unused */
1090   ierr = PetscOptionsHasName(NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1091   ierr = PetscOptionsHasName(NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1092   ierr = PetscOptionsGetBool(NULL,"-options_table",&flg2,NULL);CHKERRQ(ierr);
1093 
1094   if (flg2) {
1095     PetscViewer viewer;
1096     ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1097     ierr = PetscOptionsView(viewer);CHKERRQ(ierr);
1098     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1099   }
1100 
1101   /* to prevent PETSc -options_left from warning */
1102   ierr = PetscOptionsHasName(NULL,"-nox",&flg1);CHKERRQ(ierr);
1103   ierr = PetscOptionsHasName(NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1104 
1105   if (!PetscHMPIWorker) { /* worker processes skip this because they do not usually process options */
1106     flg3 = PETSC_FALSE; /* default value is required */
1107     ierr = PetscOptionsGetBool(NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1108     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
1109     if (flg3) {
1110       if (!flg2) { /* have not yet printed the options */
1111         PetscViewer viewer;
1112         ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
1113         ierr = PetscOptionsView(viewer);CHKERRQ(ierr);
1114         ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
1115       }
1116       if (!nopt) {
1117         ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1118       } else if (nopt == 1) {
1119         ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1120       } else {
1121         ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1122       }
1123     }
1124 #if defined(PETSC_USE_DEBUG)
1125     if (nopt && !flg3 && !flg1) {
1126       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1127       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1128       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1129     } else if (nopt && flg3) {
1130 #else
1131     if (nopt && flg3) {
1132 #endif
1133       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1134     }
1135   }
1136 
1137 #if defined(PETSC_HAVE_SAWS)
1138   ierr = SAWs_Destroy_Directory(&PETSC_OBJECTS_SAWs_ROOT_DIRECTORY);CHKERRQ(ierr);
1139   ierr = SAWs_Destroy_Directory(&PETSC_SAWs_ROOT_DIRECTORY);CHKERRQ(ierr);
1140   ierr = SAWs_Finalize();CHKERRQ(ierr);
1141 #endif
1142 
1143   {
1144     PetscThreadComm tcomm_world;
1145     ierr = PetscGetThreadCommWorld(&tcomm_world);CHKERRQ(ierr);
1146     /* Free global thread communicator */
1147     ierr = PetscThreadCommDestroy(&tcomm_world);CHKERRQ(ierr);
1148   }
1149 
1150   /*
1151        List all objects the user may have forgot to free
1152   */
1153   ierr = PetscOptionsHasName(NULL,"-objects_dump",&flg1);CHKERRQ(ierr);
1154   if (flg1) {
1155     MPI_Comm local_comm;
1156     char     string[64];
1157 
1158     ierr = PetscOptionsGetString(NULL,"-objects_dump",string,64,NULL);CHKERRQ(ierr);
1159     ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1160     ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1161     ierr = PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);CHKERRQ(ierr);
1162     ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1163     ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1164   }
1165   PetscObjectsCounts    = 0;
1166   PetscObjectsMaxCounts = 0;
1167 
1168   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1169 
1170 #if defined(PETSC_USE_LOG)
1171   ierr = PetscLogDestroy();CHKERRQ(ierr);
1172 #endif
1173 
1174   /*
1175      Destroy any packages that registered a finalize
1176   */
1177   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1178 
1179   /*
1180      Destroy all the function registration lists created
1181   */
1182   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1183 
1184   /*
1185      Print PetscFunctionLists that have not been properly freed
1186 
1187   ierr = PetscFunctionListPrintAll();CHKERRQ(ierr);
1188   */
1189 
1190   if (petsc_history) {
1191     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1192     petsc_history = 0;
1193   }
1194 
1195   ierr = PetscInfoAllow(PETSC_FALSE,NULL);CHKERRQ(ierr);
1196 
1197   {
1198     char fname[PETSC_MAX_PATH_LEN];
1199     FILE *fd;
1200     int  err;
1201 
1202     fname[0] = 0;
1203 
1204     ierr = PetscOptionsGetString(NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1205     flg2 = PETSC_FALSE;
1206     ierr = PetscOptionsGetBool(NULL,"-malloc_test",&flg2,NULL);CHKERRQ(ierr);
1207 #if defined(PETSC_USE_DEBUG)
1208     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1209 #else
1210     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1211 #endif
1212     if (flg1 && fname[0]) {
1213       char sname[PETSC_MAX_PATH_LEN];
1214 
1215       sprintf(sname,"%s_%d",fname,rank);
1216       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1217       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1218       err  = fclose(fd);
1219       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1220     } else if (flg1 || flg2) {
1221       MPI_Comm local_comm;
1222 
1223       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1224       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1225       ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1226       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1227       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1228     }
1229   }
1230 
1231   {
1232     char fname[PETSC_MAX_PATH_LEN];
1233     FILE *fd = NULL;
1234 
1235     fname[0] = 0;
1236 
1237     ierr = PetscOptionsGetString(NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1238     ierr = PetscOptionsHasName(NULL,"-malloc_log_threshold",&flg2);CHKERRQ(ierr);
1239     if (flg1 && fname[0]) {
1240       int err;
1241 
1242       if (!rank) {
1243         fd = fopen(fname,"w");
1244         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1245       }
1246       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1247       if (fd) {
1248         err = fclose(fd);
1249         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1250       }
1251     } else if (flg1 || flg2) {
1252       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1253     }
1254   }
1255   /* Can be destroyed only after all the options are used */
1256   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
1257 
1258   PetscGlobalArgc = 0;
1259   PetscGlobalArgs = 0;
1260 
1261 #if defined(PETSC_USE_REAL___FLOAT128)
1262   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1263 #if defined(PETSC_HAVE_COMPLEX)
1264   ierr = MPI_Type_free(&MPIU___COMPLEX128);CHKERRQ(ierr);
1265 #endif
1266   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1267   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1268 #endif
1269 
1270 #if defined(PETSC_HAVE_COMPLEX)
1271 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1272   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1273   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1274 #endif
1275 #endif
1276 
1277 #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1278   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1279 #endif
1280 
1281   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1282 #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1283   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1284 #endif
1285   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
1286   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
1287   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
1288 
1289   /*
1290      Destroy any known inner MPI_Comm's and attributes pointing to them
1291      Note this will not destroy any new communicators the user has created.
1292 
1293      If all PETSc objects were not destroyed those left over objects will have hanging references to
1294      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1295  */
1296   {
1297     PetscCommCounter *counter;
1298     PetscMPIInt      flg;
1299     MPI_Comm         icomm;
1300     union {MPI_Comm comm; void *ptr;} ucomm;
1301     ierr = MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1302     if (flg) {
1303       icomm = ucomm.comm;
1304       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1305       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1306 
1307       ierr = MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1308       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1309       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1310     }
1311     ierr = MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);CHKERRQ(ierr);
1312     if (flg) {
1313       icomm = ucomm.comm;
1314       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1315       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1316 
1317       ierr = MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1318       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1319       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1320     }
1321   }
1322 
1323   ierr = MPI_Keyval_free(&Petsc_Counter_keyval);CHKERRQ(ierr);
1324   ierr = MPI_Keyval_free(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1325   ierr = MPI_Keyval_free(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1326 
1327 #if defined(PETSC_HAVE_CUDA)
1328   {
1329     PetscInt p;
1330     for (p = 0; p < PetscGlobalSize; ++p) {
1331       if (p == PetscGlobalRank) cublasShutdown();
1332       ierr = MPI_Barrier(PETSC_COMM_WORLD);CHKERRQ(ierr);
1333     }
1334   }
1335 #endif
1336 
1337   if (PetscBeganMPI) {
1338 #if defined(PETSC_HAVE_MPI_FINALIZED)
1339     PetscMPIInt flag;
1340     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1341     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1342 #endif
1343     ierr = MPI_Finalize();CHKERRQ(ierr);
1344   }
1345 /*
1346 
1347      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1348    the communicator has some outstanding requests on it. Specifically if the
1349    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1350    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1351    is never freed as it should be. Thus one may obtain messages of the form
1352    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1353    memory was not freed.
1354 
1355 */
1356   ierr = PetscMallocClear();CHKERRQ(ierr);
1357 
1358   PetscInitializeCalled = PETSC_FALSE;
1359   PetscFinalizeCalled   = PETSC_TRUE;
1360   PetscFunctionReturn(ierr);
1361 }
1362 
1363 #if defined(PETSC_MISSING_LAPACK_lsame_)
1364 PETSC_EXTERN int lsame_(char *a,char *b)
1365 {
1366   if (*a == *b) return 1;
1367   if (*a + 32 == *b) return 1;
1368   if (*a - 32 == *b) return 1;
1369   return 0;
1370 }
1371 #endif
1372 
1373 #if defined(PETSC_MISSING_LAPACK_lsame)
1374 PETSC_EXTERN int lsame(char *a,char *b)
1375 {
1376   if (*a == *b) return 1;
1377   if (*a + 32 == *b) return 1;
1378   if (*a - 32 == *b) return 1;
1379   return 0;
1380 }
1381 #endif
1382