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

Generated by: LCOV version 1.14