LCOV - code coverage report
Current view: top level - src/backend/postmaster - pgstat.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12devel Lines: 1365 2059 66.3 %
Date: 2018-12-12 09:22:26 Functions: 94 113 83.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* ----------
       2             :  * pgstat.c
       3             :  *
       4             :  *  All the statistics collector stuff hacked up in one big, ugly file.
       5             :  *
       6             :  *  TODO:   - Separate collector, postmaster and backend stuff
       7             :  *            into different files.
       8             :  *
       9             :  *          - Add some automatic call for pgstat vacuuming.
      10             :  *
      11             :  *          - Add a pgstat config column to pg_database, so this
      12             :  *            entire thing can be enabled/disabled on a per db basis.
      13             :  *
      14             :  *  Copyright (c) 2001-2018, PostgreSQL Global Development Group
      15             :  *
      16             :  *  src/backend/postmaster/pgstat.c
      17             :  * ----------
      18             :  */
      19             : #include "postgres.h"
      20             : 
      21             : #include <unistd.h>
      22             : #include <fcntl.h>
      23             : #include <sys/param.h>
      24             : #include <sys/time.h>
      25             : #include <sys/socket.h>
      26             : #include <netdb.h>
      27             : #include <netinet/in.h>
      28             : #include <arpa/inet.h>
      29             : #include <signal.h>
      30             : #include <time.h>
      31             : #ifdef HAVE_SYS_SELECT_H
      32             : #include <sys/select.h>
      33             : #endif
      34             : 
      35             : #include "pgstat.h"
      36             : 
      37             : #include "access/heapam.h"
      38             : #include "access/htup_details.h"
      39             : #include "access/transam.h"
      40             : #include "access/twophase_rmgr.h"
      41             : #include "access/xact.h"
      42             : #include "catalog/pg_database.h"
      43             : #include "catalog/pg_proc.h"
      44             : #include "common/ip.h"
      45             : #include "libpq/libpq.h"
      46             : #include "libpq/pqsignal.h"
      47             : #include "mb/pg_wchar.h"
      48             : #include "miscadmin.h"
      49             : #include "pg_trace.h"
      50             : #include "postmaster/autovacuum.h"
      51             : #include "postmaster/fork_process.h"
      52             : #include "postmaster/postmaster.h"
      53             : #include "replication/walsender.h"
      54             : #include "storage/backendid.h"
      55             : #include "storage/dsm.h"
      56             : #include "storage/fd.h"
      57             : #include "storage/ipc.h"
      58             : #include "storage/latch.h"
      59             : #include "storage/lmgr.h"
      60             : #include "storage/pg_shmem.h"
      61             : #include "storage/procsignal.h"
      62             : #include "storage/sinvaladt.h"
      63             : #include "utils/ascii.h"
      64             : #include "utils/guc.h"
      65             : #include "utils/memutils.h"
      66             : #include "utils/ps_status.h"
      67             : #include "utils/rel.h"
      68             : #include "utils/snapmgr.h"
      69             : #include "utils/timestamp.h"
      70             : #include "utils/tqual.h"
      71             : 
      72             : 
      73             : /* ----------
      74             :  * Timer definitions.
      75             :  * ----------
      76             :  */
      77             : #define PGSTAT_STAT_INTERVAL    500 /* Minimum time between stats file
      78             :                                      * updates; in milliseconds. */
      79             : 
      80             : #define PGSTAT_RETRY_DELAY      10  /* How long to wait between checks for a
      81             :                                      * new file; in milliseconds. */
      82             : 
      83             : #define PGSTAT_MAX_WAIT_TIME    10000   /* Maximum time to wait for a stats
      84             :                                          * file update; in milliseconds. */
      85             : 
      86             : #define PGSTAT_INQ_INTERVAL     640 /* How often to ping the collector for a
      87             :                                      * new file; in milliseconds. */
      88             : 
      89             : #define PGSTAT_RESTART_INTERVAL 60  /* How often to attempt to restart a
      90             :                                      * failed statistics collector; in
      91             :                                      * seconds. */
      92             : 
      93             : #define PGSTAT_POLL_LOOP_COUNT  (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
      94             : #define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
      95             : 
      96             : /* Minimum receive buffer size for the collector's socket. */
      97             : #define PGSTAT_MIN_RCVBUF       (100 * 1024)
      98             : 
      99             : 
     100             : /* ----------
     101             :  * The initial size hints for the hash tables used in the collector.
     102             :  * ----------
     103             :  */
     104             : #define PGSTAT_DB_HASH_SIZE     16
     105             : #define PGSTAT_TAB_HASH_SIZE    512
     106             : #define PGSTAT_FUNCTION_HASH_SIZE   512
     107             : 
     108             : 
     109             : /* ----------
     110             :  * Total number of backends including auxiliary
     111             :  *
     112             :  * We reserve a slot for each possible BackendId, plus one for each
     113             :  * possible auxiliary process type.  (This scheme assumes there is not
     114             :  * more than one of any auxiliary process type at a time.) MaxBackends
     115             :  * includes autovacuum workers and background workers as well.
     116             :  * ----------
     117             :  */
     118             : #define NumBackendStatSlots (MaxBackends + NUM_AUXPROCTYPES)
     119             : 
     120             : 
     121             : /* ----------
     122             :  * GUC parameters
     123             :  * ----------
     124             :  */
     125             : bool        pgstat_track_activities = false;
     126             : bool        pgstat_track_counts = false;
     127             : int         pgstat_track_functions = TRACK_FUNC_OFF;
     128             : int         pgstat_track_activity_query_size = 1024;
     129             : 
     130             : /* ----------
     131             :  * Built from GUC parameter
     132             :  * ----------
     133             :  */
     134             : char       *pgstat_stat_directory = NULL;
     135             : char       *pgstat_stat_filename = NULL;
     136             : char       *pgstat_stat_tmpname = NULL;
     137             : 
     138             : /*
     139             :  * BgWriter global statistics counters (unused in other processes).
     140             :  * Stored directly in a stats message structure so it can be sent
     141             :  * without needing to copy things around.  We assume this inits to zeroes.
     142             :  */
     143             : PgStat_MsgBgWriter BgWriterStats;
     144             : 
     145             : /* ----------
     146             :  * Local data
     147             :  * ----------
     148             :  */
     149             : NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
     150             : 
     151             : static struct sockaddr_storage pgStatAddr;
     152             : 
     153             : static time_t last_pgstat_start_time;
     154             : 
     155             : static bool pgStatRunningInCollector = false;
     156             : 
     157             : /*
     158             :  * Structures in which backends store per-table info that's waiting to be
     159             :  * sent to the collector.
     160             :  *
     161             :  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
     162             :  * for the life of the backend.  Also, we zero out the t_id fields of the
     163             :  * contained PgStat_TableStatus structs whenever they are not actively in use.
     164             :  * This allows relcache pgstat_info pointers to be treated as long-lived data,
     165             :  * avoiding repeated searches in pgstat_initstats() when a relation is
     166             :  * repeatedly opened during a transaction.
     167             :  */
     168             : #define TABSTAT_QUANTUM     100 /* we alloc this many at a time */
     169             : 
     170             : typedef struct TabStatusArray
     171             : {
     172             :     struct TabStatusArray *tsa_next;    /* link to next array, if any */
     173             :     int         tsa_used;       /* # entries currently used */
     174             :     PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];    /* per-table data */
     175             : } TabStatusArray;
     176             : 
     177             : static TabStatusArray *pgStatTabList = NULL;
     178             : 
     179             : /*
     180             :  * pgStatTabHash entry: map from relation OID to PgStat_TableStatus pointer
     181             :  */
     182             : typedef struct TabStatHashEntry
     183             : {
     184             :     Oid         t_id;
     185             :     PgStat_TableStatus *tsa_entry;
     186             : } TabStatHashEntry;
     187             : 
     188             : /*
     189             :  * Hash table for O(1) t_id -> tsa_entry lookup
     190             :  */
     191             : static HTAB *pgStatTabHash = NULL;
     192             : 
     193             : /*
     194             :  * Backends store per-function info that's waiting to be sent to the collector
     195             :  * in this hash table (indexed by function OID).
     196             :  */
     197             : static HTAB *pgStatFunctions = NULL;
     198             : 
     199             : /*
     200             :  * Indicates if backend has some function stats that it hasn't yet
     201             :  * sent to the collector.
     202             :  */
     203             : static bool have_function_stats = false;
     204             : 
     205             : /*
     206             :  * Tuple insertion/deletion counts for an open transaction can't be propagated
     207             :  * into PgStat_TableStatus counters until we know if it is going to commit
     208             :  * or abort.  Hence, we keep these counts in per-subxact structs that live
     209             :  * in TopTransactionContext.  This data structure is designed on the assumption
     210             :  * that subxacts won't usually modify very many tables.
     211             :  */
     212             : typedef struct PgStat_SubXactStatus
     213             : {
     214             :     int         nest_level;     /* subtransaction nest level */
     215             :     struct PgStat_SubXactStatus *prev;  /* higher-level subxact if any */
     216             :     PgStat_TableXactStatus *first;  /* head of list for this subxact */
     217             : } PgStat_SubXactStatus;
     218             : 
     219             : static PgStat_SubXactStatus *pgStatXactStack = NULL;
     220             : 
     221             : static int  pgStatXactCommit = 0;
     222             : static int  pgStatXactRollback = 0;
     223             : PgStat_Counter pgStatBlockReadTime = 0;
     224             : PgStat_Counter pgStatBlockWriteTime = 0;
     225             : 
     226             : /* Record that's written to 2PC state file when pgstat state is persisted */
     227             : typedef struct TwoPhasePgStatRecord
     228             : {
     229             :     PgStat_Counter tuples_inserted; /* tuples inserted in xact */
     230             :     PgStat_Counter tuples_updated;  /* tuples updated in xact */
     231             :     PgStat_Counter tuples_deleted;  /* tuples deleted in xact */
     232             :     PgStat_Counter inserted_pre_trunc;  /* tuples inserted prior to truncate */
     233             :     PgStat_Counter updated_pre_trunc;   /* tuples updated prior to truncate */
     234             :     PgStat_Counter deleted_pre_trunc;   /* tuples deleted prior to truncate */
     235             :     Oid         t_id;           /* table's OID */
     236             :     bool        t_shared;       /* is it a shared catalog? */
     237             :     bool        t_truncated;    /* was the relation truncated? */
     238             : } TwoPhasePgStatRecord;
     239             : 
     240             : /*
     241             :  * Info about current "snapshot" of stats file
     242             :  */
     243             : static MemoryContext pgStatLocalContext = NULL;
     244             : static HTAB *pgStatDBHash = NULL;
     245             : 
     246             : /* Status for backends including auxiliary */
     247             : static LocalPgBackendStatus *localBackendStatusTable = NULL;
     248             : 
     249             : /* Total number of backends including auxiliary */
     250             : static int  localNumBackends = 0;
     251             : 
     252             : /*
     253             :  * Cluster wide statistics, kept in the stats collector.
     254             :  * Contains statistics that are not collected per database
     255             :  * or per table.
     256             :  */
     257             : static PgStat_ArchiverStats archiverStats;
     258             : static PgStat_GlobalStats globalStats;
     259             : 
     260             : /*
     261             :  * List of OIDs of databases we need to write out.  If an entry is InvalidOid,
     262             :  * it means to write only the shared-catalog stats ("DB 0"); otherwise, we
     263             :  * will write both that DB's data and the shared stats.
     264             :  */
     265             : static List *pending_write_requests = NIL;
     266             : 
     267             : /* Signal handler flags */
     268             : static volatile bool need_exit = false;
     269             : static volatile bool got_SIGHUP = false;
     270             : 
     271             : /*
     272             :  * Total time charged to functions so far in the current backend.
     273             :  * We use this to help separate "self" and "other" time charges.
     274             :  * (We assume this initializes to zero.)
     275             :  */
     276             : static instr_time total_func_time;
     277             : 
     278             : 
     279             : /* ----------
     280             :  * Local function forward declarations
     281             :  * ----------
     282             :  */
     283             : #ifdef EXEC_BACKEND
     284             : static pid_t pgstat_forkexec(void);
     285             : #endif
     286             : 
     287             : NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]) pg_attribute_noreturn();
     288             : static void pgstat_exit(SIGNAL_ARGS);
     289             : static void pgstat_beshutdown_hook(int code, Datum arg);
     290             : static void pgstat_sighup_handler(SIGNAL_ARGS);
     291             : 
     292             : static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
     293             : static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
     294             :                      Oid tableoid, bool create);
     295             : static void pgstat_write_statsfiles(bool permanent, bool allDbs);
     296             : static void pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent);
     297             : static HTAB *pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep);
     298             : static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent);
     299             : static void backend_read_statsfile(void);
     300             : static void pgstat_read_current_status(void);
     301             : 
     302             : static bool pgstat_write_statsfile_needed(void);
     303             : static bool pgstat_db_requested(Oid databaseid);
     304             : 
     305             : static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
     306             : static void pgstat_send_funcstats(void);
     307             : static HTAB *pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid);
     308             : 
     309             : static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
     310             : 
     311             : static void pgstat_setup_memcxt(void);
     312             : 
     313             : static const char *pgstat_get_wait_activity(WaitEventActivity w);
     314             : static const char *pgstat_get_wait_client(WaitEventClient w);
     315             : static const char *pgstat_get_wait_ipc(WaitEventIPC w);
     316             : static const char *pgstat_get_wait_timeout(WaitEventTimeout w);
     317             : static const char *pgstat_get_wait_io(WaitEventIO w);
     318             : 
     319             : static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
     320             : static void pgstat_send(void *msg, int len);
     321             : 
     322             : static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
     323             : static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
     324             : static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
     325             : static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
     326             : static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
     327             : static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
     328             : static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
     329             : static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
     330             : static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
     331             : static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
     332             : static void pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len);
     333             : static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
     334             : static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
     335             : static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
     336             : static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
     337             : static void pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len);
     338             : static void pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len);
     339             : 
     340             : /* ------------------------------------------------------------
     341             :  * Public functions called from postmaster follow
     342             :  * ------------------------------------------------------------
     343             :  */
     344             : 
     345             : /* ----------
     346             :  * pgstat_init() -
     347             :  *
     348             :  *  Called from postmaster at startup. Create the resources required
     349             :  *  by the statistics collector process.  If unable to do so, do not
     350             :  *  fail --- better to let the postmaster start with stats collection
     351             :  *  disabled.
     352             :  * ----------
     353             :  */
     354             : void
     355         528 : pgstat_init(void)
     356             : {
     357             :     ACCEPT_TYPE_ARG3 alen;
     358         528 :     struct addrinfo *addrs = NULL,
     359             :                *addr,
     360             :                 hints;
     361             :     int         ret;
     362             :     fd_set      rset;
     363             :     struct timeval tv;
     364             :     char        test_byte;
     365             :     int         sel_res;
     366         528 :     int         tries = 0;
     367             : 
     368             : #define TESTBYTEVAL ((char) 199)
     369             : 
     370             :     /*
     371             :      * This static assertion verifies that we didn't mess up the calculations
     372             :      * involved in selecting maximum payload sizes for our UDP messages.
     373             :      * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
     374             :      * be silent performance loss from fragmentation, it seems worth having a
     375             :      * compile-time cross-check that we didn't.
     376             :      */
     377             :     StaticAssertStmt(sizeof(PgStat_Msg) <= PGSTAT_MAX_MSG_SIZE,
     378             :                      "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
     379             : 
     380             :     /*
     381             :      * Create the UDP socket for sending and receiving statistic messages
     382             :      */
     383         528 :     hints.ai_flags = AI_PASSIVE;
     384         528 :     hints.ai_family = AF_UNSPEC;
     385         528 :     hints.ai_socktype = SOCK_DGRAM;
     386         528 :     hints.ai_protocol = 0;
     387         528 :     hints.ai_addrlen = 0;
     388         528 :     hints.ai_addr = NULL;
     389         528 :     hints.ai_canonname = NULL;
     390         528 :     hints.ai_next = NULL;
     391         528 :     ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
     392         528 :     if (ret || !addrs)
     393             :     {
     394           0 :         ereport(LOG,
     395             :                 (errmsg("could not resolve \"localhost\": %s",
     396             :                         gai_strerror(ret))));
     397           0 :         goto startup_failed;
     398             :     }
     399             : 
     400             :     /*
     401             :      * On some platforms, pg_getaddrinfo_all() may return multiple addresses
     402             :      * only one of which will actually work (eg, both IPv6 and IPv4 addresses
     403             :      * when kernel will reject IPv6).  Worse, the failure may occur at the
     404             :      * bind() or perhaps even connect() stage.  So we must loop through the
     405             :      * results till we find a working combination. We will generate LOG
     406             :      * messages, but no error, for bogus combinations.
     407             :      */
     408         528 :     for (addr = addrs; addr; addr = addr->ai_next)
     409             :     {
     410             : #ifdef HAVE_UNIX_SOCKETS
     411             :         /* Ignore AF_UNIX sockets, if any are returned. */
     412         528 :         if (addr->ai_family == AF_UNIX)
     413           0 :             continue;
     414             : #endif
     415             : 
     416         528 :         if (++tries > 1)
     417           0 :             ereport(LOG,
     418             :                     (errmsg("trying another address for the statistics collector")));
     419             : 
     420             :         /*
     421             :          * Create the socket.
     422             :          */
     423         528 :         if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
     424             :         {
     425           0 :             ereport(LOG,
     426             :                     (errcode_for_socket_access(),
     427             :                      errmsg("could not create socket for statistics collector: %m")));
     428           0 :             continue;
     429             :         }
     430             : 
     431             :         /*
     432             :          * Bind it to a kernel assigned port on localhost and get the assigned
     433             :          * port via getsockname().
     434             :          */
     435         528 :         if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
     436             :         {
     437           0 :             ereport(LOG,
     438             :                     (errcode_for_socket_access(),
     439             :                      errmsg("could not bind socket for statistics collector: %m")));
     440           0 :             closesocket(pgStatSock);
     441           0 :             pgStatSock = PGINVALID_SOCKET;
     442           0 :             continue;
     443             :         }
     444             : 
     445         528 :         alen = sizeof(pgStatAddr);
     446         528 :         if (getsockname(pgStatSock, (struct sockaddr *) &pgStatAddr, &alen) < 0)
     447             :         {
     448           0 :             ereport(LOG,
     449             :                     (errcode_for_socket_access(),
     450             :                      errmsg("could not get address of socket for statistics collector: %m")));
     451           0 :             closesocket(pgStatSock);
     452           0 :             pgStatSock = PGINVALID_SOCKET;
     453           0 :             continue;
     454             :         }
     455             : 
     456             :         /*
     457             :          * Connect the socket to its own address.  This saves a few cycles by
     458             :          * not having to respecify the target address on every send. This also
     459             :          * provides a kernel-level check that only packets from this same
     460             :          * address will be received.
     461             :          */
     462         528 :         if (connect(pgStatSock, (struct sockaddr *) &pgStatAddr, alen) < 0)
     463             :         {
     464           0 :             ereport(LOG,
     465             :                     (errcode_for_socket_access(),
     466             :                      errmsg("could not connect socket for statistics collector: %m")));
     467           0 :             closesocket(pgStatSock);
     468           0 :             pgStatSock = PGINVALID_SOCKET;
     469           0 :             continue;
     470             :         }
     471             : 
     472             :         /*
     473             :          * Try to send and receive a one-byte test message on the socket. This
     474             :          * is to catch situations where the socket can be created but will not
     475             :          * actually pass data (for instance, because kernel packet filtering
     476             :          * rules prevent it).
     477             :          */
     478         528 :         test_byte = TESTBYTEVAL;
     479             : 
     480             : retry1:
     481         528 :         if (send(pgStatSock, &test_byte, 1, 0) != 1)
     482             :         {
     483           0 :             if (errno == EINTR)
     484           0 :                 goto retry1;    /* if interrupted, just retry */
     485           0 :             ereport(LOG,
     486             :                     (errcode_for_socket_access(),
     487             :                      errmsg("could not send test message on socket for statistics collector: %m")));
     488           0 :             closesocket(pgStatSock);
     489           0 :             pgStatSock = PGINVALID_SOCKET;
     490           0 :             continue;
     491             :         }
     492             : 
     493             :         /*
     494             :          * There could possibly be a little delay before the message can be
     495             :          * received.  We arbitrarily allow up to half a second before deciding
     496             :          * it's broken.
     497             :          */
     498             :         for (;;)                /* need a loop to handle EINTR */
     499             :         {
     500         528 :             FD_ZERO(&rset);
     501         528 :             FD_SET(pgStatSock, &rset);
     502             : 
     503         528 :             tv.tv_sec = 0;
     504         528 :             tv.tv_usec = 500000;
     505         528 :             sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
     506         528 :             if (sel_res >= 0 || errno != EINTR)
     507             :                 break;
     508             :         }
     509         528 :         if (sel_res < 0)
     510             :         {
     511           0 :             ereport(LOG,
     512             :                     (errcode_for_socket_access(),
     513             :                      errmsg("select() failed in statistics collector: %m")));
     514           0 :             closesocket(pgStatSock);
     515           0 :             pgStatSock = PGINVALID_SOCKET;
     516           0 :             continue;
     517             :         }
     518         528 :         if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
     519             :         {
     520             :             /*
     521             :              * This is the case we actually think is likely, so take pains to
     522             :              * give a specific message for it.
     523             :              *
     524             :              * errno will not be set meaningfully here, so don't use it.
     525             :              */
     526           0 :             ereport(LOG,
     527             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
     528             :                      errmsg("test message did not get through on socket for statistics collector")));
     529           0 :             closesocket(pgStatSock);
     530           0 :             pgStatSock = PGINVALID_SOCKET;
     531           0 :             continue;
     532             :         }
     533             : 
     534         528 :         test_byte++;            /* just make sure variable is changed */
     535             : 
     536             : retry2:
     537         528 :         if (recv(pgStatSock, &test_byte, 1, 0) != 1)
     538             :         {
     539           0 :             if (errno == EINTR)
     540           0 :                 goto retry2;    /* if interrupted, just retry */
     541           0 :             ereport(LOG,
     542             :                     (errcode_for_socket_access(),
     543             :                      errmsg("could not receive test message on socket for statistics collector: %m")));
     544           0 :             closesocket(pgStatSock);
     545           0 :             pgStatSock = PGINVALID_SOCKET;
     546           0 :             continue;
     547             :         }
     548             : 
     549         528 :         if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
     550             :         {
     551           0 :             ereport(LOG,
     552             :                     (errcode(ERRCODE_INTERNAL_ERROR),
     553             :                      errmsg("incorrect test message transmission on socket for statistics collector")));
     554           0 :             closesocket(pgStatSock);
     555           0 :             pgStatSock = PGINVALID_SOCKET;
     556           0 :             continue;
     557             :         }
     558             : 
     559             :         /* If we get here, we have a working socket */
     560         528 :         break;
     561             :     }
     562             : 
     563             :     /* Did we find a working address? */
     564         528 :     if (!addr || pgStatSock == PGINVALID_SOCKET)
     565             :         goto startup_failed;
     566             : 
     567             :     /*
     568             :      * Set the socket to non-blocking IO.  This ensures that if the collector
     569             :      * falls behind, statistics messages will be discarded; backends won't
     570             :      * block waiting to send messages to the collector.
     571             :      */
     572         528 :     if (!pg_set_noblock(pgStatSock))
     573             :     {
     574           0 :         ereport(LOG,
     575             :                 (errcode_for_socket_access(),
     576             :                  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
     577           0 :         goto startup_failed;
     578             :     }
     579             : 
     580             :     /*
     581             :      * Try to ensure that the socket's receive buffer is at least
     582             :      * PGSTAT_MIN_RCVBUF bytes, so that it won't easily overflow and lose
     583             :      * data.  Use of UDP protocol means that we are willing to lose data under
     584             :      * heavy load, but we don't want it to happen just because of ridiculously
     585             :      * small default buffer sizes (such as 8KB on older Windows versions).
     586             :      */
     587             :     {
     588             :         int         old_rcvbuf;
     589             :         int         new_rcvbuf;
     590         528 :         ACCEPT_TYPE_ARG3 rcvbufsize = sizeof(old_rcvbuf);
     591             : 
     592         528 :         if (getsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
     593             :                        (char *) &old_rcvbuf, &rcvbufsize) < 0)
     594             :         {
     595           0 :             elog(LOG, "getsockopt(SO_RCVBUF) failed: %m");
     596             :             /* if we can't get existing size, always try to set it */
     597           0 :             old_rcvbuf = 0;
     598             :         }
     599             : 
     600         528 :         new_rcvbuf = PGSTAT_MIN_RCVBUF;
     601         528 :         if (old_rcvbuf < new_rcvbuf)
     602             :         {
     603           0 :             if (setsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
     604             :                            (char *) &new_rcvbuf, sizeof(new_rcvbuf)) < 0)
     605           0 :                 elog(LOG, "setsockopt(SO_RCVBUF) failed: %m");
     606             :         }
     607             :     }
     608             : 
     609         528 :     pg_freeaddrinfo_all(hints.ai_family, addrs);
     610             : 
     611         528 :     return;
     612             : 
     613             : startup_failed:
     614           0 :     ereport(LOG,
     615             :             (errmsg("disabling statistics collector for lack of working socket")));
     616             : 
     617           0 :     if (addrs)
     618           0 :         pg_freeaddrinfo_all(hints.ai_family, addrs);
     619             : 
     620           0 :     if (pgStatSock != PGINVALID_SOCKET)
     621           0 :         closesocket(pgStatSock);
     622           0 :     pgStatSock = PGINVALID_SOCKET;
     623             : 
     624             :     /*
     625             :      * Adjust GUC variables to suppress useless activity, and for debugging
     626             :      * purposes (seeing track_counts off is a clue that we failed here). We
     627             :      * use PGC_S_OVERRIDE because there is no point in trying to turn it back
     628             :      * on from postgresql.conf without a restart.
     629             :      */
     630           0 :     SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
     631             : }
     632             : 
     633             : /*
     634             :  * subroutine for pgstat_reset_all
     635             :  */
     636             : static void
     637         168 : pgstat_reset_remove_files(const char *directory)
     638             : {
     639             :     DIR        *dir;
     640             :     struct dirent *entry;
     641             :     char        fname[MAXPGPATH * 2];
     642             : 
     643         168 :     dir = AllocateDir(directory);
     644         770 :     while ((entry = ReadDir(dir, directory)) != NULL)
     645             :     {
     646             :         int         nchars;
     647             :         Oid         tmp_oid;
     648             : 
     649             :         /*
     650             :          * Skip directory entries that don't match the file names we write.
     651             :          * See get_dbstat_filename for the database-specific pattern.
     652             :          */
     653         434 :         if (strncmp(entry->d_name, "global.", 7) == 0)
     654          38 :             nchars = 7;
     655             :         else
     656             :         {
     657         396 :             nchars = 0;
     658         396 :             (void) sscanf(entry->d_name, "db_%u.%n",
     659             :                           &tmp_oid, &nchars);
     660         396 :             if (nchars <= 0)
     661         672 :                 continue;
     662             :             /* %u allows leading whitespace, so reject that */
     663          60 :             if (strchr("0123456789", entry->d_name[3]) == NULL)
     664           0 :                 continue;
     665             :         }
     666             : 
     667         196 :         if (strcmp(entry->d_name + nchars, "tmp") != 0 &&
     668          98 :             strcmp(entry->d_name + nchars, "stat") != 0)
     669           0 :             continue;
     670             : 
     671          98 :         snprintf(fname, sizeof(fname), "%s/%s", directory,
     672          98 :                  entry->d_name);
     673          98 :         unlink(fname);
     674             :     }
     675         168 :     FreeDir(dir);
     676         168 : }
     677             : 
     678             : /*
     679             :  * pgstat_reset_all() -
     680             :  *
     681             :  * Remove the stats files.  This is currently used only if WAL
     682             :  * recovery is needed after a crash.
     683             :  */
     684             : void
     685          84 : pgstat_reset_all(void)
     686             : {
     687          84 :     pgstat_reset_remove_files(pgstat_stat_directory);
     688          84 :     pgstat_reset_remove_files(PGSTAT_STAT_PERMANENT_DIRECTORY);
     689          84 : }
     690             : 
     691             : #ifdef EXEC_BACKEND
     692             : 
     693             : /*
     694             :  * pgstat_forkexec() -
     695             :  *
     696             :  * Format up the arglist for, then fork and exec, statistics collector process
     697             :  */
     698             : static pid_t
     699             : pgstat_forkexec(void)
     700             : {
     701             :     char       *av[10];
     702             :     int         ac = 0;
     703             : 
     704             :     av[ac++] = "postgres";
     705             :     av[ac++] = "--forkcol";
     706             :     av[ac++] = NULL;            /* filled in by postmaster_forkexec */
     707             : 
     708             :     av[ac] = NULL;
     709             :     Assert(ac < lengthof(av));
     710             : 
     711             :     return postmaster_forkexec(ac, av);
     712             : }
     713             : #endif                          /* EXEC_BACKEND */
     714             : 
     715             : 
     716             : /*
     717             :  * pgstat_start() -
     718             :  *
     719             :  *  Called from postmaster at startup or after an existing collector
     720             :  *  died.  Attempt to fire up a fresh statistics collector.
     721             :  *
     722             :  *  Returns PID of child process, or 0 if fail.
     723             :  *
     724             :  *  Note: if fail, we will be called again from the postmaster main loop.
     725             :  */
     726             : int
     727         532 : pgstat_start(void)
     728             : {
     729             :     time_t      curtime;
     730             :     pid_t       pgStatPid;
     731             : 
     732             :     /*
     733             :      * Check that the socket is there, else pgstat_init failed and we can do
     734             :      * nothing useful.
     735             :      */
     736         532 :     if (pgStatSock == PGINVALID_SOCKET)
     737           0 :         return 0;
     738             : 
     739             :     /*
     740             :      * Do nothing if too soon since last collector start.  This is a safety
     741             :      * valve to protect against continuous respawn attempts if the collector
     742             :      * is dying immediately at launch.  Note that since we will be re-called
     743             :      * from the postmaster main loop, we will get another chance later.
     744             :      */
     745         532 :     curtime = time(NULL);
     746         532 :     if ((unsigned int) (curtime - last_pgstat_start_time) <
     747             :         (unsigned int) PGSTAT_RESTART_INTERVAL)
     748           0 :         return 0;
     749         532 :     last_pgstat_start_time = curtime;
     750             : 
     751             :     /*
     752             :      * Okay, fork off the collector.
     753             :      */
     754             : #ifdef EXEC_BACKEND
     755             :     switch ((pgStatPid = pgstat_forkexec()))
     756             : #else
     757         532 :     switch ((pgStatPid = fork_process()))
     758             : #endif
     759             :     {
     760             :         case -1:
     761           0 :             ereport(LOG,
     762             :                     (errmsg("could not fork statistics collector: %m")));
     763           0 :             return 0;
     764             : 
     765             : #ifndef EXEC_BACKEND
     766             :         case 0:
     767             :             /* in postmaster child ... */
     768         532 :             InitPostmasterChild();
     769             : 
     770             :             /* Close the postmaster's sockets */
     771         532 :             ClosePostmasterPorts(false);
     772             : 
     773             :             /* Drop our connection to postmaster's shared memory, as well */
     774         532 :             dsm_detach_all();
     775         532 :             PGSharedMemoryDetach();
     776             : 
     777         532 :             PgstatCollectorMain(0, NULL);
     778             :             break;
     779             : #endif
     780             : 
     781             :         default:
     782         532 :             return (int) pgStatPid;
     783             :     }
     784             : 
     785             :     /* shouldn't get here */
     786             :     return 0;
     787             : }
     788             : 
     789             : void
     790           4 : allow_immediate_pgstat_restart(void)
     791             : {
     792           4 :     last_pgstat_start_time = 0;
     793           4 : }
     794             : 
     795             : /* ------------------------------------------------------------
     796             :  * Public functions used by backends follow
     797             :  *------------------------------------------------------------
     798             :  */
     799             : 
     800             : 
     801             : /* ----------
     802             :  * pgstat_report_stat() -
     803             :  *
     804             :  *  Must be called by processes that performs DML: tcop/postgres.c, logical
     805             :  *  receiver processes, SPI worker, etc. to send the so far collected
     806             :  *  per-table and function usage statistics to the collector.  Note that this
     807             :  *  is called only when not within a transaction, so it is fair to use
     808             :  *  transaction stop time as an approximation of current time.
     809             :  * ----------
     810             :  */
     811             : void
     812      369756 : pgstat_report_stat(bool force)
     813             : {
     814             :     /* we assume this inits to all zeroes: */
     815             :     static const PgStat_TableCounts all_zeroes;
     816             :     static TimestampTz last_report = 0;
     817             : 
     818             :     TimestampTz now;
     819             :     PgStat_MsgTabstat regular_msg;
     820             :     PgStat_MsgTabstat shared_msg;
     821             :     TabStatusArray *tsa;
     822             :     int         i;
     823             : 
     824             :     /* Don't expend a clock check if nothing to do */
     825      556558 :     if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
     826      187698 :         pgStatXactCommit == 0 && pgStatXactRollback == 0 &&
     827         438 :         !have_function_stats)
     828      354324 :         return;
     829             : 
     830             :     /*
     831             :      * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
     832             :      * msec since we last sent one, or the caller wants to force stats out.
     833             :      */
     834      369318 :     now = GetCurrentTransactionStopTimestamp();
     835      731186 :     if (!force &&
     836      361868 :         !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
     837      353448 :         return;
     838       15870 :     last_report = now;
     839             : 
     840             :     /*
     841             :      * Destroy pgStatTabHash before we start invalidating PgStat_TableEntry
     842             :      * entries it points to.  (Should we fail partway through the loop below,
     843             :      * it's okay to have removed the hashtable already --- the only
     844             :      * consequence is we'd get multiple entries for the same table in the
     845             :      * pgStatTabList, and that's safe.)
     846             :      */
     847       15870 :     if (pgStatTabHash)
     848       14614 :         hash_destroy(pgStatTabHash);
     849       15870 :     pgStatTabHash = NULL;
     850             : 
     851             :     /*
     852             :      * Scan through the TabStatusArray struct(s) to find tables that actually
     853             :      * have counts, and build messages to send.  We have to separate shared
     854             :      * relations from regular ones because the databaseid field in the message
     855             :      * header has to depend on that.
     856             :      */
     857       15870 :     regular_msg.m_databaseid = MyDatabaseId;
     858       15870 :     shared_msg.m_databaseid = InvalidOid;
     859       15870 :     regular_msg.m_nentries = 0;
     860       15870 :     shared_msg.m_nentries = 0;
     861             : 
     862       33614 :     for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
     863             :     {
     864      630014 :         for (i = 0; i < tsa->tsa_used; i++)
     865             :         {
     866      612270 :             PgStat_TableStatus *entry = &tsa->tsa_entries[i];
     867             :             PgStat_MsgTabstat *this_msg;
     868             :             PgStat_TableEntry *this_ent;
     869             : 
     870             :             /* Shouldn't have any pending transaction-dependent counts */
     871             :             Assert(entry->trans == NULL);
     872             : 
     873             :             /*
     874             :              * Ignore entries that didn't accumulate any actual counts, such
     875             :              * as indexes that were opened by the planner but not used.
     876             :              */
     877      612270 :             if (memcmp(&entry->t_counts, &all_zeroes,
     878             :                        sizeof(PgStat_TableCounts)) == 0)
     879      154288 :                 continue;
     880             : 
     881             :             /*
     882             :              * OK, insert data into the appropriate message, and send if full.
     883             :              */
     884      457982 :             this_msg = entry->t_shared ? &shared_msg : &regular_msg;
     885      457982 :             this_ent = &this_msg->m_entry[this_msg->m_nentries];
     886      457982 :             this_ent->t_id = entry->t_id;
     887      457982 :             memcpy(&this_ent->t_counts, &entry->t_counts,
     888             :                    sizeof(PgStat_TableCounts));
     889      457982 :             if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
     890             :             {
     891       46292 :                 pgstat_send_tabstat(this_msg);
     892       46292 :                 this_msg->m_nentries = 0;
     893             :             }
     894             :         }
     895             :         /* zero out TableStatus structs after use */
     896       17744 :         MemSet(tsa->tsa_entries, 0,
     897             :                tsa->tsa_used * sizeof(PgStat_TableStatus));
     898       17744 :         tsa->tsa_used = 0;
     899             :     }
     900             : 
     901             :     /*
     902             :      * Send partial messages.  Make sure that any pending xact commit/abort
     903             :      * gets counted, even if there are no table stats to send.
     904             :      */
     905       18548 :     if (regular_msg.m_nentries > 0 ||
     906        3834 :         pgStatXactCommit > 0 || pgStatXactRollback > 0)
     907       14720 :         pgstat_send_tabstat(&regular_msg);
     908       15870 :     if (shared_msg.m_nentries > 0)
     909        8974 :         pgstat_send_tabstat(&shared_msg);
     910             : 
     911             :     /* Now, send function statistics */
     912       15870 :     pgstat_send_funcstats();
     913             : }
     914             : 
     915             : /*
     916             :  * Subroutine for pgstat_report_stat: finish and send a tabstat message
     917             :  */
     918             : static void
     919       69986 : pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
     920             : {
     921             :     int         n;
     922             :     int         len;
     923             : 
     924             :     /* It's unlikely we'd get here with no socket, but maybe not impossible */
     925       69986 :     if (pgStatSock == PGINVALID_SOCKET)
     926         886 :         return;
     927             : 
     928             :     /*
     929             :      * Report and reset accumulated xact commit/rollback and I/O timings
     930             :      * whenever we send a normal tabstat message
     931             :      */
     932       69100 :     if (OidIsValid(tsmsg->m_databaseid))
     933             :     {
     934       55138 :         tsmsg->m_xact_commit = pgStatXactCommit;
     935       55138 :         tsmsg->m_xact_rollback = pgStatXactRollback;
     936       55138 :         tsmsg->m_block_read_time = pgStatBlockReadTime;
     937       55138 :         tsmsg->m_block_write_time = pgStatBlockWriteTime;
     938       55138 :         pgStatXactCommit = 0;
     939       55138 :         pgStatXactRollback = 0;
     940       55138 :         pgStatBlockReadTime = 0;
     941       55138 :         pgStatBlockWriteTime = 0;
     942             :     }
     943             :     else
     944             :     {
     945       13962 :         tsmsg->m_xact_commit = 0;
     946       13962 :         tsmsg->m_xact_rollback = 0;
     947       13962 :         tsmsg->m_block_read_time = 0;
     948       13962 :         tsmsg->m_block_write_time = 0;
     949             :     }
     950             : 
     951       69100 :     n = tsmsg->m_nentries;
     952       69100 :     len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
     953             :         n * sizeof(PgStat_TableEntry);
     954             : 
     955       69100 :     pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
     956       69100 :     pgstat_send(tsmsg, len);
     957             : }
     958             : 
     959             : /*
     960             :  * Subroutine for pgstat_report_stat: populate and send a function stat message
     961             :  */
     962             : static void
     963       15870 : pgstat_send_funcstats(void)
     964             : {
     965             :     /* we assume this inits to all zeroes: */
     966             :     static const PgStat_FunctionCounts all_zeroes;
     967             : 
     968             :     PgStat_MsgFuncstat msg;
     969             :     PgStat_BackendFunctionEntry *entry;
     970             :     HASH_SEQ_STATUS fstat;
     971             : 
     972       15870 :     if (pgStatFunctions == NULL)
     973       15870 :         return;
     974             : 
     975           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
     976           0 :     msg.m_databaseid = MyDatabaseId;
     977           0 :     msg.m_nentries = 0;
     978             : 
     979           0 :     hash_seq_init(&fstat, pgStatFunctions);
     980           0 :     while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
     981             :     {
     982             :         PgStat_FunctionEntry *m_ent;
     983             : 
     984             :         /* Skip it if no counts accumulated since last time */
     985           0 :         if (memcmp(&entry->f_counts, &all_zeroes,
     986             :                    sizeof(PgStat_FunctionCounts)) == 0)
     987           0 :             continue;
     988             : 
     989             :         /* need to convert format of time accumulators */
     990           0 :         m_ent = &msg.m_entry[msg.m_nentries];
     991           0 :         m_ent->f_id = entry->f_id;
     992           0 :         m_ent->f_numcalls = entry->f_counts.f_numcalls;
     993           0 :         m_ent->f_total_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_total_time);
     994           0 :         m_ent->f_self_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_self_time);
     995             : 
     996           0 :         if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
     997             :         {
     998           0 :             pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
     999           0 :                         msg.m_nentries * sizeof(PgStat_FunctionEntry));
    1000           0 :             msg.m_nentries = 0;
    1001             :         }
    1002             : 
    1003             :         /* reset the entry's counts */
    1004           0 :         MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
    1005             :     }
    1006             : 
    1007           0 :     if (msg.m_nentries > 0)
    1008           0 :         pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
    1009           0 :                     msg.m_nentries * sizeof(PgStat_FunctionEntry));
    1010             : 
    1011           0 :     have_function_stats = false;
    1012             : }
    1013             : 
    1014             : 
    1015             : /* ----------
    1016             :  * pgstat_vacuum_stat() -
    1017             :  *
    1018             :  *  Will tell the collector about objects he can get rid of.
    1019             :  * ----------
    1020             :  */
    1021             : void
    1022        1974 : pgstat_vacuum_stat(void)
    1023             : {
    1024             :     HTAB       *htab;
    1025             :     PgStat_MsgTabpurge msg;
    1026             :     PgStat_MsgFuncpurge f_msg;
    1027             :     HASH_SEQ_STATUS hstat;
    1028             :     PgStat_StatDBEntry *dbentry;
    1029             :     PgStat_StatTabEntry *tabentry;
    1030             :     PgStat_StatFuncEntry *funcentry;
    1031             :     int         len;
    1032             : 
    1033        1974 :     if (pgStatSock == PGINVALID_SOCKET)
    1034        2360 :         return;
    1035             : 
    1036             :     /*
    1037             :      * If not done for this transaction, read the statistics collector stats
    1038             :      * file into some hash tables.
    1039             :      */
    1040         798 :     backend_read_statsfile();
    1041             : 
    1042             :     /*
    1043             :      * Read pg_database and make a list of OIDs of all existing databases
    1044             :      */
    1045         798 :     htab = pgstat_collect_oids(DatabaseRelationId, Anum_pg_database_oid);
    1046             : 
    1047             :     /*
    1048             :      * Search the database hash table for dead databases and tell the
    1049             :      * collector to drop them.
    1050             :      */
    1051         798 :     hash_seq_init(&hstat, pgStatDBHash);
    1052        3784 :     while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
    1053             :     {
    1054        2188 :         Oid         dbid = dbentry->databaseid;
    1055             : 
    1056        2188 :         CHECK_FOR_INTERRUPTS();
    1057             : 
    1058             :         /* the DB entry for shared tables (with InvalidOid) is never dropped */
    1059        3586 :         if (OidIsValid(dbid) &&
    1060        1398 :             hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
    1061           0 :             pgstat_drop_database(dbid);
    1062             :     }
    1063             : 
    1064             :     /* Clean up */
    1065         798 :     hash_destroy(htab);
    1066             : 
    1067             :     /*
    1068             :      * Lookup our own database entry; if not found, nothing more to do.
    1069             :      */
    1070         798 :     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    1071             :                                                  (void *) &MyDatabaseId,
    1072             :                                                  HASH_FIND, NULL);
    1073         798 :     if (dbentry == NULL || dbentry->tables == NULL)
    1074           8 :         return;
    1075             : 
    1076             :     /*
    1077             :      * Similarly to above, make a list of all known relations in this DB.
    1078             :      */
    1079         790 :     htab = pgstat_collect_oids(RelationRelationId, Anum_pg_class_oid);
    1080             : 
    1081             :     /*
    1082             :      * Initialize our messages table counter to zero
    1083             :      */
    1084         790 :     msg.m_nentries = 0;
    1085             : 
    1086             :     /*
    1087             :      * Check for all tables listed in stats hashtable if they still exist.
    1088             :      */
    1089         790 :     hash_seq_init(&hstat, dbentry->tables);
    1090      290150 :     while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
    1091             :     {
    1092      288570 :         Oid         tabid = tabentry->tableid;
    1093             : 
    1094      288570 :         CHECK_FOR_INTERRUPTS();
    1095             : 
    1096      288570 :         if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
    1097      203352 :             continue;
    1098             : 
    1099             :         /*
    1100             :          * Not there, so add this table's Oid to the message
    1101             :          */
    1102       85218 :         msg.m_tableid[msg.m_nentries++] = tabid;
    1103             : 
    1104             :         /*
    1105             :          * If the message is full, send it out and reinitialize to empty
    1106             :          */
    1107       85218 :         if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
    1108             :         {
    1109         216 :             len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
    1110         216 :                 + msg.m_nentries * sizeof(Oid);
    1111             : 
    1112         216 :             pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
    1113         216 :             msg.m_databaseid = MyDatabaseId;
    1114         216 :             pgstat_send(&msg, len);
    1115             : 
    1116         216 :             msg.m_nentries = 0;
    1117             :         }
    1118             :     }
    1119             : 
    1120             :     /*
    1121             :      * Send the rest
    1122             :      */
    1123         790 :     if (msg.m_nentries > 0)
    1124             :     {
    1125         680 :         len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
    1126         680 :             + msg.m_nentries * sizeof(Oid);
    1127             : 
    1128         680 :         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
    1129         680 :         msg.m_databaseid = MyDatabaseId;
    1130         680 :         pgstat_send(&msg, len);
    1131             :     }
    1132             : 
    1133             :     /* Clean up */
    1134         790 :     hash_destroy(htab);
    1135             : 
    1136             :     /*
    1137             :      * Now repeat the above steps for functions.  However, we needn't bother
    1138             :      * in the common case where no function stats are being collected.
    1139             :      */
    1140        1580 :     if (dbentry->functions != NULL &&
    1141         790 :         hash_get_num_entries(dbentry->functions) > 0)
    1142             :     {
    1143           0 :         htab = pgstat_collect_oids(ProcedureRelationId, Anum_pg_proc_oid);
    1144             : 
    1145           0 :         pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
    1146           0 :         f_msg.m_databaseid = MyDatabaseId;
    1147           0 :         f_msg.m_nentries = 0;
    1148             : 
    1149           0 :         hash_seq_init(&hstat, dbentry->functions);
    1150           0 :         while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
    1151             :         {
    1152           0 :             Oid         funcid = funcentry->functionid;
    1153             : 
    1154           0 :             CHECK_FOR_INTERRUPTS();
    1155             : 
    1156           0 :             if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
    1157           0 :                 continue;
    1158             : 
    1159             :             /*
    1160             :              * Not there, so add this function's Oid to the message
    1161             :              */
    1162           0 :             f_msg.m_functionid[f_msg.m_nentries++] = funcid;
    1163             : 
    1164             :             /*
    1165             :              * If the message is full, send it out and reinitialize to empty
    1166             :              */
    1167           0 :             if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
    1168             :             {
    1169           0 :                 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
    1170           0 :                     + f_msg.m_nentries * sizeof(Oid);
    1171             : 
    1172           0 :                 pgstat_send(&f_msg, len);
    1173             : 
    1174           0 :                 f_msg.m_nentries = 0;
    1175             :             }
    1176             :         }
    1177             : 
    1178             :         /*
    1179             :          * Send the rest
    1180             :          */
    1181           0 :         if (f_msg.m_nentries > 0)
    1182             :         {
    1183           0 :             len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
    1184           0 :                 + f_msg.m_nentries * sizeof(Oid);
    1185             : 
    1186           0 :             pgstat_send(&f_msg, len);
    1187             :         }
    1188             : 
    1189           0 :         hash_destroy(htab);
    1190             :     }
    1191             : }
    1192             : 
    1193             : 
    1194             : /* ----------
    1195             :  * pgstat_collect_oids() -
    1196             :  *
    1197             :  *  Collect the OIDs of all objects listed in the specified system catalog
    1198             :  *  into a temporary hash table.  Caller should hash_destroy the result
    1199             :  *  when done with it.  (However, we make the table in CurrentMemoryContext
    1200             :  *  so that it will be freed properly in event of an error.)
    1201             :  * ----------
    1202             :  */
    1203             : static HTAB *
    1204        1588 : pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid)
    1205             : {
    1206             :     HTAB       *htab;
    1207             :     HASHCTL     hash_ctl;
    1208             :     Relation    rel;
    1209             :     HeapScanDesc scan;
    1210             :     HeapTuple   tup;
    1211             :     Snapshot    snapshot;
    1212             : 
    1213        1588 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
    1214        1588 :     hash_ctl.keysize = sizeof(Oid);
    1215        1588 :     hash_ctl.entrysize = sizeof(Oid);
    1216        1588 :     hash_ctl.hcxt = CurrentMemoryContext;
    1217        1588 :     htab = hash_create("Temporary table of OIDs",
    1218             :                        PGSTAT_TAB_HASH_SIZE,
    1219             :                        &hash_ctl,
    1220             :                        HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    1221             : 
    1222        1588 :     rel = heap_open(catalogid, AccessShareLock);
    1223        1588 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
    1224        1588 :     scan = heap_beginscan(rel, snapshot, 0, NULL);
    1225      454388 :     while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
    1226             :     {
    1227             :         Oid         thisoid;
    1228             :         bool        isnull;
    1229             : 
    1230      451212 :         thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
    1231             :         Assert(!isnull);
    1232             : 
    1233      451212 :         CHECK_FOR_INTERRUPTS();
    1234             : 
    1235      451212 :         (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
    1236             :     }
    1237        1588 :     heap_endscan(scan);
    1238        1588 :     UnregisterSnapshot(snapshot);
    1239        1588 :     heap_close(rel, AccessShareLock);
    1240             : 
    1241        1588 :     return htab;
    1242             : }
    1243             : 
    1244             : 
    1245             : /* ----------
    1246             :  * pgstat_drop_database() -
    1247             :  *
    1248             :  *  Tell the collector that we just dropped a database.
    1249             :  *  (If the message gets lost, we will still clean the dead DB eventually
    1250             :  *  via future invocations of pgstat_vacuum_stat().)
    1251             :  * ----------
    1252             :  */
    1253             : void
    1254          16 : pgstat_drop_database(Oid databaseid)
    1255             : {
    1256             :     PgStat_MsgDropdb msg;
    1257             : 
    1258          16 :     if (pgStatSock == PGINVALID_SOCKET)
    1259           0 :         return;
    1260             : 
    1261          16 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
    1262          16 :     msg.m_databaseid = databaseid;
    1263          16 :     pgstat_send(&msg, sizeof(msg));
    1264             : }
    1265             : 
    1266             : 
    1267             : /* ----------
    1268             :  * pgstat_drop_relation() -
    1269             :  *
    1270             :  *  Tell the collector that we just dropped a relation.
    1271             :  *  (If the message gets lost, we will still clean the dead entry eventually
    1272             :  *  via future invocations of pgstat_vacuum_stat().)
    1273             :  *
    1274             :  *  Currently not used for lack of any good place to call it; we rely
    1275             :  *  entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
    1276             :  * ----------
    1277             :  */
    1278             : #ifdef NOT_USED
    1279             : void
    1280             : pgstat_drop_relation(Oid relid)
    1281             : {
    1282             :     PgStat_MsgTabpurge msg;
    1283             :     int         len;
    1284             : 
    1285             :     if (pgStatSock == PGINVALID_SOCKET)
    1286             :         return;
    1287             : 
    1288             :     msg.m_tableid[0] = relid;
    1289             :     msg.m_nentries = 1;
    1290             : 
    1291             :     len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) + sizeof(Oid);
    1292             : 
    1293             :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
    1294             :     msg.m_databaseid = MyDatabaseId;
    1295             :     pgstat_send(&msg, len);
    1296             : }
    1297             : #endif                          /* NOT_USED */
    1298             : 
    1299             : 
    1300             : /* ----------
    1301             :  * pgstat_reset_counters() -
    1302             :  *
    1303             :  *  Tell the statistics collector to reset counters for our database.
    1304             :  *
    1305             :  *  Permission checking for this function is managed through the normal
    1306             :  *  GRANT system.
    1307             :  * ----------
    1308             :  */
    1309             : void
    1310           0 : pgstat_reset_counters(void)
    1311             : {
    1312             :     PgStat_MsgResetcounter msg;
    1313             : 
    1314           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1315           0 :         return;
    1316             : 
    1317           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
    1318           0 :     msg.m_databaseid = MyDatabaseId;
    1319           0 :     pgstat_send(&msg, sizeof(msg));
    1320             : }
    1321             : 
    1322             : /* ----------
    1323             :  * pgstat_reset_shared_counters() -
    1324             :  *
    1325             :  *  Tell the statistics collector to reset cluster-wide shared counters.
    1326             :  *
    1327             :  *  Permission checking for this function is managed through the normal
    1328             :  *  GRANT system.
    1329             :  * ----------
    1330             :  */
    1331             : void
    1332           0 : pgstat_reset_shared_counters(const char *target)
    1333             : {
    1334             :     PgStat_MsgResetsharedcounter msg;
    1335             : 
    1336           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1337           0 :         return;
    1338             : 
    1339           0 :     if (strcmp(target, "archiver") == 0)
    1340           0 :         msg.m_resettarget = RESET_ARCHIVER;
    1341           0 :     else if (strcmp(target, "bgwriter") == 0)
    1342           0 :         msg.m_resettarget = RESET_BGWRITER;
    1343             :     else
    1344           0 :         ereport(ERROR,
    1345             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1346             :                  errmsg("unrecognized reset target: \"%s\"", target),
    1347             :                  errhint("Target must be \"archiver\" or \"bgwriter\".")));
    1348             : 
    1349           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
    1350           0 :     pgstat_send(&msg, sizeof(msg));
    1351             : }
    1352             : 
    1353             : /* ----------
    1354             :  * pgstat_reset_single_counter() -
    1355             :  *
    1356             :  *  Tell the statistics collector to reset a single counter.
    1357             :  *
    1358             :  *  Permission checking for this function is managed through the normal
    1359             :  *  GRANT system.
    1360             :  * ----------
    1361             :  */
    1362             : void
    1363           0 : pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
    1364             : {
    1365             :     PgStat_MsgResetsinglecounter msg;
    1366             : 
    1367           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1368           0 :         return;
    1369             : 
    1370           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
    1371           0 :     msg.m_databaseid = MyDatabaseId;
    1372           0 :     msg.m_resettype = type;
    1373           0 :     msg.m_objectid = objoid;
    1374             : 
    1375           0 :     pgstat_send(&msg, sizeof(msg));
    1376             : }
    1377             : 
    1378             : /* ----------
    1379             :  * pgstat_report_autovac() -
    1380             :  *
    1381             :  *  Called from autovacuum.c to report startup of an autovacuum process.
    1382             :  *  We are called before InitPostgres is done, so can't rely on MyDatabaseId;
    1383             :  *  the db OID must be passed in, instead.
    1384             :  * ----------
    1385             :  */
    1386             : void
    1387          50 : pgstat_report_autovac(Oid dboid)
    1388             : {
    1389             :     PgStat_MsgAutovacStart msg;
    1390             : 
    1391          50 :     if (pgStatSock == PGINVALID_SOCKET)
    1392           0 :         return;
    1393             : 
    1394          50 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
    1395          50 :     msg.m_databaseid = dboid;
    1396          50 :     msg.m_start_time = GetCurrentTimestamp();
    1397             : 
    1398          50 :     pgstat_send(&msg, sizeof(msg));
    1399             : }
    1400             : 
    1401             : 
    1402             : /* ---------
    1403             :  * pgstat_report_vacuum() -
    1404             :  *
    1405             :  *  Tell the collector about the table we just vacuumed.
    1406             :  * ---------
    1407             :  */
    1408             : void
    1409       37410 : pgstat_report_vacuum(Oid tableoid, bool shared,
    1410             :                      PgStat_Counter livetuples, PgStat_Counter deadtuples)
    1411             : {
    1412             :     PgStat_MsgVacuum msg;
    1413             : 
    1414       37410 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1415       33516 :         return;
    1416             : 
    1417        3894 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
    1418        3894 :     msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
    1419        3894 :     msg.m_tableoid = tableoid;
    1420        3894 :     msg.m_autovacuum = IsAutoVacuumWorkerProcess();
    1421        3894 :     msg.m_vacuumtime = GetCurrentTimestamp();
    1422        3894 :     msg.m_live_tuples = livetuples;
    1423        3894 :     msg.m_dead_tuples = deadtuples;
    1424        3894 :     pgstat_send(&msg, sizeof(msg));
    1425             : }
    1426             : 
    1427             : /* --------
    1428             :  * pgstat_report_analyze() -
    1429             :  *
    1430             :  *  Tell the collector about the table we just analyzed.
    1431             :  *
    1432             :  * Caller must provide new live- and dead-tuples estimates, as well as a
    1433             :  * flag indicating whether to reset the changes_since_analyze counter.
    1434             :  * --------
    1435             :  */
    1436             : void
    1437       28822 : pgstat_report_analyze(Relation rel,
    1438             :                       PgStat_Counter livetuples, PgStat_Counter deadtuples,
    1439             :                       bool resetcounter)
    1440             : {
    1441             :     PgStat_MsgAnalyze msg;
    1442             : 
    1443       28822 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1444       19992 :         return;
    1445             : 
    1446             :     /*
    1447             :      * Unlike VACUUM, ANALYZE might be running inside a transaction that has
    1448             :      * already inserted and/or deleted rows in the target table. ANALYZE will
    1449             :      * have counted such rows as live or dead respectively. Because we will
    1450             :      * report our counts of such rows at transaction end, we should subtract
    1451             :      * off these counts from what we send to the collector now, else they'll
    1452             :      * be double-counted after commit.  (This approach also ensures that the
    1453             :      * collector ends up with the right numbers if we abort instead of
    1454             :      * committing.)
    1455             :      */
    1456        8830 :     if (rel->pgstat_info != NULL)
    1457             :     {
    1458             :         PgStat_TableXactStatus *trans;
    1459             : 
    1460        8854 :         for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
    1461             :         {
    1462          56 :             livetuples -= trans->tuples_inserted - trans->tuples_deleted;
    1463          56 :             deadtuples -= trans->tuples_updated + trans->tuples_deleted;
    1464             :         }
    1465             :         /* count stuff inserted by already-aborted subxacts, too */
    1466        8798 :         deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
    1467             :         /* Since ANALYZE's counts are estimates, we could have underflowed */
    1468        8798 :         livetuples = Max(livetuples, 0);
    1469        8798 :         deadtuples = Max(deadtuples, 0);
    1470             :     }
    1471             : 
    1472        8830 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
    1473        8830 :     msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
    1474        8830 :     msg.m_tableoid = RelationGetRelid(rel);
    1475        8830 :     msg.m_autovacuum = IsAutoVacuumWorkerProcess();
    1476        8830 :     msg.m_resetcounter = resetcounter;
    1477        8830 :     msg.m_analyzetime = GetCurrentTimestamp();
    1478        8830 :     msg.m_live_tuples = livetuples;
    1479        8830 :     msg.m_dead_tuples = deadtuples;
    1480        8830 :     pgstat_send(&msg, sizeof(msg));
    1481             : }
    1482             : 
    1483             : /* --------
    1484             :  * pgstat_report_recovery_conflict() -
    1485             :  *
    1486             :  *  Tell the collector about a Hot Standby recovery conflict.
    1487             :  * --------
    1488             :  */
    1489             : void
    1490           0 : pgstat_report_recovery_conflict(int reason)
    1491             : {
    1492             :     PgStat_MsgRecoveryConflict msg;
    1493             : 
    1494           0 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1495           0 :         return;
    1496             : 
    1497           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
    1498           0 :     msg.m_databaseid = MyDatabaseId;
    1499           0 :     msg.m_reason = reason;
    1500           0 :     pgstat_send(&msg, sizeof(msg));
    1501             : }
    1502             : 
    1503             : /* --------
    1504             :  * pgstat_report_deadlock() -
    1505             :  *
    1506             :  *  Tell the collector about a deadlock detected.
    1507             :  * --------
    1508             :  */
    1509             : void
    1510           4 : pgstat_report_deadlock(void)
    1511             : {
    1512             :     PgStat_MsgDeadlock msg;
    1513             : 
    1514           4 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1515           0 :         return;
    1516             : 
    1517           4 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DEADLOCK);
    1518           4 :     msg.m_databaseid = MyDatabaseId;
    1519           4 :     pgstat_send(&msg, sizeof(msg));
    1520             : }
    1521             : 
    1522             : /* --------
    1523             :  * pgstat_report_tempfile() -
    1524             :  *
    1525             :  *  Tell the collector about a temporary file.
    1526             :  * --------
    1527             :  */
    1528             : void
    1529        2874 : pgstat_report_tempfile(size_t filesize)
    1530             : {
    1531             :     PgStat_MsgTempFile msg;
    1532             : 
    1533        2874 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1534           0 :         return;
    1535             : 
    1536        2874 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TEMPFILE);
    1537        2874 :     msg.m_databaseid = MyDatabaseId;
    1538        2874 :     msg.m_filesize = filesize;
    1539        2874 :     pgstat_send(&msg, sizeof(msg));
    1540             : }
    1541             : 
    1542             : 
    1543             : /* ----------
    1544             :  * pgstat_ping() -
    1545             :  *
    1546             :  *  Send some junk data to the collector to increase traffic.
    1547             :  * ----------
    1548             :  */
    1549             : void
    1550           0 : pgstat_ping(void)
    1551             : {
    1552             :     PgStat_MsgDummy msg;
    1553             : 
    1554           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1555           0 :         return;
    1556             : 
    1557           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
    1558           0 :     pgstat_send(&msg, sizeof(msg));
    1559             : }
    1560             : 
    1561             : /* ----------
    1562             :  * pgstat_send_inquiry() -
    1563             :  *
    1564             :  *  Notify collector that we need fresh data.
    1565             :  * ----------
    1566             :  */
    1567             : static void
    1568         830 : pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
    1569             : {
    1570             :     PgStat_MsgInquiry msg;
    1571             : 
    1572         830 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
    1573         830 :     msg.clock_time = clock_time;
    1574         830 :     msg.cutoff_time = cutoff_time;
    1575         830 :     msg.databaseid = databaseid;
    1576         830 :     pgstat_send(&msg, sizeof(msg));
    1577         830 : }
    1578             : 
    1579             : 
    1580             : /*
    1581             :  * Initialize function call usage data.
    1582             :  * Called by the executor before invoking a function.
    1583             :  */
    1584             : void
    1585    13730646 : pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
    1586             :                            PgStat_FunctionCallUsage *fcu)
    1587             : {
    1588             :     PgStat_BackendFunctionEntry *htabent;
    1589             :     bool        found;
    1590             : 
    1591    13730646 :     if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
    1592             :     {
    1593             :         /* stats not wanted */
    1594    13730646 :         fcu->fs = NULL;
    1595    13730646 :         return;
    1596             :     }
    1597             : 
    1598           0 :     if (!pgStatFunctions)
    1599             :     {
    1600             :         /* First time through - initialize function stat table */
    1601             :         HASHCTL     hash_ctl;
    1602             : 
    1603           0 :         memset(&hash_ctl, 0, sizeof(hash_ctl));
    1604           0 :         hash_ctl.keysize = sizeof(Oid);
    1605           0 :         hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
    1606           0 :         pgStatFunctions = hash_create("Function stat entries",
    1607             :                                       PGSTAT_FUNCTION_HASH_SIZE,
    1608             :                                       &hash_ctl,
    1609             :                                       HASH_ELEM | HASH_BLOBS);
    1610             :     }
    1611             : 
    1612             :     /* Get the stats entry for this function, create if necessary */
    1613           0 :     htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
    1614             :                           HASH_ENTER, &found);
    1615           0 :     if (!found)
    1616           0 :         MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
    1617             : 
    1618           0 :     fcu->fs = &htabent->f_counts;
    1619             : 
    1620             :     /* save stats for this function, later used to compensate for recursion */
    1621           0 :     fcu->save_f_total_time = htabent->f_counts.f_total_time;
    1622             : 
    1623             :     /* save current backend-wide total time */
    1624           0 :     fcu->save_total = total_func_time;
    1625             : 
    1626             :     /* get clock time as of function start */
    1627           0 :     INSTR_TIME_SET_CURRENT(fcu->f_start);
    1628             : }
    1629             : 
    1630             : /*
    1631             :  * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
    1632             :  *      for specified function
    1633             :  *
    1634             :  * If no entry, return NULL, don't create a new one
    1635             :  */
    1636             : PgStat_BackendFunctionEntry *
    1637           0 : find_funcstat_entry(Oid func_id)
    1638             : {
    1639           0 :     if (pgStatFunctions == NULL)
    1640           0 :         return NULL;
    1641             : 
    1642           0 :     return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
    1643             :                                                        (void *) &func_id,
    1644             :                                                        HASH_FIND, NULL);
    1645             : }
    1646             : 
    1647             : /*
    1648             :  * Calculate function call usage and update stat counters.
    1649             :  * Called by the executor after invoking a function.
    1650             :  *
    1651             :  * In the case of a set-returning function that runs in value-per-call mode,
    1652             :  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
    1653             :  * calls for what the user considers a single call of the function.  The
    1654             :  * finalize flag should be TRUE on the last call.
    1655             :  */
    1656             : void
    1657    13729424 : pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
    1658             : {
    1659    13729424 :     PgStat_FunctionCounts *fs = fcu->fs;
    1660             :     instr_time  f_total;
    1661             :     instr_time  f_others;
    1662             :     instr_time  f_self;
    1663             : 
    1664             :     /* stats not wanted? */
    1665    13729424 :     if (fs == NULL)
    1666    13729424 :         return;
    1667             : 
    1668             :     /* total elapsed time in this function call */
    1669           0 :     INSTR_TIME_SET_CURRENT(f_total);
    1670           0 :     INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
    1671             : 
    1672             :     /* self usage: elapsed minus anything already charged to other calls */
    1673           0 :     f_others = total_func_time;
    1674           0 :     INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
    1675           0 :     f_self = f_total;
    1676           0 :     INSTR_TIME_SUBTRACT(f_self, f_others);
    1677             : 
    1678             :     /* update backend-wide total time */
    1679           0 :     INSTR_TIME_ADD(total_func_time, f_self);
    1680             : 
    1681             :     /*
    1682             :      * Compute the new f_total_time as the total elapsed time added to the
    1683             :      * pre-call value of f_total_time.  This is necessary to avoid
    1684             :      * double-counting any time taken by recursive calls of myself.  (We do
    1685             :      * not need any similar kluge for self time, since that already excludes
    1686             :      * any recursive calls.)
    1687             :      */
    1688           0 :     INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
    1689             : 
    1690             :     /* update counters in function stats table */
    1691           0 :     if (finalize)
    1692           0 :         fs->f_numcalls++;
    1693           0 :     fs->f_total_time = f_total;
    1694           0 :     INSTR_TIME_ADD(fs->f_self_time, f_self);
    1695             : 
    1696             :     /* indicate that we have something to send */
    1697           0 :     have_function_stats = true;
    1698             : }
    1699             : 
    1700             : 
    1701             : /* ----------
    1702             :  * pgstat_initstats() -
    1703             :  *
    1704             :  *  Initialize a relcache entry to count access statistics.
    1705             :  *  Called whenever a relation is opened.
    1706             :  *
    1707             :  *  We assume that a relcache entry's pgstat_info field is zeroed by
    1708             :  *  relcache.c when the relcache entry is made; thereafter it is long-lived
    1709             :  *  data.  We can avoid repeated searches of the TabStatus arrays when the
    1710             :  *  same relation is touched repeatedly within a transaction.
    1711             :  * ----------
    1712             :  */
    1713             : void
    1714    24537900 : pgstat_initstats(Relation rel)
    1715             : {
    1716    24537900 :     Oid         rel_id = rel->rd_id;
    1717    24537900 :     char        relkind = rel->rd_rel->relkind;
    1718             : 
    1719             :     /* We only count stats for things that have storage */
    1720    25151484 :     if (!(relkind == RELKIND_RELATION ||
    1721    13118162 :           relkind == RELKIND_MATVIEW ||
    1722      725586 :           relkind == RELKIND_INDEX ||
    1723             :           relkind == RELKIND_TOASTVALUE ||
    1724             :           relkind == RELKIND_SEQUENCE))
    1725             :     {
    1726      298536 :         rel->pgstat_info = NULL;
    1727      298536 :         return;
    1728             :     }
    1729             : 
    1730    24239364 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1731             :     {
    1732             :         /* We're not counting at all */
    1733    12401214 :         rel->pgstat_info = NULL;
    1734    12401214 :         return;
    1735             :     }
    1736             : 
    1737             :     /*
    1738             :      * If we already set up this relation in the current transaction, nothing
    1739             :      * to do.
    1740             :      */
    1741    23118542 :     if (rel->pgstat_info != NULL &&
    1742    11280392 :         rel->pgstat_info->t_id == rel_id)
    1743    11158352 :         return;
    1744             : 
    1745             :     /* Else find or make the PgStat_TableStatus entry, and update link */
    1746      679798 :     rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
    1747             : }
    1748             : 
    1749             : /*
    1750             :  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
    1751             :  */
    1752             : static PgStat_TableStatus *
    1753      679888 : get_tabstat_entry(Oid rel_id, bool isshared)
    1754             : {
    1755             :     TabStatHashEntry *hash_entry;
    1756             :     PgStat_TableStatus *entry;
    1757             :     TabStatusArray *tsa;
    1758             :     bool        found;
    1759             : 
    1760             :     /*
    1761             :      * Create hash table if we don't have it already.
    1762             :      */
    1763      679888 :     if (pgStatTabHash == NULL)
    1764             :     {
    1765             :         HASHCTL     ctl;
    1766             : 
    1767       15302 :         memset(&ctl, 0, sizeof(ctl));
    1768       15302 :         ctl.keysize = sizeof(Oid);
    1769       15302 :         ctl.entrysize = sizeof(TabStatHashEntry);
    1770             : 
    1771       15302 :         pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
    1772             :                                     TABSTAT_QUANTUM,
    1773             :                                     &ctl,
    1774             :                                     HASH_ELEM | HASH_BLOBS);
    1775             :     }
    1776             : 
    1777             :     /*
    1778             :      * Find an entry or create a new one.
    1779             :      */
    1780      679888 :     hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
    1781      679888 :     if (!found)
    1782             :     {
    1783             :         /* initialize new entry with null pointer */
    1784      613014 :         hash_entry->tsa_entry = NULL;
    1785             :     }
    1786             : 
    1787             :     /*
    1788             :      * If entry is already valid, we're done.
    1789             :      */
    1790      679888 :     if (hash_entry->tsa_entry)
    1791       66874 :         return hash_entry->tsa_entry;
    1792             : 
    1793             :     /*
    1794             :      * Locate the first pgStatTabList entry with free space, making a new list
    1795             :      * entry if needed.  Note that we could get an OOM failure here, but if so
    1796             :      * we have left the hashtable and the list in a consistent state.
    1797             :      */
    1798      613014 :     if (pgStatTabList == NULL)
    1799             :     {
    1800             :         /* Set up first pgStatTabList entry */
    1801        8536 :         pgStatTabList = (TabStatusArray *)
    1802        8536 :             MemoryContextAllocZero(TopMemoryContext,
    1803             :                                    sizeof(TabStatusArray));
    1804             :     }
    1805             : 
    1806      613014 :     tsa = pgStatTabList;
    1807     1323356 :     while (tsa->tsa_used >= TABSTAT_QUANTUM)
    1808             :     {
    1809       97328 :         if (tsa->tsa_next == NULL)
    1810        1498 :             tsa->tsa_next = (TabStatusArray *)
    1811        1498 :                 MemoryContextAllocZero(TopMemoryContext,
    1812             :                                        sizeof(TabStatusArray));
    1813       97328 :         tsa = tsa->tsa_next;
    1814             :     }
    1815             : 
    1816             :     /*
    1817             :      * Allocate a PgStat_TableStatus entry within this list entry.  We assume
    1818             :      * the entry was already zeroed, either at creation or after last use.
    1819             :      */
    1820      613014 :     entry = &tsa->tsa_entries[tsa->tsa_used++];
    1821      613014 :     entry->t_id = rel_id;
    1822      613014 :     entry->t_shared = isshared;
    1823             : 
    1824             :     /*
    1825             :      * Now we can fill the entry in pgStatTabHash.
    1826             :      */
    1827      613014 :     hash_entry->tsa_entry = entry;
    1828             : 
    1829      613014 :     return entry;
    1830             : }
    1831             : 
    1832             : /*
    1833             :  * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
    1834             :  *
    1835             :  * If no entry, return NULL, don't create a new one
    1836             :  *
    1837             :  * Note: if we got an error in the most recent execution of pgstat_report_stat,
    1838             :  * it's possible that an entry exists but there's no hashtable entry for it.
    1839             :  * That's okay, we'll treat this case as "doesn't exist".
    1840             :  */
    1841             : PgStat_TableStatus *
    1842           0 : find_tabstat_entry(Oid rel_id)
    1843             : {
    1844             :     TabStatHashEntry *hash_entry;
    1845             : 
    1846             :     /* If hashtable doesn't exist, there are no entries at all */
    1847           0 :     if (!pgStatTabHash)
    1848           0 :         return NULL;
    1849             : 
    1850           0 :     hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
    1851           0 :     if (!hash_entry)
    1852           0 :         return NULL;
    1853             : 
    1854             :     /* Note that this step could also return NULL, but that's correct */
    1855           0 :     return hash_entry->tsa_entry;
    1856             : }
    1857             : 
    1858             : /*
    1859             :  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
    1860             :  */
    1861             : static PgStat_SubXactStatus *
    1862      226594 : get_tabstat_stack_level(int nest_level)
    1863             : {
    1864             :     PgStat_SubXactStatus *xact_state;
    1865             : 
    1866      226594 :     xact_state = pgStatXactStack;
    1867      226594 :     if (xact_state == NULL || xact_state->nest_level != nest_level)
    1868             :     {
    1869       82058 :         xact_state = (PgStat_SubXactStatus *)
    1870       82058 :             MemoryContextAlloc(TopTransactionContext,
    1871             :                                sizeof(PgStat_SubXactStatus));
    1872       82058 :         xact_state->nest_level = nest_level;
    1873       82058 :         xact_state->prev = pgStatXactStack;
    1874       82058 :         xact_state->first = NULL;
    1875       82058 :         pgStatXactStack = xact_state;
    1876             :     }
    1877      226594 :     return xact_state;
    1878             : }
    1879             : 
    1880             : /*
    1881             :  * add_tabstat_xact_level - add a new (sub)transaction state record
    1882             :  */
    1883             : static void
    1884      225966 : add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
    1885             : {
    1886             :     PgStat_SubXactStatus *xact_state;
    1887             :     PgStat_TableXactStatus *trans;
    1888             : 
    1889             :     /*
    1890             :      * If this is the first rel to be modified at the current nest level, we
    1891             :      * first have to push a transaction stack entry.
    1892             :      */
    1893      225966 :     xact_state = get_tabstat_stack_level(nest_level);
    1894             : 
    1895             :     /* Now make a per-table stack entry */
    1896      225966 :     trans = (PgStat_TableXactStatus *)
    1897      225966 :         MemoryContextAllocZero(TopTransactionContext,
    1898             :                                sizeof(PgStat_TableXactStatus));
    1899      225966 :     trans->nest_level = nest_level;
    1900      225966 :     trans->upper = pgstat_info->trans;
    1901      225966 :     trans->parent = pgstat_info;
    1902      225966 :     trans->next = xact_state->first;
    1903      225966 :     xact_state->first = trans;
    1904      225966 :     pgstat_info->trans = trans;
    1905      225966 : }
    1906             : 
    1907             : /*
    1908             :  * pgstat_count_heap_insert - count a tuple insertion of n tuples
    1909             :  */
    1910             : void
    1911    17733742 : pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
    1912             : {
    1913    17733742 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    1914             : 
    1915    17733742 :     if (pgstat_info != NULL)
    1916             :     {
    1917             :         /* We have to log the effect at the proper transactional level */
    1918    11192242 :         int         nest_level = GetCurrentTransactionNestLevel();
    1919             : 
    1920    22238346 :         if (pgstat_info->trans == NULL ||
    1921    11046104 :             pgstat_info->trans->nest_level != nest_level)
    1922      149322 :             add_tabstat_xact_level(pgstat_info, nest_level);
    1923             : 
    1924    11192242 :         pgstat_info->trans->tuples_inserted += n;
    1925             :     }
    1926    17733742 : }
    1927             : 
    1928             : /*
    1929             :  * pgstat_count_heap_update - count a tuple update
    1930             :  */
    1931             : void
    1932      267892 : pgstat_count_heap_update(Relation rel, bool hot)
    1933             : {
    1934      267892 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    1935             : 
    1936      267892 :     if (pgstat_info != NULL)
    1937             :     {
    1938             :         /* We have to log the effect at the proper transactional level */
    1939      127360 :         int         nest_level = GetCurrentTransactionNestLevel();
    1940             : 
    1941      231164 :         if (pgstat_info->trans == NULL ||
    1942      103804 :             pgstat_info->trans->nest_level != nest_level)
    1943       23616 :             add_tabstat_xact_level(pgstat_info, nest_level);
    1944             : 
    1945      127360 :         pgstat_info->trans->tuples_updated++;
    1946             : 
    1947             :         /* t_tuples_hot_updated is nontransactional, so just advance it */
    1948      127360 :         if (hot)
    1949       68420 :             pgstat_info->t_counts.t_tuples_hot_updated++;
    1950             :     }
    1951      267892 : }
    1952             : 
    1953             : /*
    1954             :  * pgstat_count_heap_delete - count a tuple deletion
    1955             :  */
    1956             : void
    1957     1229462 : pgstat_count_heap_delete(Relation rel)
    1958             : {
    1959     1229462 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    1960             : 
    1961     1229462 :     if (pgstat_info != NULL)
    1962             :     {
    1963             :         /* We have to log the effect at the proper transactional level */
    1964     1204178 :         int         nest_level = GetCurrentTransactionNestLevel();
    1965             : 
    1966     2356584 :         if (pgstat_info->trans == NULL ||
    1967     1152406 :             pgstat_info->trans->nest_level != nest_level)
    1968       51860 :             add_tabstat_xact_level(pgstat_info, nest_level);
    1969             : 
    1970     1204178 :         pgstat_info->trans->tuples_deleted++;
    1971             :     }
    1972     1229462 : }
    1973             : 
    1974             : /*
    1975             :  * pgstat_truncate_save_counters
    1976             :  *
    1977             :  * Whenever a table is truncated, we save its i/u/d counters so that they can
    1978             :  * be cleared, and if the (sub)xact that executed the truncate later aborts,
    1979             :  * the counters can be restored to the saved (pre-truncate) values.  Note we do
    1980             :  * this on the first truncate in any particular subxact level only.
    1981             :  */
    1982             : static void
    1983        1200 : pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
    1984             : {
    1985        1200 :     if (!trans->truncated)
    1986             :     {
    1987        1192 :         trans->inserted_pre_trunc = trans->tuples_inserted;
    1988        1192 :         trans->updated_pre_trunc = trans->tuples_updated;
    1989        1192 :         trans->deleted_pre_trunc = trans->tuples_deleted;
    1990        1192 :         trans->truncated = true;
    1991             :     }
    1992        1200 : }
    1993             : 
    1994             : /*
    1995             :  * pgstat_truncate_restore_counters - restore counters when a truncate aborts
    1996             :  */
    1997             : static void
    1998        7560 : pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
    1999             : {
    2000        7560 :     if (trans->truncated)
    2001             :     {
    2002          72 :         trans->tuples_inserted = trans->inserted_pre_trunc;
    2003          72 :         trans->tuples_updated = trans->updated_pre_trunc;
    2004          72 :         trans->tuples_deleted = trans->deleted_pre_trunc;
    2005             :     }
    2006        7560 : }
    2007             : 
    2008             : /*
    2009             :  * pgstat_count_truncate - update tuple counters due to truncate
    2010             :  */
    2011             : void
    2012        1184 : pgstat_count_truncate(Relation rel)
    2013             : {
    2014        1184 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2015             : 
    2016        1184 :     if (pgstat_info != NULL)
    2017             :     {
    2018             :         /* We have to log the effect at the proper transactional level */
    2019        1184 :         int         nest_level = GetCurrentTransactionNestLevel();
    2020             : 
    2021        1216 :         if (pgstat_info->trans == NULL ||
    2022          32 :             pgstat_info->trans->nest_level != nest_level)
    2023        1168 :             add_tabstat_xact_level(pgstat_info, nest_level);
    2024             : 
    2025        1184 :         pgstat_truncate_save_counters(pgstat_info->trans);
    2026        1184 :         pgstat_info->trans->tuples_inserted = 0;
    2027        1184 :         pgstat_info->trans->tuples_updated = 0;
    2028        1184 :         pgstat_info->trans->tuples_deleted = 0;
    2029             :     }
    2030        1184 : }
    2031             : 
    2032             : /*
    2033             :  * pgstat_update_heap_dead_tuples - update dead-tuples count
    2034             :  *
    2035             :  * The semantics of this are that we are reporting the nontransactional
    2036             :  * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
    2037             :  * rather than increasing, and the change goes straight into the per-table
    2038             :  * counter, not into transactional state.
    2039             :  */
    2040             : void
    2041       30282 : pgstat_update_heap_dead_tuples(Relation rel, int delta)
    2042             : {
    2043       30282 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2044             : 
    2045       30282 :     if (pgstat_info != NULL)
    2046       10878 :         pgstat_info->t_counts.t_delta_dead_tuples -= delta;
    2047       30282 : }
    2048             : 
    2049             : 
    2050             : /* ----------
    2051             :  * AtEOXact_PgStat
    2052             :  *
    2053             :  *  Called from access/transam/xact.c at top-level transaction commit/abort.
    2054             :  * ----------
    2055             :  */
    2056             : void
    2057      447168 : AtEOXact_PgStat(bool isCommit)
    2058             : {
    2059             :     PgStat_SubXactStatus *xact_state;
    2060             : 
    2061             :     /*
    2062             :      * Count transaction commit or abort.  (We use counters, not just bools,
    2063             :      * in case the reporting message isn't sent right away.)
    2064             :      */
    2065      447168 :     if (isCommit)
    2066      429596 :         pgStatXactCommit++;
    2067             :     else
    2068       17572 :         pgStatXactRollback++;
    2069             : 
    2070             :     /*
    2071             :      * Transfer transactional insert/update counts into the base tabstat
    2072             :      * entries.  We don't bother to free any of the transactional state, since
    2073             :      * it's all in TopTransactionContext and will go away anyway.
    2074             :      */
    2075      447168 :     xact_state = pgStatXactStack;
    2076      447168 :     if (xact_state != NULL)
    2077             :     {
    2078             :         PgStat_TableXactStatus *trans;
    2079             : 
    2080             :         Assert(xact_state->nest_level == 1);
    2081             :         Assert(xact_state->prev == NULL);
    2082      300428 :         for (trans = xact_state->first; trans != NULL; trans = trans->next)
    2083             :         {
    2084             :             PgStat_TableStatus *tabstat;
    2085             : 
    2086             :             Assert(trans->nest_level == 1);
    2087             :             Assert(trans->upper == NULL);
    2088      222314 :             tabstat = trans->parent;
    2089             :             Assert(tabstat->trans == trans);
    2090             :             /* restore pre-truncate stats (if any) in case of aborted xact */
    2091      222314 :             if (!isCommit)
    2092        7078 :                 pgstat_truncate_restore_counters(trans);
    2093             :             /* count attempted actions regardless of commit/abort */
    2094      222314 :             tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
    2095      222314 :             tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
    2096      222314 :             tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
    2097      222314 :             if (isCommit)
    2098             :             {
    2099      215236 :                 tabstat->t_counts.t_truncated = trans->truncated;
    2100      215236 :                 if (trans->truncated)
    2101             :                 {
    2102             :                     /* forget live/dead stats seen by backend thus far */
    2103        1104 :                     tabstat->t_counts.t_delta_live_tuples = 0;
    2104        1104 :                     tabstat->t_counts.t_delta_dead_tuples = 0;
    2105             :                 }
    2106             :                 /* insert adds a live tuple, delete removes one */
    2107      430472 :                 tabstat->t_counts.t_delta_live_tuples +=
    2108      215236 :                     trans->tuples_inserted - trans->tuples_deleted;
    2109             :                 /* update and delete each create a dead tuple */
    2110      430472 :                 tabstat->t_counts.t_delta_dead_tuples +=
    2111      215236 :                     trans->tuples_updated + trans->tuples_deleted;
    2112             :                 /* insert, update, delete each count as one change event */
    2113      430472 :                 tabstat->t_counts.t_changed_tuples +=
    2114      430472 :                     trans->tuples_inserted + trans->tuples_updated +
    2115      215236 :                     trans->tuples_deleted;
    2116             :             }
    2117             :             else
    2118             :             {
    2119             :                 /* inserted tuples are dead, deleted tuples are unaffected */
    2120       14156 :                 tabstat->t_counts.t_delta_dead_tuples +=
    2121        7078 :                     trans->tuples_inserted + trans->tuples_updated;
    2122             :                 /* an aborted xact generates no changed_tuple events */
    2123             :             }
    2124      222314 :             tabstat->trans = NULL;
    2125             :         }
    2126             :     }
    2127      447168 :     pgStatXactStack = NULL;
    2128             : 
    2129             :     /* Make sure any stats snapshot is thrown away */
    2130      447168 :     pgstat_clear_snapshot();
    2131      447168 : }
    2132             : 
    2133             : /* ----------
    2134             :  * AtEOSubXact_PgStat
    2135             :  *
    2136             :  *  Called from access/transam/xact.c at subtransaction commit/abort.
    2137             :  * ----------
    2138             :  */
    2139             : void
    2140        7322 : AtEOSubXact_PgStat(bool isCommit, int nestDepth)
    2141             : {
    2142             :     PgStat_SubXactStatus *xact_state;
    2143             : 
    2144             :     /*
    2145             :      * Transfer transactional insert/update counts into the next higher
    2146             :      * subtransaction state.
    2147             :      */
    2148        7322 :     xact_state = pgStatXactStack;
    2149       11642 :     if (xact_state != NULL &&
    2150        4320 :         xact_state->nest_level >= nestDepth)
    2151             :     {
    2152             :         PgStat_TableXactStatus *trans;
    2153             :         PgStat_TableXactStatus *next_trans;
    2154             : 
    2155             :         /* delink xact_state from stack immediately to simplify reuse case */
    2156        3890 :         pgStatXactStack = xact_state->prev;
    2157             : 
    2158        8080 :         for (trans = xact_state->first; trans != NULL; trans = next_trans)
    2159             :         {
    2160             :             PgStat_TableStatus *tabstat;
    2161             : 
    2162        4190 :             next_trans = trans->next;
    2163             :             Assert(trans->nest_level == nestDepth);
    2164        4190 :             tabstat = trans->parent;
    2165             :             Assert(tabstat->trans == trans);
    2166        4190 :             if (isCommit)
    2167             :             {
    2168        3708 :                 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
    2169             :                 {
    2170        3080 :                     if (trans->truncated)
    2171             :                     {
    2172             :                         /* propagate the truncate status one level up */
    2173          16 :                         pgstat_truncate_save_counters(trans->upper);
    2174             :                         /* replace upper xact stats with ours */
    2175          16 :                         trans->upper->tuples_inserted = trans->tuples_inserted;
    2176          16 :                         trans->upper->tuples_updated = trans->tuples_updated;
    2177          16 :                         trans->upper->tuples_deleted = trans->tuples_deleted;
    2178             :                     }
    2179             :                     else
    2180             :                     {
    2181        3064 :                         trans->upper->tuples_inserted += trans->tuples_inserted;
    2182        3064 :                         trans->upper->tuples_updated += trans->tuples_updated;
    2183        3064 :                         trans->upper->tuples_deleted += trans->tuples_deleted;
    2184             :                     }
    2185        3080 :                     tabstat->trans = trans->upper;
    2186        3080 :                     pfree(trans);
    2187             :                 }
    2188             :                 else
    2189             :                 {
    2190             :                     /*
    2191             :                      * When there isn't an immediate parent state, we can just
    2192             :                      * reuse the record instead of going through a
    2193             :                      * palloc/pfree pushup (this works since it's all in
    2194             :                      * TopTransactionContext anyway).  We have to re-link it
    2195             :                      * into the parent level, though, and that might mean
    2196             :                      * pushing a new entry into the pgStatXactStack.
    2197             :                      */
    2198             :                     PgStat_SubXactStatus *upper_xact_state;
    2199             : 
    2200         628 :                     upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
    2201         628 :                     trans->next = upper_xact_state->first;
    2202         628 :                     upper_xact_state->first = trans;
    2203         628 :                     trans->nest_level = nestDepth - 1;
    2204             :                 }
    2205             :             }
    2206             :             else
    2207             :             {
    2208             :                 /*
    2209             :                  * On abort, update top-level tabstat counts, then forget the
    2210             :                  * subtransaction
    2211             :                  */
    2212             : 
    2213             :                 /* first restore values obliterated by truncate */
    2214         482 :                 pgstat_truncate_restore_counters(trans);
    2215             :                 /* count attempted actions regardless of commit/abort */
    2216         482 :                 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
    2217         482 :                 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
    2218         482 :                 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
    2219             :                 /* inserted tuples are dead, deleted tuples are unaffected */
    2220         964 :                 tabstat->t_counts.t_delta_dead_tuples +=
    2221         482 :                     trans->tuples_inserted + trans->tuples_updated;
    2222         482 :                 tabstat->trans = trans->upper;
    2223         482 :                 pfree(trans);
    2224             :             }
    2225             :         }
    2226        3890 :         pfree(xact_state);
    2227             :     }
    2228        7322 : }
    2229             : 
    2230             : 
    2231             : /*
    2232             :  * AtPrepare_PgStat
    2233             :  *      Save the transactional stats state at 2PC transaction prepare.
    2234             :  *
    2235             :  * In this phase we just generate 2PC records for all the pending
    2236             :  * transaction-dependent stats work.
    2237             :  */
    2238             : void
    2239          56 : AtPrepare_PgStat(void)
    2240             : {
    2241             :     PgStat_SubXactStatus *xact_state;
    2242             : 
    2243          56 :     xact_state = pgStatXactStack;
    2244          56 :     if (xact_state != NULL)
    2245             :     {
    2246             :         PgStat_TableXactStatus *trans;
    2247             : 
    2248             :         Assert(xact_state->nest_level == 1);
    2249             :         Assert(xact_state->prev == NULL);
    2250         144 :         for (trans = xact_state->first; trans != NULL; trans = trans->next)
    2251             :         {
    2252             :             PgStat_TableStatus *tabstat;
    2253             :             TwoPhasePgStatRecord record;
    2254             : 
    2255             :             Assert(trans->nest_level == 1);
    2256             :             Assert(trans->upper == NULL);
    2257          90 :             tabstat = trans->parent;
    2258             :             Assert(tabstat->trans == trans);
    2259             : 
    2260          90 :             record.tuples_inserted = trans->tuples_inserted;
    2261          90 :             record.tuples_updated = trans->tuples_updated;
    2262          90 :             record.tuples_deleted = trans->tuples_deleted;
    2263          90 :             record.inserted_pre_trunc = trans->inserted_pre_trunc;
    2264          90 :             record.updated_pre_trunc = trans->updated_pre_trunc;
    2265          90 :             record.deleted_pre_trunc = trans->deleted_pre_trunc;
    2266          90 :             record.t_id = tabstat->t_id;
    2267          90 :             record.t_shared = tabstat->t_shared;
    2268          90 :             record.t_truncated = trans->truncated;
    2269             : 
    2270          90 :             RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
    2271             :                                    &record, sizeof(TwoPhasePgStatRecord));
    2272             :         }
    2273             :     }
    2274          56 : }
    2275             : 
    2276             : /*
    2277             :  * PostPrepare_PgStat
    2278             :  *      Clean up after successful PREPARE.
    2279             :  *
    2280             :  * All we need do here is unlink the transaction stats state from the
    2281             :  * nontransactional state.  The nontransactional action counts will be
    2282             :  * reported to the stats collector immediately, while the effects on live
    2283             :  * and dead tuple counts are preserved in the 2PC state file.
    2284             :  *
    2285             :  * Note: AtEOXact_PgStat is not called during PREPARE.
    2286             :  */
    2287             : void
    2288          56 : PostPrepare_PgStat(void)
    2289             : {
    2290             :     PgStat_SubXactStatus *xact_state;
    2291             : 
    2292             :     /*
    2293             :      * We don't bother to free any of the transactional state, since it's all
    2294             :      * in TopTransactionContext and will go away anyway.
    2295             :      */
    2296          56 :     xact_state = pgStatXactStack;
    2297          56 :     if (xact_state != NULL)
    2298             :     {
    2299             :         PgStat_TableXactStatus *trans;
    2300             : 
    2301         144 :         for (trans = xact_state->first; trans != NULL; trans = trans->next)
    2302             :         {
    2303             :             PgStat_TableStatus *tabstat;
    2304             : 
    2305          90 :             tabstat = trans->parent;
    2306          90 :             tabstat->trans = NULL;
    2307             :         }
    2308             :     }
    2309          56 :     pgStatXactStack = NULL;
    2310             : 
    2311             :     /* Make sure any stats snapshot is thrown away */
    2312          56 :     pgstat_clear_snapshot();
    2313          56 : }
    2314             : 
    2315             : /*
    2316             :  * 2PC processing routine for COMMIT PREPARED case.
    2317             :  *
    2318             :  * Load the saved counts into our local pgstats state.
    2319             :  */
    2320             : void
    2321          76 : pgstat_twophase_postcommit(TransactionId xid, uint16 info,
    2322             :                            void *recdata, uint32 len)
    2323             : {
    2324          76 :     TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
    2325             :     PgStat_TableStatus *pgstat_info;
    2326             : 
    2327             :     /* Find or create a tabstat entry for the rel */
    2328          76 :     pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
    2329             : 
    2330             :     /* Same math as in AtEOXact_PgStat, commit case */
    2331          76 :     pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
    2332          76 :     pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
    2333          76 :     pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
    2334          76 :     pgstat_info->t_counts.t_truncated = rec->t_truncated;
    2335          76 :     if (rec->t_truncated)
    2336             :     {
    2337             :         /* forget live/dead stats seen by backend thus far */
    2338           0 :         pgstat_info->t_counts.t_delta_live_tuples = 0;
    2339           0 :         pgstat_info->t_counts.t_delta_dead_tuples = 0;
    2340             :     }
    2341         152 :     pgstat_info->t_counts.t_delta_live_tuples +=
    2342          76 :         rec->tuples_inserted - rec->tuples_deleted;
    2343         152 :     pgstat_info->t_counts.t_delta_dead_tuples +=
    2344          76 :         rec->tuples_updated + rec->tuples_deleted;
    2345         152 :     pgstat_info->t_counts.t_changed_tuples +=
    2346         152 :         rec->tuples_inserted + rec->tuples_updated +
    2347          76 :         rec->tuples_deleted;
    2348          76 : }
    2349             : 
    2350             : /*
    2351             :  * 2PC processing routine for ROLLBACK PREPARED case.
    2352             :  *
    2353             :  * Load the saved counts into our local pgstats state, but treat them
    2354             :  * as aborted.
    2355             :  */
    2356             : void
    2357          14 : pgstat_twophase_postabort(TransactionId xid, uint16 info,
    2358             :                           void *recdata, uint32 len)
    2359             : {
    2360          14 :     TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
    2361             :     PgStat_TableStatus *pgstat_info;
    2362             : 
    2363             :     /* Find or create a tabstat entry for the rel */
    2364          14 :     pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
    2365             : 
    2366             :     /* Same math as in AtEOXact_PgStat, abort case */
    2367          14 :     if (rec->t_truncated)
    2368             :     {
    2369           0 :         rec->tuples_inserted = rec->inserted_pre_trunc;
    2370           0 :         rec->tuples_updated = rec->updated_pre_trunc;
    2371           0 :         rec->tuples_deleted = rec->deleted_pre_trunc;
    2372             :     }
    2373          14 :     pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
    2374          14 :     pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
    2375          14 :     pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
    2376          28 :     pgstat_info->t_counts.t_delta_dead_tuples +=
    2377          14 :         rec->tuples_inserted + rec->tuples_updated;
    2378          14 : }
    2379             : 
    2380             : 
    2381             : /* ----------
    2382             :  * pgstat_fetch_stat_dbentry() -
    2383             :  *
    2384             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2385             :  *  the collected statistics for one database or NULL. NULL doesn't mean
    2386             :  *  that the database doesn't exist, it is just not yet known by the
    2387             :  *  collector, so the caller is better off to report ZERO instead.
    2388             :  * ----------
    2389             :  */
    2390             : PgStat_StatDBEntry *
    2391        2688 : pgstat_fetch_stat_dbentry(Oid dbid)
    2392             : {
    2393             :     /*
    2394             :      * If not done for this transaction, read the statistics collector stats
    2395             :      * file into some hash tables.
    2396             :      */
    2397        2688 :     backend_read_statsfile();
    2398             : 
    2399             :     /*
    2400             :      * Lookup the requested database; return NULL if not found
    2401             :      */
    2402        2688 :     return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    2403             :                                               (void *) &dbid,
    2404             :                                               HASH_FIND, NULL);
    2405             : }
    2406             : 
    2407             : 
    2408             : /* ----------
    2409             :  * pgstat_fetch_stat_tabentry() -
    2410             :  *
    2411             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2412             :  *  the collected statistics for one table or NULL. NULL doesn't mean
    2413             :  *  that the table doesn't exist, it is just not yet known by the
    2414             :  *  collector, so the caller is better off to report ZERO instead.
    2415             :  * ----------
    2416             :  */
    2417             : PgStat_StatTabEntry *
    2418         378 : pgstat_fetch_stat_tabentry(Oid relid)
    2419             : {
    2420             :     Oid         dbid;
    2421             :     PgStat_StatDBEntry *dbentry;
    2422             :     PgStat_StatTabEntry *tabentry;
    2423             : 
    2424             :     /*
    2425             :      * If not done for this transaction, read the statistics collector stats
    2426             :      * file into some hash tables.
    2427             :      */
    2428         378 :     backend_read_statsfile();
    2429             : 
    2430             :     /*
    2431             :      * Lookup our database, then look in its table hash table.
    2432             :      */
    2433         378 :     dbid = MyDatabaseId;
    2434         378 :     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    2435             :                                                  (void *) &dbid,
    2436             :                                                  HASH_FIND, NULL);
    2437         378 :     if (dbentry != NULL && dbentry->tables != NULL)
    2438             :     {
    2439         378 :         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    2440             :                                                        (void *) &relid,
    2441             :                                                        HASH_FIND, NULL);
    2442         378 :         if (tabentry)
    2443         360 :             return tabentry;
    2444             :     }
    2445             : 
    2446             :     /*
    2447             :      * If we didn't find it, maybe it's a shared table.
    2448             :      */
    2449          18 :     dbid = InvalidOid;
    2450          18 :     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    2451             :                                                  (void *) &dbid,
    2452             :                                                  HASH_FIND, NULL);
    2453          18 :     if (dbentry != NULL && dbentry->tables != NULL)
    2454             :     {
    2455          18 :         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    2456             :                                                        (void *) &relid,
    2457             :                                                        HASH_FIND, NULL);
    2458          18 :         if (tabentry)
    2459           0 :             return tabentry;
    2460             :     }
    2461             : 
    2462          18 :     return NULL;
    2463             : }
    2464             : 
    2465             : 
    2466             : /* ----------
    2467             :  * pgstat_fetch_stat_funcentry() -
    2468             :  *
    2469             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2470             :  *  the collected statistics for one function or NULL.
    2471             :  * ----------
    2472             :  */
    2473             : PgStat_StatFuncEntry *
    2474           0 : pgstat_fetch_stat_funcentry(Oid func_id)
    2475             : {
    2476             :     PgStat_StatDBEntry *dbentry;
    2477           0 :     PgStat_StatFuncEntry *funcentry = NULL;
    2478             : 
    2479             :     /* load the stats file if needed */
    2480           0 :     backend_read_statsfile();
    2481             : 
    2482             :     /* Lookup our database, then find the requested function.  */
    2483           0 :     dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
    2484           0 :     if (dbentry != NULL && dbentry->functions != NULL)
    2485             :     {
    2486           0 :         funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
    2487             :                                                          (void *) &func_id,
    2488             :                                                          HASH_FIND, NULL);
    2489             :     }
    2490             : 
    2491           0 :     return funcentry;
    2492             : }
    2493             : 
    2494             : 
    2495             : /* ----------
    2496             :  * pgstat_fetch_stat_beentry() -
    2497             :  *
    2498             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2499             :  *  our local copy of the current-activity entry for one backend.
    2500             :  *
    2501             :  *  NB: caller is responsible for a check if the user is permitted to see
    2502             :  *  this info (especially the querystring).
    2503             :  * ----------
    2504             :  */
    2505             : PgBackendStatus *
    2506           0 : pgstat_fetch_stat_beentry(int beid)
    2507             : {
    2508           0 :     pgstat_read_current_status();
    2509             : 
    2510           0 :     if (beid < 1 || beid > localNumBackends)
    2511           0 :         return NULL;
    2512             : 
    2513           0 :     return &localBackendStatusTable[beid - 1].backendStatus;
    2514             : }
    2515             : 
    2516             : 
    2517             : /* ----------
    2518             :  * pgstat_fetch_stat_local_beentry() -
    2519             :  *
    2520             :  *  Like pgstat_fetch_stat_beentry() but with locally computed additions (like
    2521             :  *  xid and xmin values of the backend)
    2522             :  *
    2523             :  *  NB: caller is responsible for a check if the user is permitted to see
    2524             :  *  this info (especially the querystring).
    2525             :  * ----------
    2526             :  */
    2527             : LocalPgBackendStatus *
    2528        2574 : pgstat_fetch_stat_local_beentry(int beid)
    2529             : {
    2530        2574 :     pgstat_read_current_status();
    2531             : 
    2532        2574 :     if (beid < 1 || beid > localNumBackends)
    2533           0 :         return NULL;
    2534             : 
    2535        2574 :     return &localBackendStatusTable[beid - 1];
    2536             : }
    2537             : 
    2538             : 
    2539             : /* ----------
    2540             :  * pgstat_fetch_stat_numbackends() -
    2541             :  *
    2542             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2543             :  *  the maximum current backend id.
    2544             :  * ----------
    2545             :  */
    2546             : int
    2547         356 : pgstat_fetch_stat_numbackends(void)
    2548             : {
    2549         356 :     pgstat_read_current_status();
    2550             : 
    2551         356 :     return localNumBackends;
    2552             : }
    2553             : 
    2554             : /*
    2555             :  * ---------
    2556             :  * pgstat_fetch_stat_archiver() -
    2557             :  *
    2558             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2559             :  *  a pointer to the archiver statistics struct.
    2560             :  * ---------
    2561             :  */
    2562             : PgStat_ArchiverStats *
    2563           0 : pgstat_fetch_stat_archiver(void)
    2564             : {
    2565           0 :     backend_read_statsfile();
    2566             : 
    2567           0 :     return &archiverStats;
    2568             : }
    2569             : 
    2570             : 
    2571             : /*
    2572             :  * ---------
    2573             :  * pgstat_fetch_global() -
    2574             :  *
    2575             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2576             :  *  a pointer to the global statistics struct.
    2577             :  * ---------
    2578             :  */
    2579             : PgStat_GlobalStats *
    2580          30 : pgstat_fetch_global(void)
    2581             : {
    2582          30 :     backend_read_statsfile();
    2583             : 
    2584          30 :     return &globalStats;
    2585             : }
    2586             : 
    2587             : 
    2588             : /* ------------------------------------------------------------
    2589             :  * Functions for management of the shared-memory PgBackendStatus array
    2590             :  * ------------------------------------------------------------
    2591             :  */
    2592             : 
    2593             : static PgBackendStatus *BackendStatusArray = NULL;
    2594             : static PgBackendStatus *MyBEEntry = NULL;
    2595             : static char *BackendAppnameBuffer = NULL;
    2596             : static char *BackendClientHostnameBuffer = NULL;
    2597             : static char *BackendActivityBuffer = NULL;
    2598             : static Size BackendActivityBufferSize = 0;
    2599             : #ifdef USE_SSL
    2600             : static PgBackendSSLStatus *BackendSslStatusBuffer = NULL;
    2601             : #endif
    2602             : 
    2603             : 
    2604             : /*
    2605             :  * Report shared-memory space needed by CreateSharedBackendStatus.
    2606             :  */
    2607             : Size
    2608        1708 : BackendStatusShmemSize(void)
    2609             : {
    2610             :     Size        size;
    2611             : 
    2612             :     /* BackendStatusArray: */
    2613        1708 :     size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
    2614             :     /* BackendAppnameBuffer: */
    2615        1708 :     size = add_size(size,
    2616        1708 :                     mul_size(NAMEDATALEN, NumBackendStatSlots));
    2617             :     /* BackendClientHostnameBuffer: */
    2618        1708 :     size = add_size(size,
    2619        1708 :                     mul_size(NAMEDATALEN, NumBackendStatSlots));
    2620             :     /* BackendActivityBuffer: */
    2621        1708 :     size = add_size(size,
    2622        1708 :                     mul_size(pgstat_track_activity_query_size, NumBackendStatSlots));
    2623             : #ifdef USE_SSL
    2624             :     /* BackendSslStatusBuffer: */
    2625        1708 :     size = add_size(size,
    2626        1708 :                     mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots));
    2627             : #endif
    2628        1708 :     return size;
    2629             : }
    2630             : 
    2631             : /*
    2632             :  * Initialize the shared status array and several string buffers
    2633             :  * during postmaster startup.
    2634             :  */
    2635             : void
    2636        1708 : CreateSharedBackendStatus(void)
    2637             : {
    2638             :     Size        size;
    2639             :     bool        found;
    2640             :     int         i;
    2641             :     char       *buffer;
    2642             : 
    2643             :     /* Create or attach to the shared array */
    2644        1708 :     size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
    2645        1708 :     BackendStatusArray = (PgBackendStatus *)
    2646        1708 :         ShmemInitStruct("Backend Status Array", size, &found);
    2647             : 
    2648        1708 :     if (!found)
    2649             :     {
    2650             :         /*
    2651             :          * We're the first - initialize.
    2652             :          */
    2653        1708 :         MemSet(BackendStatusArray, 0, size);
    2654             :     }
    2655             : 
    2656             :     /* Create or attach to the shared appname buffer */
    2657        1708 :     size = mul_size(NAMEDATALEN, NumBackendStatSlots);
    2658        1708 :     BackendAppnameBuffer = (char *)
    2659        1708 :         ShmemInitStruct("Backend Application Name Buffer", size, &found);
    2660             : 
    2661        1708 :     if (!found)
    2662             :     {
    2663        1708 :         MemSet(BackendAppnameBuffer, 0, size);
    2664             : 
    2665             :         /* Initialize st_appname pointers. */
    2666        1708 :         buffer = BackendAppnameBuffer;
    2667      181020 :         for (i = 0; i < NumBackendStatSlots; i++)
    2668             :         {
    2669      179312 :             BackendStatusArray[i].st_appname = buffer;
    2670      179312 :             buffer += NAMEDATALEN;
    2671             :         }
    2672             :     }
    2673             : 
    2674             :     /* Create or attach to the shared client hostname buffer */
    2675        1708 :     size = mul_size(NAMEDATALEN, NumBackendStatSlots);
    2676        1708 :     BackendClientHostnameBuffer = (char *)
    2677        1708 :         ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
    2678             : 
    2679        1708 :     if (!found)
    2680             :     {
    2681        1708 :         MemSet(BackendClientHostnameBuffer, 0, size);
    2682             : 
    2683             :         /* Initialize st_clienthostname pointers. */
    2684        1708 :         buffer = BackendClientHostnameBuffer;
    2685      181020 :         for (i = 0; i < NumBackendStatSlots; i++)
    2686             :         {
    2687      179312 :             BackendStatusArray[i].st_clienthostname = buffer;
    2688      179312 :             buffer += NAMEDATALEN;
    2689             :         }
    2690             :     }
    2691             : 
    2692             :     /* Create or attach to the shared activity buffer */
    2693        1708 :     BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
    2694        1708 :                                          NumBackendStatSlots);
    2695        1708 :     BackendActivityBuffer = (char *)
    2696        1708 :         ShmemInitStruct("Backend Activity Buffer",
    2697             :                         BackendActivityBufferSize,
    2698             :                         &found);
    2699             : 
    2700        1708 :     if (!found)
    2701             :     {
    2702        1708 :         MemSet(BackendActivityBuffer, 0, BackendActivityBufferSize);
    2703             : 
    2704             :         /* Initialize st_activity pointers. */
    2705        1708 :         buffer = BackendActivityBuffer;
    2706      181020 :         for (i = 0; i < NumBackendStatSlots; i++)
    2707             :         {
    2708      179312 :             BackendStatusArray[i].st_activity_raw = buffer;
    2709      179312 :             buffer += pgstat_track_activity_query_size;
    2710             :         }
    2711             :     }
    2712             : 
    2713             : #ifdef USE_SSL
    2714             :     /* Create or attach to the shared SSL status buffer */
    2715        1708 :     size = mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots);
    2716        1708 :     BackendSslStatusBuffer = (PgBackendSSLStatus *)
    2717        1708 :         ShmemInitStruct("Backend SSL Status Buffer", size, &found);
    2718             : 
    2719        1708 :     if (!found)
    2720             :     {
    2721             :         PgBackendSSLStatus *ptr;
    2722             : 
    2723        1708 :         MemSet(BackendSslStatusBuffer, 0, size);
    2724             : 
    2725             :         /* Initialize st_sslstatus pointers. */
    2726        1708 :         ptr = BackendSslStatusBuffer;
    2727      181020 :         for (i = 0; i < NumBackendStatSlots; i++)
    2728             :         {
    2729      179312 :             BackendStatusArray[i].st_sslstatus = ptr;
    2730      179312 :             ptr++;
    2731             :         }
    2732             :     }
    2733             : #endif
    2734        1708 : }
    2735             : 
    2736             : 
    2737             : /* ----------
    2738             :  * pgstat_initialize() -
    2739             :  *
    2740             :  *  Initialize pgstats state, and set up our on-proc-exit hook.
    2741             :  *  Called from InitPostgres and AuxiliaryProcessMain. For auxiliary process,
    2742             :  *  MyBackendId is invalid. Otherwise, MyBackendId must be set,
    2743             :  *  but we must not have started any transaction yet (since the
    2744             :  *  exit hook must run after the last transaction exit).
    2745             :  *  NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
    2746             :  * ----------
    2747             :  */
    2748             : void
    2749       10498 : pgstat_initialize(void)
    2750             : {
    2751             :     /* Initialize MyBEEntry */
    2752       10498 :     if (MyBackendId != InvalidBackendId)
    2753             :     {
    2754             :         Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
    2755        8830 :         MyBEEntry = &BackendStatusArray[MyBackendId - 1];
    2756             :     }
    2757             :     else
    2758             :     {
    2759             :         /* Must be an auxiliary process */
    2760             :         Assert(MyAuxProcType != NotAnAuxProcess);
    2761             : 
    2762             :         /*
    2763             :          * Assign the MyBEEntry for an auxiliary process.  Since it doesn't
    2764             :          * have a BackendId, the slot is statically allocated based on the
    2765             :          * auxiliary process type (MyAuxProcType).  Backends use slots indexed
    2766             :          * in the range from 1 to MaxBackends (inclusive), so we use
    2767             :          * MaxBackends + AuxBackendType + 1 as the index of the slot for an
    2768             :          * auxiliary process.
    2769             :          */
    2770        1668 :         MyBEEntry = &BackendStatusArray[MaxBackends + MyAuxProcType];
    2771             :     }
    2772             : 
    2773             :     /* Set up a process-exit hook to clean up */
    2774       10498 :     on_shmem_exit(pgstat_beshutdown_hook, 0);
    2775       10498 : }
    2776             : 
    2777             : /* ----------
    2778             :  * pgstat_bestart() -
    2779             :  *
    2780             :  *  Initialize this backend's entry in the PgBackendStatus array.
    2781             :  *  Called from InitPostgres.
    2782             :  *
    2783             :  *  Apart from auxiliary processes, MyBackendId, MyDatabaseId,
    2784             :  *  session userid, and application_name must be set for a
    2785             :  *  backend (hence, this cannot be combined with pgstat_initialize).
    2786             :  * ----------
    2787             :  */
    2788             : void
    2789       10448 : pgstat_bestart(void)
    2790             : {
    2791             :     SockAddr    clientaddr;
    2792             :     volatile PgBackendStatus *beentry;
    2793             : 
    2794             :     /*
    2795             :      * To minimize the time spent modifying the PgBackendStatus entry, fetch
    2796             :      * all the needed data first.
    2797             :      */
    2798             : 
    2799             :     /*
    2800             :      * We may not have a MyProcPort (eg, if this is the autovacuum process).
    2801             :      * If so, use all-zeroes client address, which is dealt with specially in
    2802             :      * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
    2803             :      */
    2804       10448 :     if (MyProcPort)
    2805        6112 :         memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
    2806             :     else
    2807        4336 :         MemSet(&clientaddr, 0, sizeof(clientaddr));
    2808             : 
    2809             :     /*
    2810             :      * Initialize my status entry, following the protocol of bumping
    2811             :      * st_changecount before and after; and make sure it's even afterwards. We
    2812             :      * use a volatile pointer here to ensure the compiler doesn't try to get
    2813             :      * cute.
    2814             :      */
    2815       10448 :     beentry = MyBEEntry;
    2816             : 
    2817             :     /* pgstats state must be initialized from pgstat_initialize() */
    2818             :     Assert(beentry != NULL);
    2819             : 
    2820       10448 :     if (MyBackendId != InvalidBackendId)
    2821             :     {
    2822        8780 :         if (IsAutoVacuumLauncherProcess())
    2823             :         {
    2824             :             /* Autovacuum Launcher */
    2825         312 :             beentry->st_backendType = B_AUTOVAC_LAUNCHER;
    2826             :         }
    2827        8468 :         else if (IsAutoVacuumWorkerProcess())
    2828             :         {
    2829             :             /* Autovacuum Worker */
    2830          48 :             beentry->st_backendType = B_AUTOVAC_WORKER;
    2831             :         }
    2832        8420 :         else if (am_walsender)
    2833             :         {
    2834             :             /* Wal sender */
    2835         432 :             beentry->st_backendType = B_WAL_SENDER;
    2836             :         }
    2837        7988 :         else if (IsBackgroundWorker)
    2838             :         {
    2839             :             /* bgworker */
    2840        2014 :             beentry->st_backendType = B_BG_WORKER;
    2841             :         }
    2842             :         else
    2843             :         {
    2844             :             /* client-backend */
    2845        5974 :             beentry->st_backendType = B_BACKEND;
    2846             :         }
    2847             :     }
    2848             :     else
    2849             :     {
    2850             :         /* Must be an auxiliary process */
    2851             :         Assert(MyAuxProcType != NotAnAuxProcess);
    2852        1668 :         switch (MyAuxProcType)
    2853             :         {
    2854             :             case StartupProcess:
    2855         476 :                 beentry->st_backendType = B_STARTUP;
    2856         476 :                 break;
    2857             :             case BgWriterProcess:
    2858         344 :                 beentry->st_backendType = B_BG_WRITER;
    2859         344 :                 break;
    2860             :             case CheckpointerProcess:
    2861         344 :                 beentry->st_backendType = B_CHECKPOINTER;
    2862         344 :                 break;
    2863             :             case WalWriterProcess:
    2864         324 :                 beentry->st_backendType = B_WAL_WRITER;
    2865         324 :                 break;
    2866             :             case WalReceiverProcess:
    2867         180 :                 beentry->st_backendType = B_WAL_RECEIVER;
    2868         180 :                 break;
    2869             :             default:
    2870           0 :                 elog(FATAL, "unrecognized process type: %d",
    2871             :                      (int) MyAuxProcType);
    2872             :                 proc_exit(1);
    2873             :         }
    2874             :     }
    2875             : 
    2876             :     do
    2877             :     {
    2878       10448 :         pgstat_increment_changecount_before(beentry);
    2879       10448 :     } while ((beentry->st_changecount & 1) == 0);
    2880             : 
    2881       10448 :     beentry->st_procpid = MyProcPid;
    2882       10448 :     beentry->st_proc_start_timestamp = MyStartTimestamp;
    2883       10448 :     beentry->st_activity_start_timestamp = 0;
    2884       10448 :     beentry->st_state_start_timestamp = 0;
    2885       10448 :     beentry->st_xact_start_timestamp = 0;
    2886       10448 :     beentry->st_databaseid = MyDatabaseId;
    2887             : 
    2888             :     /* We have userid for client-backends, wal-sender and bgworker processes */
    2889       10448 :     if (beentry->st_backendType == B_BACKEND
    2890        4474 :         || beentry->st_backendType == B_WAL_SENDER
    2891        4042 :         || beentry->st_backendType == B_BG_WORKER)
    2892        8420 :         beentry->st_userid = GetSessionUserId();
    2893             :     else
    2894        2028 :         beentry->st_userid = InvalidOid;
    2895             : 
    2896       10448 :     beentry->st_clientaddr = clientaddr;
    2897       10448 :     if (MyProcPort && MyProcPort->remote_hostname)
    2898          42 :         strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname,
    2899             :                 NAMEDATALEN);
    2900             :     else
    2901       10406 :         beentry->st_clienthostname[0] = '\0';
    2902             : #ifdef USE_SSL
    2903       10448 :     if (MyProcPort && MyProcPort->ssl != NULL)
    2904             :     {
    2905          42 :         beentry->st_ssl = true;
    2906          42 :         beentry->st_sslstatus->ssl_bits = be_tls_get_cipher_bits(MyProcPort);
    2907          42 :         beentry->st_sslstatus->ssl_compression = be_tls_get_compression(MyProcPort);
    2908          42 :         strlcpy(beentry->st_sslstatus->ssl_version, be_tls_get_version(MyProcPort), NAMEDATALEN);
    2909          42 :         strlcpy(beentry->st_sslstatus->ssl_cipher, be_tls_get_cipher(MyProcPort), NAMEDATALEN);
    2910          42 :         be_tls_get_peerdn_name(MyProcPort, beentry->st_sslstatus->ssl_clientdn, NAMEDATALEN);
    2911             :     }
    2912             :     else
    2913             :     {
    2914       10406 :         beentry->st_ssl = false;
    2915             :     }
    2916             : #else
    2917             :     beentry->st_ssl = false;
    2918             : #endif
    2919       10448 :     beentry->st_state = STATE_UNDEFINED;
    2920       10448 :     beentry->st_appname[0] = '\0';
    2921       10448 :     beentry->st_activity_raw[0] = '\0';
    2922             :     /* Also make sure the last byte in each string area is always 0 */
    2923       10448 :     beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
    2924       10448 :     beentry->st_appname[NAMEDATALEN - 1] = '\0';
    2925       10448 :     beentry->st_activity_raw[pgstat_track_activity_query_size - 1] = '\0';
    2926       10448 :     beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
    2927       10448 :     beentry->st_progress_command_target = InvalidOid;
    2928             : 
    2929             :     /*
    2930             :      * we don't zero st_progress_param here to save cycles; nobody should
    2931             :      * examine it until st_progress_command has been set to something other
    2932             :      * than PROGRESS_COMMAND_INVALID
    2933             :      */
    2934             : 
    2935       10448 :     pgstat_increment_changecount_after(beentry);
    2936             : 
    2937             :     /* Update app name to current GUC setting */
    2938       10448 :     if (application_name)
    2939       10448 :         pgstat_report_appname(application_name);
    2940       10448 : }
    2941             : 
    2942             : /*
    2943             :  * Shut down a single backend's statistics reporting at process exit.
    2944             :  *
    2945             :  * Flush any remaining statistics counts out to the collector.
    2946             :  * Without this, operations triggered during backend exit (such as
    2947             :  * temp table deletions) won't be counted.
    2948             :  *
    2949             :  * Lastly, clear out our entry in the PgBackendStatus array.
    2950             :  */
    2951             : static void
    2952       10498 : pgstat_beshutdown_hook(int code, Datum arg)
    2953             : {
    2954       10498 :     volatile PgBackendStatus *beentry = MyBEEntry;
    2955             : 
    2956             :     /*
    2957             :      * If we got as far as discovering our own database ID, we can report what
    2958             :      * we did to the collector.  Otherwise, we'd be sending an invalid
    2959             :      * database ID, so forget it.  (This means that accesses to pg_database
    2960             :      * during failed backend starts might never get counted.)
    2961             :      */
    2962       10498 :     if (OidIsValid(MyDatabaseId))
    2963        7876 :         pgstat_report_stat(true);
    2964             : 
    2965             :     /*
    2966             :      * Clear my status entry, following the protocol of bumping st_changecount
    2967             :      * before and after.  We use a volatile pointer here to ensure the
    2968             :      * compiler doesn't try to get cute.
    2969             :      */
    2970       10498 :     pgstat_increment_changecount_before(beentry);
    2971             : 
    2972       10498 :     beentry->st_procpid = 0; /* mark invalid */
    2973             : 
    2974       10498 :     pgstat_increment_changecount_after(beentry);
    2975       10498 : }
    2976             : 
    2977             : 
    2978             : /* ----------
    2979             :  * pgstat_report_activity() -
    2980             :  *
    2981             :  *  Called from tcop/postgres.c to report what the backend is actually doing
    2982             :  *  (but note cmd_str can be NULL for certain cases).
    2983             :  *
    2984             :  * All updates of the status entry follow the protocol of bumping
    2985             :  * st_changecount before and after.  We use a volatile pointer here to
    2986             :  * ensure the compiler doesn't try to get cute.
    2987             :  * ----------
    2988             :  */
    2989             : void
    2990      901644 : pgstat_report_activity(BackendState state, const char *cmd_str)
    2991             : {
    2992      901644 :     volatile PgBackendStatus *beentry = MyBEEntry;
    2993             :     TimestampTz start_timestamp;
    2994             :     TimestampTz current_timestamp;
    2995      901644 :     int         len = 0;
    2996             : 
    2997             :     TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
    2998             : 
    2999      901644 :     if (!beentry)
    3000           0 :         return;
    3001             : 
    3002      901644 :     if (!pgstat_track_activities)
    3003             :     {
    3004           0 :         if (beentry->st_state != STATE_DISABLED)
    3005             :         {
    3006           0 :             volatile PGPROC *proc = MyProc;
    3007             : 
    3008             :             /*
    3009             :              * track_activities is disabled, but we last reported a
    3010             :              * non-disabled state.  As our final update, change the state and
    3011             :              * clear fields we will not be updating anymore.
    3012             :              */
    3013           0 :             pgstat_increment_changecount_before(beentry);
    3014           0 :             beentry->st_state = STATE_DISABLED;
    3015           0 :             beentry->st_state_start_timestamp = 0;
    3016           0 :             beentry->st_activity_raw[0] = '\0';
    3017           0 :             beentry->st_activity_start_timestamp = 0;
    3018             :             /* st_xact_start_timestamp and wait_event_info are also disabled */
    3019           0 :             beentry->st_xact_start_timestamp = 0;
    3020           0 :             proc->wait_event_info = 0;
    3021           0 :             pgstat_increment_changecount_after(beentry);
    3022             :         }
    3023           0 :         return;
    3024             :     }
    3025             : 
    3026             :     /*
    3027             :      * To minimize the time spent modifying the entry, fetch all the needed
    3028             :      * data first.
    3029             :      */
    3030      901644 :     start_timestamp = GetCurrentStatementStartTimestamp();
    3031      901644 :     if (cmd_str != NULL)
    3032             :     {
    3033             :         /*
    3034             :          * Compute length of to-be-stored string unaware of multi-byte
    3035             :          * characters. For speed reasons that'll get corrected on read, rather
    3036             :          * than computed every write.
    3037             :          */
    3038      457932 :         len = Min(strlen(cmd_str), pgstat_track_activity_query_size - 1);
    3039             :     }
    3040      901644 :     current_timestamp = GetCurrentTimestamp();
    3041             : 
    3042             :     /*
    3043             :      * Now update the status entry
    3044             :      */
    3045      901644 :     pgstat_increment_changecount_before(beentry);
    3046             : 
    3047      901644 :     beentry->st_state = state;
    3048      901644 :     beentry->st_state_start_timestamp = current_timestamp;
    3049             : 
    3050      901644 :     if (cmd_str != NULL)
    3051             :     {
    3052      457932 :         memcpy((char *) beentry->st_activity_raw, cmd_str, len);
    3053      457932 :         beentry->st_activity_raw[len] = '\0';
    3054      457932 :         beentry->st_activity_start_timestamp = start_timestamp;
    3055             :     }
    3056             : 
    3057      901644 :     pgstat_increment_changecount_after(beentry);
    3058             : }
    3059             : 
    3060             : /*-----------
    3061             :  * pgstat_progress_start_command() -
    3062             :  *
    3063             :  * Set st_progress_command (and st_progress_command_target) in own backend
    3064             :  * entry.  Also, zero-initialize st_progress_param array.
    3065             :  *-----------
    3066             :  */
    3067             : void
    3068       37410 : pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
    3069             : {
    3070       37410 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3071             : 
    3072       37410 :     if (!beentry || !pgstat_track_activities)
    3073           0 :         return;
    3074             : 
    3075       37410 :     pgstat_increment_changecount_before(beentry);
    3076       37410 :     beentry->st_progress_command = cmdtype;
    3077       37410 :     beentry->st_progress_command_target = relid;
    3078       37410 :     MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
    3079       37410 :     pgstat_increment_changecount_after(beentry);
    3080             : }
    3081             : 
    3082             : /*-----------
    3083             :  * pgstat_progress_update_param() -
    3084             :  *
    3085             :  * Update index'th member in st_progress_param[] of own backend entry.
    3086             :  *-----------
    3087             :  */
    3088             : void
    3089     1152048 : pgstat_progress_update_param(int index, int64 val)
    3090             : {
    3091     1152048 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3092             : 
    3093             :     Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
    3094             : 
    3095     1152048 :     if (!beentry || !pgstat_track_activities)
    3096           0 :         return;
    3097             : 
    3098     1152048 :     pgstat_increment_changecount_before(beentry);
    3099     1152048 :     beentry->st_progress_param[index] = val;
    3100     1152048 :     pgstat_increment_changecount_after(beentry);
    3101             : }
    3102             : 
    3103             : /*-----------
    3104             :  * pgstat_progress_update_multi_param() -
    3105             :  *
    3106             :  * Update multiple members in st_progress_param[] of own backend entry.
    3107             :  * This is atomic; readers won't see intermediate states.
    3108             :  *-----------
    3109             :  */
    3110             : void
    3111       39484 : pgstat_progress_update_multi_param(int nparam, const int *index,
    3112             :                                    const int64 *val)
    3113             : {
    3114       39484 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3115             :     int         i;
    3116             : 
    3117       39484 :     if (!beentry || !pgstat_track_activities || nparam == 0)
    3118           0 :         return;
    3119             : 
    3120       39484 :     pgstat_increment_changecount_before(beentry);
    3121             : 
    3122      155862 :     for (i = 0; i < nparam; ++i)
    3123             :     {
    3124             :         Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
    3125             : 
    3126      116378 :         beentry->st_progress_param[index[i]] = val[i];
    3127             :     }
    3128             : 
    3129       39484 :     pgstat_increment_changecount_after(beentry);
    3130             : }
    3131             : 
    3132             : /*-----------
    3133             :  * pgstat_progress_end_command() -
    3134             :  *
    3135             :  * Reset st_progress_command (and st_progress_command_target) in own backend
    3136             :  * entry.  This signals the end of the command.
    3137             :  *-----------
    3138             :  */
    3139             : void
    3140       57854 : pgstat_progress_end_command(void)
    3141             : {
    3142       57854 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3143             : 
    3144       57854 :     if (!beentry)
    3145           0 :         return;
    3146       57854 :     if (!pgstat_track_activities
    3147           0 :         && beentry->st_progress_command == PROGRESS_COMMAND_INVALID)
    3148           0 :         return;
    3149             : 
    3150       57854 :     pgstat_increment_changecount_before(beentry);
    3151       57854 :     beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
    3152       57854 :     beentry->st_progress_command_target = InvalidOid;
    3153       57854 :     pgstat_increment_changecount_after(beentry);
    3154             : }
    3155             : 
    3156             : /* ----------
    3157             :  * pgstat_report_appname() -
    3158             :  *
    3159             :  *  Called to update our application name.
    3160             :  * ----------
    3161             :  */
    3162             : void
    3163       19758 : pgstat_report_appname(const char *appname)
    3164             : {
    3165       19758 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3166             :     int         len;
    3167             : 
    3168       19758 :     if (!beentry)
    3169        1710 :         return;
    3170             : 
    3171             :     /* This should be unnecessary if GUC did its job, but be safe */
    3172       18048 :     len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
    3173             : 
    3174             :     /*
    3175             :      * Update my status entry, following the protocol of bumping
    3176             :      * st_changecount before and after.  We use a volatile pointer here to
    3177             :      * ensure the compiler doesn't try to get cute.
    3178             :      */
    3179       18048 :     pgstat_increment_changecount_before(beentry);
    3180             : 
    3181       18048 :     memcpy((char *) beentry->st_appname, appname, len);
    3182       18048 :     beentry->st_appname[len] = '\0';
    3183             : 
    3184       18048 :     pgstat_increment_changecount_after(beentry);
    3185             : }
    3186             : 
    3187             : /*
    3188             :  * Report current transaction start timestamp as the specified value.
    3189             :  * Zero means there is no active transaction.
    3190             :  */
    3191             : void
    3192      894336 : pgstat_report_xact_timestamp(TimestampTz tstamp)
    3193             : {
    3194      894336 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3195             : 
    3196      894336 :     if (!pgstat_track_activities || !beentry)
    3197         588 :         return;
    3198             : 
    3199             :     /*
    3200             :      * Update my status entry, following the protocol of bumping
    3201             :      * st_changecount before and after.  We use a volatile pointer here to
    3202             :      * ensure the compiler doesn't try to get cute.
    3203             :      */
    3204      893748 :     pgstat_increment_changecount_before(beentry);
    3205      893748 :     beentry->st_xact_start_timestamp = tstamp;
    3206      893748 :     pgstat_increment_changecount_after(beentry);
    3207             : }
    3208             : 
    3209             : /* ----------
    3210             :  * pgstat_read_current_status() -
    3211             :  *
    3212             :  *  Copy the current contents of the PgBackendStatus array to local memory,
    3213             :  *  if not already done in this transaction.
    3214             :  * ----------
    3215             :  */
    3216             : static void
    3217        2930 : pgstat_read_current_status(void)
    3218             : {
    3219             :     volatile PgBackendStatus *beentry;
    3220             :     LocalPgBackendStatus *localtable;
    3221             :     LocalPgBackendStatus *localentry;
    3222             :     char       *localappname,
    3223             :                *localclienthostname,
    3224             :                *localactivity;
    3225             : #ifdef USE_SSL
    3226             :     PgBackendSSLStatus *localsslstatus;
    3227             : #endif
    3228             :     int         i;
    3229             : 
    3230             :     Assert(!pgStatRunningInCollector);
    3231        2930 :     if (localBackendStatusTable)
    3232        2574 :         return;                 /* already done */
    3233             : 
    3234         356 :     pgstat_setup_memcxt();
    3235             : 
    3236         356 :     localtable = (LocalPgBackendStatus *)
    3237         356 :         MemoryContextAlloc(pgStatLocalContext,
    3238         356 :                            sizeof(LocalPgBackendStatus) * NumBackendStatSlots);
    3239         356 :     localappname = (char *)
    3240         356 :         MemoryContextAlloc(pgStatLocalContext,
    3241         356 :                            NAMEDATALEN * NumBackendStatSlots);
    3242         356 :     localclienthostname = (char *)
    3243         356 :         MemoryContextAlloc(pgStatLocalContext,
    3244         356 :                            NAMEDATALEN * NumBackendStatSlots);
    3245         356 :     localactivity = (char *)
    3246         356 :         MemoryContextAlloc(pgStatLocalContext,
    3247         356 :                            pgstat_track_activity_query_size * NumBackendStatSlots);
    3248             : #ifdef USE_SSL
    3249         356 :     localsslstatus = (PgBackendSSLStatus *)
    3250         356 :         MemoryContextAlloc(pgStatLocalContext,
    3251         356 :                            sizeof(PgBackendSSLStatus) * NumBackendStatSlots);
    3252             : #endif
    3253             : 
    3254         356 :     localNumBackends = 0;
    3255             : 
    3256         356 :     beentry = BackendStatusArray;
    3257         356 :     localentry = localtable;
    3258       11580 :     for (i = 1; i <= NumBackendStatSlots; i++)
    3259             :     {
    3260             :         /*
    3261             :          * Follow the protocol of retrying if st_changecount changes while we
    3262             :          * copy the entry, or if it's odd.  (The check for odd is needed to
    3263             :          * cover the case where we are able to completely copy the entry while
    3264             :          * the source backend is between increment steps.)  We use a volatile
    3265             :          * pointer here to ensure the compiler doesn't try to get cute.
    3266             :          */
    3267             :         for (;;)
    3268           0 :         {
    3269             :             int         before_changecount;
    3270             :             int         after_changecount;
    3271             : 
    3272       11224 :             pgstat_save_changecount_before(beentry, before_changecount);
    3273             : 
    3274       11224 :             localentry->backendStatus.st_procpid = beentry->st_procpid;
    3275       11224 :             if (localentry->backendStatus.st_procpid > 0)
    3276             :             {
    3277        2574 :                 memcpy(&localentry->backendStatus, (char *) beentry, sizeof(PgBackendStatus));
    3278             : 
    3279             :                 /*
    3280             :                  * strcpy is safe even if the string is modified concurrently,
    3281             :                  * because there's always a \0 at the end of the buffer.
    3282             :                  */
    3283        2574 :                 strcpy(localappname, (char *) beentry->st_appname);
    3284        2574 :                 localentry->backendStatus.st_appname = localappname;
    3285        2574 :                 strcpy(localclienthostname, (char *) beentry->st_clienthostname);
    3286        2574 :                 localentry->backendStatus.st_clienthostname = localclienthostname;
    3287        2574 :                 strcpy(localactivity, (char *) beentry->st_activity_raw);
    3288        2574 :                 localentry->backendStatus.st_activity_raw = localactivity;
    3289        2574 :                 localentry->backendStatus.st_ssl = beentry->st_ssl;
    3290             : #ifdef USE_SSL
    3291        2574 :                 if (beentry->st_ssl)
    3292             :                 {
    3293           0 :                     memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
    3294           0 :                     localentry->backendStatus.st_sslstatus = localsslstatus;
    3295             :                 }
    3296             : #endif
    3297             :             }
    3298             : 
    3299       11224 :             pgstat_save_changecount_after(beentry, after_changecount);
    3300       22448 :             if (before_changecount == after_changecount &&
    3301       11224 :                 (before_changecount & 1) == 0)
    3302       11224 :                 break;
    3303             : 
    3304             :             /* Make sure we can break out of loop if stuck... */
    3305           0 :             CHECK_FOR_INTERRUPTS();
    3306             :         }
    3307             : 
    3308       11224 :         beentry++;
    3309             :         /* Only valid entries get included into the local array */
    3310       11224 :         if (localentry->backendStatus.st_procpid > 0)
    3311             :         {
    3312        2574 :             BackendIdGetTransactionIds(i,
    3313             :                                        &localentry->backend_xid,
    3314             :                                        &localentry->backend_xmin);
    3315             : 
    3316        2574 :             localentry++;
    3317        2574 :             localappname += NAMEDATALEN;
    3318        2574 :             localclienthostname += NAMEDATALEN;
    3319        2574 :             localactivity += pgstat_track_activity_query_size;
    3320             : #ifdef USE_SSL
    3321        2574 :             localsslstatus++;
    3322             : #endif
    3323        2574 :             localNumBackends++;
    3324             :         }
    3325             :     }
    3326             : 
    3327             :     /* Set the pointer only after completion of a valid table */
    3328         356 :     localBackendStatusTable = localtable;
    3329             : }
    3330             : 
    3331             : /* ----------
    3332             :  * pgstat_get_wait_event_type() -
    3333             :  *
    3334             :  *  Return a string representing the current wait event type, backend is
    3335             :  *  waiting on.
    3336             :  */
    3337             : const char *
    3338        2540 : pgstat_get_wait_event_type(uint32 wait_event_info)
    3339             : {
    3340             :     uint32      classId;
    3341             :     const char *event_type;
    3342             : 
    3343             :     /* report process as not waiting. */
    3344        2540 :     if (wait_event_info == 0)
    3345         366 :         return NULL;
    3346             : 
    3347        2174 :     classId = wait_event_info & 0xFF000000;
    3348             : 
    3349        2174 :     switch (classId)
    3350             :     {
    3351             :         case PG_WAIT_LWLOCK:
    3352           2 :             event_type = "LWLock";
    3353           2 :             break;
    3354             :         case PG_WAIT_LOCK:
    3355           0 :             event_type = "Lock";
    3356           0 :             break;
    3357             :         case PG_WAIT_BUFFER_PIN:
    3358           0 :             event_type = "BufferPin";
    3359           0 :             break;
    3360             :         case PG_WAIT_ACTIVITY:
    3361        2040 :             event_type = "Activity";
    3362        2040 :             break;
    3363             :         case PG_WAIT_CLIENT:
    3364         132 :             event_type = "Client";
    3365         132 :             break;
    3366             :         case PG_WAIT_EXTENSION:
    3367           0 :             event_type = "Extension";
    3368           0 :             break;
    3369             :         case PG_WAIT_IPC:
    3370           0 :             event_type = "IPC";
    3371           0 :             break;
    3372             :         case PG_WAIT_TIMEOUT:
    3373           0 :             event_type = "Timeout";
    3374           0 :             break;
    3375             :         case PG_WAIT_IO:
    3376           0 :             event_type = "IO";
    3377           0 :             break;
    3378             :         default:
    3379           0 :             event_type = "???";
    3380           0 :             break;
    3381             :     }
    3382             : 
    3383        2174 :     return event_type;
    3384             : }
    3385             : 
    3386             : /* ----------
    3387             :  * pgstat_get_wait_event() -
    3388             :  *
    3389             :  *  Return a string representing the current wait event, backend is
    3390             :  *  waiting on.
    3391             :  */
    3392             : const char *
    3393        2540 : pgstat_get_wait_event(uint32 wait_event_info)
    3394             : {
    3395             :     uint32      classId;
    3396             :     uint16      eventId;
    3397             :     const char *event_name;
    3398             : 
    3399             :     /* report process as not waiting. */
    3400        2540 :     if (wait_event_info == 0)
    3401         366 :         return NULL;
    3402             : 
    3403        2174 :     classId = wait_event_info & 0xFF000000;
    3404        2174 :     eventId = wait_event_info & 0x0000FFFF;
    3405             : 
    3406        2174 :     switch (classId)
    3407             :     {
    3408             :         case PG_WAIT_LWLOCK:
    3409           2 :             event_name = GetLWLockIdentifier(classId, eventId);
    3410           2 :             break;
    3411             :         case PG_WAIT_LOCK:
    3412           0 :             event_name = GetLockNameFromTagType(eventId);
    3413           0 :             break;
    3414             :         case PG_WAIT_BUFFER_PIN:
    3415           0 :             event_name = "BufferPin";
    3416           0 :             break;
    3417             :         case PG_WAIT_ACTIVITY:
    3418             :             {
    3419        2040 :                 WaitEventActivity w = (WaitEventActivity) wait_event_info;
    3420             : 
    3421        2040 :                 event_name = pgstat_get_wait_activity(w);
    3422        2040 :                 break;
    3423             :             }
    3424             :         case PG_WAIT_CLIENT:
    3425             :             {
    3426         132 :                 WaitEventClient w = (WaitEventClient) wait_event_info;
    3427             : 
    3428         132 :                 event_name = pgstat_get_wait_client(w);
    3429         132 :                 break;
    3430             :             }
    3431             :         case PG_WAIT_EXTENSION:
    3432           0 :             event_name = "Extension";
    3433           0 :             break;
    3434             :         case PG_WAIT_IPC:
    3435             :             {
    3436           0 :                 WaitEventIPC w = (WaitEventIPC) wait_event_info;
    3437             : 
    3438           0 :                 event_name = pgstat_get_wait_ipc(w);
    3439           0 :                 break;
    3440             :             }
    3441             :         case PG_WAIT_TIMEOUT:
    3442             :             {
    3443           0 :                 WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
    3444             : 
    3445           0 :                 event_name = pgstat_get_wait_timeout(w);
    3446           0 :                 break;
    3447             :             }
    3448             :         case PG_WAIT_IO:
    3449             :             {
    3450           0 :                 WaitEventIO w = (WaitEventIO) wait_event_info;
    3451             : 
    3452           0 :                 event_name = pgstat_get_wait_io(w);
    3453           0 :                 break;
    3454             :             }
    3455             :         default:
    3456           0 :             event_name = "unknown wait event";
    3457           0 :             break;
    3458             :     }
    3459             : 
    3460        2174 :     return event_name;
    3461             : }
    3462             : 
    3463             : /* ----------
    3464             :  * pgstat_get_wait_activity() -
    3465             :  *
    3466             :  * Convert WaitEventActivity to string.
    3467             :  * ----------
    3468             :  */
    3469             : static const char *
    3470        2040 : pgstat_get_wait_activity(WaitEventActivity w)
    3471             : {
    3472        2040 :     const char *event_name = "unknown wait event";
    3473             : 
    3474        2040 :     switch (w)
    3475             :     {
    3476             :         case WAIT_EVENT_ARCHIVER_MAIN:
    3477           0 :             event_name = "ArchiverMain";
    3478           0 :             break;
    3479             :         case WAIT_EVENT_AUTOVACUUM_MAIN:
    3480         344 :             event_name = "AutoVacuumMain";
    3481         344 :             break;
    3482             :         case WAIT_EVENT_BGWRITER_HIBERNATE:
    3483         168 :             event_name = "BgWriterHibernate";
    3484         168 :             break;
    3485             :         case WAIT_EVENT_BGWRITER_MAIN:
    3486         184 :             event_name = "BgWriterMain";
    3487         184 :             break;
    3488             :         case WAIT_EVENT_CHECKPOINTER_MAIN:
    3489         346 :             event_name = "CheckpointerMain";
    3490         346 :             break;
    3491             :         case WAIT_EVENT_LOGICAL_APPLY_MAIN:
    3492           0 :             event_name = "LogicalApplyMain";
    3493           0 :             break;
    3494             :         case WAIT_EVENT_LOGICAL_LAUNCHER_MAIN:
    3495         344 :             event_name = "LogicalLauncherMain";
    3496         344 :             break;
    3497             :         case WAIT_EVENT_PGSTAT_MAIN:
    3498           0 :             event_name = "PgStatMain";
    3499           0 :             break;
    3500             :         case WAIT_EVENT_RECOVERY_WAL_ALL:
    3501           8 :             event_name = "RecoveryWalAll";
    3502           8 :             break;
    3503             :         case WAIT_EVENT_RECOVERY_WAL_STREAM:
    3504           0 :             event_name = "RecoveryWalStream";
    3505           0 :             break;
    3506             :         case WAIT_EVENT_SYSLOGGER_MAIN:
    3507           0 :             event_name = "SysLoggerMain";
    3508           0 :             break;
    3509             :         case WAIT_EVENT_WAL_RECEIVER_MAIN:
    3510           8 :             event_name = "WalReceiverMain";
    3511           8 :             break;
    3512             :         case WAIT_EVENT_WAL_SENDER_MAIN:
    3513         294 :             event_name = "WalSenderMain";
    3514         294 :             break;
    3515             :         case WAIT_EVENT_WAL_WRITER_MAIN:
    3516         344 :             event_name = "WalWriterMain";
    3517         344 :             break;
    3518             :             /* no default case, so that compiler will warn */
    3519             :     }
    3520             : 
    3521        2040 :     return event_name;
    3522             : }
    3523             : 
    3524             : /* ----------
    3525             :  * pgstat_get_wait_client() -
    3526             :  *
    3527             :  * Convert WaitEventClient to string.
    3528             :  * ----------
    3529             :  */
    3530             : static const char *
    3531         132 : pgstat_get_wait_client(WaitEventClient w)
    3532             : {
    3533         132 :     const char *event_name = "unknown wait event";
    3534             : 
    3535         132 :     switch (w)
    3536             :     {
    3537             :         case WAIT_EVENT_CLIENT_READ:
    3538           0 :             event_name = "ClientRead";
    3539           0 :             break;
    3540             :         case WAIT_EVENT_CLIENT_WRITE:
    3541           0 :             event_name = "ClientWrite";
    3542           0 :             break;
    3543             :         case WAIT_EVENT_LIBPQWALRECEIVER_CONNECT:
    3544           0 :             event_name = "LibPQWalReceiverConnect";
    3545           0 :             break;
    3546             :         case WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE:
    3547           0 :             event_name = "LibPQWalReceiverReceive";
    3548           0 :             break;
    3549             :         case WAIT_EVENT_SSL_OPEN_SERVER:
    3550           0 :             event_name = "SSLOpenServer";
    3551           0 :             break;
    3552             :         case WAIT_EVENT_WAL_RECEIVER_WAIT_START:
    3553           0 :             event_name = "WalReceiverWaitStart";
    3554           0 :             break;
    3555             :         case WAIT_EVENT_WAL_SENDER_WAIT_WAL:
    3556         132 :             event_name = "WalSenderWaitForWAL";
    3557         132 :             break;
    3558             :         case WAIT_EVENT_WAL_SENDER_WRITE_DATA:
    3559           0 :             event_name = "WalSenderWriteData";
    3560           0 :             break;
    3561             :             /* no default case, so that compiler will warn */
    3562             :     }
    3563             : 
    3564         132 :     return event_name;
    3565             : }
    3566             : 
    3567             : /* ----------
    3568             :  * pgstat_get_wait_ipc() -
    3569             :  *
    3570             :  * Convert WaitEventIPC to string.
    3571             :  * ----------
    3572             :  */
    3573             : static const char *
    3574           0 : pgstat_get_wait_ipc(WaitEventIPC w)
    3575             : {
    3576           0 :     const char *event_name = "unknown wait event";
    3577             : 
    3578           0 :     switch (w)
    3579             :     {
    3580             :         case WAIT_EVENT_BGWORKER_SHUTDOWN:
    3581           0 :             event_name = "BgWorkerShutdown";
    3582           0 :             break;
    3583             :         case WAIT_EVENT_BGWORKER_STARTUP:
    3584           0 :             event_name = "BgWorkerStartup";
    3585           0 :             break;
    3586             :         case WAIT_EVENT_BTREE_PAGE:
    3587           0 :             event_name = "BtreePage";
    3588           0 :             break;
    3589             :         case WAIT_EVENT_CLOG_GROUP_UPDATE:
    3590           0 :             event_name = "ClogGroupUpdate";
    3591           0 :             break;
    3592             :         case WAIT_EVENT_EXECUTE_GATHER:
    3593           0 :             event_name = "ExecuteGather";
    3594           0 :             break;
    3595             :         case WAIT_EVENT_HASH_BATCH_ALLOCATING:
    3596           0 :             event_name = "Hash/Batch/Allocating";
    3597           0 :             break;
    3598             :         case WAIT_EVENT_HASH_BATCH_ELECTING:
    3599           0 :             event_name = "Hash/Batch/Electing";
    3600           0 :             break;
    3601             :         case WAIT_EVENT_HASH_BATCH_LOADING:
    3602           0 :             event_name = "Hash/Batch/Loading";
    3603           0 :             break;
    3604             :         case WAIT_EVENT_HASH_BUILD_ALLOCATING:
    3605           0 :             event_name = "Hash/Build/Allocating";
    3606           0 :             break;
    3607             :         case WAIT_EVENT_HASH_BUILD_ELECTING:
    3608           0 :             event_name = "Hash/Build/Electing";
    3609           0 :             break;
    3610             :         case WAIT_EVENT_HASH_BUILD_HASHING_INNER:
    3611           0 :             event_name = "Hash/Build/HashingInner";
    3612           0 :             break;
    3613             :         case WAIT_EVENT_HASH_BUILD_HASHING_OUTER:
    3614           0 :             event_name = "Hash/Build/HashingOuter";
    3615           0 :             break;
    3616             :         case WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATING:
    3617           0 :             event_name = "Hash/GrowBatches/Allocating";
    3618           0 :             break;
    3619             :         case WAIT_EVENT_HASH_GROW_BATCHES_DECIDING:
    3620           0 :             event_name = "Hash/GrowBatches/Deciding";
    3621           0 :             break;
    3622             :         case WAIT_EVENT_HASH_GROW_BATCHES_ELECTING:
    3623           0 :             event_name = "Hash/GrowBatches/Electing";
    3624           0 :             break;
    3625             :         case WAIT_EVENT_HASH_GROW_BATCHES_FINISHING:
    3626           0 :             event_name = "Hash/GrowBatches/Finishing";
    3627           0 :             break;
    3628             :         case WAIT_EVENT_HASH_GROW_BATCHES_REPARTITIONING:
    3629           0 :             event_name = "Hash/GrowBatches/Repartitioning";
    3630           0 :             break;
    3631             :         case WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATING:
    3632           0 :             event_name = "Hash/GrowBuckets/Allocating";
    3633           0 :             break;
    3634             :         case WAIT_EVENT_HASH_GROW_BUCKETS_ELECTING:
    3635           0 :             event_name = "Hash/GrowBuckets/Electing";
    3636           0 :             break;
    3637             :         case WAIT_EVENT_HASH_GROW_BUCKETS_REINSERTING:
    3638           0 :             event_name = "Hash/GrowBuckets/Reinserting";
    3639           0 :             break;
    3640             :         case WAIT_EVENT_LOGICAL_SYNC_DATA:
    3641           0 :             event_name = "LogicalSyncData";
    3642           0 :             break;
    3643             :         case WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE:
    3644           0 :             event_name = "LogicalSyncStateChange";
    3645           0 :             break;
    3646             :         case WAIT_EVENT_MQ_INTERNAL:
    3647           0 :             event_name = "MessageQueueInternal";
    3648           0 :             break;
    3649             :         case WAIT_EVENT_MQ_PUT_MESSAGE:
    3650           0 :             event_name = "MessageQueuePutMessage";
    3651           0 :             break;
    3652             :         case WAIT_EVENT_MQ_RECEIVE:
    3653           0 :             event_name = "MessageQueueReceive";
    3654           0 :             break;
    3655             :         case WAIT_EVENT_MQ_SEND:
    3656           0 :             event_name = "MessageQueueSend";
    3657           0 :             break;
    3658             :         case WAIT_EVENT_PARALLEL_BITMAP_SCAN:
    3659           0 :             event_name = "ParallelBitmapScan";
    3660           0 :             break;
    3661             :         case WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN:
    3662           0 :             event_name = "ParallelCreateIndexScan";
    3663           0 :             break;
    3664             :         case WAIT_EVENT_PARALLEL_FINISH:
    3665           0 :             event_name = "ParallelFinish";
    3666           0 :             break;
    3667             :         case WAIT_EVENT_PROCARRAY_GROUP_UPDATE:
    3668           0 :             event_name = "ProcArrayGroupUpdate";
    3669           0 :             break;
    3670             :         case WAIT_EVENT_PROMOTE:
    3671           0 :             event_name = "Promote";
    3672           0 :             break;
    3673             :         case WAIT_EVENT_REPLICATION_ORIGIN_DROP:
    3674           0 :             event_name = "ReplicationOriginDrop";
    3675           0 :             break;
    3676             :         case WAIT_EVENT_REPLICATION_SLOT_DROP:
    3677           0 :             event_name = "ReplicationSlotDrop";
    3678           0 :             break;
    3679             :         case WAIT_EVENT_SAFE_SNAPSHOT:
    3680           0 :             event_name = "SafeSnapshot";
    3681           0 :             break;
    3682             :         case WAIT_EVENT_SYNC_REP:
    3683           0 :             event_name = "SyncRep";
    3684           0 :             break;
    3685             :             /* no default case, so that compiler will warn */
    3686             :     }
    3687             : 
    3688           0 :     return event_name;
    3689             : }
    3690             : 
    3691             : /* ----------
    3692             :  * pgstat_get_wait_timeout() -
    3693             :  *
    3694             :  * Convert WaitEventTimeout to string.
    3695             :  * ----------
    3696             :  */
    3697             : static const char *
    3698           0 : pgstat_get_wait_timeout(WaitEventTimeout w)
    3699             : {
    3700           0 :     const char *event_name = "unknown wait event";
    3701             : 
    3702           0 :     switch (w)
    3703             :     {
    3704             :         case WAIT_EVENT_BASE_BACKUP_THROTTLE:
    3705           0 :             event_name = "BaseBackupThrottle";
    3706           0 :             break;
    3707             :         case WAIT_EVENT_PG_SLEEP:
    3708           0 :             event_name = "PgSleep";
    3709           0 :             break;
    3710             :         case WAIT_EVENT_RECOVERY_APPLY_DELAY:
    3711           0 :             event_name = "RecoveryApplyDelay";
    3712           0 :             break;
    3713             :             /* no default case, so that compiler will warn */
    3714             :     }
    3715             : 
    3716           0 :     return event_name;
    3717             : }
    3718             : 
    3719             : /* ----------
    3720             :  * pgstat_get_wait_io() -
    3721             :  *
    3722             :  * Convert WaitEventIO to string.
    3723             :  * ----------
    3724             :  */
    3725             : static const char *
    3726           0 : pgstat_get_wait_io(WaitEventIO w)
    3727             : {
    3728           0 :     const char *event_name = "unknown wait event";
    3729             : 
    3730           0 :     switch (w)
    3731             :     {
    3732             :         case WAIT_EVENT_BUFFILE_READ:
    3733           0 :             event_name = "BufFileRead";
    3734           0 :             break;
    3735             :         case WAIT_EVENT_BUFFILE_WRITE:
    3736           0 :             event_name = "BufFileWrite";
    3737           0 :             break;
    3738             :         case WAIT_EVENT_CONTROL_FILE_READ:
    3739           0 :             event_name = "ControlFileRead";
    3740           0 :             break;
    3741             :         case WAIT_EVENT_CONTROL_FILE_SYNC:
    3742           0 :             event_name = "ControlFileSync";
    3743           0 :             break;
    3744             :         case WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE:
    3745           0 :             event_name = "ControlFileSyncUpdate";
    3746           0 :             break;
    3747             :         case WAIT_EVENT_CONTROL_FILE_WRITE:
    3748           0 :             event_name = "ControlFileWrite";
    3749           0 :             break;
    3750             :         case WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE:
    3751           0 :             event_name = "ControlFileWriteUpdate";
    3752           0 :             break;
    3753             :         case WAIT_EVENT_COPY_FILE_READ:
    3754           0 :             event_name = "CopyFileRead";
    3755           0 :             break;
    3756             :         case WAIT_EVENT_COPY_FILE_WRITE:
    3757           0 :             event_name = "CopyFileWrite";
    3758           0 :             break;
    3759             :         case WAIT_EVENT_DATA_FILE_EXTEND:
    3760           0 :             event_name = "DataFileExtend";
    3761           0 :             break;
    3762             :         case WAIT_EVENT_DATA_FILE_FLUSH:
    3763           0 :             event_name = "DataFileFlush";
    3764           0 :             break;
    3765             :         case WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC:
    3766           0 :             event_name = "DataFileImmediateSync";
    3767           0 :             break;
    3768             :         case WAIT_EVENT_DATA_FILE_PREFETCH:
    3769           0 :             event_name = "DataFilePrefetch";
    3770           0 :             break;
    3771             :         case WAIT_EVENT_DATA_FILE_READ:
    3772           0 :             event_name = "DataFileRead";
    3773           0 :             break;
    3774             :         case WAIT_EVENT_DATA_FILE_SYNC:
    3775           0 :             event_name = "DataFileSync";
    3776           0 :             break;
    3777             :         case WAIT_EVENT_DATA_FILE_TRUNCATE:
    3778           0 :             event_name = "DataFileTruncate";
    3779           0 :             break;
    3780             :         case WAIT_EVENT_DATA_FILE_WRITE:
    3781           0 :             event_name = "DataFileWrite";
    3782           0 :             break;
    3783             :         case WAIT_EVENT_DSM_FILL_ZERO_WRITE:
    3784           0 :             event_name = "DSMFillZeroWrite";
    3785           0 :             break;
    3786             :         case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ:
    3787           0 :             event_name = "LockFileAddToDataDirRead";
    3788           0 :             break;
    3789             :         case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC:
    3790           0 :             event_name = "LockFileAddToDataDirSync";
    3791           0 :             break;
    3792             :         case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE:
    3793           0 :             event_name = "LockFileAddToDataDirWrite";
    3794           0 :             break;
    3795             :         case WAIT_EVENT_LOCK_FILE_CREATE_READ:
    3796           0 :             event_name = "LockFileCreateRead";
    3797           0 :             break;
    3798             :         case WAIT_EVENT_LOCK_FILE_CREATE_SYNC:
    3799           0 :             event_name = "LockFileCreateSync";
    3800           0 :             break;
    3801             :         case WAIT_EVENT_LOCK_FILE_CREATE_WRITE:
    3802           0 :             event_name = "LockFileCreateWRITE";
    3803           0 :             break;
    3804             :         case WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ:
    3805           0 :             event_name = "LockFileReCheckDataDirRead";
    3806           0 :             break;
    3807             :         case WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC:
    3808           0 :             event_name = "LogicalRewriteCheckpointSync";
    3809           0 :             break;
    3810             :         case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC:
    3811           0 :             event_name = "LogicalRewriteMappingSync";
    3812           0 :             break;
    3813             :         case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE:
    3814           0 :             event_name = "LogicalRewriteMappingWrite";
    3815           0 :             break;
    3816             :         case WAIT_EVENT_LOGICAL_REWRITE_SYNC:
    3817           0 :             event_name = "LogicalRewriteSync";
    3818           0 :             break;
    3819             :         case WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE:
    3820           0 :             event_name = "LogicalRewriteTruncate";
    3821           0 :             break;
    3822             :         case WAIT_EVENT_LOGICAL_REWRITE_WRITE:
    3823           0 :             event_name = "LogicalRewriteWrite";
    3824           0 :             break;
    3825             :         case WAIT_EVENT_RELATION_MAP_READ:
    3826           0 :             event_name = "RelationMapRead";
    3827           0 :             break;
    3828             :         case WAIT_EVENT_RELATION_MAP_SYNC:
    3829           0 :             event_name = "RelationMapSync";
    3830           0 :             break;
    3831             :         case WAIT_EVENT_RELATION_MAP_WRITE:
    3832           0 :             event_name = "RelationMapWrite";
    3833           0 :             break;
    3834             :         case WAIT_EVENT_REORDER_BUFFER_READ:
    3835           0 :             event_name = "ReorderBufferRead";
    3836           0 :             break;
    3837             :         case WAIT_EVENT_REORDER_BUFFER_WRITE:
    3838           0 :             event_name = "ReorderBufferWrite";
    3839           0 :             break;
    3840             :         case WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ:
    3841           0 :             event_name = "ReorderLogicalMappingRead";
    3842           0 :             break;
    3843             :         case WAIT_EVENT_REPLICATION_SLOT_READ:
    3844           0 :             event_name = "ReplicationSlotRead";
    3845           0 :             break;
    3846             :         case WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC:
    3847           0 :             event_name = "ReplicationSlotRestoreSync";
    3848           0 :             break;
    3849             :         case WAIT_EVENT_REPLICATION_SLOT_SYNC:
    3850           0 :             event_name = "ReplicationSlotSync";
    3851           0 :             break;
    3852             :         case WAIT_EVENT_REPLICATION_SLOT_WRITE:
    3853           0 :             event_name = "ReplicationSlotWrite";
    3854           0 :             break;
    3855             :         case WAIT_EVENT_SLRU_FLUSH_SYNC:
    3856           0 :             event_name = "SLRUFlushSync";
    3857           0 :             break;
    3858             :         case WAIT_EVENT_SLRU_READ:
    3859           0 :             event_name = "SLRURead";
    3860           0 :             break;
    3861             :         case WAIT_EVENT_SLRU_SYNC:
    3862           0 :             event_name = "SLRUSync";
    3863           0 :             break;
    3864             :         case WAIT_EVENT_SLRU_WRITE:
    3865           0 :             event_name = "SLRUWrite";
    3866           0 :             break;
    3867             :         case WAIT_EVENT_SNAPBUILD_READ:
    3868           0 :             event_name = "SnapbuildRead";
    3869           0 :             break;
    3870             :         case WAIT_EVENT_SNAPBUILD_SYNC:
    3871           0 :             event_name = "SnapbuildSync";
    3872           0 :             break;
    3873             :         case WAIT_EVENT_SNAPBUILD_WRITE:
    3874           0 :             event_name = "SnapbuildWrite";
    3875           0 :             break;
    3876             :         case WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC:
    3877           0 :             event_name = "TimelineHistoryFileSync";
    3878           0 :             break;
    3879             :         case WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE:
    3880           0 :             event_name = "TimelineHistoryFileWrite";
    3881           0 :             break;
    3882             :         case WAIT_EVENT_TIMELINE_HISTORY_READ:
    3883           0 :             event_name = "TimelineHistoryRead";
    3884           0 :             break;
    3885             :         case WAIT_EVENT_TIMELINE_HISTORY_SYNC:
    3886           0 :             event_name = "TimelineHistorySync";
    3887           0 :             break;
    3888             :         case WAIT_EVENT_TIMELINE_HISTORY_WRITE:
    3889           0 :             event_name = "TimelineHistoryWrite";
    3890           0 :             break;
    3891             :         case WAIT_EVENT_TWOPHASE_FILE_READ:
    3892           0 :             event_name = "TwophaseFileRead";
    3893           0 :             break;
    3894             :         case WAIT_EVENT_TWOPHASE_FILE_SYNC:
    3895           0 :             event_name = "TwophaseFileSync";
    3896           0 :             break;
    3897             :         case WAIT_EVENT_TWOPHASE_FILE_WRITE:
    3898           0 :             event_name = "TwophaseFileWrite";
    3899           0 :             break;
    3900             :         case WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ:
    3901           0 :             event_name = "WALSenderTimelineHistoryRead";
    3902           0 :             break;
    3903             :         case WAIT_EVENT_WAL_BOOTSTRAP_SYNC:
    3904           0 :             event_name = "WALBootstrapSync";
    3905           0 :             break;
    3906             :         case WAIT_EVENT_WAL_BOOTSTRAP_WRITE:
    3907           0 :             event_name = "WALBootstrapWrite";
    3908           0 :             break;
    3909             :         case WAIT_EVENT_WAL_COPY_READ:
    3910           0 :             event_name = "WALCopyRead";
    3911           0 :             break;
    3912             :         case WAIT_EVENT_WAL_COPY_SYNC:
    3913           0 :             event_name = "WALCopySync";
    3914           0 :             break;
    3915             :         case WAIT_EVENT_WAL_COPY_WRITE:
    3916           0 :             event_name = "WALCopyWrite";
    3917           0 :             break;
    3918             :         case WAIT_EVENT_WAL_INIT_SYNC:
    3919           0 :             event_name = "WALInitSync";
    3920           0 :             break;
    3921             :         case WAIT_EVENT_WAL_INIT_WRITE:
    3922           0 :             event_name = "WALInitWrite";
    3923           0 :             break;
    3924             :         case WAIT_EVENT_WAL_READ:
    3925           0 :             event_name = "WALRead";
    3926           0 :             break;
    3927             :         case WAIT_EVENT_WAL_SYNC:
    3928           0 :             event_name = "WALSync";
    3929           0 :             break;
    3930             :         case WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN:
    3931           0 :             event_name = "WALSyncMethodAssign";
    3932           0 :             break;
    3933             :         case WAIT_EVENT_WAL_WRITE:
    3934           0 :             event_name = "WALWrite";
    3935           0 :             break;
    3936             : 
    3937             :             /* no default case, so that compiler will warn */
    3938             :     }
    3939             : 
    3940           0 :     return event_name;
    3941             : }
    3942             : 
    3943             : 
    3944             : /* ----------
    3945             :  * pgstat_get_backend_current_activity() -
    3946             :  *
    3947             :  *  Return a string representing the current activity of the backend with
    3948             :  *  the specified PID.  This looks directly at the BackendStatusArray,
    3949             :  *  and so will provide current information regardless of the age of our
    3950             :  *  transaction's snapshot of the status array.
    3951             :  *
    3952             :  *  It is the caller's responsibility to invoke this only for backends whose
    3953             :  *  state is expected to remain stable while the result is in use.  The
    3954             :  *  only current use is in deadlock reporting, where we can expect that
    3955             :  *  the target backend is blocked on a lock.  (There are corner cases
    3956             :  *  where the target's wait could get aborted while we are looking at it,
    3957             :  *  but the very worst consequence is to return a pointer to a string
    3958             :  *  that's been changed, so we won't worry too much.)
    3959             :  *
    3960             :  *  Note: return strings for special cases match pg_stat_get_backend_activity.
    3961             :  * ----------
    3962             :  */
    3963             : const char *
    3964          20 : pgstat_get_backend_current_activity(int pid, bool checkUser)
    3965             : {
    3966             :     PgBackendStatus *beentry;
    3967             :     int         i;
    3968             : 
    3969          20 :     beentry = BackendStatusArray;
    3970         138 :     for (i = 1; i <= MaxBackends; i++)
    3971             :     {
    3972             :         /*
    3973             :          * Although we expect the target backend's entry to be stable, that
    3974             :          * doesn't imply that anyone else's is.  To avoid identifying the
    3975             :          * wrong backend, while we check for a match to the desired PID we
    3976             :          * must follow the protocol of retrying if st_changecount changes
    3977             :          * while we examine the entry, or if it's odd.  (This might be
    3978             :          * unnecessary, since fetching or storing an int is almost certainly
    3979             :          * atomic, but let's play it safe.)  We use a volatile pointer here to
    3980             :          * ensure the compiler doesn't try to get cute.
    3981             :          */
    3982         138 :         volatile PgBackendStatus *vbeentry = beentry;
    3983             :         bool        found;
    3984             : 
    3985             :         for (;;)
    3986           0 :         {
    3987             :             int         before_changecount;
    3988             :             int         after_changecount;
    3989             : 
    3990         138 :             pgstat_save_changecount_before(vbeentry, before_changecount);
    3991             : 
    3992         138 :             found = (vbeentry->st_procpid == pid);
    3993             : 
    3994         138 :             pgstat_save_changecount_after(vbeentry, after_changecount);
    3995             : 
    3996         276 :             if (before_changecount == after_changecount &&
    3997         138 :                 (before_changecount & 1) == 0)
    3998         138 :                 break;
    3999             : 
    4000             :             /* Make sure we can break out of loop if stuck... */
    4001           0 :             CHECK_FOR_INTERRUPTS();
    4002             :         }
    4003             : 
    4004         138 :         if (found)
    4005             :         {
    4006             :             /* Now it is safe to use the non-volatile pointer */
    4007          20 :             if (checkUser && !superuser() && beentry->st_userid != GetUserId())
    4008           0 :                 return "<insufficient privilege>";
    4009          20 :             else if (*(beentry->st_activity_raw) == '\0')
    4010           0 :                 return "<command string not enabled>";
    4011             :             else
    4012             :             {
    4013             :                 /* this'll leak a bit of memory, but that seems acceptable */
    4014          20 :                 return pgstat_clip_activity(beentry->st_activity_raw);
    4015             :             }
    4016             :         }
    4017             : 
    4018         118 :         beentry++;
    4019             :     }
    4020             : 
    4021             :     /* If we get here, caller is in error ... */
    4022           0 :     return "<backend information not available>";
    4023             : }
    4024             : 
    4025             : /* ----------
    4026             :  * pgstat_get_crashed_backend_activity() -
    4027             :  *
    4028             :  *  Return a string representing the current activity of the backend with
    4029             :  *  the specified PID.  Like the function above, but reads shared memory with
    4030             :  *  the expectation that it may be corrupt.  On success, copy the string
    4031             :  *  into the "buffer" argument and return that pointer.  On failure,
    4032             :  *  return NULL.
    4033             :  *
    4034             :  *  This function is only intended to be used by the postmaster to report the
    4035             :  *  query that crashed a backend.  In particular, no attempt is made to
    4036             :  *  follow the correct concurrency protocol when accessing the
    4037             :  *  BackendStatusArray.  But that's OK, in the worst case we'll return a
    4038             :  *  corrupted message.  We also must take care not to trip on ereport(ERROR).
    4039             :  * ----------
    4040             :  */
    4041             : const char *
    4042         594 : pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
    4043             : {
    4044             :     volatile PgBackendStatus *beentry;
    4045             :     int         i;
    4046             : 
    4047         594 :     beentry = BackendStatusArray;
    4048             : 
    4049             :     /*
    4050             :      * We probably shouldn't get here before shared memory has been set up,
    4051             :      * but be safe.
    4052             :      */
    4053         594 :     if (beentry == NULL || BackendActivityBuffer == NULL)
    4054           0 :         return NULL;
    4055             : 
    4056       42746 :     for (i = 1; i <= MaxBackends; i++)
    4057             :     {
    4058       42202 :         if (beentry->st_procpid == pid)
    4059             :         {
    4060             :             /* Read pointer just once, so it can't change after validation */
    4061          50 :             const char *activity = beentry->st_activity_raw;
    4062             :             const char *activity_last;
    4063             : 
    4064             :             /*
    4065             :              * We mustn't access activity string before we verify that it
    4066             :              * falls within the BackendActivityBuffer. To make sure that the
    4067             :              * entire string including its ending is contained within the
    4068             :              * buffer, subtract one activity length from the buffer size.
    4069             :              */
    4070          50 :             activity_last = BackendActivityBuffer + BackendActivityBufferSize
    4071          50 :                 - pgstat_track_activity_query_size;
    4072             : 
    4073          50 :             if (activity < BackendActivityBuffer ||
    4074             :                 activity > activity_last)
    4075           0 :                 return NULL;
    4076             : 
    4077             :             /* If no string available, no point in a report */
    4078          50 :             if (activity[0] == '\0')
    4079          36 :                 return NULL;
    4080             : 
    4081             :             /*
    4082             :              * Copy only ASCII-safe characters so we don't run into encoding
    4083             :              * problems when reporting the message; and be sure not to run off
    4084             :              * the end of memory.  As only ASCII characters are reported, it
    4085             :              * doesn't seem necessary to perform multibyte aware clipping.
    4086             :              */
    4087          14 :             ascii_safe_strlcpy(buffer, activity,
    4088          14 :                                Min(buflen, pgstat_track_activity_query_size));
    4089             : 
    4090          14 :             return buffer;
    4091             :         }
    4092             : 
    4093       42152 :         beentry++;
    4094             :     }
    4095             : 
    4096             :     /* PID not found */
    4097         544 :     return NULL;
    4098             : }
    4099             : 
    4100             : const char *
    4101        4658 : pgstat_get_backend_desc(BackendType backendType)
    4102             : {
    4103        4658 :     const char *backendDesc = "unknown process type";
    4104             : 
    4105        4658 :     switch (backendType)
    4106             :     {
    4107             :         case B_AUTOVAC_LAUNCHER:
    4108         656 :             backendDesc = "autovacuum launcher";
    4109         656 :             break;
    4110             :         case B_AUTOVAC_WORKER:
    4111          50 :             backendDesc = "autovacuum worker";
    4112          50 :             break;
    4113             :         case B_BACKEND:
    4114         362 :             backendDesc = "client backend";
    4115         362 :             break;
    4116             :         case B_BG_WORKER:
    4117           0 :             backendDesc = "background worker";
    4118           0 :             break;
    4119             :         case B_BG_WRITER:
    4120         696 :             backendDesc = "background writer";
    4121         696 :             break;
    4122             :         case B_CHECKPOINTER:
    4123         696 :             backendDesc = "checkpointer";
    4124         696 :             break;
    4125             :         case B_STARTUP:
    4126         484 :             backendDesc = "startup";
    4127         484 :             break;
    4128             :         case B_WAL_RECEIVER:
    4129         188 :             backendDesc = "walreceiver";
    4130         188 :             break;
    4131             :         case B_WAL_SENDER:
    4132         858 :             backendDesc = "walsender";
    4133         858 :             break;
    4134             :         case B_WAL_WRITER:
    4135         668 :             backendDesc = "walwriter";
    4136         668 :             break;
    4137             :     }
    4138             : 
    4139        4658 :     return backendDesc;
    4140             : }
    4141             : 
    4142             : /* ------------------------------------------------------------
    4143             :  * Local support functions follow
    4144             :  * ------------------------------------------------------------
    4145             :  */
    4146             : 
    4147             : 
    4148             : /* ----------
    4149             :  * pgstat_setheader() -
    4150             :  *
    4151             :  *      Set common header fields in a statistics message
    4152             :  * ----------
    4153             :  */
    4154             : static void
    4155       91012 : pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
    4156             : {
    4157       91012 :     hdr->m_type = mtype;
    4158       91012 : }
    4159             : 
    4160             : 
    4161             : /* ----------
    4162             :  * pgstat_send() -
    4163             :  *
    4164             :  *      Send out one statistics message to the collector
    4165             :  * ----------
    4166             :  */
    4167             : static void
    4168       91012 : pgstat_send(void *msg, int len)
    4169             : {
    4170             :     int         rc;
    4171             : 
    4172       91012 :     if (pgStatSock == PGINVALID_SOCKET)
    4173           0 :         return;
    4174             : 
    4175       91012 :     ((PgStat_MsgHdr *) msg)->m_size = len;
    4176             : 
    4177             :     /* We'll retry after EINTR, but ignore all other failures */
    4178             :     do
    4179             :     {
    4180       91012 :         rc = send(pgStatSock, msg, len, 0);
    4181       91012 :     } while (rc < 0 && errno == EINTR);
    4182             : 
    4183             : #ifdef USE_ASSERT_CHECKING
    4184             :     /* In debug builds, log send failures ... */
    4185             :     if (rc < 0)
    4186             :         elog(LOG, "could not send to statistics collector: %m");
    4187             : #endif
    4188             : }
    4189             : 
    4190             : /* ----------
    4191             :  * pgstat_send_archiver() -
    4192             :  *
    4193             :  *  Tell the collector about the WAL file that we successfully
    4194             :  *  archived or failed to archive.
    4195             :  * ----------
    4196             :  */
    4197             : void
    4198          26 : pgstat_send_archiver(const char *xlog, bool failed)
    4199             : {
    4200             :     PgStat_MsgArchiver msg;
    4201             : 
    4202             :     /*
    4203             :      * Prepare and send the message
    4204             :      */
    4205          26 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ARCHIVER);
    4206          26 :     msg.m_failed = failed;
    4207          26 :     StrNCpy(msg.m_xlog, xlog, sizeof(msg.m_xlog));
    4208          26 :     msg.m_timestamp = GetCurrentTimestamp();
    4209          26 :     pgstat_send(&msg, sizeof(msg));
    4210          26 : }
    4211             : 
    4212             : /* ----------
    4213             :  * pgstat_send_bgwriter() -
    4214             :  *
    4215             :  *      Send bgwriter statistics to the collector
    4216             :  * ----------
    4217             :  */
    4218             : void
    4219        7966 : pgstat_send_bgwriter(void)
    4220             : {
    4221             :     /* We assume this initializes to zeroes */
    4222             :     static const PgStat_MsgBgWriter all_zeroes;
    4223             : 
    4224             :     /*
    4225             :      * This function can be called even if nothing at all has happened. In
    4226             :      * this case, avoid sending a completely empty message to the stats
    4227             :      * collector.
    4228             :      */
    4229        7966 :     if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
    4230        3474 :         return;
    4231             : 
    4232             :     /*
    4233             :      * Prepare and send the message
    4234             :      */
    4235        4492 :     pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
    4236        4492 :     pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
    4237             : 
    4238             :     /*
    4239             :      * Clear out the statistics buffer, so it can be re-used.
    4240             :      */
    4241        4492 :     MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
    4242             : }
    4243             : 
    4244             : 
    4245             : /* ----------
    4246             :  * PgstatCollectorMain() -
    4247             :  *
    4248             :  *  Start up the statistics collector process.  This is the body of the
    4249             :  *  postmaster child process.
    4250             :  *
    4251             :  *  The argc/argv parameters are valid only in EXEC_BACKEND case.
    4252             :  * ----------
    4253             :  */
    4254             : NON_EXEC_STATIC void
    4255         532 : PgstatCollectorMain(int argc, char *argv[])
    4256             : {
    4257             :     int         len;
    4258             :     PgStat_Msg  msg;
    4259             :     int         wr;
    4260             : 
    4261             :     /*
    4262             :      * Ignore all signals usually bound to some action in the postmaster,
    4263             :      * except SIGHUP and SIGQUIT.  Note we don't need a SIGUSR1 handler to
    4264             :      * support latch operations, because we only use a local latch.
    4265             :      */
    4266         532 :     pqsignal(SIGHUP, pgstat_sighup_handler);
    4267         532 :     pqsignal(SIGINT, SIG_IGN);
    4268         532 :     pqsignal(SIGTERM, SIG_IGN);
    4269         532 :     pqsignal(SIGQUIT, pgstat_exit);
    4270         532 :     pqsignal(SIGALRM, SIG_IGN);
    4271         532 :     pqsignal(SIGPIPE, SIG_IGN);
    4272         532 :     pqsignal(SIGUSR1, SIG_IGN);
    4273         532 :     pqsignal(SIGUSR2, SIG_IGN);
    4274             :     /* Reset some signals that are accepted by postmaster but not here */
    4275         532 :     pqsignal(SIGCHLD, SIG_DFL);
    4276         532 :     PG_SETMASK(&UnBlockSig);
    4277             : 
    4278             :     /*
    4279             :      * Identify myself via ps
    4280             :      */
    4281         532 :     init_ps_display("stats collector", "", "", "");
    4282             : 
    4283             :     /*
    4284             :      * Read in existing stats files or initialize the stats to zero.
    4285             :      */
    4286         532 :     pgStatRunningInCollector = true;
    4287         532 :     pgStatDBHash = pgstat_read_statsfiles(InvalidOid, true, true);
    4288             : 
    4289             :     /*
    4290             :      * Loop to process messages until we get SIGQUIT or detect ungraceful
    4291             :      * death of our parent postmaster.
    4292             :      *
    4293             :      * For performance reasons, we don't want to do ResetLatch/WaitLatch after
    4294             :      * every message; instead, do that only after a recv() fails to obtain a
    4295             :      * message.  (This effectively means that if backends are sending us stuff
    4296             :      * like mad, we won't notice postmaster death until things slack off a
    4297             :      * bit; which seems fine.)  To do that, we have an inner loop that
    4298             :      * iterates as long as recv() succeeds.  We do recognize got_SIGHUP inside
    4299             :      * the inner loop, which means that such interrupts will get serviced but
    4300             :      * the latch won't get cleared until next time there is a break in the
    4301             :      * action.
    4302             :      */
    4303             :     for (;;)
    4304             :     {
    4305             :         /* Clear any already-pending wakeups */
    4306      171100 :         ResetLatch(MyLatch);
    4307             : 
    4308             :         /*
    4309             :          * Quit if we get SIGQUIT from the postmaster.
    4310             :          */
    4311       85816 :         if (need_exit)
    4312         532 :             break;
    4313             : 
    4314             :         /*
    4315             :          * Inner loop iterates as long as we keep getting messages, or until
    4316             :          * need_exit becomes set.
    4317             :          */
    4318      263150 :         while (!need_exit)
    4319             :         {
    4320             :             /*
    4321             :              * Reload configuration if we got SIGHUP from the postmaster.
    4322             :              */
    4323      177866 :             if (got_SIGHUP)
    4324             :             {
    4325          46 :                 got_SIGHUP = false;
    4326          46 :                 ProcessConfigFile(PGC_SIGHUP);
    4327             :             }
    4328             : 
    4329             :             /*
    4330             :              * Write the stats file(s) if a new request has arrived that is
    4331             :              * not satisfied by existing file(s).
    4332             :              */
    4333      177866 :             if (pgstat_write_statsfile_needed())
    4334         976 :                 pgstat_write_statsfiles(false, false);
    4335             : 
    4336             :             /*
    4337             :              * Try to receive and process a message.  This will not block,
    4338             :              * since the socket is set to non-blocking mode.
    4339             :              *
    4340             :              * XXX On Windows, we have to force pgwin32_recv to cooperate,
    4341             :              * despite the previous use of pg_set_noblock() on the socket.
    4342             :              * This is extremely broken and should be fixed someday.
    4343             :              */
    4344             : #ifdef WIN32
    4345             :             pgwin32_noblock = 1;
    4346             : #endif
    4347             : 
    4348      177866 :             len = recv(pgStatSock, (char *) &msg,
    4349             :                        sizeof(PgStat_Msg), 0);
    4350             : 
    4351             : #ifdef WIN32
    4352             :             pgwin32_noblock = 0;
    4353             : #endif
    4354             : 
    4355      177866 :             if (len < 0)
    4356             :             {
    4357       85284 :                 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
    4358             :                     break;      /* out of inner loop */
    4359           0 :                 ereport(ERROR,
    4360             :                         (errcode_for_socket_access(),
    4361             :                          errmsg("could not read statistics message: %m")));
    4362             :             }
    4363             : 
    4364             :             /*
    4365             :              * We ignore messages that are smaller than our common header
    4366             :              */
    4367       92582 :             if (len < sizeof(PgStat_MsgHdr))
    4368           0 :                 continue;
    4369             : 
    4370             :             /*
    4371             :              * The received length must match the length in the header
    4372             :              */
    4373       92582 :             if (msg.msg_hdr.m_size != len)
    4374           0 :                 continue;
    4375             : 
    4376             :             /*
    4377             :              * O.K. - we accept this message.  Process it.
    4378             :              */
    4379       92582 :             switch (msg.msg_hdr.m_type)
    4380             :             {
    4381             :                 case PGSTAT_MTYPE_DUMMY:
    4382           0 :                     break;
    4383             : 
    4384             :                 case PGSTAT_MTYPE_INQUIRY:
    4385         976 :                     pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
    4386         976 :                     break;
    4387             : 
    4388             :                 case PGSTAT_MTYPE_TABSTAT:
    4389       69494 :                     pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
    4390       69494 :                     break;
    4391             : 
    4392             :                 case PGSTAT_MTYPE_TABPURGE:
    4393         896 :                     pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
    4394         896 :                     break;
    4395             : 
    4396             :                 case PGSTAT_MTYPE_DROPDB:
    4397          16 :                     pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
    4398          16 :                     break;
    4399             : 
    4400             :                 case PGSTAT_MTYPE_RESETCOUNTER:
    4401           0 :                     pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
    4402             :                                              len);
    4403           0 :                     break;
    4404             : 
    4405             :                 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
    4406           0 :                     pgstat_recv_resetsharedcounter(
    4407             :                                                    (PgStat_MsgResetsharedcounter *) &msg,
    4408             :                                                    len);
    4409           0 :                     break;
    4410             : 
    4411             :                 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
    4412           0 :                     pgstat_recv_resetsinglecounter(
    4413             :                                                    (PgStat_MsgResetsinglecounter *) &msg,
    4414             :                                                    len);
    4415           0 :                     break;
    4416             : 
    4417             :                 case PGSTAT_MTYPE_AUTOVAC_START:
    4418          50 :                     pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
    4419          50 :                     break;
    4420             : 
    4421             :                 case PGSTAT_MTYPE_VACUUM:
    4422        3894 :                     pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
    4423        3894 :                     break;
    4424             : 
    4425             :                 case PGSTAT_MTYPE_ANALYZE:
    4426        8830 :                     pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
    4427        8830 :                     break;
    4428             : 
    4429             :                 case PGSTAT_MTYPE_ARCHIVER:
    4430          26 :                     pgstat_recv_archiver((PgStat_MsgArchiver *) &msg, len);
    4431          26 :                     break;
    4432             : 
    4433             :                 case PGSTAT_MTYPE_BGWRITER:
    4434        5522 :                     pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
    4435        5522 :                     break;
    4436             : 
    4437             :                 case PGSTAT_MTYPE_FUNCSTAT:
    4438           0 :                     pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
    4439           0 :                     break;
    4440             : 
    4441             :                 case PGSTAT_MTYPE_FUNCPURGE:
    4442           0 :                     pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
    4443           0 :                     break;
    4444             : 
    4445             :                 case PGSTAT_MTYPE_RECOVERYCONFLICT:
    4446           0 :                     pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
    4447           0 :                     break;
    4448             : 
    4449             :                 case PGSTAT_MTYPE_DEADLOCK:
    4450           4 :                     pgstat_recv_deadlock((PgStat_MsgDeadlock *) &msg, len);
    4451           4 :                     break;
    4452             : 
    4453             :                 case PGSTAT_MTYPE_TEMPFILE:
    4454        2874 :                     pgstat_recv_tempfile((PgStat_MsgTempFile *) &msg, len);
    4455        2874 :                     break;
    4456             : 
    4457             :                 default:
    4458           0 :                     break;
    4459             :             }
    4460             :         }                       /* end of inner message-processing loop */
    4461             : 
    4462             :         /* Sleep until there's something to do */
    4463             : #ifndef WIN32
    4464       85284 :         wr = WaitLatchOrSocket(MyLatch,
    4465             :                                WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
    4466             :                                pgStatSock, -1L,
    4467             :                                WAIT_EVENT_PGSTAT_MAIN);
    4468             : #else
    4469             : 
    4470             :         /*
    4471             :          * Windows, at least in its Windows Server 2003 R2 incarnation,
    4472             :          * sometimes loses FD_READ events.  Waking up and retrying the recv()
    4473             :          * fixes that, so don't sleep indefinitely.  This is a crock of the
    4474             :          * first water, but until somebody wants to debug exactly what's
    4475             :          * happening there, this is the best we can do.  The two-second
    4476             :          * timeout matches our pre-9.2 behavior, and needs to be short enough
    4477             :          * to not provoke "using stale statistics" complaints from
    4478             :          * backend_read_statsfile.
    4479             :          */
    4480             :         wr = WaitLatchOrSocket(MyLatch,
    4481             :                                WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE | WL_TIMEOUT,
    4482             :                                pgStatSock,
    4483             :                                2 * 1000L /* msec */ ,
    4484             :                                WAIT_EVENT_PGSTAT_MAIN);
    4485             : #endif
    4486             : 
    4487             :         /*
    4488             :          * Emergency bailout if postmaster has died.  This is to avoid the
    4489             :          * necessity for manual cleanup of all postmaster children.
    4490             :          */
    4491       85284 :         if (wr & WL_POSTMASTER_DEATH)
    4492           0 :             break;
    4493             :     }                           /* end of outer loop */
    4494             : 
    4495             :     /*
    4496             :      * Save the final stats to reuse at next startup.
    4497             :      */
    4498         532 :     pgstat_write_statsfiles(true, true);
    4499             : 
    4500         532 :     exit(0);
    4501             : }
    4502             : 
    4503             : 
    4504             : /* SIGQUIT signal handler for collector process */
    4505             : static void
    4506         532 : pgstat_exit(SIGNAL_ARGS)
    4507             : {
    4508         532 :     int         save_errno = errno;
    4509             : 
    4510         532 :     need_exit = true;
    4511         532 :     SetLatch(MyLatch);
    4512             : 
    4513         532 :     errno = save_errno;
    4514         532 : }
    4515             : 
    4516             : /* SIGHUP handler for collector process */
    4517             : static void
    4518          46 : pgstat_sighup_handler(SIGNAL_ARGS)
    4519             : {
    4520          46 :     int         save_errno = errno;
    4521             : 
    4522          46 :     got_SIGHUP = true;
    4523          46 :     SetLatch(MyLatch);
    4524             : 
    4525          46 :     errno = save_errno;
    4526          46 : }
    4527             : 
    4528             : /*
    4529             :  * Subroutine to clear stats in a database entry
    4530             :  *
    4531             :  * Tables and functions hashes are initialized to empty.
    4532             :  */
    4533             : static void
    4534         992 : reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
    4535             : {
    4536             :     HASHCTL     hash_ctl;
    4537             : 
    4538         992 :     dbentry->n_xact_commit = 0;
    4539         992 :     dbentry->n_xact_rollback = 0;
    4540         992 :     dbentry->n_blocks_fetched = 0;
    4541         992 :     dbentry->n_blocks_hit = 0;
    4542         992 :     dbentry->n_tuples_returned = 0;
    4543         992 :     dbentry->n_tuples_fetched = 0;
    4544         992 :     dbentry->n_tuples_inserted = 0;
    4545         992 :     dbentry->n_tuples_updated = 0;
    4546         992 :     dbentry->n_tuples_deleted = 0;
    4547         992 :     dbentry->last_autovac_time = 0;
    4548         992 :     dbentry->n_conflict_tablespace = 0;
    4549         992 :     dbentry->n_conflict_lock = 0;
    4550         992 :     dbentry->n_conflict_snapshot = 0;
    4551         992 :     dbentry->n_conflict_bufferpin = 0;
    4552         992 :     dbentry->n_conflict_startup_deadlock = 0;
    4553         992 :     dbentry->n_temp_files = 0;
    4554         992 :     dbentry->n_temp_bytes = 0;
    4555         992 :     dbentry->n_deadlocks = 0;
    4556         992 :     dbentry->n_block_read_time = 0;
    4557         992 :     dbentry->n_block_write_time = 0;
    4558             : 
    4559         992 :     dbentry->stat_reset_timestamp = GetCurrentTimestamp();
    4560         992 :     dbentry->stats_timestamp = 0;
    4561             : 
    4562         992 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
    4563         992 :     hash_ctl.keysize = sizeof(Oid);
    4564         992 :     hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
    4565         992 :     dbentry->tables = hash_create("Per-database table",
    4566             :                                   PGSTAT_TAB_HASH_SIZE,
    4567             :                                   &hash_ctl,
    4568             :                                   HASH_ELEM | HASH_BLOBS);
    4569             : 
    4570         992 :     hash_ctl.keysize = sizeof(Oid);
    4571         992 :     hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
    4572         992 :     dbentry->functions = hash_create("Per-database function",
    4573             :                                      PGSTAT_FUNCTION_HASH_SIZE,
    4574             :                                      &hash_ctl,
    4575             :                                      HASH_ELEM | HASH_BLOBS);
    4576         992 : }
    4577             : 
    4578             : /*
    4579             :  * Lookup the hash table entry for the specified database. If no hash
    4580             :  * table entry exists, initialize it, if the create parameter is true.
    4581             :  * Else, return NULL.
    4582             :  */
    4583             : static PgStat_StatDBEntry *
    4584       87034 : pgstat_get_db_entry(Oid databaseid, bool create)
    4585             : {
    4586             :     PgStat_StatDBEntry *result;
    4587             :     bool        found;
    4588       87034 :     HASHACTION  action = (create ? HASH_ENTER : HASH_FIND);
    4589             : 
    4590             :     /* Lookup or create the hash table entry for this database */
    4591       87034 :     result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    4592             :                                                 &databaseid,
    4593             :                                                 action, &found);
    4594             : 
    4595       87034 :     if (!create && !found)
    4596         334 :         return NULL;
    4597             : 
    4598             :     /*
    4599             :      * If not found, initialize the new one.  This creates empty hash tables
    4600             :      * for tables and functions, too.
    4601             :      */
    4602       86700 :     if (!found)
    4603         992 :         reset_dbentry_counters(result);
    4604             : 
    4605       86700 :     return result;
    4606             : }
    4607             : 
    4608             : 
    4609             : /*
    4610             :  * Lookup the hash table entry for the specified table. If no hash
    4611             :  * table entry exists, initialize it, if the create parameter is true.
    4612             :  * Else, return NULL.
    4613             :  */
    4614             : static PgStat_StatTabEntry *
    4615       12724 : pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
    4616             : {
    4617             :     PgStat_StatTabEntry *result;
    4618             :     bool        found;
    4619       12724 :     HASHACTION  action = (create ? HASH_ENTER : HASH_FIND);
    4620             : 
    4621             :     /* Lookup or create the hash table entry for this table */
    4622       12724 :     result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    4623             :                                                  &tableoid,
    4624             :                                                  action, &found);
    4625             : 
    4626       12724 :     if (!create && !found)
    4627           0 :         return NULL;
    4628             : 
    4629             :     /* If not found, initialize the new one. */
    4630       12724 :     if (!found)
    4631             :     {
    4632        3950 :         result->numscans = 0;
    4633        3950 :         result->tuples_returned = 0;
    4634        3950 :         result->tuples_fetched = 0;
    4635        3950 :         result->tuples_inserted = 0;
    4636        3950 :         result->tuples_updated = 0;
    4637        3950 :         result->tuples_deleted = 0;
    4638        3950 :         result->tuples_hot_updated = 0;
    4639        3950 :         result->n_live_tuples = 0;
    4640        3950 :         result->n_dead_tuples = 0;
    4641        3950 :         result->changes_since_analyze = 0;
    4642        3950 :         result->blocks_fetched = 0;
    4643        3950 :         result->blocks_hit = 0;
    4644        3950 :         result->vacuum_timestamp = 0;
    4645        3950 :         result->vacuum_count = 0;
    4646        3950 :         result->autovac_vacuum_timestamp = 0;
    4647        3950 :         result->autovac_vacuum_count = 0;
    4648        3950 :         result->analyze_timestamp = 0;
    4649        3950 :         result->analyze_count = 0;
    4650        3950 :         result->autovac_analyze_timestamp = 0;
    4651        3950 :         result->autovac_analyze_count = 0;
    4652             :     }
    4653             : 
    4654       12724 :     return result;
    4655             : }
    4656             : 
    4657             : 
    4658             : /* ----------
    4659             :  * pgstat_write_statsfiles() -
    4660             :  *      Write the global statistics file, as well as requested DB files.
    4661             :  *
    4662             :  *  'permanent' specifies writing to the permanent files not temporary ones.
    4663             :  *  When true (happens only when the collector is shutting down), also remove
    4664             :  *  the temporary files so that backends starting up under a new postmaster
    4665             :  *  can't read old data before the new collector is ready.
    4666             :  *
    4667             :  *  When 'allDbs' is false, only the requested databases (listed in
    4668             :  *  pending_write_requests) will be written; otherwise, all databases
    4669             :  *  will be written.
    4670             :  * ----------
    4671             :  */
    4672             : static void
    4673        1508 : pgstat_write_statsfiles(bool permanent, bool allDbs)
    4674             : {
    4675             :     HASH_SEQ_STATUS hstat;
    4676             :     PgStat_StatDBEntry *dbentry;
    4677             :     FILE       *fpout;
    4678             :     int32       format_id;
    4679        1508 :     const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
    4680        1508 :     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
    4681             :     int         rc;
    4682             : 
    4683        1508 :     elog(DEBUG2, "writing stats file \"%s\"", statfile);
    4684             : 
    4685             :     /*
    4686             :      * Open the statistics temp file to write out the current values.
    4687             :      */
    4688        1508 :     fpout = AllocateFile(tmpfile, PG_BINARY_W);
    4689        1508 :     if (fpout == NULL)
    4690             :     {
    4691           0 :         ereport(LOG,
    4692             :                 (errcode_for_file_access(),
    4693             :                  errmsg("could not open temporary statistics file \"%s\": %m",
    4694             :                         tmpfile)));
    4695           0 :         return;
    4696             :     }
    4697             : 
    4698             :     /*
    4699             :      * Set the timestamp of the stats file.
    4700             :      */
    4701        1508 :     globalStats.stats_timestamp = GetCurrentTimestamp();
    4702             : 
    4703             :     /*
    4704             :      * Write the file header --- currently just a format ID.
    4705             :      */
    4706        1508 :     format_id = PGSTAT_FILE_FORMAT_ID;
    4707        1508 :     rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
    4708             :     (void) rc;                  /* we'll check for error with ferror */
    4709             : 
    4710             :     /*
    4711             :      * Write global stats struct
    4712             :      */
    4713        1508 :     rc = fwrite(&globalStats, sizeof(globalStats), 1, fpout);
    4714             :     (void) rc;                  /* we'll check for error with ferror */
    4715             : 
    4716             :     /*
    4717             :      * Write archiver stats struct
    4718             :      */
    4719        1508 :     rc = fwrite(&archiverStats, sizeof(archiverStats), 1, fpout);
    4720             :     (void) rc;                  /* we'll check for error with ferror */
    4721             : 
    4722             :     /*
    4723             :      * Walk through the database table.
    4724             :      */
    4725        1508 :     hash_seq_init(&hstat, pgStatDBHash);
    4726        6108 :     while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
    4727             :     {
    4728             :         /*
    4729             :          * Write out the table and function stats for this DB into the
    4730             :          * appropriate per-DB stat file, if required.
    4731             :          */
    4732        3092 :         if (allDbs || pgstat_db_requested(dbentry->databaseid))
    4733             :         {
    4734             :             /* Make DB's timestamp consistent with the global stats */
    4735        2356 :             dbentry->stats_timestamp = globalStats.stats_timestamp;
    4736             : 
    4737        2356 :             pgstat_write_db_statsfile(dbentry, permanent);
    4738             :         }
    4739             : 
    4740             :         /*
    4741             :          * Write out the DB entry. We don't write the tables or functions
    4742             :          * pointers, since they're of no use to any other process.
    4743             :          */
    4744        3092 :         fputc('D', fpout);
    4745        3092 :         rc = fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
    4746             :         (void) rc;              /* we'll check for error with ferror */
    4747             :     }
    4748             : 
    4749             :     /*
    4750             :      * No more output to be done. Close the temp file and replace the old
    4751             :      * pgstat.stat with it.  The ferror() check replaces testing for error
    4752             :      * after each individual fputc or fwrite above.
    4753             :      */
    4754        1508 :     fputc('E', fpout);
    4755             : 
    4756        1508 :     if (ferror(fpout))
    4757             :     {
    4758           0 :         ereport(LOG,
    4759             :                 (errcode_for_file_access(),
    4760             :                  errmsg("could not write temporary statistics file \"%s\": %m",
    4761             :                         tmpfile)));
    4762           0 :         FreeFile(fpout);
    4763           0 :         unlink(tmpfile);
    4764             :     }
    4765        1508 :     else if (FreeFile(fpout) < 0)
    4766             :     {
    4767           0 :         ereport(LOG,
    4768             :                 (errcode_for_file_access(),
    4769             :                  errmsg("could not close temporary statistics file \"%s\": %m",
    4770             :                         tmpfile)));
    4771           0 :         unlink(tmpfile);
    4772             :     }
    4773        1508 :     else if (rename(tmpfile, statfile) < 0)
    4774             :     {
    4775           0 :         ereport(LOG,
    4776             :                 (errcode_for_file_access(),
    4777             :                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
    4778             :                         tmpfile, statfile)));
    4779           0 :         unlink(tmpfile);
    4780             :     }
    4781             : 
    4782        1508 :     if (permanent)
    4783         532 :         unlink(pgstat_stat_filename);
    4784             : 
    4785             :     /*
    4786             :      * Now throw away the list of requests.  Note that requests sent after we
    4787             :      * started the write are still waiting on the network socket.
    4788             :      */
    4789        1508 :     list_free(pending_write_requests);
    4790        1508 :     pending_write_requests = NIL;
    4791             : }
    4792             : 
    4793             : /*
    4794             :  * return the filename for a DB stat file; filename is the output buffer,
    4795             :  * of length len.
    4796             :  */
    4797             : static void
    4798        8396 : get_dbstat_filename(bool permanent, bool tempname, Oid databaseid,
    4799             :                     char *filename, int len)
    4800             : {
    4801             :     int         printed;
    4802             : 
    4803             :     /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
    4804        8396 :     printed = snprintf(filename, len, "%s/db_%u.%s",
    4805             :                        permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
    4806             :                        pgstat_stat_directory,
    4807             :                        databaseid,
    4808             :                        tempname ? "tmp" : "stat");
    4809        8396 :     if (printed >= len)
    4810           0 :         elog(ERROR, "overlength pgstat path");
    4811        8396 : }
    4812             : 
    4813             : /* ----------
    4814             :  * pgstat_write_db_statsfile() -
    4815             :  *      Write the stat file for a single database.
    4816             :  *
    4817             :  *  If writing to the permanent file (happens when the collector is
    4818             :  *  shutting down only), remove the temporary file so that backends
    4819             :  *  starting up under a new postmaster can't read the old data before
    4820             :  *  the new collector is ready.
    4821             :  * ----------
    4822             :  */
    4823             : static void
    4824        2356 : pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent)
    4825             : {
    4826             :     HASH_SEQ_STATUS tstat;
    4827             :     HASH_SEQ_STATUS fstat;
    4828             :     PgStat_StatTabEntry *tabentry;
    4829             :     PgStat_StatFuncEntry *funcentry;
    4830             :     FILE       *fpout;
    4831             :     int32       format_id;
    4832        2356 :     Oid         dbid = dbentry->databaseid;
    4833             :     int         rc;
    4834             :     char        tmpfile[MAXPGPATH];
    4835             :     char        statfile[MAXPGPATH];
    4836             : 
    4837        2356 :     get_dbstat_filename(permanent, true, dbid, tmpfile, MAXPGPATH);
    4838        2356 :     get_dbstat_filename(permanent, false, dbid, statfile, MAXPGPATH);
    4839             : 
    4840        2356 :     elog(DEBUG2, "writing stats file \"%s\"", statfile);
    4841             : 
    4842             :     /*
    4843             :      * Open the statistics temp file to write out the current values.
    4844             :      */
    4845        2356 :     fpout = AllocateFile(tmpfile, PG_BINARY_W);
    4846        2356 :     if (fpout == NULL)
    4847             :     {
    4848           0 :         ereport(LOG,
    4849             :                 (errcode_for_file_access(),
    4850             :                  errmsg("could not open temporary statistics file \"%s\": %m",
    4851             :                         tmpfile)));
    4852           0 :         return;
    4853             :     }
    4854             : 
    4855             :     /*
    4856             :      * Write the file header --- currently just a format ID.
    4857             :      */
    4858        2356 :     format_id = PGSTAT_FILE_FORMAT_ID;
    4859        2356 :     rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
    4860             :     (void) rc;                  /* we'll check for error with ferror */
    4861             : 
    4862             :     /*
    4863             :      * Walk through the database's access stats per table.
    4864             :      */
    4865        2356 :     hash_seq_init(&tstat, dbentry->tables);
    4866      277084 :     while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
    4867             :     {
    4868      272372 :         fputc('T', fpout);
    4869      272372 :         rc = fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
    4870             :         (void) rc;              /* we'll check for error with ferror */
    4871             :     }
    4872             : 
    4873             :     /*
    4874             :      * Walk through the database's function stats table.
    4875             :      */
    4876        2356 :     hash_seq_init(&fstat, dbentry->functions);
    4877        4712 :     while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
    4878             :     {
    4879           0 :         fputc('F', fpout);
    4880           0 :         rc = fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
    4881             :         (void) rc;              /* we'll check for error with ferror */
    4882             :     }
    4883             : 
    4884             :     /*
    4885             :      * No more output to be done. Close the temp file and replace the old
    4886             :      * pgstat.stat with it.  The ferror() check replaces testing for error
    4887             :      * after each individual fputc or fwrite above.
    4888             :      */
    4889        2356 :     fputc('E', fpout);
    4890             : 
    4891        2356 :     if (ferror(fpout))
    4892             :     {
    4893           0 :         ereport(LOG,
    4894             :                 (errcode_for_file_access(),
    4895             :                  errmsg("could not write temporary statistics file \"%s\": %m",
    4896             :                         tmpfile)));
    4897           0 :         FreeFile(fpout);
    4898           0 :         unlink(tmpfile);
    4899             :     }
    4900        2356 :     else if (FreeFile(fpout) < 0)
    4901             :     {
    4902           0 :         ereport(LOG,
    4903             :                 (errcode_for_file_access(),
    4904             :                  errmsg("could not close temporary statistics file \"%s\": %m",
    4905             :                         tmpfile)));
    4906           0 :         unlink(tmpfile);
    4907             :     }
    4908        2356 :     else if (rename(tmpfile, statfile) < 0)
    4909             :     {
    4910           0 :         ereport(LOG,
    4911             :                 (errcode_for_file_access(),
    4912             :                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
    4913             :                         tmpfile, statfile)));
    4914           0 :         unlink(tmpfile);
    4915             :     }
    4916             : 
    4917        2356 :     if (permanent)
    4918             :     {
    4919        1230 :         get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
    4920             : 
    4921        1230 :         elog(DEBUG2, "removing temporary stats file \"%s\"", statfile);
    4922        1230 :         unlink(statfile);
    4923             :     }
    4924             : }
    4925             : 
    4926             : /* ----------
    4927             :  * pgstat_read_statsfiles() -
    4928             :  *
    4929             :  *  Reads in some existing statistics collector files and returns the
    4930             :  *  databases hash table that is the top level of the data.
    4931             :  *
    4932             :  *  If 'onlydb' is not InvalidOid, it means we only want data for that DB
    4933             :  *  plus the shared catalogs ("DB 0").  We'll still populate the DB hash
    4934             :  *  table for all databases, but we don't bother even creating table/function
    4935             :  *  hash tables for other databases.
    4936             :  *
    4937             :  *  'permanent' specifies reading from the permanent files not temporary ones.
    4938             :  *  When true (happens only when the collector is starting up), remove the
    4939             :  *  files after reading; the in-memory status is now authoritative, and the
    4940             :  *  files would be out of date in case somebody else reads them.
    4941             :  *
    4942             :  *  If a 'deep' read is requested, table/function stats are read, otherwise
    4943             :  *  the table/function hash tables remain empty.
    4944             :  * ----------
    4945             :  */
    4946             : static HTAB *
    4947        2264 : pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
    4948             : {
    4949             :     PgStat_StatDBEntry *dbentry;
    4950             :     PgStat_StatDBEntry dbbuf;
    4951             :     HASHCTL     hash_ctl;
    4952             :     HTAB       *dbhash;
    4953             :     FILE       *fpin;
    4954             :     int32       format_id;
    4955             :     bool        found;
    4956        2264 :     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
    4957             : 
    4958             :     /*
    4959             :      * The tables will live in pgStatLocalContext.
    4960             :      */
    4961        2264 :     pgstat_setup_memcxt();
    4962             : 
    4963             :     /*
    4964             :      * Create the DB hashtable
    4965             :      */
    4966        2264 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
    4967        2264 :     hash_ctl.keysize = sizeof(Oid);
    4968        2264 :     hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
    4969        2264 :     hash_ctl.hcxt = pgStatLocalContext;
    4970        2264 :     dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
    4971             :                          HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    4972             : 
    4973             :     /*
    4974             :      * Clear out global and archiver statistics so they start from zero in
    4975             :      * case we can't load an existing statsfile.
    4976             :      */
    4977        2264 :     memset(&globalStats, 0, sizeof(globalStats));
    4978        2264 :     memset(&archiverStats, 0, sizeof(archiverStats));
    4979             : 
    4980             :     /*
    4981             :      * Set the current timestamp (will be kept only in case we can't load an
    4982             :      * existing statsfile).
    4983             :      */
    4984        2264 :     globalStats.stat_reset_timestamp = GetCurrentTimestamp();
    4985        2264 :     archiverStats.stat_reset_timestamp = globalStats.stat_reset_timestamp;
    4986             : 
    4987             :     /*
    4988             :      * Try to open the stats file. If it doesn't exist, the backends simply
    4989             :      * return zero for anything and the collector simply starts from scratch
    4990             :      * with empty counters.
    4991             :      *
    4992             :      * ENOENT is a possibility if the stats collector is not running or has
    4993             :      * not yet written the stats file the first time.  Any other failure
    4994             :      * condition is suspicious.
    4995             :      */
    4996        2264 :     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
    4997             :     {
    4998         424 :         if (errno != ENOENT)
    4999           0 :             ereport(pgStatRunningInCollector ? LOG : WARNING,
    5000             :                     (errcode_for_file_access(),
    5001             :                      errmsg("could not open statistics file \"%s\": %m",
    5002             :                             statfile)));
    5003         424 :         return dbhash;
    5004             :     }
    5005             : 
    5006             :     /*
    5007             :      * Verify it's of the expected format.
    5008             :      */
    5009        3680 :     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
    5010        1840 :         format_id != PGSTAT_FILE_FORMAT_ID)
    5011             :     {
    5012           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5013             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5014           0 :         goto done;
    5015             :     }
    5016             : 
    5017             :     /*
    5018             :      * Read global stats struct
    5019             :      */
    5020        1840 :     if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
    5021             :     {
    5022           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5023             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5024           0 :         memset(&globalStats, 0, sizeof(globalStats));
    5025           0 :         goto done;
    5026             :     }
    5027             : 
    5028             :     /*
    5029             :      * In the collector, disregard the timestamp we read from the permanent
    5030             :      * stats file; we should be willing to write a temp stats file immediately
    5031             :      * upon the first request from any backend.  This only matters if the old
    5032             :      * file's timestamp is less than PGSTAT_STAT_INTERVAL ago, but that's not
    5033             :      * an unusual scenario.
    5034             :      */
    5035        1840 :     if (pgStatRunningInCollector)
    5036         108 :         globalStats.stats_timestamp = 0;
    5037             : 
    5038             :     /*
    5039             :      * Read archiver stats struct
    5040             :      */
    5041        1840 :     if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
    5042             :     {
    5043           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5044             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5045           0 :         memset(&archiverStats, 0, sizeof(archiverStats));
    5046           0 :         goto done;
    5047             :     }
    5048             : 
    5049             :     /*
    5050             :      * We found an existing collector stats file. Read it and put all the
    5051             :      * hashtable entries into place.
    5052             :      */
    5053             :     for (;;)
    5054             :     {
    5055        9436 :         switch (fgetc(fpin))
    5056             :         {
    5057             :                 /*
    5058             :                  * 'D'  A PgStat_StatDBEntry struct describing a database
    5059             :                  * follows.
    5060             :                  */
    5061             :             case 'D':
    5062        3798 :                 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
    5063             :                           fpin) != offsetof(PgStat_StatDBEntry, tables))
    5064             :                 {
    5065           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5066             :                             (errmsg("corrupted statistics file \"%s\"",
    5067             :                                     statfile)));
    5068           0 :                     goto done;
    5069             :                 }
    5070             : 
    5071             :                 /*
    5072             :                  * Add to the DB hash
    5073             :                  */
    5074        3798 :                 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
    5075             :                                                              (void *) &dbbuf.databaseid,
    5076             :                                                              HASH_ENTER,
    5077             :                                                              &found);
    5078        3798 :                 if (found)
    5079             :                 {
    5080           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5081             :                             (errmsg("corrupted statistics file \"%s\"",
    5082             :                                     statfile)));
    5083           0 :                     goto done;
    5084             :                 }
    5085             : 
    5086        3798 :                 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
    5087        3798 :                 dbentry->tables = NULL;
    5088        3798 :                 dbentry->functions = NULL;
    5089             : 
    5090             :                 /*
    5091             :                  * In the collector, disregard the timestamp we read from the
    5092             :                  * permanent stats file; we should be willing to write a temp
    5093             :                  * stats file immediately upon the first request from any
    5094             :                  * backend.
    5095             :                  */
    5096        3798 :                 if (pgStatRunningInCollector)
    5097         248 :                     dbentry->stats_timestamp = 0;
    5098             : 
    5099             :                 /*
    5100             :                  * Don't create tables/functions hashtables for uninteresting
    5101             :                  * databases.
    5102             :                  */
    5103        3798 :                 if (onlydb != InvalidOid)
    5104             :                 {
    5105        5170 :                     if (dbbuf.databaseid != onlydb &&
    5106        2036 :                         dbbuf.databaseid != InvalidOid)
    5107         938 :                         break;
    5108             :                 }
    5109             : 
    5110        2860 :                 memset(&hash_ctl, 0, sizeof(hash_ctl));
    5111        2860 :                 hash_ctl.keysize = sizeof(Oid);
    5112        2860 :                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
    5113        2860 :                 hash_ctl.hcxt = pgStatLocalContext;
    5114        2860 :                 dbentry->tables = hash_create("Per-database table",
    5115             :                                               PGSTAT_TAB_HASH_SIZE,
    5116             :                                               &hash_ctl,
    5117             :                                               HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    5118             : 
    5119        2860 :                 hash_ctl.keysize = sizeof(Oid);
    5120        2860 :                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
    5121        2860 :                 hash_ctl.hcxt = pgStatLocalContext;
    5122        2860 :                 dbentry->functions = hash_create("Per-database function",
    5123             :                                                  PGSTAT_FUNCTION_HASH_SIZE,
    5124             :                                                  &hash_ctl,
    5125             :                                                  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    5126             : 
    5127             :                 /*
    5128             :                  * If requested, read the data from the database-specific
    5129             :                  * file.  Otherwise we just leave the hashtables empty.
    5130             :                  */
    5131        2860 :                 if (deep)
    5132        2444 :                     pgstat_read_db_statsfile(dbentry->databaseid,
    5133             :                                              dbentry->tables,
    5134             :                                              dbentry->functions,
    5135             :                                              permanent);
    5136             : 
    5137        2860 :                 break;
    5138             : 
    5139             :             case 'E':
    5140        1840 :                 goto done;
    5141             : 
    5142             :             default:
    5143           0 :                 ereport(pgStatRunningInCollector ? LOG : WARNING,
    5144             :                         (errmsg("corrupted statistics file \"%s\"",
    5145             :                                 statfile)));
    5146           0 :                 goto done;
    5147             :         }
    5148             :     }
    5149             : 
    5150             : done:
    5151        1840 :     FreeFile(fpin);
    5152             : 
    5153             :     /* If requested to read the permanent file, also get rid of it. */
    5154        1840 :     if (permanent)
    5155             :     {
    5156         108 :         elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
    5157         108 :         unlink(statfile);
    5158             :     }
    5159             : 
    5160        1840 :     return dbhash;
    5161             : }
    5162             : 
    5163             : 
    5164             : /* ----------
    5165             :  * pgstat_read_db_statsfile() -
    5166             :  *
    5167             :  *  Reads in the existing statistics collector file for the given database,
    5168             :  *  filling the passed-in tables and functions hash tables.
    5169             :  *
    5170             :  *  As in pgstat_read_statsfiles, if the permanent file is requested, it is
    5171             :  *  removed after reading.
    5172             :  *
    5173             :  *  Note: this code has the ability to skip storing per-table or per-function
    5174             :  *  data, if NULL is passed for the corresponding hashtable.  That's not used
    5175             :  *  at the moment though.
    5176             :  * ----------
    5177             :  */
    5178             : static void
    5179        2444 : pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash,
    5180             :                          bool permanent)
    5181             : {
    5182             :     PgStat_StatTabEntry *tabentry;
    5183             :     PgStat_StatTabEntry tabbuf;
    5184             :     PgStat_StatFuncEntry funcbuf;
    5185             :     PgStat_StatFuncEntry *funcentry;
    5186             :     FILE       *fpin;
    5187             :     int32       format_id;
    5188             :     bool        found;
    5189             :     char        statfile[MAXPGPATH];
    5190             : 
    5191        2444 :     get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
    5192             : 
    5193             :     /*
    5194             :      * Try to open the stats file. If it doesn't exist, the backends simply
    5195             :      * return zero for anything and the collector simply starts from scratch
    5196             :      * with empty counters.
    5197             :      *
    5198             :      * ENOENT is a possibility if the stats collector is not running or has
    5199             :      * not yet written the stats file the first time.  Any other failure
    5200             :      * condition is suspicious.
    5201             :      */
    5202        2444 :     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
    5203             :     {
    5204           0 :         if (errno != ENOENT)
    5205           0 :             ereport(pgStatRunningInCollector ? LOG : WARNING,
    5206             :                     (errcode_for_file_access(),
    5207             :                      errmsg("could not open statistics file \"%s\": %m",
    5208             :                             statfile)));
    5209           0 :         return;
    5210             :     }
    5211             : 
    5212             :     /*
    5213             :      * Verify it's of the expected format.
    5214             :      */
    5215        4888 :     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
    5216        2444 :         format_id != PGSTAT_FILE_FORMAT_ID)
    5217             :     {
    5218           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5219             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5220           0 :         goto done;
    5221             :     }
    5222             : 
    5223             :     /*
    5224             :      * We found an existing collector stats file. Read it and put all the
    5225             :      * hashtable entries into place.
    5226             :      */
    5227             :     for (;;)
    5228             :     {
    5229     1017612 :         switch (fgetc(fpin))
    5230             :         {
    5231             :                 /*
    5232             :                  * 'T'  A PgStat_StatTabEntry follows.
    5233             :                  */
    5234             :             case 'T':
    5235      507584 :                 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
    5236             :                           fpin) != sizeof(PgStat_StatTabEntry))
    5237             :                 {
    5238           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5239             :                             (errmsg("corrupted statistics file \"%s\"",
    5240             :                                     statfile)));
    5241           0 :                     goto done;
    5242             :                 }
    5243             : 
    5244             :                 /*
    5245             :                  * Skip if table data not wanted.
    5246             :                  */
    5247      507584 :                 if (tabhash == NULL)
    5248           0 :                     break;
    5249             : 
    5250      507584 :                 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
    5251             :                                                                (void *) &tabbuf.tableid,
    5252             :                                                                HASH_ENTER, &found);
    5253             : 
    5254      507584 :                 if (found)
    5255             :                 {
    5256           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5257             :                             (errmsg("corrupted statistics file \"%s\"",
    5258             :                                     statfile)));
    5259           0 :                     goto done;
    5260             :                 }
    5261             : 
    5262      507584 :                 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
    5263      507584 :                 break;
    5264             : 
    5265             :                 /*
    5266             :                  * 'F'  A PgStat_StatFuncEntry follows.
    5267             :                  */
    5268             :             case 'F':
    5269           0 :                 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
    5270             :                           fpin) != sizeof(PgStat_StatFuncEntry))
    5271             :                 {
    5272           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5273             :                             (errmsg("corrupted statistics file \"%s\"",
    5274             :                                     statfile)));
    5275           0 :                     goto done;
    5276             :                 }
    5277             : 
    5278             :                 /*
    5279             :                  * Skip if function data not wanted.
    5280             :                  */
    5281           0 :                 if (funchash == NULL)
    5282           0 :                     break;
    5283             : 
    5284           0 :                 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
    5285             :                                                                  (void *) &funcbuf.functionid,
    5286             :                                                                  HASH_ENTER, &found);
    5287             : 
    5288           0 :                 if (found)
    5289             :                 {
    5290           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5291             :                             (errmsg("corrupted statistics file \"%s\"",
    5292             :                                     statfile)));
    5293           0 :                     goto done;
    5294             :                 }
    5295             : 
    5296           0 :                 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
    5297           0 :                 break;
    5298             : 
    5299             :                 /*
    5300             :                  * 'E'  The EOF marker of a complete stats file.
    5301             :                  */
    5302             :             case 'E':
    5303        2444 :                 goto done;
    5304             : 
    5305             :             default:
    5306           0 :                 ereport(pgStatRunningInCollector ? LOG : WARNING,
    5307             :                         (errmsg("corrupted statistics file \"%s\"",
    5308             :                                 statfile)));
    5309           0 :                 goto done;
    5310             :         }
    5311             :     }
    5312             : 
    5313             : done:
    5314        2444 :     FreeFile(fpin);
    5315             : 
    5316        2444 :     if (permanent)
    5317             :     {
    5318         248 :         elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
    5319         248 :         unlink(statfile);
    5320             :     }
    5321             : }
    5322             : 
    5323             : /* ----------
    5324             :  * pgstat_read_db_statsfile_timestamp() -
    5325             :  *
    5326             :  *  Attempt to determine the timestamp of the last db statfile write.
    5327             :  *  Returns true if successful; the timestamp is stored in *ts.
    5328             :  *
    5329             :  *  This needs to be careful about handling databases for which no stats file
    5330             :  *  exists, such as databases without a stat entry or those not yet written:
    5331             :  *
    5332             :  *  - if there's a database entry in the global file, return the corresponding
    5333             :  *  stats_timestamp value.
    5334             :  *
    5335             :  *  - if there's no db stat entry (e.g. for a new or inactive database),
    5336             :  *  there's no stats_timestamp value, but also nothing to write so we return
    5337             :  *  the timestamp of the global statfile.
    5338             :  * ----------
    5339             :  */
    5340             : static bool
    5341        3164 : pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent,
    5342             :                                    TimestampTz *ts)
    5343             : {
    5344             :     PgStat_StatDBEntry dbentry;
    5345             :     PgStat_GlobalStats myGlobalStats;
    5346             :     PgStat_ArchiverStats myArchiverStats;
    5347             :     FILE       *fpin;
    5348             :     int32       format_id;
    5349        3164 :     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
    5350             : 
    5351             :     /*
    5352             :      * Try to open the stats file.  As above, anything but ENOENT is worthy of
    5353             :      * complaining about.
    5354             :      */
    5355        3164 :     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
    5356             :     {
    5357         918 :         if (errno != ENOENT)
    5358           0 :             ereport(pgStatRunningInCollector ? LOG : WARNING,
    5359             :                     (errcode_for_file_access(),
    5360             :                      errmsg("could not open statistics file \"%s\": %m",
    5361             :                             statfile)));
    5362         918 :         return false;
    5363             :     }
    5364             : 
    5365             :     /*
    5366             :      * Verify it's of the expected format.
    5367             :      */
    5368        4492 :     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
    5369        2246 :         format_id != PGSTAT_FILE_FORMAT_ID)
    5370             :     {
    5371           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5372             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5373           0 :         FreeFile(fpin);
    5374           0 :         return false;
    5375             :     }
    5376             : 
    5377             :     /*
    5378             :      * Read global stats struct
    5379             :      */
    5380        2246 :     if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
    5381             :               fpin) != sizeof(myGlobalStats))
    5382             :     {
    5383           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5384             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5385           0 :         FreeFile(fpin);
    5386           0 :         return false;
    5387             :     }
    5388             : 
    5389             :     /*
    5390             :      * Read archiver stats struct
    5391             :      */
    5392        2246 :     if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
    5393             :               fpin) != sizeof(myArchiverStats))
    5394             :     {
    5395           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5396             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5397           0 :         FreeFile(fpin);
    5398           0 :         return false;
    5399             :     }
    5400             : 
    5401             :     /* By default, we're going to return the timestamp of the global file. */
    5402        2246 :     *ts = myGlobalStats.stats_timestamp;
    5403             : 
    5404             :     /*
    5405             :      * We found an existing collector stats file.  Read it and look for a
    5406             :      * record for the requested database.  If found, use its timestamp.
    5407             :      */
    5408             :     for (;;)
    5409             :     {
    5410        3146 :         switch (fgetc(fpin))
    5411             :         {
    5412             :                 /*
    5413             :                  * 'D'  A PgStat_StatDBEntry struct describing a database
    5414             :                  * follows.
    5415             :                  */
    5416             :             case 'D':
    5417        2168 :                 if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
    5418             :                           fpin) != offsetof(PgStat_StatDBEntry, tables))
    5419             :                 {
    5420           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5421             :                             (errmsg("corrupted statistics file \"%s\"",
    5422             :                                     statfile)));
    5423           0 :                     goto done;
    5424             :                 }
    5425             : 
    5426             :                 /*
    5427             :                  * If this is the DB we're looking for, save its timestamp and
    5428             :                  * we're done.
    5429             :                  */
    5430        2168 :                 if (dbentry.databaseid == databaseid)
    5431             :                 {
    5432        1718 :                     *ts = dbentry.stats_timestamp;
    5433        1718 :                     goto done;
    5434             :                 }
    5435             : 
    5436         450 :                 break;
    5437             : 
    5438             :             case 'E':
    5439         528 :                 goto done;
    5440             : 
    5441             :             default:
    5442           0 :                 ereport(pgStatRunningInCollector ? LOG : WARNING,
    5443             :                         (errmsg("corrupted statistics file \"%s\"",
    5444             :                                 statfile)));
    5445           0 :                 goto done;
    5446             :         }
    5447             :     }
    5448             : 
    5449             : done:
    5450        2246 :     FreeFile(fpin);
    5451        2246 :     return true;
    5452             : }
    5453             : 
    5454             : /*
    5455             :  * If not already done, read the statistics collector stats file into
    5456             :  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
    5457             :  * is called (typically, at end of transaction).
    5458             :  */
    5459             : static void
    5460        3894 : backend_read_statsfile(void)
    5461             : {
    5462        3894 :     TimestampTz min_ts = 0;
    5463        3894 :     TimestampTz ref_ts = 0;
    5464             :     Oid         inquiry_db;
    5465             :     int         count;
    5466             : 
    5467             :     /* already read it? */
    5468        3894 :     if (pgStatDBHash)
    5469        2162 :         return;
    5470             :     Assert(!pgStatRunningInCollector);
    5471             : 
    5472             :     /*
    5473             :      * In a normal backend, we check staleness of the data for our own DB, and
    5474             :      * so we send MyDatabaseId in inquiry messages.  In the autovac launcher,
    5475             :      * check staleness of the shared-catalog data, and send InvalidOid in
    5476             :      * inquiry messages so as not to force writing unnecessary data.
    5477             :      */
    5478        1732 :     if (IsAutoVacuumLauncherProcess())
    5479         626 :         inquiry_db = InvalidOid;
    5480             :     else
    5481        1106 :         inquiry_db = MyDatabaseId;
    5482             : 
    5483             :     /*
    5484             :      * Loop until fresh enough stats file is available or we ran out of time.
    5485             :      * The stats inquiry message is sent repeatedly in case collector drops
    5486             :      * it; but not every single time, as that just swamps the collector.
    5487             :      */
    5488        6328 :     for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
    5489             :     {
    5490             :         bool        ok;
    5491        3164 :         TimestampTz file_ts = 0;
    5492             :         TimestampTz cur_ts;
    5493             : 
    5494        3164 :         CHECK_FOR_INTERRUPTS();
    5495             : 
    5496        3164 :         ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
    5497             : 
    5498        3164 :         cur_ts = GetCurrentTimestamp();
    5499             :         /* Calculate min acceptable timestamp, if we didn't already */
    5500        3164 :         if (count == 0 || cur_ts < ref_ts)
    5501             :         {
    5502             :             /*
    5503             :              * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
    5504             :              * msec before now.  This indirectly ensures that the collector
    5505             :              * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
    5506             :              * an autovacuum worker, however, we want a lower delay to avoid
    5507             :              * using stale data, so we use PGSTAT_RETRY_DELAY (since the
    5508             :              * number of workers is low, this shouldn't be a problem).
    5509             :              *
    5510             :              * We don't recompute min_ts after sleeping, except in the
    5511             :              * unlikely case that cur_ts went backwards.  So we might end up
    5512             :              * accepting a file a bit older than PGSTAT_STAT_INTERVAL.  In
    5513             :              * practice that shouldn't happen, though, as long as the sleep
    5514             :              * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
    5515             :              * tell the collector that our cutoff time is less than what we'd
    5516             :              * actually accept.
    5517             :              */
    5518        1732 :             ref_ts = cur_ts;
    5519        1732 :             if (IsAutoVacuumWorkerProcess())
    5520         314 :                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
    5521             :                                                      -PGSTAT_RETRY_DELAY);
    5522             :             else
    5523        1418 :                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
    5524             :                                                      -PGSTAT_STAT_INTERVAL);
    5525             :         }
    5526             : 
    5527             :         /*
    5528             :          * If the file timestamp is actually newer than cur_ts, we must have
    5529             :          * had a clock glitch (system time went backwards) or there is clock
    5530             :          * skew between our processor and the stats collector's processor.
    5531             :          * Accept the file, but send an inquiry message anyway to make
    5532             :          * pgstat_recv_inquiry do a sanity check on the collector's time.
    5533             :          */
    5534        3164 :         if (ok && file_ts > cur_ts)
    5535             :         {
    5536             :             /*
    5537             :              * A small amount of clock skew between processors isn't terribly
    5538             :              * surprising, but a large difference is worth logging.  We
    5539             :              * arbitrarily define "large" as 1000 msec.
    5540             :              */
    5541           0 :             if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
    5542             :             {
    5543             :                 char       *filetime;
    5544             :                 char       *mytime;
    5545             : 
    5546             :                 /* Copy because timestamptz_to_str returns a static buffer */
    5547           0 :                 filetime = pstrdup(timestamptz_to_str(file_ts));
    5548           0 :                 mytime = pstrdup(timestamptz_to_str(cur_ts));
    5549           0 :                 elog(LOG, "stats collector's time %s is later than backend local time %s",
    5550             :                      filetime, mytime);
    5551           0 :                 pfree(filetime);
    5552           0 :                 pfree(mytime);
    5553             :             }
    5554             : 
    5555           0 :             pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
    5556           0 :             break;
    5557             :         }
    5558             : 
    5559             :         /* Normal acceptance case: file is not older than cutoff time */
    5560        3164 :         if (ok && file_ts >= min_ts)
    5561        1732 :             break;
    5562             : 
    5563             :         /* Not there or too old, so kick the collector and wait a bit */
    5564        1432 :         if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
    5565         830 :             pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
    5566             : 
    5567        1432 :         pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
    5568             :     }
    5569             : 
    5570        1732 :     if (count >= PGSTAT_POLL_LOOP_COUNT)
    5571           0 :         ereport(LOG,
    5572             :                 (errmsg("using stale statistics instead of current ones "
    5573             :                         "because stats collector is not responding")));
    5574             : 
    5575             :     /*
    5576             :      * Autovacuum launcher wants stats about all databases, but a shallow read
    5577             :      * is sufficient.  Regular backends want a deep read for just the tables
    5578             :      * they can see (MyDatabaseId + shared catalogs).
    5579             :      */
    5580        1732 :     if (IsAutoVacuumLauncherProcess())
    5581         626 :         pgStatDBHash = pgstat_read_statsfiles(InvalidOid, false, false);
    5582             :     else
    5583        1106 :         pgStatDBHash = pgstat_read_statsfiles(MyDatabaseId, false, true);
    5584             : }
    5585             : 
    5586             : 
    5587             : /* ----------
    5588             :  * pgstat_setup_memcxt() -
    5589             :  *
    5590             :  *  Create pgStatLocalContext, if not already done.
    5591             :  * ----------
    5592             :  */
    5593             : static void
    5594        2620 : pgstat_setup_memcxt(void)
    5595             : {
    5596        2620 :     if (!pgStatLocalContext)
    5597        2620 :         pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
    5598             :                                                    "Statistics snapshot",
    5599             :                                                    ALLOCSET_SMALL_SIZES);
    5600        2620 : }
    5601             : 
    5602             : 
    5603             : /* ----------
    5604             :  * pgstat_clear_snapshot() -
    5605             :  *
    5606             :  *  Discard any data collected in the current transaction.  Any subsequent
    5607             :  *  request will cause new snapshots to be read.
    5608             :  *
    5609             :  *  This is also invoked during transaction commit or abort to discard
    5610             :  *  the no-longer-wanted snapshot.
    5611             :  * ----------
    5612             :  */
    5613             : void
    5614      447864 : pgstat_clear_snapshot(void)
    5615             : {
    5616             :     /* Release memory, if any was allocated */
    5617      447864 :     if (pgStatLocalContext)
    5618        1790 :         MemoryContextDelete(pgStatLocalContext);
    5619             : 
    5620             :     /* Reset variables */
    5621      447864 :     pgStatLocalContext = NULL;
    5622      447864 :     pgStatDBHash = NULL;
    5623      447864 :     localBackendStatusTable = NULL;
    5624      447864 :     localNumBackends = 0;
    5625      447864 : }
    5626             : 
    5627             : 
    5628             : /* ----------
    5629             :  * pgstat_recv_inquiry() -
    5630             :  *
    5631             :  *  Process stat inquiry requests.
    5632             :  * ----------
    5633             :  */
    5634             : static void
    5635         976 : pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
    5636             : {
    5637             :     PgStat_StatDBEntry *dbentry;
    5638             : 
    5639         976 :     elog(DEBUG2, "received inquiry for database %u", msg->databaseid);
    5640             : 
    5641             :     /*
    5642             :      * If there's already a write request for this DB, there's nothing to do.
    5643             :      *
    5644             :      * Note that if a request is found, we return early and skip the below
    5645             :      * check for clock skew.  This is okay, since the only way for a DB
    5646             :      * request to be present in the list is that we have been here since the
    5647             :      * last write round.  It seems sufficient to check for clock skew once per
    5648             :      * write round.
    5649             :      */
    5650         976 :     if (list_member_oid(pending_write_requests, msg->databaseid))
    5651           0 :         return;
    5652             : 
    5653             :     /*
    5654             :      * Check to see if we last wrote this database at a time >= the requested
    5655             :      * cutoff time.  If so, this is a stale request that was generated before
    5656             :      * we updated the DB file, and we don't need to do so again.
    5657             :      *
    5658             :      * If the requestor's local clock time is older than stats_timestamp, we
    5659             :      * should suspect a clock glitch, ie system time going backwards; though
    5660             :      * the more likely explanation is just delayed message receipt.  It is
    5661             :      * worth expending a GetCurrentTimestamp call to be sure, since a large
    5662             :      * retreat in the system clock reading could otherwise cause us to neglect
    5663             :      * to update the stats file for a long time.
    5664             :      */
    5665         976 :     dbentry = pgstat_get_db_entry(msg->databaseid, false);
    5666         976 :     if (dbentry == NULL)
    5667             :     {
    5668             :         /*
    5669             :          * We have no data for this DB.  Enter a write request anyway so that
    5670             :          * the global stats will get updated.  This is needed to prevent
    5671             :          * backend_read_statsfile from waiting for data that we cannot supply,
    5672             :          * in the case of a new DB that nobody has yet reported any stats for.
    5673             :          * See the behavior of pgstat_read_db_statsfile_timestamp.
    5674             :          */
    5675             :     }
    5676         648 :     else if (msg->clock_time < dbentry->stats_timestamp)
    5677             :     {
    5678           0 :         TimestampTz cur_ts = GetCurrentTimestamp();
    5679             : 
    5680           0 :         if (cur_ts < dbentry->stats_timestamp)
    5681             :         {
    5682             :             /*
    5683             :              * Sure enough, time went backwards.  Force a new stats file write
    5684             :              * to get back in sync; but first, log a complaint.
    5685             :              */
    5686             :             char       *writetime;
    5687             :             char       *mytime;
    5688             : 
    5689             :             /* Copy because timestamptz_to_str returns a static buffer */
    5690           0 :             writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
    5691           0 :             mytime = pstrdup(timestamptz_to_str(cur_ts));
    5692           0 :             elog(LOG,
    5693             :                  "stats_timestamp %s is later than collector's time %s for database %u",
    5694             :                  writetime, mytime, dbentry->databaseid);
    5695           0 :             pfree(writetime);
    5696           0 :             pfree(mytime);
    5697             :         }
    5698             :         else
    5699             :         {
    5700             :             /*
    5701             :              * Nope, it's just an old request.  Assuming msg's clock_time is
    5702             :              * >= its cutoff_time, it must be stale, so we can ignore it.
    5703             :              */
    5704           0 :             return;
    5705             :         }
    5706             :     }
    5707         648 :     else if (msg->cutoff_time <= dbentry->stats_timestamp)
    5708             :     {
    5709             :         /* Stale request, ignore it */
    5710           0 :         return;
    5711             :     }
    5712             : 
    5713             :     /*
    5714             :      * We need to write this DB, so create a request.
    5715             :      */
    5716         976 :     pending_write_requests = lappend_oid(pending_write_requests,
    5717             :                                          msg->databaseid);
    5718             : }
    5719             : 
    5720             : 
    5721             : /* ----------
    5722             :  * pgstat_recv_tabstat() -
    5723             :  *
    5724             :  *  Count what the backend has done.
    5725             :  * ----------
    5726             :  */
    5727             : static void
    5728       69494 : pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
    5729             : {
    5730             :     PgStat_StatDBEntry *dbentry;
    5731             :     PgStat_StatTabEntry *tabentry;
    5732             :     int         i;
    5733             :     bool        found;
    5734             : 
    5735       69494 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    5736             : 
    5737             :     /*
    5738             :      * Update database-wide stats.
    5739             :      */
    5740       69494 :     dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
    5741       69494 :     dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
    5742       69494 :     dbentry->n_block_read_time += msg->m_block_read_time;
    5743       69494 :     dbentry->n_block_write_time += msg->m_block_write_time;
    5744             : 
    5745             :     /*
    5746             :      * Process all table entries in the message.
    5747             :      */
    5748      529468 :     for (i = 0; i < msg->m_nentries; i++)
    5749             :     {
    5750      459974 :         PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
    5751             : 
    5752      459974 :         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    5753      459974 :                                                        (void *) &(tabmsg->t_id),
    5754             :                                                        HASH_ENTER, &found);
    5755             : 
    5756      459974 :         if (!found)
    5757             :         {
    5758             :             /*
    5759             :              * If it's a new table entry, initialize counters to the values we
    5760             :              * just got.
    5761             :              */
    5762       55614 :             tabentry->numscans = tabmsg->t_counts.t_numscans;
    5763       55614 :             tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
    5764       55614 :             tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
    5765       55614 :             tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
    5766       55614 :             tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
    5767       55614 :             tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
    5768       55614 :             tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
    5769       55614 :             tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
    5770       55614 :             tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
    5771       55614 :             tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
    5772       55614 :             tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
    5773       55614 :             tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
    5774             : 
    5775       55614 :             tabentry->vacuum_timestamp = 0;
    5776       55614 :             tabentry->vacuum_count = 0;
    5777       55614 :             tabentry->autovac_vacuum_timestamp = 0;
    5778       55614 :             tabentry->autovac_vacuum_count = 0;
    5779       55614 :             tabentry->analyze_timestamp = 0;
    5780       55614 :             tabentry->analyze_count = 0;
    5781       55614 :             tabentry->autovac_analyze_timestamp = 0;
    5782       55614 :             tabentry->autovac_analyze_count = 0;
    5783             :         }
    5784             :         else
    5785             :         {
    5786             :             /*
    5787             :              * Otherwise add the values to the existing entry.
    5788             :              */
    5789      404360 :             tabentry->numscans += tabmsg->t_counts.t_numscans;
    5790      404360 :             tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
    5791      404360 :             tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
    5792      404360 :             tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
    5793      404360 :             tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
    5794      404360 :             tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
    5795      404360 :             tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
    5796             :             /* If table was truncated, first reset the live/dead counters */
    5797      404360 :             if (tabmsg->t_counts.t_truncated)
    5798             :             {
    5799         132 :                 tabentry->n_live_tuples = 0;
    5800         132 :                 tabentry->n_dead_tuples = 0;
    5801             :             }
    5802      404360 :             tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
    5803      404360 :             tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
    5804      404360 :             tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
    5805      404360 :             tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
    5806      404360 :             tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
    5807             :         }
    5808             : 
    5809             :         /* Clamp n_live_tuples in case of negative delta_live_tuples */
    5810      459974 :         tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
    5811             :         /* Likewise for n_dead_tuples */
    5812      459974 :         tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
    5813             : 
    5814             :         /*
    5815             :          * Add per-table stats to the per-database entry, too.
    5816             :          */
    5817      459974 :         dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
    5818      459974 :         dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
    5819      459974 :         dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
    5820      459974 :         dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
    5821      459974 :         dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
    5822      459974 :         dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
    5823      459974 :         dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
    5824             :     }
    5825       69494 : }
    5826             : 
    5827             : 
    5828             : /* ----------
    5829             :  * pgstat_recv_tabpurge() -
    5830             :  *
    5831             :  *  Arrange for dead table removal.
    5832             :  * ----------
    5833             :  */
    5834             : static void
    5835         896 : pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
    5836             : {
    5837             :     PgStat_StatDBEntry *dbentry;
    5838             :     int         i;
    5839             : 
    5840         896 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    5841             : 
    5842             :     /*
    5843             :      * No need to purge if we don't even know the database.
    5844             :      */
    5845         896 :     if (!dbentry || !dbentry->tables)
    5846           0 :         return;
    5847             : 
    5848             :     /*
    5849             :      * Process all table entries in the message.
    5850             :      */
    5851       86114 :     for (i = 0; i < msg->m_nentries; i++)
    5852             :     {
    5853             :         /* Remove from hashtable if present; we don't care if it's not. */
    5854       85218 :         (void) hash_search(dbentry->tables,
    5855       85218 :                            (void *) &(msg->m_tableid[i]),
    5856             :                            HASH_REMOVE, NULL);
    5857             :     }
    5858             : }
    5859             : 
    5860             : 
    5861             : /* ----------
    5862             :  * pgstat_recv_dropdb() -
    5863             :  *
    5864             :  *  Arrange for dead database removal
    5865             :  * ----------
    5866             :  */
    5867             : static void
    5868          16 : pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
    5869             : {
    5870          16 :     Oid         dbid = msg->m_databaseid;
    5871             :     PgStat_StatDBEntry *dbentry;
    5872             : 
    5873             :     /*
    5874             :      * Lookup the database in the hashtable.
    5875             :      */
    5876          16 :     dbentry = pgstat_get_db_entry(dbid, false);
    5877             : 
    5878             :     /*
    5879             :      * If found, remove it (along with the db statfile).
    5880             :      */
    5881          16 :     if (dbentry)
    5882             :     {
    5883             :         char        statfile[MAXPGPATH];
    5884             : 
    5885          10 :         get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
    5886             : 
    5887          10 :         elog(DEBUG2, "removing stats file \"%s\"", statfile);
    5888          10 :         unlink(statfile);
    5889             : 
    5890          10 :         if (dbentry->tables != NULL)
    5891          10 :             hash_destroy(dbentry->tables);
    5892          10 :         if (dbentry->functions != NULL)
    5893          10 :             hash_destroy(dbentry->functions);
    5894             : 
    5895          10 :         if (hash_search(pgStatDBHash,
    5896             :                         (void *) &dbid,
    5897             :                         HASH_REMOVE, NULL) == NULL)
    5898           0 :             ereport(ERROR,
    5899             :                     (errmsg("database hash table corrupted during cleanup --- abort")));
    5900             :     }
    5901          16 : }
    5902             : 
    5903             : 
    5904             : /* ----------
    5905             :  * pgstat_recv_resetcounter() -
    5906             :  *
    5907             :  *  Reset the statistics for the specified database.
    5908             :  * ----------
    5909             :  */
    5910             : static void
    5911           0 : pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
    5912             : {
    5913             :     PgStat_StatDBEntry *dbentry;
    5914             : 
    5915             :     /*
    5916             :      * Lookup the database in the hashtable.  Nothing to do if not there.
    5917             :      */
    5918           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    5919             : 
    5920           0 :     if (!dbentry)
    5921           0 :         return;
    5922             : 
    5923             :     /*
    5924             :      * We simply throw away all the database's table entries by recreating a
    5925             :      * new hash table for them.
    5926             :      */
    5927           0 :     if (dbentry->tables != NULL)
    5928           0 :         hash_destroy(dbentry->tables);
    5929           0 :     if (dbentry->functions != NULL)
    5930           0 :         hash_destroy(dbentry->functions);
    5931             : 
    5932           0 :     dbentry->tables = NULL;
    5933           0 :     dbentry->functions = NULL;
    5934             : 
    5935             :     /*
    5936             :      * Reset database-level stats, too.  This creates empty hash tables for
    5937             :      * tables and functions.
    5938             :      */
    5939           0 :     reset_dbentry_counters(dbentry);
    5940             : }
    5941             : 
    5942             : /* ----------
    5943             :  * pgstat_recv_resetshared() -
    5944             :  *
    5945             :  *  Reset some shared statistics of the cluster.
    5946             :  * ----------
    5947             :  */
    5948             : static void
    5949           0 : pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
    5950             : {
    5951           0 :     if (msg->m_resettarget == RESET_BGWRITER)
    5952             :     {
    5953             :         /* Reset the global background writer statistics for the cluster. */
    5954           0 :         memset(&globalStats, 0, sizeof(globalStats));
    5955           0 :         globalStats.stat_reset_timestamp = GetCurrentTimestamp();
    5956             :     }
    5957           0 :     else if (msg->m_resettarget == RESET_ARCHIVER)
    5958             :     {
    5959             :         /* Reset the archiver statistics for the cluster. */
    5960           0 :         memset(&archiverStats, 0, sizeof(archiverStats));
    5961           0 :         archiverStats.stat_reset_timestamp = GetCurrentTimestamp();
    5962             :     }
    5963             : 
    5964             :     /*
    5965             :      * Presumably the sender of this message validated the target, don't
    5966             :      * complain here if it's not valid
    5967             :      */
    5968           0 : }
    5969             : 
    5970             : /* ----------
    5971             :  * pgstat_recv_resetsinglecounter() -
    5972             :  *
    5973             :  *  Reset a statistics for a single object
    5974             :  * ----------
    5975             :  */
    5976             : static void
    5977           0 : pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
    5978             : {
    5979             :     PgStat_StatDBEntry *dbentry;
    5980             : 
    5981           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    5982             : 
    5983           0 :     if (!dbentry)
    5984           0 :         return;
    5985             : 
    5986             :     /* Set the reset timestamp for the whole database */
    5987           0 :     dbentry->stat_reset_timestamp = GetCurrentTimestamp();
    5988             : 
    5989             :     /* Remove object if it exists, ignore it if not */
    5990           0 :     if (msg->m_resettype == RESET_TABLE)
    5991           0 :         (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
    5992             :                            HASH_REMOVE, NULL);
    5993           0 :     else if (msg->m_resettype == RESET_FUNCTION)
    5994           0 :         (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
    5995             :                            HASH_REMOVE, NULL);
    5996             : }
    5997             : 
    5998             : /* ----------
    5999             :  * pgstat_recv_autovac() -
    6000             :  *
    6001             :  *  Process an autovacuum signalling message.
    6002             :  * ----------
    6003             :  */
    6004             : static void
    6005          50 : pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
    6006             : {
    6007             :     PgStat_StatDBEntry *dbentry;
    6008             : 
    6009             :     /*
    6010             :      * Store the last autovacuum time in the database's hashtable entry.
    6011             :      */
    6012          50 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6013             : 
    6014          50 :     dbentry->last_autovac_time = msg->m_start_time;
    6015          50 : }
    6016             : 
    6017             : /* ----------
    6018             :  * pgstat_recv_vacuum() -
    6019             :  *
    6020             :  *  Process a VACUUM message.
    6021             :  * ----------
    6022             :  */
    6023             : static void
    6024        3894 : pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
    6025             : {
    6026             :     PgStat_StatDBEntry *dbentry;
    6027             :     PgStat_StatTabEntry *tabentry;
    6028             : 
    6029             :     /*
    6030             :      * Store the data in the table's hashtable entry.
    6031             :      */
    6032        3894 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6033             : 
    6034        3894 :     tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
    6035             : 
    6036        3894 :     tabentry->n_live_tuples = msg->m_live_tuples;
    6037        3894 :     tabentry->n_dead_tuples = msg->m_dead_tuples;
    6038             : 
    6039        3894 :     if (msg->m_autovacuum)
    6040             :     {
    6041          70 :         tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
    6042          70 :         tabentry->autovac_vacuum_count++;
    6043             :     }
    6044             :     else
    6045             :     {
    6046        3824 :         tabentry->vacuum_timestamp = msg->m_vacuumtime;
    6047        3824 :         tabentry->vacuum_count++;
    6048             :     }
    6049        3894 : }
    6050             : 
    6051             : /* ----------
    6052             :  * pgstat_recv_analyze() -
    6053             :  *
    6054             :  *  Process an ANALYZE message.
    6055             :  * ----------
    6056             :  */
    6057             : static void
    6058        8830 : pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
    6059             : {
    6060             :     PgStat_StatDBEntry *dbentry;
    6061             :     PgStat_StatTabEntry *tabentry;
    6062             : 
    6063             :     /*
    6064             :      * Store the data in the table's hashtable entry.
    6065             :      */
    6066        8830 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6067             : 
    6068        8830 :     tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
    6069             : 
    6070        8830 :     tabentry->n_live_tuples = msg->m_live_tuples;
    6071        8830 :     tabentry->n_dead_tuples = msg->m_dead_tuples;
    6072             : 
    6073             :     /*
    6074             :      * If commanded, reset changes_since_analyze to zero.  This forgets any
    6075             :      * changes that were committed while the ANALYZE was in progress, but we
    6076             :      * have no good way to estimate how many of those there were.
    6077             :      */
    6078        8830 :     if (msg->m_resetcounter)
    6079        8810 :         tabentry->changes_since_analyze = 0;
    6080             : 
    6081        8830 :     if (msg->m_autovacuum)
    6082             :     {
    6083         254 :         tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
    6084         254 :         tabentry->autovac_analyze_count++;
    6085             :     }
    6086             :     else
    6087             :     {
    6088        8576 :         tabentry->analyze_timestamp = msg->m_analyzetime;
    6089        8576 :         tabentry->analyze_count++;
    6090             :     }
    6091        8830 : }
    6092             : 
    6093             : 
    6094             : /* ----------
    6095             :  * pgstat_recv_archiver() -
    6096             :  *
    6097             :  *  Process a ARCHIVER message.
    6098             :  * ----------
    6099             :  */
    6100             : static void
    6101          26 : pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len)
    6102             : {
    6103          26 :     if (msg->m_failed)
    6104             :     {
    6105             :         /* Failed archival attempt */
    6106           0 :         ++archiverStats.failed_count;
    6107           0 :         memcpy(archiverStats.last_failed_wal, msg->m_xlog,
    6108             :                sizeof(archiverStats.last_failed_wal));
    6109           0 :         archiverStats.last_failed_timestamp = msg->m_timestamp;
    6110             :     }
    6111             :     else
    6112             :     {
    6113             :         /* Successful archival operation */
    6114          26 :         ++archiverStats.archived_count;
    6115          26 :         memcpy(archiverStats.last_archived_wal, msg->m_xlog,
    6116             :                sizeof(archiverStats.last_archived_wal));
    6117          26 :         archiverStats.last_archived_timestamp = msg->m_timestamp;
    6118             :     }
    6119          26 : }
    6120             : 
    6121             : /* ----------
    6122             :  * pgstat_recv_bgwriter() -
    6123             :  *
    6124             :  *  Process a BGWRITER message.
    6125             :  * ----------
    6126             :  */
    6127             : static void
    6128        5522 : pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
    6129             : {
    6130        5522 :     globalStats.timed_checkpoints += msg->m_timed_checkpoints;
    6131        5522 :     globalStats.requested_checkpoints += msg->m_requested_checkpoints;
    6132        5522 :     globalStats.checkpoint_write_time += msg->m_checkpoint_write_time;
    6133        5522 :     globalStats.checkpoint_sync_time += msg->m_checkpoint_sync_time;
    6134        5522 :     globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
    6135        5522 :     globalStats.buf_written_clean += msg->m_buf_written_clean;
    6136        5522 :     globalStats.maxwritten_clean += msg->m_maxwritten_clean;
    6137        5522 :     globalStats.buf_written_backend += msg->m_buf_written_backend;
    6138        5522 :     globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
    6139        5522 :     globalStats.buf_alloc += msg->m_buf_alloc;
    6140        5522 : }
    6141             : 
    6142             : /* ----------
    6143             :  * pgstat_recv_recoveryconflict() -
    6144             :  *
    6145             :  *  Process a RECOVERYCONFLICT message.
    6146             :  * ----------
    6147             :  */
    6148             : static void
    6149           0 : pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
    6150             : {
    6151             :     PgStat_StatDBEntry *dbentry;
    6152             : 
    6153           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6154             : 
    6155           0 :     switch (msg->m_reason)
    6156             :     {
    6157             :         case PROCSIG_RECOVERY_CONFLICT_DATABASE:
    6158             : 
    6159             :             /*
    6160             :              * Since we drop the information about the database as soon as it
    6161             :              * replicates, there is no point in counting these conflicts.
    6162             :              */
    6163           0 :             break;
    6164             :         case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
    6165           0 :             dbentry->n_conflict_tablespace++;
    6166           0 :             break;
    6167             :         case PROCSIG_RECOVERY_CONFLICT_LOCK:
    6168           0 :             dbentry->n_conflict_lock++;
    6169           0 :             break;
    6170             :         case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
    6171           0 :             dbentry->n_conflict_snapshot++;
    6172           0 :             break;
    6173             :         case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
    6174           0 :             dbentry->n_conflict_bufferpin++;
    6175           0 :             break;
    6176             :         case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
    6177           0 :             dbentry->n_conflict_startup_deadlock++;
    6178           0 :             break;
    6179             :     }
    6180           0 : }
    6181             : 
    6182             : /* ----------
    6183             :  * pgstat_recv_deadlock() -
    6184             :  *
    6185             :  *  Process a DEADLOCK message.
    6186             :  * ----------
    6187             :  */
    6188             : static void
    6189           4 : pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len)
    6190             : {
    6191             :     PgStat_StatDBEntry *dbentry;
    6192             : 
    6193           4 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6194             : 
    6195           4 :     dbentry->n_deadlocks++;
    6196           4 : }
    6197             : 
    6198             : /* ----------
    6199             :  * pgstat_recv_tempfile() -
    6200             :  *
    6201             :  *  Process a TEMPFILE message.
    6202             :  * ----------
    6203             :  */
    6204             : static void
    6205        2874 : pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len)
    6206             : {
    6207             :     PgStat_StatDBEntry *dbentry;
    6208             : 
    6209        2874 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6210             : 
    6211        2874 :     dbentry->n_temp_bytes += msg->m_filesize;
    6212        2874 :     dbentry->n_temp_files += 1;
    6213        2874 : }
    6214             : 
    6215             : /* ----------
    6216             :  * pgstat_recv_funcstat() -
    6217             :  *
    6218             :  *  Count what the backend has done.
    6219             :  * ----------
    6220             :  */
    6221             : static void
    6222           0 : pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
    6223             : {
    6224           0 :     PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
    6225             :     PgStat_StatDBEntry *dbentry;
    6226             :     PgStat_StatFuncEntry *funcentry;
    6227             :     int         i;
    6228             :     bool        found;
    6229             : 
    6230           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6231             : 
    6232             :     /*
    6233             :      * Process all function entries in the message.
    6234             :      */
    6235           0 :     for (i = 0; i < msg->m_nentries; i++, funcmsg++)
    6236             :     {
    6237           0 :         funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
    6238           0 :                                                          (void *) &(funcmsg->f_id),
    6239             :                                                          HASH_ENTER, &found);
    6240             : 
    6241           0 :         if (!found)
    6242             :         {
    6243             :             /*
    6244             :              * If it's a new function entry, initialize counters to the values
    6245             :              * we just got.
    6246             :              */
    6247           0 :             funcentry->f_numcalls = funcmsg->f_numcalls;
    6248           0 :             funcentry->f_total_time = funcmsg->f_total_time;
    6249           0 :             funcentry->f_self_time = funcmsg->f_self_time;
    6250             :         }
    6251             :         else
    6252             :         {
    6253             :             /*
    6254             :              * Otherwise add the values to the existing entry.
    6255             :              */
    6256           0 :             funcentry->f_numcalls += funcmsg->f_numcalls;
    6257           0 :             funcentry->f_total_time += funcmsg->f_total_time;
    6258           0 :             funcentry->f_self_time += funcmsg->f_self_time;
    6259             :         }
    6260             :     }
    6261           0 : }
    6262             : 
    6263             : /* ----------
    6264             :  * pgstat_recv_funcpurge() -
    6265             :  *
    6266             :  *  Arrange for dead function removal.
    6267             :  * ----------
    6268             :  */
    6269             : static void
    6270           0 : pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
    6271             : {
    6272             :     PgStat_StatDBEntry *dbentry;
    6273             :     int         i;
    6274             : 
    6275           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    6276             : 
    6277             :     /*
    6278             :      * No need to purge if we don't even know the database.
    6279             :      */
    6280           0 :     if (!dbentry || !dbentry->functions)
    6281           0 :         return;
    6282             : 
    6283             :     /*
    6284             :      * Process all function entries in the message.
    6285             :      */
    6286           0 :     for (i = 0; i < msg->m_nentries; i++)
    6287             :     {
    6288             :         /* Remove from hashtable if present; we don't care if it's not. */
    6289           0 :         (void) hash_search(dbentry->functions,
    6290           0 :                            (void *) &(msg->m_functionid[i]),
    6291             :                            HASH_REMOVE, NULL);
    6292             :     }
    6293             : }
    6294             : 
    6295             : /* ----------
    6296             :  * pgstat_write_statsfile_needed() -
    6297             :  *
    6298             :  *  Do we need to write out any stats files?
    6299             :  * ----------
    6300             :  */
    6301             : static bool
    6302      177866 : pgstat_write_statsfile_needed(void)
    6303             : {
    6304      177866 :     if (pending_write_requests != NIL)
    6305         976 :         return true;
    6306             : 
    6307             :     /* Everything was written recently */
    6308      176890 :     return false;
    6309             : }
    6310             : 
    6311             : /* ----------
    6312             :  * pgstat_db_requested() -
    6313             :  *
    6314             :  *  Checks whether stats for a particular DB need to be written to a file.
    6315             :  * ----------
    6316             :  */
    6317             : static bool
    6318        1862 : pgstat_db_requested(Oid databaseid)
    6319             : {
    6320             :     /*
    6321             :      * If any requests are outstanding at all, we should write the stats for
    6322             :      * shared catalogs (the "database" with OID 0).  This ensures that
    6323             :      * backends will see up-to-date stats for shared catalogs, even though
    6324             :      * they send inquiry messages mentioning only their own DB.
    6325             :      */
    6326        1862 :     if (databaseid == InvalidOid && pending_write_requests != NIL)
    6327         648 :         return true;
    6328             : 
    6329             :     /* Search to see if there's an open request to write this database. */
    6330        1214 :     if (list_member_oid(pending_write_requests, databaseid))
    6331         478 :         return true;
    6332             : 
    6333         736 :     return false;
    6334             : }
    6335             : 
    6336             : /*
    6337             :  * Convert a potentially unsafely truncated activity string (see
    6338             :  * PgBackendStatus.st_activity_raw's documentation) into a correctly truncated
    6339             :  * one.
    6340             :  *
    6341             :  * The returned string is allocated in the caller's memory context and may be
    6342             :  * freed.
    6343             :  */
    6344             : char *
    6345        2560 : pgstat_clip_activity(const char *raw_activity)
    6346             : {
    6347             :     char       *activity;
    6348             :     int         rawlen;
    6349             :     int         cliplen;
    6350             : 
    6351             :     /*
    6352             :      * Some callers, like pgstat_get_backend_current_activity(), do not
    6353             :      * guarantee that the buffer isn't concurrently modified. We try to take
    6354             :      * care that the buffer is always terminated by a NUL byte regardless, but
    6355             :      * let's still be paranoid about the string's length. In those cases the
    6356             :      * underlying buffer is guaranteed to be pgstat_track_activity_query_size
    6357             :      * large.
    6358             :      */
    6359        2560 :     activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
    6360             : 
    6361             :     /* now double-guaranteed to be NUL terminated */
    6362        2560 :     rawlen = strlen(activity);
    6363             : 
    6364             :     /*
    6365             :      * All supported server-encodings make it possible to determine the length
    6366             :      * of a multi-byte character from its first byte (this is not the case for
    6367             :      * client encodings, see GB18030). As st_activity is always stored using
    6368             :      * server encoding, this allows us to perform multi-byte aware truncation,
    6369             :      * even if the string earlier was truncated in the middle of a multi-byte
    6370             :      * character.
    6371             :      */
    6372        2560 :     cliplen = pg_mbcliplen(activity, rawlen,
    6373             :                            pgstat_track_activity_query_size - 1);
    6374             : 
    6375        2560 :     activity[cliplen] = '\0';
    6376             : 
    6377        2560 :     return activity;
    6378             : }

Generated by: LCOV version 1.13