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.11 1997/08/19 21:35:50 momjian 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 *-------------------------------------------------------------------------
34 #include <sys/types.h>
41 #include <storage/ipc.h>
42 #include <storage/backendid.h>
43 #include <storage/buf_internals.h>
44 #include <storage/smgr.h>
45 #include <storage/proc.h>
46 #include <utils/relcache.h>
48 #include "access/heapam.h"
49 #include "access/xact.h"
50 #include "storage/bufmgr.h"
51 #include "access/transam.h" /* XXX dependency problem */
52 #include "utils/tqual.h"
53 #include "utils/syscache.h"
54 #include "storage/bufpage.h" /* for page layout, for InitMyDatabaseId() */
55 #include "storage/sinval.h"
56 #include "storage/sinvaladt.h"
57 #include "storage/lmgr.h"
59 #include "miscadmin.h" /* for global decls */
60 #include "utils/portal.h" /* for EnablePortalManager, etc. */
62 #include "utils/exc.h" /* for EnableExceptionHandling, etc. */
63 #include "fmgr.h" /* for EnableDynamicFunctionManager, etc. */
64 #include "utils/elog.h"
65 #include "utils/palloc.h"
66 #include "utils/mcxt.h" /* for EnableMemoryContext, etc. */
68 #include "catalog/catname.h"
69 #include "catalog/pg_database.h"
71 #include "port-protos.h"
72 #include "libpq/libpq-be.h"
74 static void InitCommunication(void);
75 static void InitMyDatabaseId(void);
76 static void InitStdio(void);
77 static void InitUserid(void);
80 static IPCKey PostgresIpcKey;
85 #define private static
86 #else /* !defined(EBUG) */
88 #endif /* !defined(EBUG) */
89 #endif /* !defined(private) */
91 /* ----------------------------------------------------------------
92 * InitPostgres support
93 * ----------------------------------------------------------------
96 /* --------------------------------
97 * InitMyDatabaseId() -- Find and record the OID of the database we are
100 * The database's oid forms half of the unique key for the system
101 * caches and lock tables. We therefore want it initialized before
102 * we open any relations, since opening relations puts things in the
103 * cache. To get around this problem, this code opens and scans the
104 * pg_database relation by hand.
106 * This algorithm relies on the fact that first attribute in the
107 * pg_database relation schema is the database name. It also knows
108 * about the internal format of tuples on disk and the length of
109 * the datname attribute. It knows the location of the pg_database
112 * This code is called from InitDatabase(), after we chdir() to the
113 * database directory but before we open any relations.
114 * --------------------------------
127 Form_pg_database tup_db;
130 * At bootstrap time, we don't need to check the oid of the database
131 * in use, since we're not using shared memory. This is lucky, since
132 * the database may not be in the tables yet.
135 if (IsBootstrapProcessingMode()) {
140 dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2);
141 sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR);
142 fileflags = O_RDONLY;
144 if ((dbfd = open(dbfname, O_RDONLY, 0666)) < 0)
145 elog(FATAL, "Cannot open %s", dbfname);
150 * read and examine every page in pg_database
152 * Raw I/O! Read those tuples the hard way! Yow!
154 * Why don't we use the access methods or move this code
155 * someplace else? This is really pg_database schema dependent
156 * code. Perhaps it should go in lib/catalog/pg_database?
159 * mao replies 4 apr 91: yeah, maybe this should be moved to
160 * lib/catalog. however, we CANNOT use the access methods since
161 * those use the buffer cache, which uses the relation cache, which
162 * requires that the dbid be set, which is what we're trying to do
166 pg = (Page) palloc(BLCKSZ);
167 ph = (PageHeader) pg;
169 while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ) {
170 max = PageGetMaxOffsetNumber(pg);
172 /* look at each tuple on the page */
173 for (i = 0; i <= max; i++) {
176 /* if it's a freed tuple, ignore it */
177 if (!(ph->pd_linp[i].lp_flags & LP_USED))
180 /* get a pointer to the tuple itself */
181 offset = (int) ph->pd_linp[i].lp_off;
182 tup = (HeapTuple) (((char *) pg) + offset);
185 * if the tuple has been deleted (the database was destroyed),
186 * skip this tuple. XXX warning, will robinson: violation of
187 * transaction semantics happens right here. we should check
188 * to be sure that the xact that deleted this tuple actually
189 * committed. only way to do this at init time is to paw over
190 * the log relation by hand, too. let's be optimistic.
192 * XXX This is an evil type cast. tup->t_xmax is char[5] while
193 * TransactionId is struct * { char data[5] }. It works but
194 * if data is ever moved and no longer the first field this
195 * will be broken!! -mer 11 Nov 1991.
197 if (TransactionIdIsValid((TransactionId)tup->t_xmax))
201 * Okay, see if this is the one we want.
202 * XXX 1 july 91: mao and mer discover that tuples now squash
203 * t_bits. Why is this?
205 * 24 july 92: mer realizes that the t_bits field is only
206 * used in the event of null values. If no
207 * fields are null we reduce the header size
208 * by doing the squash. t_hoff tells you exactly
209 * how big the header actually is. use the PC
210 * means of getting at sys cat attrs.
212 tup_db = (Form_pg_database)GETSTRUCT(tup);
214 if (strncmp(GetDatabaseName(),
215 &(tup_db->datname.data[0]),
218 MyDatabaseId = tup->t_oid;
228 if (!OidIsValid(MyDatabaseId))
230 "Database %s does not exist in %s",
232 DatabaseRelationName);
238 * DoChdirAndInitDatabaseNameAndPath --
239 * Set current directory to the database directory for the database
241 * Also set global variables DatabasePath and DatabaseName to those
242 * values. Also check for proper version of database system and
243 * database. Exit program via elog() if anything doesn't check out.
246 * Path and name are invalid if it invalid as a string.
247 * Path is "badly formated" if it is not a string containing a path
248 * to a writable directory.
249 * Name is "badly formated" if it contains more than 16 characters or if
250 * it is a bad file name (e.g., it contains a '/' or an 8-bit character).
253 * BadState if called more than once.
254 * BadArg if both path and name are "badly formated" or invalid.
255 * BadArg if path and name are both "inconsistent" and valid.
257 * This routine is inappropriate in bootstrap mode, since the directories
258 * and version files need not exist yet if we're in bootstrap mode.
261 DoChdirAndInitDatabaseNameAndPath(char *name) {
263 /* Failure reason returned by some function. NULL if no failure */
267 if (stat(DataDir, &statbuf) < 0)
268 sprintf(errormsg, "Database system does not exist. "
269 "PGDATA directory '%s' not found. Normally, you "
270 "create a database system by running initdb.",
273 char myPath[MAXPGPATH]; /* DatabasePath points here! */
275 if (strlen(DataDir) + strlen(name) + 10 > sizeof(myPath))
276 sprintf(errormsg, "Internal error in postinit.c: database "
277 "pathname exceeds maximum allowable length.");
279 sprintf(myPath, "%s/base/%s", DataDir, name);
281 if (stat(myPath, &statbuf) < 0)
283 "Database '%s' does not exist. "
284 "(We know this because the directory '%s' "
285 "does not exist). You can create a database "
286 "with the SQL command CREATE DATABASE. To see "
287 "what databases exist, look at the subdirectories "
289 name, myPath, DataDir);
291 ValidatePgVersion(DataDir, &reason);
294 "InitPostgres could not validate that the database "
295 "system version is compatible with this level of "
296 "Postgres. You may need to run initdb to create "
297 "a new database system. %s",
300 ValidatePgVersion(myPath, &reason);
303 "InitPostgres could not validate that the "
304 "database version is compatible with this level "
305 "of Postgres, even though the database system "
306 "as a whole appears to be at a compatible level. "
307 "You may need to recreate the database with SQL "
308 "commands DROP DATABASE and CREATE DATABASE. "
312 /* The directories and PG_VERSION files are in order.*/
313 int rc; /* return code from some function we call */
315 SetDatabasePath(myPath);
316 SetDatabaseName(name);
320 "InitPostgres unable to change "
321 "current directory to '%s', errno = %s (%d).",
322 myPath, strerror(errno), errno);
323 else errormsg[0] = '\0';
329 if (errormsg[0] != '\0')
330 elog(FATAL, errormsg);
331 /* Above does not return */
336 /* --------------------------------
339 * initializes crap associated with the user id.
340 * --------------------------------
349 /* --------------------------------
352 * This routine initializes stuff needed for ipc, locking, etc.
353 * it should be called something more informative.
356 * This does not set MyBackendId. MyBackendTag is set, however.
357 * --------------------------------
367 * try and get the backend tag from POSTID
372 postid = getenv("POSTID");
373 if (!PointerIsValid(postid)) {
376 MyBackendTag = atoi(postid);
377 Assert(MyBackendTag >= 0);
381 * try and get the ipc key from POSTPORT
384 postport = getenv("POSTPORT");
386 if (PointerIsValid(postport)) {
387 SystemPortAddress address = atoi(postport);
390 elog(FATAL, "InitCommunication: invalid POSTPORT");
392 if (MyBackendTag == -1)
393 elog(FATAL, "InitCommunication: missing POSTID");
395 key = SystemPortAddressCreateIPCKey(address);
398 * Enable this if you are trying to force the backend to run as if it
399 * is running under the postmaster.
401 * This goto forces Postgres to attach to shared memory instead of
402 * using malloc'ed memory (which is the normal behavior if run
405 * To enable emulation, run the following shell commands (in addition
406 * to enabling this goto)
409 * % setenv POSTPORT 4321
413 * Upon doing this, Postmaster will have allocated the shared memory
414 * resources that Postgres will attach to if you enable
415 * EMULATE_UNDER_POSTMASTER.
417 * This comment may well age with time - it is current as of
423 #ifdef EMULATE_UNDER_POSTMASTER
425 goto forcesharedmemory;
429 } else if (IsUnderPostmaster) {
431 "InitCommunication: under postmaster and POSTPORT not set");
434 * assume we're running a postgres backend by itself with
435 * no front end or postmaster.
438 if (MyBackendTag == -1) {
446 * initialize shared memory and semaphores appropriately.
449 #ifdef EMULATE_UNDER_POSTMASTER
455 PostgresIpcKey = key;
456 AttachSharedMemoryAndSemaphores(key);
460 /* --------------------------------
463 * this routine consists of a bunch of code fragments
464 * that used to be randomly scattered through cinit().
465 * they all seem to do stuff associated with io.
466 * --------------------------------
474 /* --------------------------------
476 * Initialize POSTGRES.
479 * Be very careful with the order of calls in the InitPostgres function.
480 * --------------------------------
482 bool PostgresIsInitialized = false;
486 * this global is used by wei for testing his code, but must be declared
487 * here rather than in postgres.c so that it's defined for cinterface.a
491 /*int testFlag = 0;*/
497 InitPostgres(char *name) /* database name */
499 bool bootstrap; /* true if BootstrapProcessing */
502 * see if we're running in BootstrapProcessing mode
505 bootstrap = IsBootstrapProcessingMode();
508 * turn on the exception handler. Note: we cannot use elog, Assert,
509 * AssertState, etc. until after exception handling is on.
512 EnableExceptionHandling(true);
515 * A stupid check to make sure we don't call this more than once.
516 * But things like ReinitPostgres() get around this by just diddling
517 * the PostgresIsInitialized flag.
520 AssertState(!PostgresIsInitialized);
523 * Memory system initialization.
524 * (we may call palloc after EnableMemoryContext())
526 * Note EnableMemoryContext() must happen before EnablePortalManager().
529 EnableMemoryContext(true); /* initializes the "top context" */
530 EnablePortalManager(true); /* memory for portal/transaction stuff */
533 * initialize the backend local portal stack used by
534 * internal PQ function calls. see src/lib/libpq/be-dumpdata.c
535 * This is different from the "portal manager" so this goes here.
542 * attach to shared memory and semaphores, and initialize our
543 * input/output/debugging file descriptors.
550 * initialize the local buffer manager
554 if (!TransactionFlushEnabled())
555 on_exitpg(FlushBufferPool, (caddr_t) NULL);
558 SetDatabasePath(".");
559 SetDatabaseName(name);
561 DoChdirAndInitDatabaseNameAndPath(name);
564 /* ********************************
565 * code after this point assumes we are in the proper directory!
566 * ********************************
570 * initialize the database id used for system caches and lock tables
578 * initialize the transaction system and the relation descriptor
579 * cache. Note we have to make certain the lock manager is off while
583 AmiTransactionOverride(IsBootstrapProcessingMode());
587 * Part of the initialization processing done here sets a read
588 * lock on pg_log. Since locking is disabled the set doesn't have
589 * intended effect of locking out writers, but this is ok, since
590 * we only lock it to examine AMI transaction status, and this is
591 * never written after initdb is done. -mer 15 June 1992
593 RelationInitialize(); /* pre-allocated reldescs created here */
594 InitializeTransactionSystem(); /* pg_log,etc init/crash recovery here */
599 * anyone knows what this does? something having to do with
600 * system catalog cache invalidation in the case of multiple
601 * backends, I think -cim 10/3/90
602 * Sets up MyBackendId a unique backend identifier.
605 InitSharedInvalidationState();
608 * Set up a per backend process in shared memory. Must be done after
609 * InitSharedInvalidationState() as it relies on MyBackendId being
610 * initialized already. XXX -mer 11 Aug 1991
613 InitProcess(PostgresIpcKey);
615 if (MyBackendId > MaxBackendId || MyBackendId <= 0) {
616 elog(FATAL, "cinit2: bad backend id %d (%d)",
622 * initialize the access methods.
628 * initialize all the system catalog caches.
635 * set ourselves to the proper user id and figure out our postgres
636 * user id. If we ever add security so that we check for valid
637 * postgres users, we might do it here.
643 * ok, all done, now let's make sure we don't do it again.
646 PostgresIsInitialized = true;
647 /* on_exitpg(DestroyLocalRelList, (caddr_t) NULL); */
650 * Done with "InitPostgres", now change to NormalProcessing unless
651 * we're in BootstrapProcessing mode.
655 SetProcessingMode(NormalProcessing);
656 /* if (testFlag || lockingOff) */