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.10 1997/08/12 22:54:54 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"
75 static IPCKey PostgresIpcKey;
80 #define private static
81 #else /* !defined(EBUG) */
83 #endif /* !defined(EBUG) */
84 #endif /* !defined(private) */
86 /* ----------------------------------------------------------------
87 * InitPostgres support
88 * ----------------------------------------------------------------
91 /* --------------------------------
92 * InitMyDatabaseId() -- Find and record the OID of the database we are
95 * The database's oid forms half of the unique key for the system
96 * caches and lock tables. We therefore want it initialized before
97 * we open any relations, since opening relations puts things in the
98 * cache. To get around this problem, this code opens and scans the
99 * pg_database relation by hand.
101 * This algorithm relies on the fact that first attribute in the
102 * pg_database relation schema is the database name. It also knows
103 * about the internal format of tuples on disk and the length of
104 * the datname attribute. It knows the location of the pg_database
107 * This code is called from InitDatabase(), after we chdir() to the
108 * database directory but before we open any relations.
109 * --------------------------------
122 Form_pg_database tup_db;
125 * At bootstrap time, we don't need to check the oid of the database
126 * in use, since we're not using shared memory. This is lucky, since
127 * the database may not be in the tables yet.
130 if (IsBootstrapProcessingMode()) {
135 dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2);
136 sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR);
137 fileflags = O_RDONLY;
139 if ((dbfd = open(dbfname, O_RDONLY, 0666)) < 0)
140 elog(FATAL, "Cannot open %s", dbfname);
145 * read and examine every page in pg_database
147 * Raw I/O! Read those tuples the hard way! Yow!
149 * Why don't we use the access methods or move this code
150 * someplace else? This is really pg_database schema dependent
151 * code. Perhaps it should go in lib/catalog/pg_database?
154 * mao replies 4 apr 91: yeah, maybe this should be moved to
155 * lib/catalog. however, we CANNOT use the access methods since
156 * those use the buffer cache, which uses the relation cache, which
157 * requires that the dbid be set, which is what we're trying to do
161 pg = (Page) palloc(BLCKSZ);
162 ph = (PageHeader) pg;
164 while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ) {
165 max = PageGetMaxOffsetNumber(pg);
167 /* look at each tuple on the page */
168 for (i = 0; i <= max; i++) {
171 /* if it's a freed tuple, ignore it */
172 if (!(ph->pd_linp[i].lp_flags & LP_USED))
175 /* get a pointer to the tuple itself */
176 offset = (int) ph->pd_linp[i].lp_off;
177 tup = (HeapTuple) (((char *) pg) + offset);
180 * if the tuple has been deleted (the database was destroyed),
181 * skip this tuple. XXX warning, will robinson: violation of
182 * transaction semantics happens right here. we should check
183 * to be sure that the xact that deleted this tuple actually
184 * committed. only way to do this at init time is to paw over
185 * the log relation by hand, too. let's be optimistic.
187 * XXX This is an evil type cast. tup->t_xmax is char[5] while
188 * TransactionId is struct * { char data[5] }. It works but
189 * if data is ever moved and no longer the first field this
190 * will be broken!! -mer 11 Nov 1991.
192 if (TransactionIdIsValid((TransactionId)tup->t_xmax))
196 * Okay, see if this is the one we want.
197 * XXX 1 july 91: mao and mer discover that tuples now squash
198 * t_bits. Why is this?
200 * 24 july 92: mer realizes that the t_bits field is only
201 * used in the event of null values. If no
202 * fields are null we reduce the header size
203 * by doing the squash. t_hoff tells you exactly
204 * how big the header actually is. use the PC
205 * means of getting at sys cat attrs.
207 tup_db = (Form_pg_database)GETSTRUCT(tup);
209 if (strncmp(GetDatabaseName(),
210 &(tup_db->datname.data[0]),
213 MyDatabaseId = tup->t_oid;
223 if (!OidIsValid(MyDatabaseId))
225 "Database %s does not exist in %s",
227 DatabaseRelationName);
233 * DoChdirAndInitDatabaseNameAndPath --
234 * Set current directory to the database directory for the database
236 * Also set global variables DatabasePath and DatabaseName to those
237 * values. Also check for proper version of database system and
238 * database. Exit program via elog() if anything doesn't check out.
241 * Path and name are invalid if it invalid as a string.
242 * Path is "badly formated" if it is not a string containing a path
243 * to a writable directory.
244 * Name is "badly formated" if it contains more than 16 characters or if
245 * it is a bad file name (e.g., it contains a '/' or an 8-bit character).
248 * BadState if called more than once.
249 * BadArg if both path and name are "badly formated" or invalid.
250 * BadArg if path and name are both "inconsistent" and valid.
252 * This routine is inappropriate in bootstrap mode, since the directories
253 * and version files need not exist yet if we're in bootstrap mode.
256 DoChdirAndInitDatabaseNameAndPath(char *name) {
258 /* Failure reason returned by some function. NULL if no failure */
262 if (stat(DataDir, &statbuf) < 0)
263 sprintf(errormsg, "Database system does not exist. "
264 "PGDATA directory '%s' not found. Normally, you "
265 "create a database system by running initdb.",
268 char myPath[MAXPGPATH]; /* DatabasePath points here! */
270 if (strlen(DataDir) + strlen(name) + 10 > sizeof(myPath))
271 sprintf(errormsg, "Internal error in postinit.c: database "
272 "pathname exceeds maximum allowable length.");
274 sprintf(myPath, "%s/base/%s", DataDir, name);
276 if (stat(myPath, &statbuf) < 0)
278 "Database '%s' does not exist. "
279 "(We know this because the directory '%s' "
280 "does not exist). You can create a database "
281 "with the SQL command CREATE DATABASE. To see "
282 "what databases exist, look at the subdirectories "
284 name, myPath, DataDir);
286 ValidatePgVersion(DataDir, &reason);
289 "InitPostgres could not validate that the database "
290 "system version is compatible with this level of "
291 "Postgres. You may need to run initdb to create "
292 "a new database system. %s",
295 ValidatePgVersion(myPath, &reason);
298 "InitPostgres could not validate that the "
299 "database version is compatible with this level "
300 "of Postgres, even though the database system "
301 "as a whole appears to be at a compatible level. "
302 "You may need to recreate the database with SQL "
303 "commands DROP DATABASE and CREATE DATABASE. "
307 /* The directories and PG_VERSION files are in order.*/
308 int rc; /* return code from some function we call */
310 SetDatabasePath(myPath);
311 SetDatabaseName(name);
315 "InitPostgres unable to change "
316 "current directory to '%s', errno = %s (%d).",
317 myPath, strerror(errno), errno);
318 else errormsg[0] = '\0';
324 if (errormsg[0] != '\0')
325 elog(FATAL, errormsg);
326 /* Above does not return */
331 /* --------------------------------
334 * initializes crap associated with the user id.
335 * --------------------------------
344 /* --------------------------------
347 * This routine initializes stuff needed for ipc, locking, etc.
348 * it should be called something more informative.
351 * This does not set MyBackendId. MyBackendTag is set, however.
352 * --------------------------------
362 * try and get the backend tag from POSTID
367 postid = getenv("POSTID");
368 if (!PointerIsValid(postid)) {
371 MyBackendTag = atoi(postid);
372 Assert(MyBackendTag >= 0);
376 * try and get the ipc key from POSTPORT
379 postport = getenv("POSTPORT");
381 if (PointerIsValid(postport)) {
382 SystemPortAddress address = atoi(postport);
385 elog(FATAL, "InitCommunication: invalid POSTPORT");
387 if (MyBackendTag == -1)
388 elog(FATAL, "InitCommunication: missing POSTID");
390 key = SystemPortAddressCreateIPCKey(address);
393 * Enable this if you are trying to force the backend to run as if it
394 * is running under the postmaster.
396 * This goto forces Postgres to attach to shared memory instead of
397 * using malloc'ed memory (which is the normal behavior if run
400 * To enable emulation, run the following shell commands (in addition
401 * to enabling this goto)
404 * % setenv POSTPORT 4321
408 * Upon doing this, Postmaster will have allocated the shared memory
409 * resources that Postgres will attach to if you enable
410 * EMULATE_UNDER_POSTMASTER.
412 * This comment may well age with time - it is current as of
418 #ifdef EMULATE_UNDER_POSTMASTER
420 goto forcesharedmemory;
424 } else if (IsUnderPostmaster) {
426 "InitCommunication: under postmaster and POSTPORT not set");
429 * assume we're running a postgres backend by itself with
430 * no front end or postmaster.
433 if (MyBackendTag == -1) {
441 * initialize shared memory and semaphores appropriately.
444 #ifdef EMULATE_UNDER_POSTMASTER
450 PostgresIpcKey = key;
451 AttachSharedMemoryAndSemaphores(key);
455 /* --------------------------------
458 * this routine consists of a bunch of code fragments
459 * that used to be randomly scattered through cinit().
460 * they all seem to do stuff associated with io.
461 * --------------------------------
469 /* --------------------------------
471 * Initialize POSTGRES.
474 * Be very careful with the order of calls in the InitPostgres function.
475 * --------------------------------
477 bool PostgresIsInitialized = false;
481 * this global is used by wei for testing his code, but must be declared
482 * here rather than in postgres.c so that it's defined for cinterface.a
486 /*int testFlag = 0;*/
492 InitPostgres(char *name) /* database name */
494 bool bootstrap; /* true if BootstrapProcessing */
497 * see if we're running in BootstrapProcessing mode
500 bootstrap = IsBootstrapProcessingMode();
503 * turn on the exception handler. Note: we cannot use elog, Assert,
504 * AssertState, etc. until after exception handling is on.
507 EnableExceptionHandling(true);
510 * A stupid check to make sure we don't call this more than once.
511 * But things like ReinitPostgres() get around this by just diddling
512 * the PostgresIsInitialized flag.
515 AssertState(!PostgresIsInitialized);
518 * Memory system initialization.
519 * (we may call palloc after EnableMemoryContext())
521 * Note EnableMemoryContext() must happen before EnablePortalManager().
524 EnableMemoryContext(true); /* initializes the "top context" */
525 EnablePortalManager(true); /* memory for portal/transaction stuff */
528 * initialize the backend local portal stack used by
529 * internal PQ function calls. see src/lib/libpq/be-dumpdata.c
530 * This is different from the "portal manager" so this goes here.
537 * attach to shared memory and semaphores, and initialize our
538 * input/output/debugging file descriptors.
545 * initialize the local buffer manager
549 if (!TransactionFlushEnabled())
550 on_exitpg(FlushBufferPool, (caddr_t) NULL);
553 SetDatabasePath(".");
554 SetDatabaseName(name);
556 DoChdirAndInitDatabaseNameAndPath(name);
559 /* ********************************
560 * code after this point assumes we are in the proper directory!
561 * ********************************
565 * initialize the database id used for system caches and lock tables
573 * initialize the transaction system and the relation descriptor
574 * cache. Note we have to make certain the lock manager is off while
578 AmiTransactionOverride(IsBootstrapProcessingMode());
582 * Part of the initialization processing done here sets a read
583 * lock on pg_log. Since locking is disabled the set doesn't have
584 * intended effect of locking out writers, but this is ok, since
585 * we only lock it to examine AMI transaction status, and this is
586 * never written after initdb is done. -mer 15 June 1992
588 RelationInitialize(); /* pre-allocated reldescs created here */
589 InitializeTransactionSystem(); /* pg_log,etc init/crash recovery here */
594 * anyone knows what this does? something having to do with
595 * system catalog cache invalidation in the case of multiple
596 * backends, I think -cim 10/3/90
597 * Sets up MyBackendId a unique backend identifier.
600 InitSharedInvalidationState();
603 * Set up a per backend process in shared memory. Must be done after
604 * InitSharedInvalidationState() as it relies on MyBackendId being
605 * initialized already. XXX -mer 11 Aug 1991
608 InitProcess(PostgresIpcKey);
610 if (MyBackendId > MaxBackendId || MyBackendId <= 0) {
611 elog(FATAL, "cinit2: bad backend id %d (%d)",
617 * initialize the access methods.
623 * initialize all the system catalog caches.
630 * set ourselves to the proper user id and figure out our postgres
631 * user id. If we ever add security so that we check for valid
632 * postgres users, we might do it here.
638 * ok, all done, now let's make sure we don't do it again.
641 PostgresIsInitialized = true;
642 /* on_exitpg(DestroyLocalRelList, (caddr_t) NULL); */
645 * Done with "InitPostgres", now change to NormalProcessing unless
646 * we're in BootstrapProcessing mode.
650 SetProcessingMode(NormalProcessing);
651 /* if (testFlag || lockingOff) */