LCOV - code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 329 359 91.6 %
Date: 2025-04-01 15:15:16 Functions: 19 20 95.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * postinit.c
       4             :  *    postgres initialization utilities
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/utils/init/postinit.c
      12             :  *
      13             :  *
      14             :  *-------------------------------------------------------------------------
      15             :  */
      16             : #include "postgres.h"
      17             : 
      18             : #include <ctype.h>
      19             : #include <fcntl.h>
      20             : #include <unistd.h>
      21             : 
      22             : #include "access/genam.h"
      23             : #include "access/heapam.h"
      24             : #include "access/htup_details.h"
      25             : #include "access/session.h"
      26             : #include "access/tableam.h"
      27             : #include "access/xact.h"
      28             : #include "access/xlog.h"
      29             : #include "access/xloginsert.h"
      30             : #include "catalog/namespace.h"
      31             : #include "catalog/pg_authid.h"
      32             : #include "catalog/pg_collation.h"
      33             : #include "catalog/pg_database.h"
      34             : #include "catalog/pg_db_role_setting.h"
      35             : #include "catalog/pg_tablespace.h"
      36             : #include "libpq/auth.h"
      37             : #include "libpq/libpq-be.h"
      38             : #include "mb/pg_wchar.h"
      39             : #include "miscadmin.h"
      40             : #include "pgstat.h"
      41             : #include "postmaster/autovacuum.h"
      42             : #include "postmaster/postmaster.h"
      43             : #include "replication/slot.h"
      44             : #include "replication/slotsync.h"
      45             : #include "replication/walsender.h"
      46             : #include "storage/aio_subsys.h"
      47             : #include "storage/bufmgr.h"
      48             : #include "storage/fd.h"
      49             : #include "storage/ipc.h"
      50             : #include "storage/lmgr.h"
      51             : #include "storage/proc.h"
      52             : #include "storage/procarray.h"
      53             : #include "storage/procnumber.h"
      54             : #include "storage/procsignal.h"
      55             : #include "storage/sinvaladt.h"
      56             : #include "storage/smgr.h"
      57             : #include "storage/sync.h"
      58             : #include "tcop/backend_startup.h"
      59             : #include "tcop/tcopprot.h"
      60             : #include "utils/acl.h"
      61             : #include "utils/builtins.h"
      62             : #include "utils/fmgroids.h"
      63             : #include "utils/guc_hooks.h"
      64             : #include "utils/injection_point.h"
      65             : #include "utils/memutils.h"
      66             : #include "utils/pg_locale.h"
      67             : #include "utils/portal.h"
      68             : #include "utils/ps_status.h"
      69             : #include "utils/snapmgr.h"
      70             : #include "utils/syscache.h"
      71             : #include "utils/timeout.h"
      72             : 
      73             : static HeapTuple GetDatabaseTuple(const char *dbname);
      74             : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
      75             : static void PerformAuthentication(Port *port);
      76             : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
      77             : static void ShutdownPostgres(int code, Datum arg);
      78             : static void StatementTimeoutHandler(void);
      79             : static void LockTimeoutHandler(void);
      80             : static void IdleInTransactionSessionTimeoutHandler(void);
      81             : static void TransactionTimeoutHandler(void);
      82             : static void IdleSessionTimeoutHandler(void);
      83             : static void IdleStatsUpdateTimeoutHandler(void);
      84             : static void ClientCheckTimeoutHandler(void);
      85             : static bool ThereIsAtLeastOneRole(void);
      86             : static void process_startup_options(Port *port, bool am_superuser);
      87             : static void process_settings(Oid databaseid, Oid roleid);
      88             : 
      89             : 
      90             : /*** InitPostgres support ***/
      91             : 
      92             : 
      93             : /*
      94             :  * GetDatabaseTuple -- fetch the pg_database row for a database
      95             :  *
      96             :  * This is used during backend startup when we don't yet have any access to
      97             :  * system catalogs in general.  In the worst case, we can seqscan pg_database
      98             :  * using nothing but the hard-wired descriptor that relcache.c creates for
      99             :  * pg_database.  In more typical cases, relcache.c was able to load
     100             :  * descriptors for both pg_database and its indexes from the shared relcache
     101             :  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
     102             :  * tells whether we got the cached descriptors.
     103             :  */
     104             : static HeapTuple
     105       25998 : GetDatabaseTuple(const char *dbname)
     106             : {
     107             :     HeapTuple   tuple;
     108             :     Relation    relation;
     109             :     SysScanDesc scan;
     110             :     ScanKeyData key[1];
     111             : 
     112             :     /*
     113             :      * form a scan key
     114             :      */
     115       25998 :     ScanKeyInit(&key[0],
     116             :                 Anum_pg_database_datname,
     117             :                 BTEqualStrategyNumber, F_NAMEEQ,
     118             :                 CStringGetDatum(dbname));
     119             : 
     120             :     /*
     121             :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     122             :      * built the critical shared relcache entries (i.e., we're starting up
     123             :      * without a shared relcache cache file).
     124             :      */
     125       25998 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     126       25998 :     scan = systable_beginscan(relation, DatabaseNameIndexId,
     127             :                               criticalSharedRelcachesBuilt,
     128             :                               NULL,
     129             :                               1, key);
     130             : 
     131       25998 :     tuple = systable_getnext(scan);
     132             : 
     133             :     /* Must copy tuple before releasing buffer */
     134       25998 :     if (HeapTupleIsValid(tuple))
     135       25980 :         tuple = heap_copytuple(tuple);
     136             : 
     137             :     /* all done */
     138       25998 :     systable_endscan(scan);
     139       25998 :     table_close(relation, AccessShareLock);
     140             : 
     141       25998 :     return tuple;
     142             : }
     143             : 
     144             : /*
     145             :  * GetDatabaseTupleByOid -- as above, but search by database OID
     146             :  */
     147             : static HeapTuple
     148       31940 : GetDatabaseTupleByOid(Oid dboid)
     149             : {
     150             :     HeapTuple   tuple;
     151             :     Relation    relation;
     152             :     SysScanDesc scan;
     153             :     ScanKeyData key[1];
     154             : 
     155             :     /*
     156             :      * form a scan key
     157             :      */
     158       31940 :     ScanKeyInit(&key[0],
     159             :                 Anum_pg_database_oid,
     160             :                 BTEqualStrategyNumber, F_OIDEQ,
     161             :                 ObjectIdGetDatum(dboid));
     162             : 
     163             :     /*
     164             :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     165             :      * built the critical shared relcache entries (i.e., we're starting up
     166             :      * without a shared relcache cache file).
     167             :      */
     168       31940 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     169       31940 :     scan = systable_beginscan(relation, DatabaseOidIndexId,
     170             :                               criticalSharedRelcachesBuilt,
     171             :                               NULL,
     172             :                               1, key);
     173             : 
     174       31940 :     tuple = systable_getnext(scan);
     175             : 
     176             :     /* Must copy tuple before releasing buffer */
     177       31940 :     if (HeapTupleIsValid(tuple))
     178       31940 :         tuple = heap_copytuple(tuple);
     179             : 
     180             :     /* all done */
     181       31940 :     systable_endscan(scan);
     182       31940 :     table_close(relation, AccessShareLock);
     183             : 
     184       31940 :     return tuple;
     185             : }
     186             : 
     187             : 
     188             : /*
     189             :  * PerformAuthentication -- authenticate a remote client
     190             :  *
     191             :  * returns: nothing.  Will not return at all if there's any failure.
     192             :  */
     193             : static void
     194       26934 : PerformAuthentication(Port *port)
     195             : {
     196             :     /* This should be set already, but let's make sure */
     197       26934 :     ClientAuthInProgress = true;    /* limit visibility of log messages */
     198             : 
     199             :     /*
     200             :      * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
     201             :      * etcetera from the postmaster, and have to load them ourselves.
     202             :      *
     203             :      * FIXME: [fork/exec] Ugh.  Is there a way around this overhead?
     204             :      */
     205             : #ifdef EXEC_BACKEND
     206             : 
     207             :     /*
     208             :      * load_hba() and load_ident() want to work within the PostmasterContext,
     209             :      * so create that if it doesn't exist (which it won't).  We'll delete it
     210             :      * again later, in PostgresMain.
     211             :      */
     212             :     if (PostmasterContext == NULL)
     213             :         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
     214             :                                                   "Postmaster",
     215             :                                                   ALLOCSET_DEFAULT_SIZES);
     216             : 
     217             :     if (!load_hba())
     218             :     {
     219             :         /*
     220             :          * It makes no sense to continue if we fail to load the HBA file,
     221             :          * since there is no way to connect to the database in this case.
     222             :          */
     223             :         ereport(FATAL,
     224             :         /* translator: %s is a configuration file */
     225             :                 (errmsg("could not load %s", HbaFileName)));
     226             :     }
     227             : 
     228             :     if (!load_ident())
     229             :     {
     230             :         /*
     231             :          * It is ok to continue if we fail to load the IDENT file, although it
     232             :          * means that you cannot log in using any of the authentication
     233             :          * methods that need a user name mapping. load_ident() already logged
     234             :          * the details of error to the log.
     235             :          */
     236             :     }
     237             : #endif
     238             : 
     239             :     /* Capture authentication start time for logging */
     240       26934 :     conn_timing.auth_start = GetCurrentTimestamp();
     241             : 
     242             :     /*
     243             :      * Set up a timeout in case a buggy or malicious client fails to respond
     244             :      * during authentication.  Since we're inside a transaction and might do
     245             :      * database access, we have to use the statement_timeout infrastructure.
     246             :      */
     247       26934 :     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
     248             : 
     249             :     /*
     250             :      * Now perform authentication exchange.
     251             :      */
     252       26934 :     set_ps_display("authentication");
     253       26934 :     ClientAuthentication(port); /* might not return, if failure */
     254             : 
     255             :     /*
     256             :      * Done with authentication.  Disable the timeout, and log if needed.
     257             :      */
     258       26800 :     disable_timeout(STATEMENT_TIMEOUT, false);
     259             : 
     260             :     /* Capture authentication end time for logging */
     261       26800 :     conn_timing.auth_end = GetCurrentTimestamp();
     262             : 
     263       26800 :     if (log_connections & LOG_CONNECTION_AUTHORIZATION)
     264             :     {
     265             :         StringInfoData logmsg;
     266             : 
     267         624 :         initStringInfo(&logmsg);
     268         624 :         if (am_walsender)
     269           6 :             appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
     270             :                              port->user_name);
     271             :         else
     272         618 :             appendStringInfo(&logmsg, _("connection authorized: user=%s"),
     273             :                              port->user_name);
     274         624 :         if (!am_walsender)
     275         618 :             appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
     276             : 
     277         624 :         if (port->application_name != NULL)
     278         624 :             appendStringInfo(&logmsg, _(" application_name=%s"),
     279             :                              port->application_name);
     280             : 
     281             : #ifdef USE_SSL
     282         624 :         if (port->ssl_in_use)
     283         170 :             appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
     284             :                              be_tls_get_version(port),
     285             :                              be_tls_get_cipher(port),
     286             :                              be_tls_get_cipher_bits(port));
     287             : #endif
     288             : #ifdef ENABLE_GSS
     289             :         if (port->gss)
     290             :         {
     291             :             const char *princ = be_gssapi_get_princ(port);
     292             : 
     293             :             if (princ)
     294             :                 appendStringInfo(&logmsg,
     295             :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
     296             :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
     297             :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
     298             :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"),
     299             :                                  princ);
     300             :             else
     301             :                 appendStringInfo(&logmsg,
     302             :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
     303             :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
     304             :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
     305             :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"));
     306             :         }
     307             : #endif
     308             : 
     309         624 :         ereport(LOG, errmsg_internal("%s", logmsg.data));
     310         624 :         pfree(logmsg.data);
     311             :     }
     312             : 
     313       26800 :     set_ps_display("startup");
     314             : 
     315       26800 :     ClientAuthInProgress = false;   /* client_min_messages is active now */
     316       26800 : }
     317             : 
     318             : 
     319             : /*
     320             :  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
     321             :  */
     322             : static void
     323       31924 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
     324             : {
     325             :     HeapTuple   tup;
     326             :     Form_pg_database dbform;
     327             :     Datum       datum;
     328             :     bool        isnull;
     329             :     char       *collate;
     330             :     char       *ctype;
     331             : 
     332             :     /* Fetch our pg_database row normally, via syscache */
     333       31924 :     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
     334       31924 :     if (!HeapTupleIsValid(tup))
     335           0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
     336       31924 :     dbform = (Form_pg_database) GETSTRUCT(tup);
     337             : 
     338             :     /* This recheck is strictly paranoia */
     339       31924 :     if (strcmp(name, NameStr(dbform->datname)) != 0)
     340           0 :         ereport(FATAL,
     341             :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
     342             :                  errmsg("database \"%s\" has disappeared from pg_database",
     343             :                         name),
     344             :                  errdetail("Database OID %u now seems to belong to \"%s\".",
     345             :                            MyDatabaseId, NameStr(dbform->datname))));
     346             : 
     347             :     /*
     348             :      * Check permissions to connect to the database.
     349             :      *
     350             :      * These checks are not enforced when in standalone mode, so that there is
     351             :      * a way to recover from disabling all access to all databases, for
     352             :      * example "UPDATE pg_database SET datallowconn = false;".
     353             :      */
     354       31924 :     if (IsUnderPostmaster)
     355             :     {
     356             :         /*
     357             :          * Check that the database is currently allowing connections.
     358             :          * (Background processes can override this test and the next one by
     359             :          * setting override_allow_connections.)
     360             :          */
     361       31816 :         if (!dbform->datallowconn && !override_allow_connections)
     362           2 :             ereport(FATAL,
     363             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     364             :                      errmsg("database \"%s\" is not currently accepting connections",
     365             :                             name)));
     366             : 
     367             :         /*
     368             :          * Check privilege to connect to the database.  (The am_superuser test
     369             :          * is redundant, but since we have the flag, might as well check it
     370             :          * and save a few cycles.)
     371             :          */
     372       32340 :         if (!am_superuser && !override_allow_connections &&
     373         526 :             object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
     374             :                             ACL_CONNECT) != ACLCHECK_OK)
     375           0 :             ereport(FATAL,
     376             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     377             :                      errmsg("permission denied for database \"%s\"", name),
     378             :                      errdetail("User does not have CONNECT privilege.")));
     379             : 
     380             :         /*
     381             :          * Check connection limit for this database.  We enforce the limit
     382             :          * only for regular backends, since other process types have their own
     383             :          * PGPROC pools.
     384             :          *
     385             :          * There is a race condition here --- we create our PGPROC before
     386             :          * checking for other PGPROCs.  If two backends did this at about the
     387             :          * same time, they might both think they were over the limit, while
     388             :          * ideally one should succeed and one fail.  Getting that to work
     389             :          * exactly seems more trouble than it is worth, however; instead we
     390             :          * just document that the connection limit is approximate.
     391             :          */
     392       31814 :         if (dbform->datconnlimit >= 0 &&
     393           0 :             AmRegularBackendProcess() &&
     394           0 :             !am_superuser &&
     395           0 :             CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
     396           0 :             ereport(FATAL,
     397             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     398             :                      errmsg("too many connections for database \"%s\"",
     399             :                             name)));
     400             :     }
     401             : 
     402             :     /*
     403             :      * OK, we're golden.  Next to-do item is to save the encoding info out of
     404             :      * the pg_database tuple.
     405             :      */
     406       31922 :     SetDatabaseEncoding(dbform->encoding);
     407             :     /* Record it as a GUC internal option, too */
     408       31922 :     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
     409             :                     PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
     410             :     /* If we have no other source of client_encoding, use server encoding */
     411       31922 :     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
     412             :                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
     413             : 
     414             :     /* assign locale variables */
     415       31922 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
     416       31922 :     collate = TextDatumGetCString(datum);
     417       31922 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
     418       31922 :     ctype = TextDatumGetCString(datum);
     419             : 
     420       31922 :     if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
     421           0 :         ereport(FATAL,
     422             :                 (errmsg("database locale is incompatible with operating system"),
     423             :                  errdetail("The database was initialized with LC_COLLATE \"%s\", "
     424             :                            " which is not recognized by setlocale().", collate),
     425             :                  errhint("Recreate the database with another locale or install the missing locale.")));
     426             : 
     427       31922 :     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
     428           0 :         ereport(FATAL,
     429             :                 (errmsg("database locale is incompatible with operating system"),
     430             :                  errdetail("The database was initialized with LC_CTYPE \"%s\", "
     431             :                            " which is not recognized by setlocale().", ctype),
     432             :                  errhint("Recreate the database with another locale or install the missing locale.")));
     433             : 
     434       31922 :     if (strcmp(ctype, "C") == 0 ||
     435       29110 :         strcmp(ctype, "POSIX") == 0)
     436        2812 :         database_ctype_is_c = true;
     437             : 
     438       31922 :     init_database_collation();
     439             : 
     440             :     /*
     441             :      * Check collation version.  See similar code in
     442             :      * pg_newlocale_from_collation().  Note that here we warn instead of error
     443             :      * in any case, so that we don't prevent connecting.
     444             :      */
     445       31918 :     datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
     446             :                             &isnull);
     447       31918 :     if (!isnull)
     448             :     {
     449             :         char       *actual_versionstr;
     450             :         char       *collversionstr;
     451             :         char       *locale;
     452             : 
     453       30156 :         collversionstr = TextDatumGetCString(datum);
     454             : 
     455       30156 :         if (dbform->datlocprovider == COLLPROVIDER_LIBC)
     456       28446 :             locale = collate;
     457             :         else
     458             :         {
     459        1710 :             datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
     460        1710 :             locale = TextDatumGetCString(datum);
     461             :         }
     462             : 
     463       30156 :         actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
     464       30156 :         if (!actual_versionstr)
     465             :             /* should not happen */
     466           0 :             elog(WARNING,
     467             :                  "database \"%s\" has no actual collation version, but a version was recorded",
     468             :                  name);
     469       30156 :         else if (strcmp(actual_versionstr, collversionstr) != 0)
     470           0 :             ereport(WARNING,
     471             :                     (errmsg("database \"%s\" has a collation version mismatch",
     472             :                             name),
     473             :                      errdetail("The database was created using collation version %s, "
     474             :                                "but the operating system provides version %s.",
     475             :                                collversionstr, actual_versionstr),
     476             :                      errhint("Rebuild all objects in this database that use the default collation and run "
     477             :                              "ALTER DATABASE %s REFRESH COLLATION VERSION, "
     478             :                              "or build PostgreSQL with the right library version.",
     479             :                              quote_identifier(name))));
     480             :     }
     481             : 
     482       31918 :     ReleaseSysCache(tup);
     483       31918 : }
     484             : 
     485             : 
     486             : /*
     487             :  * pg_split_opts -- split a string of options and append it to an argv array
     488             :  *
     489             :  * The caller is responsible for ensuring the argv array is large enough.  The
     490             :  * maximum possible number of arguments added by this routine is
     491             :  * (strlen(optstr) + 1) / 2.
     492             :  *
     493             :  * Because some option values can contain spaces we allow escaping using
     494             :  * backslashes, with \\ representing a literal backslash.
     495             :  */
     496             : void
     497        7016 : pg_split_opts(char **argv, int *argcp, const char *optstr)
     498             : {
     499             :     StringInfoData s;
     500             : 
     501        7016 :     initStringInfo(&s);
     502             : 
     503       25596 :     while (*optstr)
     504             :     {
     505       18580 :         bool        last_was_escape = false;
     506             : 
     507       18580 :         resetStringInfo(&s);
     508             : 
     509             :         /* skip over leading space */
     510       34448 :         while (isspace((unsigned char) *optstr))
     511       15868 :             optstr++;
     512             : 
     513       18580 :         if (*optstr == '\0')
     514           0 :             break;
     515             : 
     516             :         /*
     517             :          * Parse a single option, stopping at the first space, unless it's
     518             :          * escaped.
     519             :          */
     520      283944 :         while (*optstr)
     521             :         {
     522      276928 :             if (isspace((unsigned char) *optstr) && !last_was_escape)
     523       11564 :                 break;
     524             : 
     525      265364 :             if (!last_was_escape && *optstr == '\\')
     526          28 :                 last_was_escape = true;
     527             :             else
     528             :             {
     529      265336 :                 last_was_escape = false;
     530      265336 :                 appendStringInfoChar(&s, *optstr);
     531             :             }
     532             : 
     533      265364 :             optstr++;
     534             :         }
     535             : 
     536             :         /* now store the option in the next argv[] position */
     537       18580 :         argv[(*argcp)++] = pstrdup(s.data);
     538             :     }
     539             : 
     540        7016 :     pfree(s.data);
     541        7016 : }
     542             : 
     543             : /*
     544             :  * Initialize MaxBackends value from config options.
     545             :  *
     546             :  * This must be called after modules have had the chance to alter GUCs in
     547             :  * shared_preload_libraries and before shared memory size is determined.
     548             :  *
     549             :  * Note that in EXEC_BACKEND environment, the value is passed down from
     550             :  * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
     551             :  * postmaster itself and processes not under postmaster control should call
     552             :  * this.
     553             :  */
     554             : void
     555        2028 : InitializeMaxBackends(void)
     556             : {
     557             :     Assert(MaxBackends == 0);
     558             : 
     559             :     /* Note that this does not include "auxiliary" processes */
     560        2028 :     MaxBackends = MaxConnections + autovacuum_worker_slots +
     561        2028 :         max_worker_processes + max_wal_senders + NUM_SPECIAL_WORKER_PROCS;
     562             : 
     563        2028 :     if (MaxBackends > MAX_BACKENDS)
     564           0 :         ereport(ERROR,
     565             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     566             :                  errmsg("too many server processes configured"),
     567             :                  errdetail("\"max_connections\" (%d) plus \"autovacuum_worker_slots\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
     568             :                            MaxConnections, autovacuum_worker_slots,
     569             :                            max_worker_processes, max_wal_senders,
     570             :                            MAX_BACKENDS - (NUM_SPECIAL_WORKER_PROCS - 1))));
     571        2028 : }
     572             : 
     573             : /*
     574             :  * Initialize the number of fast-path lock slots in PGPROC.
     575             :  *
     576             :  * This must be called after modules have had the chance to alter GUCs in
     577             :  * shared_preload_libraries and before shared memory size is determined.
     578             :  *
     579             :  * The default max_locks_per_xact=64 means 4 groups by default.
     580             :  *
     581             :  * We allow anything between 1 and 1024 groups, with the usual power-of-2
     582             :  * logic. The 1 is the "old" size with only 16 slots, 1024 is an arbitrary
     583             :  * limit (matching max_locks_per_xact = 16k). Values over 1024 are unlikely
     584             :  * to be beneficial - there are bottlenecks we'll hit way before that.
     585             :  */
     586             : void
     587        2028 : InitializeFastPathLocks(void)
     588             : {
     589             :     /* Should be initialized only once. */
     590             :     Assert(FastPathLockGroupsPerBackend == 0);
     591             : 
     592             :     /* we need at least one group */
     593        2028 :     FastPathLockGroupsPerBackend = 1;
     594             : 
     595        6084 :     while (FastPathLockGroupsPerBackend < FP_LOCK_GROUPS_PER_BACKEND_MAX)
     596             :     {
     597             :         /* stop once we exceed max_locks_per_xact */
     598        6084 :         if (FastPathLockSlotsPerBackend() >= max_locks_per_xact)
     599        2028 :             break;
     600             : 
     601        4056 :         FastPathLockGroupsPerBackend *= 2;
     602             :     }
     603             : 
     604             :     Assert(FastPathLockGroupsPerBackend <= FP_LOCK_GROUPS_PER_BACKEND_MAX);
     605        2028 : }
     606             : 
     607             : /*
     608             :  * Early initialization of a backend (either standalone or under postmaster).
     609             :  * This happens even before InitPostgres.
     610             :  *
     611             :  * This is separate from InitPostgres because it is also called by auxiliary
     612             :  * processes, such as the background writer process, which may not call
     613             :  * InitPostgres at all.
     614             :  */
     615             : void
     616       42486 : BaseInit(void)
     617             : {
     618             :     Assert(MyProc != NULL);
     619             : 
     620             :     /*
     621             :      * Initialize our input/output/debugging file descriptors.
     622             :      */
     623       42486 :     DebugFileOpen();
     624             : 
     625             :     /*
     626             :      * Initialize file access. Done early so other subsystems can access
     627             :      * files.
     628             :      */
     629       42486 :     InitFileAccess();
     630             : 
     631             :     /*
     632             :      * Initialize statistics reporting. This needs to happen early to ensure
     633             :      * that pgstat's shutdown callback runs after the shutdown callbacks of
     634             :      * all subsystems that can produce stats (like e.g. transaction commits
     635             :      * can).
     636             :      */
     637       42486 :     pgstat_initialize();
     638             : 
     639             :     /*
     640             :      * Initialize AIO before infrastructure that might need to actually
     641             :      * execute AIO.
     642             :      */
     643       42486 :     pgaio_init_backend();
     644             : 
     645             :     /* Do local initialization of storage and buffer managers */
     646       42486 :     InitSync();
     647       42486 :     smgrinit();
     648       42486 :     InitBufferManagerAccess();
     649             : 
     650             :     /*
     651             :      * Initialize temporary file access after pgstat, so that the temporary
     652             :      * file shutdown hook can report temporary file statistics.
     653             :      */
     654       42486 :     InitTemporaryFileAccess();
     655             : 
     656             :     /*
     657             :      * Initialize local buffers for WAL record construction, in case we ever
     658             :      * try to insert XLOG.
     659             :      */
     660       42486 :     InitXLogInsert();
     661             : 
     662             :     /* Initialize lock manager's local structs */
     663       42486 :     InitLockManagerAccess();
     664             : 
     665             :     /*
     666             :      * Initialize replication slots after pgstat. The exit hook might need to
     667             :      * drop ephemeral slots, which in turn triggers stats reporting.
     668             :      */
     669       42486 :     ReplicationSlotInitialize();
     670       42486 : }
     671             : 
     672             : 
     673             : /* --------------------------------
     674             :  * InitPostgres
     675             :  *      Initialize POSTGRES.
     676             :  *
     677             :  * Parameters:
     678             :  *  in_dbname, dboid: specify database to connect to, as described below
     679             :  *  username, useroid: specify role to connect as, as described below
     680             :  *  flags:
     681             :  *    - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
     682             :  *    - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
     683             :  *    - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
     684             :  *  out_dbname: optional output parameter, see below; pass NULL if not used
     685             :  *
     686             :  * The database can be specified by name, using the in_dbname parameter, or by
     687             :  * OID, using the dboid parameter.  Specify NULL or InvalidOid respectively
     688             :  * for the unused parameter.  If dboid is provided, the actual database
     689             :  * name can be returned to the caller in out_dbname.  If out_dbname isn't
     690             :  * NULL, it must point to a buffer of size NAMEDATALEN.
     691             :  *
     692             :  * Similarly, the role can be passed by name, using the username parameter,
     693             :  * or by OID using the useroid parameter.
     694             :  *
     695             :  * In bootstrap mode the database and username parameters are NULL/InvalidOid.
     696             :  * The autovacuum launcher process doesn't specify these parameters either,
     697             :  * because it only goes far enough to be able to read pg_database; it doesn't
     698             :  * connect to any particular database.  An autovacuum worker specifies a
     699             :  * database but not a username; conversely, a physical walsender specifies
     700             :  * username but not database.
     701             :  *
     702             :  * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
     703             :  * "interactive" sessions (including standalone backends), but not in
     704             :  * background processes such as autovacuum.  Note in particular that it
     705             :  * shouldn't be true in parallel worker processes; those have another
     706             :  * mechanism for replicating their leader's set of loaded libraries.
     707             :  *
     708             :  * We expect that InitProcess() was already called, so we already have a
     709             :  * PGPROC struct ... but it's not completely filled in yet.
     710             :  *
     711             :  * Note:
     712             :  *      Be very careful with the order of calls in the InitPostgres function.
     713             :  * --------------------------------
     714             :  */
     715             : void
     716       34610 : InitPostgres(const char *in_dbname, Oid dboid,
     717             :              const char *username, Oid useroid,
     718             :              bits32 flags,
     719             :              char *out_dbname)
     720             : {
     721       34610 :     bool        bootstrap = IsBootstrapProcessingMode();
     722             :     bool        am_superuser;
     723             :     char       *fullpath;
     724             :     char        dbname[NAMEDATALEN];
     725       34610 :     int         nfree = 0;
     726             : 
     727       34610 :     elog(DEBUG3, "InitPostgres");
     728             : 
     729             :     /*
     730             :      * Add my PGPROC struct to the ProcArray.
     731             :      *
     732             :      * Once I have done this, I am visible to other backends!
     733             :      */
     734       34610 :     InitProcessPhase2();
     735             : 
     736             :     /* Initialize status reporting */
     737       34610 :     pgstat_beinit();
     738             : 
     739             :     /*
     740             :      * And initialize an entry in the PgBackendStatus array.  That way, if
     741             :      * LWLocks or third-party authentication should happen to hang, it is
     742             :      * possible to retrieve some information about what is going on.
     743             :      */
     744       34610 :     if (!bootstrap)
     745             :     {
     746       34520 :         pgstat_bestart_initial();
     747       34520 :         INJECTION_POINT("init-pre-auth");
     748             :     }
     749             : 
     750             :     /*
     751             :      * Initialize my entry in the shared-invalidation manager's array of
     752             :      * per-backend data.
     753             :      */
     754       34610 :     SharedInvalBackendInit(false);
     755             : 
     756       34610 :     ProcSignalInit(MyCancelKeyValid, MyCancelKey);
     757             : 
     758             :     /*
     759             :      * Also set up timeout handlers needed for backend operation.  We need
     760             :      * these in every case except bootstrap.
     761             :      */
     762       34610 :     if (!bootstrap)
     763             :     {
     764       34520 :         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
     765       34520 :         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
     766       34520 :         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
     767       34520 :         RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
     768             :                         IdleInTransactionSessionTimeoutHandler);
     769       34520 :         RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
     770       34520 :         RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
     771       34520 :         RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
     772       34520 :         RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
     773             :                         IdleStatsUpdateTimeoutHandler);
     774             :     }
     775             : 
     776             :     /*
     777             :      * If this is either a bootstrap process or a standalone backend, start up
     778             :      * the XLOG machinery, and register to have it closed down at exit. In
     779             :      * other cases, the startup process is responsible for starting up the
     780             :      * XLOG machinery, and the checkpointer for closing it down.
     781             :      */
     782       34610 :     if (!IsUnderPostmaster)
     783             :     {
     784             :         /*
     785             :          * We don't yet have an aux-process resource owner, but StartupXLOG
     786             :          * and ShutdownXLOG will need one.  Hence, create said resource owner
     787             :          * (and register a callback to clean it up after ShutdownXLOG runs).
     788             :          */
     789         198 :         CreateAuxProcessResourceOwner();
     790             : 
     791         198 :         StartupXLOG();
     792             :         /* Release (and warn about) any buffer pins leaked in StartupXLOG */
     793         198 :         ReleaseAuxProcessResources(true);
     794             :         /* Reset CurrentResourceOwner to nothing for the moment */
     795         198 :         CurrentResourceOwner = NULL;
     796             : 
     797             :         /*
     798             :          * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
     799             :          * segments etc to work (which in turn is required for pgstats).
     800             :          */
     801         198 :         before_shmem_exit(pgstat_before_server_shutdown, 0);
     802         198 :         before_shmem_exit(ShutdownXLOG, 0);
     803             :     }
     804             : 
     805             :     /*
     806             :      * Initialize the relation cache and the system catalog caches.  Note that
     807             :      * no catalog access happens here; we only set up the hashtable structure.
     808             :      * We must do this before starting a transaction because transaction abort
     809             :      * would try to touch these hashtables.
     810             :      */
     811       34610 :     RelationCacheInitialize();
     812       34610 :     InitCatalogCache();
     813       34610 :     InitPlanCache();
     814             : 
     815             :     /* Initialize portal manager */
     816       34610 :     EnablePortalManager();
     817             : 
     818             :     /*
     819             :      * Load relcache entries for the shared system catalogs.  This must create
     820             :      * at least entries for pg_database and catalogs used for authentication.
     821             :      */
     822       34610 :     RelationCacheInitializePhase2();
     823             : 
     824             :     /*
     825             :      * Set up process-exit callback to do pre-shutdown cleanup.  This is the
     826             :      * one of the first before_shmem_exit callbacks we register; thus, this
     827             :      * will be one the last things we do before low-level modules like the
     828             :      * buffer manager begin to close down.  We need to have this in place
     829             :      * before we begin our first transaction --- if we fail during the
     830             :      * initialization transaction, as is entirely possible, we need the
     831             :      * AbortTransaction call to clean up.
     832             :      */
     833       34610 :     before_shmem_exit(ShutdownPostgres, 0);
     834             : 
     835             :     /* The autovacuum launcher is done here */
     836       34610 :     if (AmAutoVacuumLauncherProcess())
     837             :     {
     838             :         /* fill in the remainder of this entry in the PgBackendStatus array */
     839         730 :         pgstat_bestart_final();
     840             : 
     841        2414 :         return;
     842             :     }
     843             : 
     844             :     /*
     845             :      * Start a new transaction here before first access to db.
     846             :      */
     847       33880 :     if (!bootstrap)
     848             :     {
     849             :         /* statement_timestamp must be set for timeouts to work correctly */
     850       33790 :         SetCurrentStatementStartTimestamp();
     851       33790 :         StartTransactionCommand();
     852             : 
     853             :         /*
     854             :          * transaction_isolation will have been set to the default by the
     855             :          * above.  If the default is "serializable", and we are in hot
     856             :          * standby, we will fail if we don't change it to something lower.
     857             :          * Fortunately, "read committed" is plenty good enough.
     858             :          */
     859       33790 :         XactIsoLevel = XACT_READ_COMMITTED;
     860             :     }
     861             : 
     862             :     /*
     863             :      * Perform client authentication if necessary, then figure out our
     864             :      * postgres user ID, and see if we are a superuser.
     865             :      *
     866             :      * In standalone mode, autovacuum worker processes and slot sync worker
     867             :      * process, we use a fixed ID, otherwise we figure it out from the
     868             :      * authenticated user name.
     869             :      */
     870       33880 :     if (bootstrap || AmAutoVacuumWorkerProcess() || AmLogicalSlotSyncWorkerProcess())
     871             :     {
     872        2484 :         InitializeSessionUserIdStandalone();
     873        2484 :         am_superuser = true;
     874             :     }
     875       31396 :     else if (!IsUnderPostmaster)
     876             :     {
     877         108 :         InitializeSessionUserIdStandalone();
     878         108 :         am_superuser = true;
     879         108 :         if (!ThereIsAtLeastOneRole())
     880           0 :             ereport(WARNING,
     881             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     882             :                      errmsg("no roles are defined in this database system"),
     883             :                      errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
     884             :                              username != NULL ? username : "postgres")));
     885             :     }
     886       31288 :     else if (AmBackgroundWorkerProcess())
     887             :     {
     888        4354 :         if (username == NULL && !OidIsValid(useroid))
     889             :         {
     890         782 :             InitializeSessionUserIdStandalone();
     891         782 :             am_superuser = true;
     892             :         }
     893             :         else
     894             :         {
     895        3572 :             InitializeSessionUserId(username, useroid,
     896        3572 :                                     (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
     897        3570 :             am_superuser = superuser();
     898             :         }
     899             :     }
     900             :     else
     901             :     {
     902             :         /* normal multiuser case */
     903             :         Assert(MyProcPort != NULL);
     904       26934 :         PerformAuthentication(MyProcPort);
     905       26800 :         InitializeSessionUserId(username, useroid, false);
     906             :         /* ensure that auth_method is actually valid, aka authn_id is not NULL */
     907       26792 :         if (MyClientConnectionInfo.authn_id)
     908         246 :             InitializeSystemUser(MyClientConnectionInfo.authn_id,
     909             :                                  hba_authname(MyClientConnectionInfo.auth_method));
     910       26792 :         am_superuser = superuser();
     911             :     }
     912             : 
     913             :     /* Report any SSL/GSS details for the session. */
     914       33736 :     if (MyProcPort != NULL)
     915             :     {
     916             :         Assert(!bootstrap);
     917             : 
     918       26792 :         pgstat_bestart_security();
     919             :     }
     920             : 
     921             :     /*
     922             :      * Binary upgrades only allowed super-user connections
     923             :      */
     924       33736 :     if (IsBinaryUpgrade && !am_superuser)
     925             :     {
     926           0 :         ereport(FATAL,
     927             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     928             :                  errmsg("must be superuser to connect in binary upgrade mode")));
     929             :     }
     930             : 
     931             :     /*
     932             :      * The last few regular connection slots are reserved for superusers and
     933             :      * roles with privileges of pg_use_reserved_connections.  We do not apply
     934             :      * these limits to background processes, since they all have their own
     935             :      * pools of PGPROC slots.
     936             :      *
     937             :      * Note: At this point, the new backend has already claimed a proc struct,
     938             :      * so we must check whether the number of free slots is strictly less than
     939             :      * the reserved connection limits.
     940             :      */
     941       33736 :     if (AmRegularBackendProcess() && !am_superuser &&
     942         482 :         (SuperuserReservedConnections + ReservedConnections) > 0 &&
     943         482 :         !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
     944             :     {
     945           8 :         if (nfree < SuperuserReservedConnections)
     946           2 :             ereport(FATAL,
     947             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     948             :                      errmsg("remaining connection slots are reserved for roles with the %s attribute",
     949             :                             "SUPERUSER")));
     950             : 
     951           6 :         if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
     952           2 :             ereport(FATAL,
     953             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     954             :                      errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
     955             :                             "pg_use_reserved_connections")));
     956             :     }
     957             : 
     958             :     /* Check replication permissions needed for walsender processes. */
     959       33732 :     if (am_walsender)
     960             :     {
     961             :         Assert(!bootstrap);
     962             : 
     963        2204 :         if (!has_rolreplication(GetUserId()))
     964           0 :             ereport(FATAL,
     965             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     966             :                      errmsg("permission denied to start WAL sender"),
     967             :                      errdetail("Only roles with the %s attribute may start a WAL sender process.",
     968             :                                "REPLICATION")));
     969             :     }
     970             : 
     971             :     /*
     972             :      * If this is a plain walsender only supporting physical replication, we
     973             :      * don't want to connect to any particular database. Just finish the
     974             :      * backend startup by processing any options from the startup packet, and
     975             :      * we're done.
     976             :      */
     977       33732 :     if (am_walsender && !am_db_walsender)
     978             :     {
     979             :         /* process any options passed in the startup packet */
     980         906 :         if (MyProcPort != NULL)
     981         906 :             process_startup_options(MyProcPort, am_superuser);
     982             : 
     983             :         /* Apply PostAuthDelay as soon as we've read all options */
     984         906 :         if (PostAuthDelay > 0)
     985           0 :             pg_usleep(PostAuthDelay * 1000000L);
     986             : 
     987             :         /* initialize client encoding */
     988         906 :         InitializeClientEncoding();
     989             : 
     990             :         /* fill in the remainder of this entry in the PgBackendStatus array */
     991         906 :         pgstat_bestart_final();
     992             : 
     993             :         /* close the transaction we started above */
     994         906 :         CommitTransactionCommand();
     995             : 
     996         906 :         return;
     997             :     }
     998             : 
     999             :     /*
    1000             :      * Set up the global variables holding database id and default tablespace.
    1001             :      * But note we won't actually try to touch the database just yet.
    1002             :      *
    1003             :      * We take a shortcut in the bootstrap case, otherwise we have to look up
    1004             :      * the db's entry in pg_database.
    1005             :      */
    1006       32826 :     if (bootstrap)
    1007             :     {
    1008          90 :         dboid = Template1DbOid;
    1009          90 :         MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
    1010             :     }
    1011       32736 :     else if (in_dbname != NULL)
    1012             :     {
    1013             :         HeapTuple   tuple;
    1014             :         Form_pg_database dbform;
    1015             : 
    1016       25998 :         tuple = GetDatabaseTuple(in_dbname);
    1017       25998 :         if (!HeapTupleIsValid(tuple))
    1018          18 :             ereport(FATAL,
    1019             :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
    1020             :                      errmsg("database \"%s\" does not exist", in_dbname)));
    1021       25980 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
    1022       25980 :         dboid = dbform->oid;
    1023             :     }
    1024        6738 :     else if (!OidIsValid(dboid))
    1025             :     {
    1026             :         /*
    1027             :          * If this is a background worker not bound to any particular
    1028             :          * database, we're done now.  Everything that follows only makes sense
    1029             :          * if we are bound to a specific database.  We do need to close the
    1030             :          * transaction we started before returning.
    1031             :          */
    1032         778 :         if (!bootstrap)
    1033             :         {
    1034         778 :             pgstat_bestart_final();
    1035         778 :             CommitTransactionCommand();
    1036             :         }
    1037         778 :         return;
    1038             :     }
    1039             : 
    1040             :     /*
    1041             :      * Now, take a writer's lock on the database we are trying to connect to.
    1042             :      * If there is a concurrently running DROP DATABASE on that database, this
    1043             :      * will block us until it finishes (and has committed its update of
    1044             :      * pg_database).
    1045             :      *
    1046             :      * Note that the lock is not held long, only until the end of this startup
    1047             :      * transaction.  This is OK since we will advertise our use of the
    1048             :      * database in the ProcArray before dropping the lock (in fact, that's the
    1049             :      * next thing to do).  Anyone trying a DROP DATABASE after this point will
    1050             :      * see us in the array once they have the lock.  Ordering is important for
    1051             :      * this because we don't want to advertise ourselves as being in this
    1052             :      * database until we have the lock; otherwise we create what amounts to a
    1053             :      * deadlock with CountOtherDBBackends().
    1054             :      *
    1055             :      * Note: use of RowExclusiveLock here is reasonable because we envision
    1056             :      * our session as being a concurrent writer of the database.  If we had a
    1057             :      * way of declaring a session as being guaranteed-read-only, we could use
    1058             :      * AccessShareLock for such sessions and thereby not conflict against
    1059             :      * CREATE DATABASE.
    1060             :      */
    1061       32030 :     if (!bootstrap)
    1062       31940 :         LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
    1063             : 
    1064             :     /*
    1065             :      * Recheck pg_database to make sure the target database hasn't gone away.
    1066             :      * If there was a concurrent DROP DATABASE, this ensures we will die
    1067             :      * cleanly without creating a mess.
    1068             :      */
    1069       32030 :     if (!bootstrap)
    1070             :     {
    1071             :         HeapTuple   tuple;
    1072             :         Form_pg_database datform;
    1073             : 
    1074       31940 :         tuple = GetDatabaseTupleByOid(dboid);
    1075       31940 :         if (HeapTupleIsValid(tuple))
    1076       31940 :             datform = (Form_pg_database) GETSTRUCT(tuple);
    1077             : 
    1078       31940 :         if (!HeapTupleIsValid(tuple) ||
    1079       25980 :             (in_dbname && namestrcmp(&datform->datname, in_dbname)))
    1080             :         {
    1081           0 :             if (in_dbname)
    1082           0 :                 ereport(FATAL,
    1083             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1084             :                          errmsg("database \"%s\" does not exist", in_dbname),
    1085             :                          errdetail("It seems to have just been dropped or renamed.")));
    1086             :             else
    1087           0 :                 ereport(FATAL,
    1088             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1089             :                          errmsg("database %u does not exist", dboid)));
    1090             :         }
    1091             : 
    1092       31940 :         strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
    1093             : 
    1094       31940 :         if (database_is_invalid_form(datform))
    1095             :         {
    1096          10 :             ereport(FATAL,
    1097             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1098             :                     errmsg("cannot connect to invalid database \"%s\"", dbname),
    1099             :                     errhint("Use DROP DATABASE to drop invalid databases."));
    1100             :         }
    1101             : 
    1102       31930 :         MyDatabaseTableSpace = datform->dattablespace;
    1103       31930 :         MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
    1104             :         /* pass the database name back to the caller */
    1105       31930 :         if (out_dbname)
    1106        2386 :             strcpy(out_dbname, dbname);
    1107             :     }
    1108             : 
    1109             :     /*
    1110             :      * Now that we rechecked, we are certain to be connected to a database and
    1111             :      * thus can set MyDatabaseId.
    1112             :      *
    1113             :      * It is important that MyDatabaseId only be set once we are sure that the
    1114             :      * target database can no longer be concurrently dropped or renamed.  For
    1115             :      * example, without this guarantee, pgstat_update_dbstats() could create
    1116             :      * entries for databases that were just dropped in the pgstat shutdown
    1117             :      * callback, which could confuse other code paths like the autovacuum
    1118             :      * scheduler.
    1119             :      */
    1120       32020 :     MyDatabaseId = dboid;
    1121             : 
    1122             :     /*
    1123             :      * Now we can mark our PGPROC entry with the database ID.
    1124             :      *
    1125             :      * We assume this is an atomic store so no lock is needed; though actually
    1126             :      * things would work fine even if it weren't atomic.  Anyone searching the
    1127             :      * ProcArray for this database's ID should hold the database lock, so they
    1128             :      * would not be executing concurrently with this store.  A process looking
    1129             :      * for another database's ID could in theory see a chance match if it read
    1130             :      * a partially-updated databaseId value; but as long as all such searches
    1131             :      * wait and retry, as in CountOtherDBBackends(), they will certainly see
    1132             :      * the correct value on their next try.
    1133             :      */
    1134       32020 :     MyProc->databaseId = MyDatabaseId;
    1135             : 
    1136             :     /*
    1137             :      * We established a catalog snapshot while reading pg_authid and/or
    1138             :      * pg_database; but until we have set up MyDatabaseId, we won't react to
    1139             :      * incoming sinval messages for unshared catalogs, so we won't realize it
    1140             :      * if the snapshot has been invalidated.  Assume it's no good anymore.
    1141             :      */
    1142       32020 :     InvalidateCatalogSnapshot();
    1143             : 
    1144             :     /*
    1145             :      * Now we should be able to access the database directory safely. Verify
    1146             :      * it's there and looks reasonable.
    1147             :      */
    1148       32020 :     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
    1149             : 
    1150       32020 :     if (!bootstrap)
    1151             :     {
    1152       31930 :         if (access(fullpath, F_OK) == -1)
    1153             :         {
    1154           0 :             if (errno == ENOENT)
    1155           0 :                 ereport(FATAL,
    1156             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1157             :                          errmsg("database \"%s\" does not exist",
    1158             :                                 dbname),
    1159             :                          errdetail("The database subdirectory \"%s\" is missing.",
    1160             :                                    fullpath)));
    1161             :             else
    1162           0 :                 ereport(FATAL,
    1163             :                         (errcode_for_file_access(),
    1164             :                          errmsg("could not access directory \"%s\": %m",
    1165             :                                 fullpath)));
    1166             :         }
    1167             : 
    1168       31930 :         ValidatePgVersion(fullpath);
    1169             :     }
    1170             : 
    1171       32020 :     SetDatabasePath(fullpath);
    1172       32020 :     pfree(fullpath);
    1173             : 
    1174             :     /*
    1175             :      * It's now possible to do real access to the system catalogs.
    1176             :      *
    1177             :      * Load relcache entries for the system catalogs.  This must create at
    1178             :      * least the minimum set of "nailed-in" cache entries.
    1179             :      */
    1180       32020 :     RelationCacheInitializePhase3();
    1181             : 
    1182             :     /* set up ACL framework (so CheckMyDatabase can check permissions) */
    1183       32014 :     initialize_acl();
    1184             : 
    1185             :     /*
    1186             :      * Re-read the pg_database row for our database, check permissions and set
    1187             :      * up database-specific GUC settings.  We can't do this until all the
    1188             :      * database-access infrastructure is up.  (Also, it wants to know if the
    1189             :      * user is a superuser, so the above stuff has to happen first.)
    1190             :      */
    1191       32014 :     if (!bootstrap)
    1192       31924 :         CheckMyDatabase(dbname, am_superuser,
    1193       31924 :                         (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
    1194             : 
    1195             :     /*
    1196             :      * Now process any command-line switches and any additional GUC variable
    1197             :      * settings passed in the startup packet.   We couldn't do this before
    1198             :      * because we didn't know if client is a superuser.
    1199             :      */
    1200       32008 :     if (MyProcPort != NULL)
    1201       25854 :         process_startup_options(MyProcPort, am_superuser);
    1202             : 
    1203             :     /* Process pg_db_role_setting options */
    1204       32008 :     process_settings(MyDatabaseId, GetSessionUserId());
    1205             : 
    1206             :     /* Apply PostAuthDelay as soon as we've read all options */
    1207       32008 :     if (PostAuthDelay > 0)
    1208           0 :         pg_usleep(PostAuthDelay * 1000000L);
    1209             : 
    1210             :     /*
    1211             :      * Initialize various default states that can't be set up until we've
    1212             :      * selected the active user and gotten the right GUC settings.
    1213             :      */
    1214             : 
    1215             :     /* set default namespace search path */
    1216       32008 :     InitializeSearchPath();
    1217             : 
    1218             :     /* initialize client encoding */
    1219       32008 :     InitializeClientEncoding();
    1220             : 
    1221             :     /* Initialize this backend's session state. */
    1222       32008 :     InitializeSession();
    1223             : 
    1224             :     /*
    1225             :      * If this is an interactive session, load any libraries that should be
    1226             :      * preloaded at backend start.  Since those are determined by GUCs, this
    1227             :      * can't happen until GUC settings are complete, but we want it to happen
    1228             :      * during the initial transaction in case anything that requires database
    1229             :      * access needs to be done.
    1230             :      */
    1231       32008 :     if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
    1232       24660 :         process_session_preload_libraries();
    1233             : 
    1234             :     /* fill in the remainder of this entry in the PgBackendStatus array */
    1235       32008 :     if (!bootstrap)
    1236       31918 :         pgstat_bestart_final();
    1237             : 
    1238             :     /* close the transaction we started above */
    1239       32008 :     if (!bootstrap)
    1240       31918 :         CommitTransactionCommand();
    1241             : }
    1242             : 
    1243             : /*
    1244             :  * Process any command-line switches and any additional GUC variable
    1245             :  * settings passed in the startup packet.
    1246             :  */
    1247             : static void
    1248       26760 : process_startup_options(Port *port, bool am_superuser)
    1249             : {
    1250             :     GucContext  gucctx;
    1251             :     ListCell   *gucopts;
    1252             : 
    1253       26760 :     gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
    1254             : 
    1255             :     /*
    1256             :      * First process any command-line switches that were included in the
    1257             :      * startup packet, if we are in a regular backend.
    1258             :      */
    1259       26760 :     if (port->cmdline_options != NULL)
    1260             :     {
    1261             :         /*
    1262             :          * The maximum possible number of commandline arguments that could
    1263             :          * come from port->cmdline_options is (strlen + 1) / 2; see
    1264             :          * pg_split_opts().
    1265             :          */
    1266             :         char      **av;
    1267             :         int         maxac;
    1268             :         int         ac;
    1269             : 
    1270        7016 :         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
    1271             : 
    1272        7016 :         av = (char **) palloc(maxac * sizeof(char *));
    1273        7016 :         ac = 0;
    1274             : 
    1275        7016 :         av[ac++] = "postgres";
    1276             : 
    1277        7016 :         pg_split_opts(av, &ac, port->cmdline_options);
    1278             : 
    1279        7016 :         av[ac] = NULL;
    1280             : 
    1281             :         Assert(ac < maxac);
    1282             : 
    1283        7016 :         (void) process_postgres_switches(ac, av, gucctx, NULL);
    1284             :     }
    1285             : 
    1286             :     /*
    1287             :      * Process any additional GUC variable settings passed in startup packet.
    1288             :      * These are handled exactly like command-line variables.
    1289             :      */
    1290       26760 :     gucopts = list_head(port->guc_options);
    1291       63618 :     while (gucopts)
    1292             :     {
    1293             :         char       *name;
    1294             :         char       *value;
    1295             : 
    1296       36858 :         name = lfirst(gucopts);
    1297       36858 :         gucopts = lnext(port->guc_options, gucopts);
    1298             : 
    1299       36858 :         value = lfirst(gucopts);
    1300       36858 :         gucopts = lnext(port->guc_options, gucopts);
    1301             : 
    1302       36858 :         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
    1303             :     }
    1304       26760 : }
    1305             : 
    1306             : /*
    1307             :  * Load GUC settings from pg_db_role_setting.
    1308             :  *
    1309             :  * We try specific settings for the database/role combination, as well as
    1310             :  * general for this database and for this user.
    1311             :  */
    1312             : static void
    1313       32008 : process_settings(Oid databaseid, Oid roleid)
    1314             : {
    1315             :     Relation    relsetting;
    1316             :     Snapshot    snapshot;
    1317             : 
    1318       32008 :     if (!IsUnderPostmaster)
    1319         194 :         return;
    1320             : 
    1321       31814 :     relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
    1322             : 
    1323             :     /* read all the settings under the same snapshot for efficiency */
    1324       31814 :     snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
    1325             : 
    1326             :     /* Later settings are ignored if set earlier. */
    1327       31814 :     ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
    1328       31814 :     ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
    1329       31814 :     ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
    1330       31814 :     ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
    1331             : 
    1332       31814 :     UnregisterSnapshot(snapshot);
    1333       31814 :     table_close(relsetting, AccessShareLock);
    1334             : }
    1335             : 
    1336             : /*
    1337             :  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
    1338             :  * before all the supporting modules begin to nail their doors shut via
    1339             :  * their own callbacks.
    1340             :  *
    1341             :  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
    1342             :  * via separate callbacks that execute before this one.  We don't combine the
    1343             :  * callbacks because we still want this one to happen if the user-level
    1344             :  * cleanup fails.
    1345             :  */
    1346             : static void
    1347       34610 : ShutdownPostgres(int code, Datum arg)
    1348             : {
    1349             :     /* Make sure we've killed any active transaction */
    1350       34610 :     AbortOutOfAnyTransaction();
    1351             : 
    1352             :     /*
    1353             :      * User locks are not released by transaction end, so be sure to release
    1354             :      * them explicitly.
    1355             :      */
    1356       34610 :     LockReleaseAll(USER_LOCKMETHOD, true);
    1357       34610 : }
    1358             : 
    1359             : 
    1360             : /*
    1361             :  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
    1362             :  */
    1363             : static void
    1364          12 : StatementTimeoutHandler(void)
    1365             : {
    1366          12 :     int         sig = SIGINT;
    1367             : 
    1368             :     /*
    1369             :      * During authentication the timeout is used to deal with
    1370             :      * authentication_timeout - we want to quit in response to such timeouts.
    1371             :      */
    1372          12 :     if (ClientAuthInProgress)
    1373           0 :         sig = SIGTERM;
    1374             : 
    1375             : #ifdef HAVE_SETSID
    1376             :     /* try to signal whole process group */
    1377          12 :     kill(-MyProcPid, sig);
    1378             : #endif
    1379          12 :     kill(MyProcPid, sig);
    1380          12 : }
    1381             : 
    1382             : /*
    1383             :  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
    1384             :  */
    1385             : static void
    1386           8 : LockTimeoutHandler(void)
    1387             : {
    1388             : #ifdef HAVE_SETSID
    1389             :     /* try to signal whole process group */
    1390           8 :     kill(-MyProcPid, SIGINT);
    1391             : #endif
    1392           8 :     kill(MyProcPid, SIGINT);
    1393           8 : }
    1394             : 
    1395             : static void
    1396           2 : TransactionTimeoutHandler(void)
    1397             : {
    1398           2 :     TransactionTimeoutPending = true;
    1399           2 :     InterruptPending = true;
    1400           2 :     SetLatch(MyLatch);
    1401           2 : }
    1402             : 
    1403             : static void
    1404           2 : IdleInTransactionSessionTimeoutHandler(void)
    1405             : {
    1406           2 :     IdleInTransactionSessionTimeoutPending = true;
    1407           2 :     InterruptPending = true;
    1408           2 :     SetLatch(MyLatch);
    1409           2 : }
    1410             : 
    1411             : static void
    1412           2 : IdleSessionTimeoutHandler(void)
    1413             : {
    1414           2 :     IdleSessionTimeoutPending = true;
    1415           2 :     InterruptPending = true;
    1416           2 :     SetLatch(MyLatch);
    1417           2 : }
    1418             : 
    1419             : static void
    1420          24 : IdleStatsUpdateTimeoutHandler(void)
    1421             : {
    1422          24 :     IdleStatsUpdateTimeoutPending = true;
    1423          24 :     InterruptPending = true;
    1424          24 :     SetLatch(MyLatch);
    1425          24 : }
    1426             : 
    1427             : static void
    1428           0 : ClientCheckTimeoutHandler(void)
    1429             : {
    1430           0 :     CheckClientConnectionPending = true;
    1431           0 :     InterruptPending = true;
    1432           0 :     SetLatch(MyLatch);
    1433           0 : }
    1434             : 
    1435             : /*
    1436             :  * Returns true if at least one role is defined in this database cluster.
    1437             :  */
    1438             : static bool
    1439         108 : ThereIsAtLeastOneRole(void)
    1440             : {
    1441             :     Relation    pg_authid_rel;
    1442             :     TableScanDesc scan;
    1443             :     bool        result;
    1444             : 
    1445         108 :     pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
    1446             : 
    1447         108 :     scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
    1448         108 :     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
    1449             : 
    1450         108 :     table_endscan(scan);
    1451         108 :     table_close(pg_authid_rel, AccessShareLock);
    1452             : 
    1453         108 :     return result;
    1454             : }

Generated by: LCOV version 1.14