1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.2 1996/08/27 22:21:34 scrappy Exp $
13 * InitPostgres() is the function called from PostgresMain
14 * which does all non-trival initialization, mainly by calling
15 * all the other initialization functions. InitPostgres()
16 * is only used within the "postgres" backend and so that routine
17 * is in tcop/postgres.c InitPostgres() is needed in cinterface.a
18 * because things like the bootstrap backend program need it. Hence
19 * you find that in this file...
21 * If you feel the need to add more initialization code, it should be
22 * done in InitPostgres() or someplace lower. Do not start
23 * putting stuff in PostgresMain - if you do then someone
24 * will have to clean it up later, and it's not going to be me!
27 *-------------------------------------------------------------------------
33 #include <sys/types.h>
38 #include "access/heapam.h"
39 #include "access/xact.h"
40 #include "storage/bufmgr.h"
41 #include "access/transam.h" /* XXX dependency problem */
42 #include "utils/tqual.h"
43 #include "utils/syscache.h"
44 #include "storage/bufpage.h" /* for page layout, for InitMyDatabaseId() */
45 #include "storage/sinval.h"
46 #include "storage/sinvaladt.h"
47 #include "storage/lmgr.h"
49 #include "miscadmin.h" /* for global decls */
50 #include "utils/portal.h" /* for EnablePortalManager, etc. */
52 #include "utils/exc.h" /* for EnableExceptionHandling, etc. */
53 #include "fmgr.h" /* for EnableDynamicFunctionManager, etc. */
54 #include "utils/elog.h"
55 #include "utils/palloc.h"
56 #include "utils/mcxt.h" /* for EnableMemoryContext, etc. */
58 #include "catalog/catname.h"
59 #include "catalog/pg_database.h"
61 #include "port-protos.h"
62 #include "libpq/libpq-be.h"
65 static IPCKey PostgresIpcKey;
70 #define private static
71 #else /* !defined(EBUG) */
73 #endif /* !defined(EBUG) */
74 #endif /* !defined(private) */
76 /* ----------------------------------------------------------------
77 * InitPostgres support
78 * ----------------------------------------------------------------
81 /* --------------------------------
82 * InitMyDatabaseId() -- Find and record the OID of the database we are
85 * The database's oid forms half of the unique key for the system
86 * caches and lock tables. We therefore want it initialized before
87 * we open any relations, since opening relations puts things in the
88 * cache. To get around this problem, this code opens and scans the
89 * pg_database relation by hand.
91 * This algorithm relies on the fact that first attribute in the
92 * pg_database relation schema is the database name. It also knows
93 * about the internal format of tuples on disk and the length of
94 * the datname attribute. It knows the location of the pg_database
97 * This code is called from InitDatabase(), after we chdir() to the
98 * database directory but before we open any relations.
99 * --------------------------------
112 Form_pg_database tup_db;
115 * At bootstrap time, we don't need to check the oid of the database
116 * in use, since we're not using shared memory. This is lucky, since
117 * the database may not be in the tables yet.
120 if (IsBootstrapProcessingMode()) {
125 dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2);
126 sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR);
127 fileflags = O_RDONLY;
129 fileflags |= _O_BINARY;
132 if ((dbfd = open(dbfname, O_RDONLY, 0666)) < 0)
133 elog(FATAL, "Cannot open %s", dbfname);
138 * read and examine every page in pg_database
140 * Raw I/O! Read those tuples the hard way! Yow!
142 * Why don't we use the access methods or move this code
143 * someplace else? This is really pg_database schema dependent
144 * code. Perhaps it should go in lib/catalog/pg_database?
147 * mao replies 4 apr 91: yeah, maybe this should be moved to
148 * lib/catalog. however, we CANNOT use the access methods since
149 * those use the buffer cache, which uses the relation cache, which
150 * requires that the dbid be set, which is what we're trying to do
154 pg = (Page) palloc(BLCKSZ);
155 ph = (PageHeader) pg;
157 while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ) {
158 max = PageGetMaxOffsetNumber(pg);
160 /* look at each tuple on the page */
161 for (i = 0; i <= max; i++) {
164 /* if it's a freed tuple, ignore it */
165 if (!(ph->pd_linp[i].lp_flags & LP_USED))
168 /* get a pointer to the tuple itself */
169 offset = (int) ph->pd_linp[i].lp_off;
170 tup = (HeapTuple) (((char *) pg) + offset);
173 * if the tuple has been deleted (the database was destroyed),
174 * skip this tuple. XXX warning, will robinson: violation of
175 * transaction semantics happens right here. we should check
176 * to be sure that the xact that deleted this tuple actually
177 * committed. only way to do this at init time is to paw over
178 * the log relation by hand, too. let's be optimistic.
180 * XXX This is an evil type cast. tup->t_xmax is char[5] while
181 * TransactionId is struct * { char data[5] }. It works but
182 * if data is ever moved and no longer the first field this
183 * will be broken!! -mer 11 Nov 1991.
185 if (TransactionIdIsValid((TransactionId)tup->t_xmax))
189 * Okay, see if this is the one we want.
190 * XXX 1 july 91: mao and mer discover that tuples now squash
191 * t_bits. Why is this?
193 * 24 july 92: mer realizes that the t_bits field is only
194 * used in the event of null values. If no
195 * fields are null we reduce the header size
196 * by doing the squash. t_hoff tells you exactly
197 * how big the header actually is. use the PC
198 * means of getting at sys cat attrs.
200 tup_db = (Form_pg_database)GETSTRUCT(tup);
202 if (strncmp(GetDatabaseName(),
203 &(tup_db->datname.data[0]),
206 MyDatabaseId = tup->t_oid;
216 if (!OidIsValid(MyDatabaseId))
218 "Database %s does not exist in %s",
220 DatabaseRelationName);
224 * DoChdirAndInitDatabaseNameAndPath --
225 * Sets current directory appropriately for given path and name.
228 * Path and name are invalid if it invalid as a string.
229 * Path is "badly formated" if it is not a string containing a path
230 * to a writable directory.
231 * Name is "badly formated" if it contains more than 16 characters or if
232 * it is a bad file name (e.g., it contains a '/' or an 8-bit character).
235 * Initially, DatabasePath and DatabaseName are invalid. They are
236 * set to valid strings before this function returns.
239 * BadState if called more than once.
240 * BadArg if both path and name are "badly formated" or invalid.
241 * BadArg if path and name are both "inconsistent" and valid.
244 * DoChdirAndInitDatabaseNameAndPath
246 * this just chdir's to the proper data/base directory
247 * XXX clean this up more.
249 * XXX The following code is an incorrect of the semantics
250 * XXX described in the header file. Handling of defaults
251 * XXX should happen here, too.
255 DoChdirAndInitDatabaseNameAndPath(char *name, /* name of database */
256 char *path) /* full path to database */
263 SetDatabasePath(path);
265 elog(FATAL, "DoChdirAndInitDatabaseNameAndPath: path:%s is not valid",
273 SetDatabaseName(name);
275 elog(FATAL, "DoChdirAndInitDatabaseNameAndPath: name:%s is not valid",
279 * change to the directory, or die trying.
281 * XXX unless the path hasn't been set because we're bootstrapping.
282 * HP-UX doesn't like chdir("") so check for that case before
283 * doing anything drastic.
286 if (*path && (chdir(path) < 0))
287 elog(FATAL, "DoChdirAndInitDatabaseNameAndPath: chdir(\"%s\"): %m",
291 /* --------------------------------
294 * initializes crap associated with the user id.
295 * --------------------------------
304 /* --------------------------------
307 * This routine initializes stuff needed for ipc, locking, etc.
308 * it should be called something more informative.
311 * This does not set MyBackendId. MyBackendTag is set, however.
312 * --------------------------------
317 char *getenv(); /* XXX style */
323 * try and get the backend tag from POSTID
328 postid = getenv("POSTID");
329 if (!PointerIsValid(postid)) {
332 MyBackendTag = atoi(postid);
333 Assert(MyBackendTag >= 0);
337 * try and get the ipc key from POSTPORT
340 postport = getenv("POSTPORT");
342 if (PointerIsValid(postport)) {
343 SystemPortAddress address = atoi(postport);
346 elog(FATAL, "InitCommunication: invalid POSTPORT");
348 if (MyBackendTag == -1)
349 elog(FATAL, "InitCommunication: missing POSTID");
351 key = SystemPortAddressCreateIPCKey(address);
354 * Enable this if you are trying to force the backend to run as if it
355 * is running under the postmaster.
357 * This goto forces Postgres to attach to shared memory instead of
358 * using malloc'ed memory (which is the normal behavior if run
361 * To enable emulation, run the following shell commands (in addition
362 * to enabling this goto)
365 * % setenv POSTPORT 4321
369 * Upon doing this, Postmaster will have allocated the shared memory
370 * resources that Postgres will attach to if you enable
371 * EMULATE_UNDER_POSTMASTER.
373 * This comment may well age with time - it is current as of
379 #ifdef EMULATE_UNDER_POSTMASTER
381 goto forcesharedmemory;
385 } else if (IsUnderPostmaster) {
387 "InitCommunication: under postmaster and POSTPORT not set");
390 * assume we're running a postgres backend by itself with
391 * no front end or postmaster.
394 if (MyBackendTag == -1) {
402 * initialize shared memory and semaphores appropriately.
405 #ifdef EMULATE_UNDER_POSTMASTER
411 PostgresIpcKey = key;
412 AttachSharedMemoryAndSemaphores(key);
416 /* --------------------------------
419 * this routine consists of a bunch of code fragments
420 * that used to be randomly scattered through cinit().
421 * they all seem to do stuff associated with io.
422 * --------------------------------
427 (void) DebugFileOpen();
430 /* --------------------------------
432 * Initialize POSTGRES.
435 * Be very careful with the order of calls in the InitPostgres function.
436 * --------------------------------
438 bool PostgresIsInitialized = false;
442 * this global is used by wei for testing his code, but must be declared
443 * here rather than in postgres.c so that it's defined for cinterface.a
447 /*int testFlag = 0;*/
453 InitPostgres(char *name) /* database name */
455 bool bootstrap; /* true if BootstrapProcessing */
458 * see if we're running in BootstrapProcessing mode
461 bootstrap = IsBootstrapProcessingMode();
464 * turn on the exception handler. Note: we cannot use elog, Assert,
465 * AssertState, etc. until after exception handling is on.
468 EnableExceptionHandling(true);
471 * A stupid check to make sure we don't call this more than once.
472 * But things like ReinitPostgres() get around this by just diddling
473 * the PostgresIsInitialized flag.
476 AssertState(!PostgresIsInitialized);
479 * Memory system initialization.
480 * (we may call palloc after EnableMemoryContext())
482 * Note EnableMemoryContext() must happen before EnablePortalManager().
485 EnableMemoryContext(true); /* initializes the "top context" */
486 EnablePortalManager(true); /* memory for portal/transaction stuff */
489 * initialize the backend local portal stack used by
490 * internal PQ function calls. see src/lib/libpq/be-dumpdata.c
491 * This is different from the "portal manager" so this goes here.
498 * attach to shared memory and semaphores, and initialize our
499 * input/output/debugging file descriptors.
506 * initialize the local buffer manager
510 if (!TransactionFlushEnabled())
511 on_exitpg(FlushBufferPool, (caddr_t) NULL);
514 * check for valid "meta gunk" (??? -cim 10/5/90) and change to
515 * database directory.
517 * Note: DatabaseName, MyDatabaseName, and DatabasePath are all
518 * initialized with DatabaseMetaGunkIsConsistent(), strncpy() and
519 * DoChdirAndInitDatabase() below! XXX clean this crap up!
524 char myPath[MAXPGPATH] = "."; /* DatabasePath points here! */
527 * DatabaseMetaGunkIsConsistent fills in myPath, but what about
528 * when bootstrap or Noversion is true?? -cim 10/5/90
533 ! DatabaseMetaGunkIsConsistent(name, myPath) &&
535 elog(NOTICE, "InitPostgres: could not locate valid PG_VERSION\n");
536 elog(NOTICE, "files for %s and %s.", DataDir, name);
537 elog(FATAL, "Have you run initdb/createdb and set PGDATA properly?");
541 * ok, we've figured out myName and myPath, now save these
542 * and chdir to myPath.
545 DoChdirAndInitDatabaseNameAndPath(name, myPath);
548 /* ********************************
549 * code after this point assumes we are in the proper directory!
550 * ********************************
554 * initialize the database id used for system caches and lock tables
562 * initialize the transaction system and the relation descriptor
563 * cache. Note we have to make certain the lock manager is off while
567 AmiTransactionOverride(IsBootstrapProcessingMode());
571 * Part of the initialization processing done here sets a read
572 * lock on pg_log. Since locking is disabled the set doesn't have
573 * intended effect of locking out writers, but this is ok, since
574 * we only lock it to examine AMI transaction status, and this is
575 * never written after initdb is done. -mer 15 June 1992
577 RelationInitialize(); /* pre-allocated reldescs created here */
578 InitializeTransactionSystem(); /* pg_log,etc init/crash recovery here */
583 * anyone knows what this does? something having to do with
584 * system catalog cache invalidation in the case of multiple
585 * backends, I think -cim 10/3/90
586 * Sets up MyBackendId a unique backend identifier.
589 InitSharedInvalidationState();
592 * Set up a per backend process in shared memory. Must be done after
593 * InitSharedInvalidationState() as it relies on MyBackendId being
594 * initialized already. XXX -mer 11 Aug 1991
597 InitProcess(PostgresIpcKey);
599 if (MyBackendId > MaxBackendId || MyBackendId <= 0) {
600 elog(FATAL, "cinit2: bad backend id %d (%d)",
606 * initialize the access methods.
612 * initialize all the system catalog caches.
619 * set ourselves to the proper user id and figure out our postgres
620 * user id. If we ever add security so that we check for valid
621 * postgres users, we might do it here.
627 * ok, all done, now let's make sure we don't do it again.
630 PostgresIsInitialized = true;
631 /* on_exitpg(DestroyLocalRelList, (caddr_t) NULL); */
634 * Done with "InitPostgres", now change to NormalProcessing unless
635 * we're in BootstrapProcessing mode.
639 SetProcessingMode(NormalProcessing);
640 /* if (testFlag || lockingOff) */