Actual source code: pinit.c

petsc-master 2017-06-24
Report Typos and Errors

  2: /*
  3:    This file defines the initialization of PETSc, including PetscInitialize()
  4: */
  5:  #include <petsc/private/petscimpl.h>
  6:  #include <petscvalgrind.h>
  7:  #include <petscviewer.h>

  9: #if defined(PETSC_USE_LOG)
 10: extern PetscErrorCode PetscLogInitialize(void);
 11: #endif

 13: #if defined(PETSC_SERIALIZE_FUNCTIONS)
 14: PetscFPT PetscFPTData = 0;
 15: #endif

 17: #if defined(PETSC_HAVE_CUDA)
 18: cublasHandle_t cublasv2handle = NULL;
 19: #endif

 21: #if defined(PETSC_HAVE_SAWS)
 22:  #include <petscviewersaws.h>
 23: #endif
 24: /* -----------------------------------------------------------------------------------------*/

 26: extern FILE *petsc_history;

 28: extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
 29: extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
 30: extern PetscErrorCode PetscFunctionListPrintAll(void);
 31: extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
 32: extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
 33: extern PetscErrorCode PetscCloseHistoryFile(FILE**);

 35: /* user may set this BEFORE calling PetscInitialize() */
 36: MPI_Comm PETSC_COMM_WORLD = MPI_COMM_NULL;

 38: PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
 39: PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
 40: PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;

 42: /*
 43:      Declare and set all the string names of the PETSc enums
 44: */
 45: const char *const PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
 46: const char *const PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
 47: const char *const PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
 48:                                       "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","OBJECT","FUNCTION","PetscDataType","PETSC_",0};

 50: PetscBool PetscPreLoadingUsed = PETSC_FALSE;
 51: PetscBool PetscPreLoadingOn   = PETSC_FALSE;

 53: PetscInt PetscHotRegionDepth;

 55: #if defined(PETSC_HAVE_THREADSAFETY)
 56: PetscSpinlock PetscViewerASCIISpinLockOpen;
 57: PetscSpinlock PetscViewerASCIISpinLockStdout;
 58: PetscSpinlock PetscViewerASCIISpinLockStderr;
 59: PetscSpinlock PetscCommSpinLock;
 60: #endif

 62: /*
 63:        Checks the options database for initializations related to the
 64:     PETSc components
 65: */
 66: PetscErrorCode  PetscOptionsCheckInitial_Components(void)
 67: {
 68:   PetscBool      flg1;

 72:   PetscOptionsHasName(NULL,NULL,"-help",&flg1);
 73:   if (flg1) {
 74: #if defined(PETSC_USE_LOG)
 75:     MPI_Comm comm = PETSC_COMM_WORLD;
 76:     (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");
 77:     (*PetscHelpPrintf)(comm," -log_exclude: <vec,mat,pc.ksp,snes>\n");
 78:     (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");
 79:     (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");
 80: #endif
 81:   }
 82:   return(0);
 83: }

 85: /*
 86:       PetscInitializeNoPointers - Calls PetscInitialize() from C/C++ without the pointers to argc and args

 88:    Collective

 90:    Level: advanced

 92:     Notes: this is called only by the PETSc MATLAB and Julia interface. Even though it might start MPI it sets the flag to
 93:      indicate that it did NOT start MPI so that the PetscFinalize() does not end MPI, thus allowing PetscInitialize() to
 94:      be called multiple times from MATLAB and Julia without the problem of trying to initialize MPI more than once.

 96:      Turns off PETSc signal handling because that can interact with MATLAB's signal handling causing random crashes.

 98: .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
 99: */
100: PetscErrorCode  PetscInitializeNoPointers(int argc,char **args,const char *filename,const char *help)
101: {
103:   int            myargc   = argc;
104:   char           **myargs = args;

107:   PetscInitialize(&myargc,&myargs,filename,help);
108:   PetscPopSignalHandler();
109:   PetscBeganMPI = PETSC_FALSE;
110:   PetscFunctionReturn(ierr);
111: }

113: /*
114:       Used by MATLAB and Julia interface to get communicator
115: */
116: PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
117: {
119:   *comm = PETSC_COMM_SELF;
120:   return(0);
121: }

123: /*@C
124:       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
125:         the command line arguments.

127:    Collective

129:    Level: advanced

131: .seealso: PetscInitialize(), PetscInitializeFortran()
132: @*/
133: PetscErrorCode  PetscInitializeNoArguments(void)
134: {
136:   int            argc   = 0;
137:   char           **args = 0;

140:   PetscInitialize(&argc,&args,NULL,NULL);
141:   PetscFunctionReturn(ierr);
142: }

144: /*@
145:       PetscInitialized - Determine whether PETSc is initialized.

147:    Level: beginner

149: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
150: @*/
151: PetscErrorCode PetscInitialized(PetscBool  *isInitialized)
152: {
153:   *isInitialized = PetscInitializeCalled;
154:   return 0;
155: }

157: /*@
158:       PetscFinalized - Determine whether PetscFinalize() has been called yet

160:    Level: developer

162: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
163: @*/
164: PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
165: {
166:   *isFinalized = PetscFinalizeCalled;
167:   return 0;
168: }

170: extern PetscErrorCode PetscOptionsCheckInitial_Private(void);

172: /*
173:        This function is the MPI reduction operation used to compute the sum of the
174:    first half of the datatype and the max of the second half.
175: */
176: MPI_Op MPIU_MAXSUM_OP = 0;

178: PETSC_INTERN void MPIAPI MPIU_MaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
179: {
180:   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;

183:   if (*datatype != MPIU_2INT) {
184:     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
185:     MPI_Abort(MPI_COMM_WORLD,1);
186:   }

188:   for (i=0; i<count; i++) {
189:     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
190:     xout[2*i+1] += xin[2*i+1];
191:   }
192:   PetscFunctionReturnVoid();
193: }

195: /*
196:     Returns the max of the first entry owned by this processor and the
197: sum of the second entry.

199:     The reason sizes[2*i] contains lengths sizes[2*i+1] contains flag of 1 if length is nonzero
200: is so that the MPIU_MAXSUM_OP() can set TWO values, if we passed in only sizes[i] with lengths
201: there would be no place to store the both needed results.
202: */
203: PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt sizes[],PetscInt *max,PetscInt *sum)
204: {

208: #if defined(PETSC_HAVE_MPI_REDUCE_SCATTER_BLOCK)
209:   {
210:     struct {PetscInt max,sum;} work;
211:     MPI_Reduce_scatter_block((void*)sizes,&work,1,MPIU_2INT,MPIU_MAXSUM_OP,comm);
212:     *max = work.max;
213:     *sum = work.sum;
214:   }
215: #else
216:   {
217:     PetscMPIInt    size,rank;
218:     struct {PetscInt max,sum;} *work;
219:     MPI_Comm_size(comm,&size);
220:     MPI_Comm_rank(comm,&rank);
221:     PetscMalloc1(size,&work);
222:     MPIU_Allreduce((void*)sizes,work,size,MPIU_2INT,MPIU_MAXSUM_OP,comm);
223:     *max = work[rank].max;
224:     *sum = work[rank].sum;
225:     PetscFree(work);
226:   }
227: #endif
228:   return(0);
229: }

231: /* ----------------------------------------------------------------------------*/

233: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
234: MPI_Op MPIU_SUM = 0;

236: PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
237: {
238:   PetscInt i,count = *cnt;

241:   if (*datatype == MPIU_REAL) {
242:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
243:     for (i=0; i<count; i++) xout[i] += xin[i];
244:   }
245: #if defined(PETSC_HAVE_COMPLEX)
246:   else if (*datatype == MPIU_COMPLEX) {
247:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
248:     for (i=0; i<count; i++) xout[i] += xin[i];
249:   }
250: #endif
251:   else {
252:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
253:     MPI_Abort(MPI_COMM_WORLD,1);
254:   }
255:   PetscFunctionReturnVoid();
256: }
257: #endif

259: #if defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
260: MPI_Op MPIU_MAX = 0;
261: MPI_Op MPIU_MIN = 0;

263: PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
264: {
265:   PetscInt i,count = *cnt;

268:   if (*datatype == MPIU_REAL) {
269:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
270:     for (i=0; i<count; i++) xout[i] = PetscMax(xout[i],xin[i]);
271:   }
272: #if defined(PETSC_HAVE_COMPLEX)
273:   else if (*datatype == MPIU_COMPLEX) {
274:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
275:     for (i=0; i<count; i++) {
276:       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
277:     }
278:   }
279: #endif
280:   else {
281:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
282:     MPI_Abort(MPI_COMM_WORLD,1);
283:   }
284:   PetscFunctionReturnVoid();
285: }

287: PETSC_EXTERN void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
288: {
289:   PetscInt    i,count = *cnt;

292:   if (*datatype == MPIU_REAL) {
293:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
294:     for (i=0; i<count; i++) xout[i] = PetscMin(xout[i],xin[i]);
295:   }
296: #if defined(PETSC_HAVE_COMPLEX)
297:   else if (*datatype == MPIU_COMPLEX) {
298:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
299:     for (i=0; i<count; i++) {
300:       xout[i] = PetscRealPartComplex(xout[i])>PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
301:     }
302:   }
303: #endif
304:   else {
305:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
306:     MPI_Abort(MPI_COMM_WORLD,1);
307:   }
308:   PetscFunctionReturnVoid();
309: }
310: #endif

312: /*
313:    Private routine to delete internal tag/name counter storage when a communicator is freed.

315:    This is called by MPI, not by users. This is called by MPI_Comm_free() when the communicator that has this  data as an attribute is freed.

317:    Note: this is declared extern "C" because it is passed to MPI_Keyval_create()

319: */
320: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
321: {

325:   PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
326:   PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
327:   PetscFunctionReturn(MPI_SUCCESS);
328: }

330: /*
331:   This is invoked on the outer comm as a result of either PetscCommDestroy() (via MPI_Attr_delete) or when the user
332:   calls MPI_Comm_free().

334:   This is the only entry point for breaking the links between inner and outer comms.

336:   This is called by MPI, not by users. This is called when MPI_Comm_free() is called on the communicator.

338:   Note: this is declared extern "C" because it is passed to MPI_Keyval_create()

340: */
341: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
342: {
344:   PetscMPIInt    flg;
345:   union {MPI_Comm comm; void *ptr;} icomm,ocomm;

348:   if (keyval != Petsc_InnerComm_keyval) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Unexpected keyval");
349:   icomm.ptr = attr_val;

351:   MPI_Attr_get(icomm.comm,Petsc_OuterComm_keyval,&ocomm,&flg);
352:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
353:   if (ocomm.comm != comm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm has reference to non-matching outer comm");
354:   MPI_Attr_delete(icomm.comm,Petsc_OuterComm_keyval); /* Calls Petsc_DelComm_Inner */
355:   PetscInfo1(0,"User MPI_Comm %ld is being freed after removing reference from inner PETSc comm to this outer comm\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
356:   PetscFunctionReturn(MPI_SUCCESS);
357: }

359: /*
360:  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Attr_delete.  It should not be reached any other way.
361:  */
362: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
363: {

367:   PetscInfo1(0,"Removing reference to PETSc communicator embedded in a user MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
368:   PetscFunctionReturn(MPI_SUCCESS);
369: }

371: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
372: #if !defined(PETSC_WORDS_BIGENDIAN)
373: PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
374: PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
375: PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
376: #endif
377: #endif

379: int  PetscGlobalArgc   = 0;
380: char **PetscGlobalArgs = 0;
381: PetscSegBuffer PetscCitationsList;

383: PetscErrorCode PetscCitationsInitialize(void)
384: {

388:   PetscSegBufferCreate(1,10000,&PetscCitationsList);
389:   PetscCitationsRegister("@TechReport{petsc-user-ref,\n  Author = {Satish Balay and Shrirang Abhyankar and Mark F. Adams and Jed Brown and Peter Brune\n            and Kris Buschelman and Lisandro Dalcin and Victor Eijkhout and William D. Gropp\n            and Dinesh Kaushik and Matthew G. Knepley\n            and Lois Curfman McInnes and Karl Rupp and Barry F. Smith\n            and Stefano Zampini and Hong Zhang and Hong Zhang},\n  Title = {{PETS}c Users Manual},\n  Number = {ANL-95/11 - Revision 3.7},\n  Institution = {Argonne National Laboratory},\n  Year = {2016}\n}\n",NULL);
390:   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);
391:   return(0);
392: }

394: /*@C
395:    PetscGetArgs - Allows you to access the raw command line arguments anywhere
396:      after PetscInitialize() is called but before PetscFinalize().

398:    Not Collective

400:    Output Parameters:
401: +  argc - count of number of command line arguments
402: -  args - the command line arguments

404:    Level: intermediate

406:    Notes:
407:       This is usually used to pass the command line arguments into other libraries
408:    that are called internally deep in PETSc or the application.

410:       The first argument contains the program name as is normal for C arguments.

412:    Concepts: command line arguments

414: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArguments()

416: @*/
417: PetscErrorCode  PetscGetArgs(int *argc,char ***args)
418: {
420:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
421:   *argc = PetscGlobalArgc;
422:   *args = PetscGlobalArgs;
423:   return(0);
424: }

426: /*@C
427:    PetscGetArguments - Allows you to access the  command line arguments anywhere
428:      after PetscInitialize() is called but before PetscFinalize().

430:    Not Collective

432:    Output Parameters:
433: .  args - the command line arguments

435:    Level: intermediate

437:    Notes:
438:       This does NOT start with the program name and IS null terminated (final arg is void)

440:    Concepts: command line arguments

442: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscFreeArguments()

444: @*/
445: PetscErrorCode  PetscGetArguments(char ***args)
446: {
447:   PetscInt       i,argc = PetscGlobalArgc;

451:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
452:   if (!argc) {*args = 0; return(0);}
453:   PetscMalloc1(argc,args);
454:   for (i=0; i<argc-1; i++) {
455:     PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);
456:   }
457:   (*args)[argc-1] = 0;
458:   return(0);
459: }

461: /*@C
462:    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()

464:    Not Collective

466:    Output Parameters:
467: .  args - the command line arguments

469:    Level: intermediate

471:    Concepts: command line arguments

473: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscGetArguments()

475: @*/
476: PetscErrorCode  PetscFreeArguments(char **args)
477: {
478:   PetscInt       i = 0;

482:   if (!args) return(0);
483:   while (args[i]) {
484:     PetscFree(args[i]);
485:     i++;
486:   }
487:   PetscFree(args);
488:   return(0);
489: }

491: #if defined(PETSC_HAVE_SAWS)
492: #include <petscconfiginfo.h>

494: PetscErrorCode  PetscInitializeSAWs(const char help[])
495: {
496:   if (!PetscGlobalRank) {
497:     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
498:     int            port;
499:     PetscBool      flg,rootlocal = PETSC_FALSE,flg2,selectport = PETSC_FALSE;
500:     size_t         applinelen,introlen;
502:     char           sawsurl[256];

504:     PetscOptionsHasName(NULL,NULL,"-saws_log",&flg);
505:     if (flg) {
506:       char  sawslog[PETSC_MAX_PATH_LEN];

508:       PetscOptionsGetString(NULL,NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);
509:       if (sawslog[0]) {
510:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
511:       } else {
512:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
513:       }
514:     }
515:     PetscOptionsGetString(NULL,NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);
516:     if (flg) {
517:       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
518:     }
519:     PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select",&selectport,NULL);
520:     if (selectport) {
521:         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
522:         PetscStackCallSAWs(SAWs_Set_Port,(port));
523:     } else {
524:       PetscOptionsGetInt(NULL,NULL,"-saws_port",&port,&flg);
525:       if (flg) {
526:         PetscStackCallSAWs(SAWs_Set_Port,(port));
527:       }
528:     }
529:     PetscOptionsGetString(NULL,NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);
530:     if (flg) {
531:       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
532:       PetscStrcmp(root,".",&rootlocal);
533:     } else {
534:       PetscOptionsHasName(NULL,NULL,"-saws_options",&flg);
535:       if (flg) {
536:         PetscStrreplace(PETSC_COMM_WORLD,"${PETSC_DIR}/share/petsc/saws",root,PETSC_MAX_PATH_LEN);
537:         PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
538:       }
539:     }
540:     PetscOptionsHasName(NULL,NULL,"-saws_local",&flg2);
541:     if (flg2) {
542:       char jsdir[PETSC_MAX_PATH_LEN];
543:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
544:       PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);
545:       PetscTestDirectory(jsdir,'r',&flg);
546:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
547:       PetscStackCallSAWs(SAWs_Push_Local_Header,());
548:     }
549:     PetscGetProgramName(programname,64);
550:     PetscStrlen(help,&applinelen);
551:     introlen   = 4096 + applinelen;
552:     applinelen += 1024;
553:     PetscMalloc(applinelen,&appline);
554:     PetscMalloc(introlen,&intro);

556:     if (rootlocal) {
557:       PetscSNPrintf(appline,applinelen,"%s.c.html",programname);
558:       PetscTestFile(appline,'r',&rootlocal);
559:     }
560:     PetscOptionsGetAll(NULL,&options);
561:     if (rootlocal && help) {
562:       PetscSNPrintf(appline,applinelen,"<center> Running <a href=\"%s.c.html\">%s</a> %s</center><br><center><pre>%s</pre></center><br>\n",programname,programname,options,help);
563:     } else if (help) {
564:       PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>",programname,options,help);
565:     } else {
566:       PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
567:     }
568:     PetscFree(options);
569:     PetscGetVersion(version,sizeof(version));
570:     PetscSNPrintf(intro,introlen,"<body>\n"
571:                                     "<center><h2> <a href=\"http://www.mcs.anl.gov/petsc\">PETSc</a> Application Web server powered by <a href=\"https://bitbucket.org/saws/saws\">SAWs</a> </h2></center>\n"
572:                                     "<center>This is the default PETSc application dashboard, from it you can access any published PETSc objects or logging data</center><br><center>%s configured with %s</center><br>\n"
573:                                     "%s",version,petscconfigureoptions,appline);
574:     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
575:     PetscFree(intro);
576:     PetscFree(appline);
577:     if (selectport) {
578:       PetscBool silent;

580:       SAWs_Initialize();
581:       /* another process may have grabbed the port so keep trying */
582:       while (ierr) {
583:         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
584:         PetscStackCallSAWs(SAWs_Set_Port,(port));
585:         SAWs_Initialize();
586:       }

588:       PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select_silent",&silent,NULL);
589:       if (!silent) {
590:         PetscStackCallSAWs(SAWs_Get_FullURL,(sizeof(sawsurl),sawsurl));
591:         PetscPrintf(PETSC_COMM_WORLD,"Point your browser to %s for SAWs\n",sawsurl);
592:       }
593:     } else {
594:       PetscStackCallSAWs(SAWs_Initialize,());
595:     }
596:     PetscCitationsRegister("@TechReport{ saws,\n"
597:                                   "  Author = {Matt Otten and Jed Brown and Barry Smith},\n"
598:                                   "  Title  = {Scientific Application Web Server (SAWs) Users Manual},\n"
599:                                   "  Institution = {Argonne National Laboratory},\n"
600:                                   "  Year   = 2013\n}\n",NULL);
601:   }
602:   return(0);
603: }
604: #endif

606: /*@C
607:    PetscInitialize - Initializes the PETSc database and MPI.
608:    PetscInitialize() calls MPI_Init() if that has yet to be called,
609:    so this routine should always be called near the beginning of
610:    your program -- usually the very first line!

612:    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set

614:    Input Parameters:
615: +  argc - count of number of command line arguments
616: .  args - the command line arguments
617: .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
618:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
619: -  help - [optional] Help message to print, use NULL for no message

621:    If you wish PETSc code to run ONLY on a subcommunicator of MPI_COMM_WORLD, create that
622:    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize(). Thus if you are running a
623:    four process job and two processes will run PETSc and have PetscInitialize() and PetscFinalize() and two process will not,
624:    then do this. If ALL processes in the job are using PetscInitialize() and PetscFinalize() then you don't need to do this, even
625:    if different subcommunicators of the job are doing different things with PETSc.

627:    Options Database Keys:
628: +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
629: .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
630: .  -on_error_emacs <machinename> causes emacsclient to jump to error file
631: .  -on_error_abort calls abort() when error detected (no traceback)
632: .  -on_error_mpiabort calls MPI_abort() when error detected
633: .  -error_output_stderr prints error messages to stderr instead of the default stdout
634: .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
635: .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
636: .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
637: .  -stop_for_debugger - Print message on how to attach debugger manually to
638:                         process and wait (-debugger_pause) seconds for attachment
639: .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
640: .  -malloc no - Indicates not to use error-checking malloc
641: .  -malloc_debug - check for memory corruption at EVERY malloc or free
642: .  -malloc_dump - prints a list of all unfreed memory at the end of the run
643: .  -malloc_test - like -malloc_dump -malloc_debug, but only active for debugging builds
644: .  -fp_trap - Stops on floating point exceptions (Note that on the
645:               IBM RS6000 this slows code by at least a factor of 10.)
646: .  -no_signal_handler - Indicates not to trap error signals
647: .  -shared_tmp - indicates /tmp directory is shared by all processors
648: .  -not_shared_tmp - each processor has own /tmp
649: .  -tmp - alternative name of /tmp directory
650: .  -get_total_flops - returns total flops done by all processors
651: -  -memory_view - Print memory usage at end of run

653:    Options Database Keys for Profiling:
654:    See Users-Manual: Chapter 13 Profiling for details.
655: +  -info <optional filename> - Prints verbose information to the screen
656: .  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
657: .  -log_sync - Log the synchronization in scatters, inner products and norms
658: .  -log_trace [filename] - Print traces of all PETSc calls to the screen (useful to determine where a program
659:         hangs without running in the debugger).  See PetscLogTraceBegin().
660: .  -log_view [:filename:format] - Prints summary of flop and timing information to screen or file, see PetscLogView().
661: .  -log_summary [filename] - (Deprecated, use -log_view) Prints summary of flop and timing information to screen. If the filename is specified the
662:         summary is written to the file.  See PetscLogView().
663: .  -log_exclude: <vec,mat,pc.ksp,snes> - excludes subset of object classes from logging
664: .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
665: .  -log [filename] - Logs basic profiline information  See PetscLogDump().
666: -  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)

668:     Only one of -log_trace, -log_view, -log_view, -log_all, -log, or -log_mpe may be used at a time

670:    Options Database Keys for SAWs:
671: +  -saws_port <portnumber> - port number to publish SAWs data, default is 8080
672: .  -saws_port_auto_select - have SAWs select a new unique port number where it publishes the data, the URL is printed to the screen
673:                             this is useful when you are running many jobs that utilize SAWs at the same time
674: .  -saws_log <filename> - save a log of all SAWs communication
675: .  -saws_https <certificate file> - have SAWs use HTTPS instead of HTTP
676: -  -saws_root <directory> - allow SAWs to have access to the given directory to search for requested resources and files

678:    Environmental Variables:
679: +   PETSC_TMP - alternative tmp directory
680: .   PETSC_SHARED_TMP - tmp is shared by all processes
681: .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
682: .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
683: -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to


686:    Level: beginner

688:    Notes:
689:    If for some reason you must call MPI_Init() separately, call
690:    it before PetscInitialize().

692:    Fortran Version:
693:    In Fortran this routine has the format
694: $       call PetscInitialize(file,ierr)

696: +   ierr - error return code
697: -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL_CHARACTER to not check for
698:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files

700:    Important Fortran Note:
701:    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
702:    null character string; you CANNOT just use NULL as
703:    in the C version. See Users-Manual: Chapter 11 PETSc for Fortran Users for details.

705:    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
706:    calling PetscInitialize().

708:    Concepts: initializing PETSc

710: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()

712: @*/
713: PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
714: {
716:   PetscMPIInt    flag, size;
717:   PetscBool      flg;
718:   char           hostname[256];
719: #if defined(PETSC_HAVE_CUDA)
720:   cublasStatus_t cberr;
721: #endif

724:   if (PetscInitializeCalled) return(0);

726:   /* these must be initialized in a routine, not as a constant declaration*/
727:   PETSC_STDOUT = stdout;
728:   PETSC_STDERR = stderr;

730:   /* on Windows - set printf to default to printing 2 digit exponents */
731: #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
732:   _set_output_format(_TWO_DIGIT_EXPONENT);
733: #endif

735:   PetscOptionsCreateDefault();

737:   /*
738:      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
739:      it that it sets args[0] on all processors to be args[0] on the first processor.
740:   */
741:   if (argc && *argc) {
742:     PetscSetProgramName(**args);
743:   } else {
744:     PetscSetProgramName("Unknown Name");
745:   }

747:   MPI_Initialized(&flag);
748:   if (!flag) {
749:     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");
750: #if defined(PETSC_HAVE_MPI_INIT_THREAD)
751:     {
752:       PetscMPIInt provided;
753:       MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);
754:     }
755: #else
756:     MPI_Init(argc,args);
757: #endif
758:     PetscBeganMPI = PETSC_TRUE;
759:   }
760:   if (argc && args) {
761:     PetscGlobalArgc = *argc;
762:     PetscGlobalArgs = *args;
763:   }
764:   PetscFinalizeCalled = PETSC_FALSE;
765:   PetscSpinlockCreate(&PetscViewerASCIISpinLockOpen);
766:   PetscSpinlockCreate(&PetscViewerASCIISpinLockStdout);
767:   PetscSpinlockCreate(&PetscViewerASCIISpinLockStderr);
768:   PetscSpinlockCreate(&PetscCommSpinLock);

770:   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
771:   MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);

773:   /* Done after init due to a bug in MPICH-GM? */
774:   PetscErrorPrintfInitialize();

776:   MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);
777:   MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);

779:   MPIU_BOOL = MPI_INT;
780:   MPIU_ENUM = MPI_INT;

782:   /*
783:      Initialized the global complex variable; this is because with
784:      shared libraries the constructors for global variables
785:      are not called; at least on IRIX.
786:   */
787: #if defined(PETSC_HAVE_COMPLEX)
788:   {
789: #if defined(PETSC_CLANGUAGE_CXX)
790:     PetscComplex ic(0.0,1.0);
791:     PETSC_i = ic;
792: #elif defined(PETSC_CLANGUAGE_C)
793:     PETSC_i = _Complex_I;
794: #endif
795:   }

797: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
798:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);
799:   MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);
800:   MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);
801:   MPI_Type_commit(&MPIU_C_COMPLEX);
802: #endif
803: #endif /* PETSC_HAVE_COMPLEX */

805:   /*
806:      Create the PETSc MPI reduction operator that sums of the first
807:      half of the entries and maxes the second half.
808:   */
809:   MPI_Op_create(MPIU_MaxSum_Local,1,&MPIU_MAXSUM_OP);

811: #if defined(PETSC_USE_REAL___FLOAT128)
812:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);
813:   MPI_Type_commit(&MPIU___FLOAT128);
814: #if defined(PETSC_HAVE_COMPLEX)
815:   MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);
816:   MPI_Type_commit(&MPIU___COMPLEX128);
817: #endif
818:   MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);
819:   MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);
820: #elif defined(PETSC_USE_REAL___FP16)
821:   MPI_Type_contiguous(2,MPI_CHAR,&MPIU___FP16);
822:   MPI_Type_commit(&MPIU___FP16);
823:   MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);
824:   MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);
825: #endif

827: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
828:   MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);
829: #endif

831:   MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);
832:   MPI_Type_commit(&MPIU_2SCALAR);

834: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
835:   MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);
836:   MPI_Type_commit(&MPIU_2INT);
837: #endif


840:   /*
841:      Attributes to be set on PETSc communicators
842:   */
843:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);
844:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);
845:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);

847:   /*
848:      Build the options database
849:   */
850:   PetscOptionsInsert(NULL,argc,args,file);


853:   /*
854:      Print main application help message
855:   */
856:   PetscOptionsHasName(NULL,NULL,"-help",&flg);
857:   if (help && flg) {
858:     PetscPrintf(PETSC_COMM_WORLD,help);
859:   }
860:   PetscOptionsCheckInitial_Private();

862:   PetscCitationsInitialize();

864: #if defined(PETSC_HAVE_SAWS)
865:   PetscInitializeSAWs(help);
866: #endif

868:   /* Creates the logging data structures; this is enabled even if logging is not turned on */
869: #if defined(PETSC_USE_LOG)
870:   PetscLogInitialize();
871: #endif

873:   /*
874:      Load the dynamic libraries (on machines that support them), this registers all
875:      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
876:   */
877:   PetscInitialize_DynamicLibraries();

879:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
880:   PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);
881:   PetscGetHostName(hostname,256);
882:   PetscInfo1(0,"Running on machine: %s\n",hostname);

884:   PetscOptionsCheckInitial_Components();
885:   /* Check the options database for options related to the options database itself */
886:   PetscOptionsSetFromOptions(NULL);

888: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
889:   /*
890:       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI

892:       Currently not used because it is not supported by MPICH.
893:   */
894: #if !defined(PETSC_WORDS_BIGENDIAN)
895:   MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);
896: #endif
897: #endif

899: #if defined(PETSC_HAVE_CUDA)
900:   flg  = PETSC_TRUE;
901:   PetscOptionsGetBool(NULL,NULL,"-cublas",&flg,NULL);
902:   if (flg) {
903:     PetscMPIInt p;
904:     for (p = 0; p < PetscGlobalSize; ++p) {
905:       if (p == PetscGlobalRank) {
906:         cberr = cublasCreate(&cublasv2handle);CHKERRCUBLAS(cberr);
907:       }
908:       MPI_Barrier(PETSC_COMM_WORLD);
909:     }
910:   }
911: #endif

913:   PetscOptionsHasName(NULL,NULL,"-python",&flg);
914:   if (flg) {
915:     PetscInitializeCalled = PETSC_TRUE;
916:     PetscPythonInitialize(NULL,NULL);
917:   }

919:   /*
920:       Setup building of stack frames for all function calls
921:   */
922: #if defined(PETSC_USE_DEBUG) && !defined(PETSC_HAVE_THREADSAFETY)
923:   PetscStackCreate();
924: #endif

926: #if defined(PETSC_SERIALIZE_FUNCTIONS)
927:   PetscFPTCreate(10000);
928: #endif


931:   /*
932:       Once we are completedly initialized then we can set this variables
933:   */
934:   PetscInitializeCalled = PETSC_TRUE;
935:   return(0);
936: }

938: #if defined(PETSC_USE_LOG)
939: extern PetscObject *PetscObjects;
940: extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
941: extern PetscBool   PetscObjectsLog;
942: #endif

944: /*@C
945:    PetscFinalize - Checks for options to be called at the conclusion
946:    of the program. MPI_Finalize() is called only if the user had not
947:    called MPI_Init() before calling PetscInitialize().

949:    Collective on PETSC_COMM_WORLD

951:    Options Database Keys:
952: +  -options_table - Calls PetscOptionsView()
953: .  -options_left - Prints unused options that remain in the database
954: .  -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
955: .  -mpidump - Calls PetscMPIDump()
956: .  -malloc_dump - Calls PetscMallocDump()
957: .  -malloc_info - Prints total memory usage
958: -  -malloc_log - Prints summary of memory usage

960:    Level: beginner

962:    Note:
963:    See PetscInitialize() for more general runtime options.

965: .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
966: @*/
967: PetscErrorCode  PetscFinalize(void)
968: {
970:   PetscMPIInt    rank;
971:   PetscInt       nopt;
972:   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
973:   PetscBool      flg;
974: #if defined(PETSC_USE_LOG)
975:   char           mname[PETSC_MAX_PATH_LEN];
976: #endif
977: #if defined(PETSC_HAVE_CUDA)
978:   cublasStatus_t cberr;
979: #endif

982:   if (!PetscInitializeCalled) {
983:     printf("PetscInitialize() must be called before PetscFinalize()\n");
984:     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
985:   }
986:   PetscInfo(NULL,"PetscFinalize() called\n");

988:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

990:   PetscOptionsHasName(NULL,NULL,"-citations",&flg);
991:   if (flg) {
992:     char  *cits, filename[PETSC_MAX_PATH_LEN];
993:     FILE  *fd = PETSC_STDOUT;

995:     PetscOptionsGetString(NULL,NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);
996:     if (filename[0]) {
997:       PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);
998:     }
999:     PetscSegBufferGet(PetscCitationsList,1,&cits);
1000:     cits[0] = 0;
1001:     PetscSegBufferExtractAlloc(PetscCitationsList,&cits);
1002:     PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");
1003:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1004:     PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);
1005:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1006:     PetscFClose(PETSC_COMM_WORLD,fd);
1007:     PetscFree(cits);
1008:   }
1009:   PetscSegBufferDestroy(&PetscCitationsList);

1011: #if defined(PETSC_HAVE_SSL) && defined(PETSC_USE_SOCKET_VIEWER)
1012:   /* TextBelt is run for testing purposes only, please do not use this feature often */
1013:   {
1014:     PetscInt nmax = 2;
1015:     char     **buffs;
1016:     PetscMalloc1(2,&buffs);
1017:     PetscOptionsGetStringArray(NULL,NULL,"-textbelt",buffs,&nmax,&flg1);
1018:     if (flg1) {
1019:       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-textbelt requires either the phone number or number,\"message\"");
1020:       if (nmax == 1) {
1021:         PetscMalloc1(128,&buffs[1]);
1022:         PetscGetProgramName(buffs[1],32);
1023:         PetscStrcat(buffs[1]," has completed");
1024:       }
1025:       PetscTextBelt(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);
1026:       PetscFree(buffs[0]);
1027:       PetscFree(buffs[1]);
1028:     }
1029:     PetscFree(buffs);
1030:   }
1031:   {
1032:     PetscInt nmax = 2;
1033:     char     **buffs;
1034:     PetscMalloc1(2,&buffs);
1035:     PetscOptionsGetStringArray(NULL,NULL,"-tellmycell",buffs,&nmax,&flg1);
1036:     if (flg1) {
1037:       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-tellmycell requires either the phone number or number,\"message\"");
1038:       if (nmax == 1) {
1039:         PetscMalloc1(128,&buffs[1]);
1040:         PetscGetProgramName(buffs[1],32);
1041:         PetscStrcat(buffs[1]," has completed");
1042:       }
1043:       PetscTellMyCell(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);
1044:       PetscFree(buffs[0]);
1045:       PetscFree(buffs[1]);
1046:     }
1047:     PetscFree(buffs);
1048:   }
1049: #endif
1050:   /*
1051:     It should be safe to cancel the options monitors, since we don't expect to be setting options
1052:     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1053:     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1054:   */
1055:   PetscOptionsMonitorCancel();

1057: #if defined(PETSC_SERIALIZE_FUNCTIONS)
1058:   PetscFPTDestroy();
1059: #endif


1062: #if defined(PETSC_HAVE_SAWS)
1063:   flg = PETSC_FALSE;
1064:   PetscOptionsGetBool(NULL,NULL,"-saw_options",&flg,NULL);
1065:   if (flg) {
1066:     PetscOptionsSAWsDestroy();
1067:   }
1068: #endif

1070: #if defined(PETSC_HAVE_X)
1071:   flg1 = PETSC_FALSE;
1072:   PetscOptionsGetBool(NULL,NULL,"-x_virtual",&flg1,NULL);
1073:   if (flg1) {
1074:     /*  this is a crude hack, but better than nothing */
1075:     PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);
1076:   }
1077: #endif

1079: #if !defined(PETSC_HAVE_THREADSAFETY)
1080:   PetscOptionsGetBool(NULL,NULL,"-malloc_info",&flg2,NULL);
1081:   if (!flg2) {
1082:     flg2 = PETSC_FALSE;
1083:     PetscOptionsGetBool(NULL,NULL,"-memory_view",&flg2,NULL);
1084:   }
1085:   if (flg2) {
1086:     PetscMemoryView(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");
1087:   }
1088: #endif

1090: #if defined(PETSC_USE_LOG)
1091:   flg1 = PETSC_FALSE;
1092:   PetscOptionsGetBool(NULL,NULL,"-get_total_flops",&flg1,NULL);
1093:   if (flg1) {
1094:     PetscLogDouble flops = 0;
1095:     MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);
1096:     PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);
1097:   }
1098: #endif


1101: #if defined(PETSC_USE_LOG)
1102: #if defined(PETSC_HAVE_MPE)
1103:   mname[0] = 0;

1105:   PetscOptionsGetString(NULL,NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);
1106:   if (flg1) {
1107:     if (mname[0]) {PetscLogMPEDump(mname);}
1108:     else          {PetscLogMPEDump(0);}
1109:   }
1110: #endif
1111:   mname[0] = 0;

1113:   PetscLogViewFromOptions();
1114:   PetscOptionsGetString(NULL,NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);
1115:   if (flg1) {
1116:     PetscViewer viewer;
1117:     (*PetscHelpPrintf)(PETSC_COMM_WORLD,"\n\n WARNING:   -log_summary is being deprecated; switch to -log_view\n\n\n");
1118:     if (mname[0]) {
1119:       PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);
1120:       PetscLogView(viewer);
1121:       PetscViewerDestroy(&viewer);
1122:     } else {
1123:       viewer = PETSC_VIEWER_STDOUT_WORLD;
1124:       PetscViewerPushFormat(viewer,PETSC_VIEWER_DEFAULT);
1125:       PetscLogView(viewer);
1126:       PetscViewerPopFormat(viewer);
1127:     }
1128:   }
1129:   mname[0] = 0;

1131:   PetscOptionsGetString(NULL,NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);
1132:   PetscOptionsGetString(NULL,NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);
1133:   if (flg1 || flg2) {
1134:     if (mname[0]) PetscLogDump(mname);
1135:     else          PetscLogDump(0);
1136:   }
1137: #endif

1139:   /*
1140:      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1141:   */
1142:   PetscObjectRegisterDestroyAll();

1144:   PetscStackDestroy();

1146:   flg1 = PETSC_FALSE;
1147:   PetscOptionsGetBool(NULL,NULL,"-no_signal_handler",&flg1,NULL);
1148:   if (!flg1) { PetscPopSignalHandler();}
1149:   flg1 = PETSC_FALSE;
1150:   PetscOptionsGetBool(NULL,NULL,"-mpidump",&flg1,NULL);
1151:   if (flg1) {
1152:     PetscMPIDump(stdout);
1153:   }
1154:   flg1 = PETSC_FALSE;
1155:   flg2 = PETSC_FALSE;
1156:   /* preemptive call to avoid listing this option in options table as unused */
1157:   PetscOptionsHasName(NULL,NULL,"-malloc_dump",&flg1);
1158:   PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);
1159:   PetscOptionsGetBool(NULL,NULL,"-options_view",&flg2,NULL);

1161:   if (flg2) {
1162:     PetscViewer viewer;
1163:     PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1164:     PetscViewerSetType(viewer,PETSCVIEWERASCII);
1165:     PetscOptionsView(NULL,viewer);
1166:     PetscViewerDestroy(&viewer);
1167:   }

1169:   /* to prevent PETSc -options_left from warning */
1170:   PetscOptionsHasName(NULL,NULL,"-nox",&flg1);
1171:   PetscOptionsHasName(NULL,NULL,"-nox_warning",&flg1);

1173:   flg3 = PETSC_FALSE; /* default value is required */
1174:   PetscOptionsGetBool(NULL,NULL,"-options_left",&flg3,&flg1);
1175:   PetscOptionsAllUsed(NULL,&nopt);
1176:   if (flg3) {
1177:     if (!flg2) { /* have not yet printed the options */
1178:       PetscViewer viewer;
1179:       PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1180:       PetscViewerSetType(viewer,PETSCVIEWERASCII);
1181:       PetscOptionsView(NULL,viewer);
1182:       PetscViewerDestroy(&viewer);
1183:     }
1184:     if (!nopt) {
1185:       PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");
1186:     } else if (nopt == 1) {
1187:       PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");
1188:     } else {
1189:       PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);
1190:     }
1191:   }
1192: #if defined(PETSC_USE_DEBUG)
1193:   if (nopt && !flg3 && !flg1) {
1194:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");
1195:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");
1196:     PetscOptionsLeft(NULL);
1197:   } else if (nopt && flg3) {
1198: #else
1199:   if (nopt && flg3) {
1200: #endif
1201:     PetscOptionsLeft(NULL);
1202:   }

1204: #if defined(PETSC_HAVE_SAWS)
1205:   if (!PetscGlobalRank) {
1206:     PetscStackSAWsViewOff();
1207:     PetscStackCallSAWs(SAWs_Finalize,());
1208:   }
1209: #endif

1211: #if defined(PETSC_USE_LOG)
1212:   /*
1213:        List all objects the user may have forgot to free
1214:   */
1215:   if (PetscObjectsLog) {
1216:     PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);
1217:     if (flg1) {
1218:       MPI_Comm local_comm;
1219:       char     string[64];

1221:       PetscOptionsGetString(NULL,NULL,"-objects_dump",string,64,NULL);
1222:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1223:       PetscSequentialPhaseBegin_Private(local_comm,1);
1224:       PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);
1225:       PetscSequentialPhaseEnd_Private(local_comm,1);
1226:       MPI_Comm_free(&local_comm);
1227:     }
1228:   }
1229: #endif

1231: #if defined(PETSC_USE_LOG)
1232:   PetscObjectsCounts    = 0;
1233:   PetscObjectsMaxCounts = 0;
1234:   PetscFree(PetscObjects);
1235: #endif

1237:   /*
1238:      Destroy any packages that registered a finalize
1239:   */
1240:   PetscRegisterFinalizeAll();

1242: #if defined(PETSC_USE_LOG)
1243:   PetscLogDestroy();
1244: #endif

1246:   /*
1247:      Print PetscFunctionLists that have not been properly freed

1249:   PetscFunctionListPrintAll();
1250:   */

1252:   if (petsc_history) {
1253:     PetscCloseHistoryFile(&petsc_history);
1254:     petsc_history = 0;
1255:   }
1256:   PetscOptionsHelpPrintedDestroy(&PetscOptionsHelpPrintedSingleton);

1258:   PetscInfoAllow(PETSC_FALSE,NULL);

1260: #if !defined(PETSC_HAVE_THREADSAFETY)
1261:   {
1262:     char fname[PETSC_MAX_PATH_LEN];
1263:     FILE *fd;
1264:     int  err;

1266:     fname[0] = 0;

1268:     PetscOptionsGetString(NULL,NULL,"-malloc_dump",fname,250,&flg1);
1269:     flg2 = PETSC_FALSE;
1270:     PetscOptionsGetBool(NULL,NULL,"-malloc_test",&flg2,NULL);
1271: #if defined(PETSC_USE_DEBUG)
1272:     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1273: #else
1274:     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1275: #endif
1276:     if (flg1 && fname[0]) {
1277:       char sname[PETSC_MAX_PATH_LEN];

1279:       sprintf(sname,"%s_%d",fname,rank);
1280:       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1281:       PetscMallocDump(fd);
1282:       err  = fclose(fd);
1283:       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1284:     } else if (flg1 || flg2) {
1285:       MPI_Comm local_comm;

1287:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1288:       PetscSequentialPhaseBegin_Private(local_comm,1);
1289:       PetscMallocDump(stdout);
1290:       PetscSequentialPhaseEnd_Private(local_comm,1);
1291:       MPI_Comm_free(&local_comm);
1292:     }
1293:   }

1295:   {
1296:     char fname[PETSC_MAX_PATH_LEN];
1297:     FILE *fd = NULL;

1299:     fname[0] = 0;

1301:     PetscOptionsGetString(NULL,NULL,"-malloc_log",fname,250,&flg1);
1302:     PetscOptionsHasName(NULL,NULL,"-malloc_log_threshold",&flg2);
1303:     if (flg1 && fname[0]) {
1304:       int err;

1306:       if (!rank) {
1307:         fd = fopen(fname,"w");
1308:         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1309:       }
1310:       PetscMallocDumpLog(fd);
1311:       if (fd) {
1312:         err = fclose(fd);
1313:         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1314:       }
1315:     } else if (flg1 || flg2) {
1316:       PetscMallocDumpLog(stdout);
1317:     }
1318:   }
1319: #endif

1321:   /*
1322:      Close any open dynamic libraries
1323:   */
1324:   PetscFinalize_DynamicLibraries();

1326: #if defined(PETSC_HAVE_CUDA)
1327:   flg  = PETSC_TRUE;
1328:   PetscOptionsGetBool(NULL,NULL,"-cublas",&flg,NULL);
1329:   if (flg) {
1330:     PetscInt p;
1331:     for (p = 0; p < PetscGlobalSize; ++p) {
1332:       if (p == PetscGlobalRank) {
1333:         if (cublasv2handle) {
1334:           cberr = cublasDestroy(cublasv2handle);CHKERRCUBLAS(cberr);
1335:         }
1336:       }
1337:       MPI_Barrier(PETSC_COMM_WORLD);
1338:     }
1339:   }
1340: #endif

1342:   /* Can be destroyed only after all the options are used */
1343:   PetscOptionsDestroyDefault();

1345:   PetscGlobalArgc = 0;
1346:   PetscGlobalArgs = 0;

1348: #if defined(PETSC_USE_REAL___FLOAT128)
1349:   MPI_Type_free(&MPIU___FLOAT128);
1350: #if defined(PETSC_HAVE_COMPLEX)
1351:   MPI_Type_free(&MPIU___COMPLEX128);
1352: #endif
1353:   MPI_Op_free(&MPIU_MAX);
1354:   MPI_Op_free(&MPIU_MIN);
1355: #elif defined(PETSC_USE_REAL___FP16)
1356:   MPI_Type_free(&MPIU___FP16);
1357:   MPI_Op_free(&MPIU_MAX);
1358:   MPI_Op_free(&MPIU_MIN);
1359: #endif

1361: #if defined(PETSC_HAVE_COMPLEX)
1362: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1363:   MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);
1364:   MPI_Type_free(&MPIU_C_COMPLEX);
1365: #endif
1366: #endif

1368: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
1369:   MPI_Op_free(&MPIU_SUM);
1370: #endif

1372:   MPI_Type_free(&MPIU_2SCALAR);
1373: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1374:   MPI_Type_free(&MPIU_2INT);
1375: #endif
1376:   MPI_Op_free(&MPIU_MAXSUM_OP);

1378:   /*
1379:      Destroy any known inner MPI_Comm's and attributes pointing to them
1380:      Note this will not destroy any new communicators the user has created.

1382:      If all PETSc objects were not destroyed those left over objects will have hanging references to
1383:      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1384:  */
1385:   {
1386:     PetscCommCounter *counter;
1387:     PetscMPIInt      flg;
1388:     MPI_Comm         icomm;
1389:     union {MPI_Comm comm; void *ptr;} ucomm;
1390:     MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);
1391:     if (flg) {
1392:       icomm = ucomm.comm;
1393:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1394:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1396:       MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);
1397:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1398:       MPI_Comm_free(&icomm);
1399:     }
1400:     MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);
1401:     if (flg) {
1402:       icomm = ucomm.comm;
1403:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1404:       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1406:       MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);
1407:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1408:       MPI_Comm_free(&icomm);
1409:     }
1410:   }

1412:   MPI_Keyval_free(&Petsc_Counter_keyval);
1413:   MPI_Keyval_free(&Petsc_InnerComm_keyval);
1414:   MPI_Keyval_free(&Petsc_OuterComm_keyval);

1416:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockOpen);
1417:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStdout);
1418:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStderr);
1419:   PetscSpinlockDestroy(&PetscCommSpinLock);

1421:   if (PetscBeganMPI) {
1422: #if defined(PETSC_HAVE_MPI_FINALIZED)
1423:     PetscMPIInt flag;
1424:     MPI_Finalized(&flag);
1425:     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1426: #endif
1427:     MPI_Finalize();
1428:   }
1429: /*

1431:      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1432:    the communicator has some outstanding requests on it. Specifically if the
1433:    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1434:    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1435:    is never freed as it should be. Thus one may obtain messages of the form
1436:    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1437:    memory was not freed.

1439: */
1440:   PetscMallocClear();

1442:   PetscInitializeCalled = PETSC_FALSE;
1443:   PetscFinalizeCalled   = PETSC_TRUE;
1444:   return(0);
1445: }

1447: #if defined(PETSC_MISSING_LAPACK_lsame_)
1448: PETSC_EXTERN int lsame_(char *a,char *b)
1449: {
1450:   if (*a == *b) return 1;
1451:   if (*a + 32 == *b) return 1;
1452:   if (*a - 32 == *b) return 1;
1453:   return 0;
1454: }
1455: #endif

1457: #if defined(PETSC_MISSING_LAPACK_lsame)
1458: PETSC_EXTERN int lsame(char *a,char *b)
1459: {
1460:   if (*a == *b) return 1;
1461:   if (*a + 32 == *b) return 1;
1462:   if (*a - 32 == *b) return 1;
1463:   return 0;
1464: }
1465: #endif