]> granicus.if.org Git - postgresql/blobdiff - src/backend/postmaster/pgstat.c
Fix VACUUM so that it always updates pg_class.reltuples/relpages.
[postgresql] / src / backend / postmaster / pgstat.c
index d3455cee1924a133afc6caafa2e9f5ab464fe06e..1d80c311d879d9cf9009621860cda3ab19c6dea9 100644 (file)
@@ -11,9 +11,9 @@
  *                     - Add a pgstat config column to pg_database, so this
  *                       entire thing can be enabled/disabled on a per db basis.
  *
- *     Copyright (c) 2001-2008, PostgreSQL Global Development Group
+ *     Copyright (c) 2001-2011, PostgreSQL Global Development Group
  *
- *     $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.182 2008/11/03 01:17:08 tgl Exp $
+ *     src/backend/postmaster/pgstat.c
  * ----------
  */
 #include "postgres.h"
@@ -57,6 +57,7 @@
 #include "storage/ipc.h"
 #include "storage/pg_shmem.h"
 #include "storage/pmsignal.h"
+#include "storage/procsignal.h"
 #include "utils/guc.h"
 #include "utils/memutils.h"
 #include "utils/ps_status.h"
@@ -130,7 +131,7 @@ PgStat_MsgBgWriter BgWriterStats;
  * Local data
  * ----------
  */
-NON_EXEC_STATIC int pgStatSock = -1;
+NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
 
 static struct sockaddr_storage pgStatAddr;
 
@@ -195,6 +196,7 @@ static int  pgStatXactRollback = 0;
 typedef struct TwoPhasePgStatRecord
 {
        PgStat_Counter tuples_inserted;         /* tuples inserted in xact */
+       PgStat_Counter tuples_updated;          /* tuples updated in xact */
        PgStat_Counter tuples_deleted;          /* tuples deleted in xact */
        Oid                     t_id;                   /* table's OID */
        bool            t_shared;               /* is it a shared catalog? */
@@ -217,6 +219,7 @@ static PgStat_GlobalStats globalStats;
 
 /* Last time the collector successfully wrote the stats file */
 static TimestampTz last_statwrite;
+
 /* Latest statistics request time from backends */
 static TimestampTz last_statrequest;
 
@@ -245,6 +248,8 @@ static void pgstat_beshutdown_hook(int code, Datum arg);
 static void pgstat_sighup_handler(SIGNAL_ARGS);
 
 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
+static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
+                                        Oid tableoid, bool create);
 static void pgstat_write_statsfile(bool permanent);
 static HTAB *pgstat_read_statsfile(Oid onlydb, bool permanent);
 static void backend_read_statsfile(void);
@@ -266,12 +271,15 @@ static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
+static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
+static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
+static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
 
 
 /* ------------------------------------------------------------
@@ -347,7 +355,7 @@ pgstat_init(void)
                /*
                 * Create the socket.
                 */
-               if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
+               if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
                {
                        ereport(LOG,
                                        (errcode_for_socket_access(),
@@ -365,7 +373,7 @@ pgstat_init(void)
                                        (errcode_for_socket_access(),
                          errmsg("could not bind socket for statistics collector: %m")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -376,7 +384,7 @@ pgstat_init(void)
                                        (errcode_for_socket_access(),
                                         errmsg("could not get address of socket for statistics collector: %m")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -392,7 +400,7 @@ pgstat_init(void)
                                        (errcode_for_socket_access(),
                        errmsg("could not connect socket for statistics collector: %m")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -413,7 +421,7 @@ retry1:
                                        (errcode_for_socket_access(),
                                         errmsg("could not send test message on socket for statistics collector: %m")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -426,6 +434,7 @@ retry1:
                {
                        FD_ZERO(&rset);
                        FD_SET(pgStatSock, &rset);
+
                        tv.tv_sec = 0;
                        tv.tv_usec = 500000;
                        sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
@@ -438,7 +447,7 @@ retry1:
                                        (errcode_for_socket_access(),
                                         errmsg("select() failed in statistics collector: %m")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
                if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
@@ -453,7 +462,7 @@ retry1:
                                        (errcode(ERRCODE_CONNECTION_FAILURE),
                                         errmsg("test message did not get through on socket for statistics collector")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -468,7 +477,7 @@ retry2:
                                        (errcode_for_socket_access(),
                                         errmsg("could not receive test message on socket for statistics collector: %m")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -478,7 +487,7 @@ retry2:
                                        (errcode(ERRCODE_INTERNAL_ERROR),
                                         errmsg("incorrect test message transmission on socket for statistics collector")));
                        closesocket(pgStatSock);
-                       pgStatSock = -1;
+                       pgStatSock = PGINVALID_SOCKET;
                        continue;
                }
 
@@ -487,7 +496,7 @@ retry2:
        }
 
        /* Did we find a working address? */
-       if (!addr || pgStatSock < 0)
+       if (!addr || pgStatSock == PGINVALID_SOCKET)
                goto startup_failed;
 
        /*
@@ -514,9 +523,9 @@ startup_failed:
        if (addrs)
                pg_freeaddrinfo_all(hints.ai_family, addrs);
 
-       if (pgStatSock >= 0)
+       if (pgStatSock != PGINVALID_SOCKET)
                closesocket(pgStatSock);
-       pgStatSock = -1;
+       pgStatSock = PGINVALID_SOCKET;
 
        /*
         * Adjust GUC variables to suppress useless activity, and for debugging
@@ -585,7 +594,7 @@ pgstat_start(void)
         * Check that the socket is there, else pgstat_init failed and we can do
         * nothing useful.
         */
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return 0;
 
        /*
@@ -761,7 +770,7 @@ pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
        int                     len;
 
        /* It's unlikely we'd get here with no socket, but maybe not impossible */
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        /*
@@ -863,7 +872,7 @@ pgstat_vacuum_stat(void)
        PgStat_StatFuncEntry *funcentry;
        int                     len;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        /*
@@ -967,55 +976,60 @@ pgstat_vacuum_stat(void)
        hash_destroy(htab);
 
        /*
-        * Now repeat the above steps for functions.
+        * Now repeat the above steps for functions.  However, we needn't bother
+        * in the common case where no function stats are being collected.
         */
-       htab = pgstat_collect_oids(ProcedureRelationId);
+       if (dbentry->functions != NULL &&
+               hash_get_num_entries(dbentry->functions) > 0)
+       {
+               htab = pgstat_collect_oids(ProcedureRelationId);
 
-       pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
-       f_msg.m_databaseid = MyDatabaseId;
-       f_msg.m_nentries = 0;
+               pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
+               f_msg.m_databaseid = MyDatabaseId;
+               f_msg.m_nentries = 0;
 
-       hash_seq_init(&hstat, dbentry->functions);
-       while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
-       {
-               Oid                     funcid = funcentry->functionid;
+               hash_seq_init(&hstat, dbentry->functions);
+               while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
+               {
+                       Oid                     funcid = funcentry->functionid;
 
-               CHECK_FOR_INTERRUPTS();
+                       CHECK_FOR_INTERRUPTS();
 
-               if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
-                       continue;
+                       if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
+                               continue;
 
-               /*
-                * Not there, so add this function's Oid to the message
-                */
-               f_msg.m_functionid[f_msg.m_nentries++] = funcid;
+                       /*
+                        * Not there, so add this function's Oid to the message
+                        */
+                       f_msg.m_functionid[f_msg.m_nentries++] = funcid;
+
+                       /*
+                        * If the message is full, send it out and reinitialize to empty
+                        */
+                       if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
+                       {
+                               len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
+                                       +f_msg.m_nentries * sizeof(Oid);
+
+                               pgstat_send(&f_msg, len);
+
+                               f_msg.m_nentries = 0;
+                       }
+               }
 
                /*
-                * If the message is full, send it out and reinitialize to empty
+                * Send the rest
                 */
-               if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
+               if (f_msg.m_nentries > 0)
                {
                        len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
                                +f_msg.m_nentries * sizeof(Oid);
 
                        pgstat_send(&f_msg, len);
-
-                       f_msg.m_nentries = 0;
                }
-       }
-
-       /*
-        * Send the rest
-        */
-       if (f_msg.m_nentries > 0)
-       {
-               len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
-                       +f_msg.m_nentries * sizeof(Oid);
 
-               pgstat_send(&f_msg, len);
+               hash_destroy(htab);
        }
-
-       hash_destroy(htab);
 }
 
 
@@ -1024,7 +1038,8 @@ pgstat_vacuum_stat(void)
  *
  *     Collect the OIDs of all objects listed in the specified system catalog
  *     into a temporary hash table.  Caller should hash_destroy the result
- *     when done with it.
+ *     when done with it.      (However, we make the table in CurrentMemoryContext
+ *     so that it will be freed properly in event of an error.)
  * ----------
  */
 static HTAB *
@@ -1040,10 +1055,11 @@ pgstat_collect_oids(Oid catalogid)
        hash_ctl.keysize = sizeof(Oid);
        hash_ctl.entrysize = sizeof(Oid);
        hash_ctl.hash = oid_hash;
+       hash_ctl.hcxt = CurrentMemoryContext;
        htab = hash_create("Temporary table of OIDs",
                                           PGSTAT_TAB_HASH_SIZE,
                                           &hash_ctl,
-                                          HASH_ELEM | HASH_FUNCTION);
+                                          HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
 
        rel = heap_open(catalogid, AccessShareLock);
        scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
@@ -1075,7 +1091,7 @@ pgstat_drop_database(Oid databaseid)
 {
        PgStat_MsgDropdb msg;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
@@ -1102,7 +1118,7 @@ pgstat_drop_relation(Oid relid)
        PgStat_MsgTabpurge msg;
        int                     len;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        msg.m_tableid[0] = relid;
@@ -1128,7 +1144,7 @@ pgstat_reset_counters(void)
 {
        PgStat_MsgResetcounter msg;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        if (!superuser())
@@ -1141,6 +1157,63 @@ pgstat_reset_counters(void)
        pgstat_send(&msg, sizeof(msg));
 }
 
+/* ----------
+ * pgstat_reset_shared_counters() -
+ *
+ *     Tell the statistics collector to reset cluster-wide shared counters.
+ * ----------
+ */
+void
+pgstat_reset_shared_counters(const char *target)
+{
+       PgStat_MsgResetsharedcounter msg;
+
+       if (pgStatSock == PGINVALID_SOCKET)
+               return;
+
+       if (!superuser())
+               ereport(ERROR,
+                               (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+                                errmsg("must be superuser to reset statistics counters")));
+
+       if (strcmp(target, "bgwriter") == 0)
+               msg.m_resettarget = RESET_BGWRITER;
+       else
+               ereport(ERROR,
+                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                errmsg("unrecognized reset target: \"%s\"", target),
+                                errhint("Target must be \"bgwriter\".")));
+
+       pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
+       pgstat_send(&msg, sizeof(msg));
+}
+
+/* ----------
+ * pgstat_reset_single_counter() -
+ *
+ *     Tell the statistics collector to reset a single counter.
+ * ----------
+ */
+void
+pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
+{
+       PgStat_MsgResetsinglecounter msg;
+
+       if (pgStatSock == PGINVALID_SOCKET)
+               return;
+
+       if (!superuser())
+               ereport(ERROR,
+                               (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+                                errmsg("must be superuser to reset statistics counters")));
+
+       pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
+       msg.m_databaseid = MyDatabaseId;
+       msg.m_resettype = type;
+       msg.m_objectid = objoid;
+
+       pgstat_send(&msg, sizeof(msg));
+}
 
 /* ----------
  * pgstat_report_autovac() -
@@ -1155,7 +1228,7 @@ pgstat_report_autovac(Oid dboid)
 {
        PgStat_MsgAutovacStart msg;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
@@ -1173,19 +1246,17 @@ pgstat_report_autovac(Oid dboid)
  * ---------
  */
 void
-pgstat_report_vacuum(Oid tableoid, bool shared,
-                                        bool analyze, PgStat_Counter tuples)
+pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter tuples)
 {
        PgStat_MsgVacuum msg;
 
-       if (pgStatSock < 0 || !pgstat_track_counts)
+       if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
                return;
 
        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
        msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
        msg.m_tableoid = tableoid;
-       msg.m_analyze = analyze;
-       msg.m_autovacuum = IsAutoVacuumWorkerProcess();         /* is this autovacuum? */
+       msg.m_autovacuum = IsAutoVacuumWorkerProcess();
        msg.m_vacuumtime = GetCurrentTimestamp();
        msg.m_tuples = tuples;
        pgstat_send(&msg, sizeof(msg));
@@ -1198,23 +1269,23 @@ pgstat_report_vacuum(Oid tableoid, bool shared,
  * --------
  */
 void
-pgstat_report_analyze(Relation rel, PgStat_Counter livetuples,
-                                         PgStat_Counter deadtuples)
+pgstat_report_analyze(Relation rel,
+                                         PgStat_Counter livetuples, PgStat_Counter deadtuples)
 {
        PgStat_MsgAnalyze msg;
 
-       if (pgStatSock < 0 || !pgstat_track_counts)
+       if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
                return;
 
        /*
-        * Unlike VACUUM, ANALYZE might be running inside a transaction that
-        * has already inserted and/or deleted rows in the target table.
-        * ANALYZE will have counted such rows as live or dead respectively.
-        * Because we will report our counts of such rows at transaction end,
-        * we should subtract off these counts from what we send to the collector
-        * now, else they'll be double-counted after commit.  (This approach also
-        * ensures that the collector ends up with the right numbers if we abort
-        * instead of committing.)
+        * Unlike VACUUM, ANALYZE might be running inside a transaction that has
+        * already inserted and/or deleted rows in the target table. ANALYZE will
+        * have counted such rows as live or dead respectively. Because we will
+        * report our counts of such rows at transaction end, we should subtract
+        * off these counts from what we send to the collector now, else they'll
+        * be double-counted after commit.      (This approach also ensures that the
+        * collector ends up with the right numbers if we abort instead of
+        * committing.)
         */
        if (rel->pgstat_info != NULL)
        {
@@ -1223,10 +1294,10 @@ pgstat_report_analyze(Relation rel, PgStat_Counter livetuples,
                for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
                {
                        livetuples -= trans->tuples_inserted - trans->tuples_deleted;
-                       deadtuples -= trans->tuples_deleted;
+                       deadtuples -= trans->tuples_updated + trans->tuples_deleted;
                }
                /* count stuff inserted by already-aborted subxacts, too */
-               deadtuples -= rel->pgstat_info->t_counts.t_new_dead_tuples;
+               deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
                /* Since ANALYZE's counts are estimates, we could have underflowed */
                livetuples = Max(livetuples, 0);
                deadtuples = Max(deadtuples, 0);
@@ -1235,13 +1306,32 @@ pgstat_report_analyze(Relation rel, PgStat_Counter livetuples,
        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
        msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
        msg.m_tableoid = RelationGetRelid(rel);
-       msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
+       msg.m_autovacuum = IsAutoVacuumWorkerProcess();
        msg.m_analyzetime = GetCurrentTimestamp();
        msg.m_live_tuples = livetuples;
        msg.m_dead_tuples = deadtuples;
        pgstat_send(&msg, sizeof(msg));
 }
 
+/* --------
+ * pgstat_report_recovery_conflict() -
+ *
+ *     Tell the collector about a Hot Standby recovery conflict.
+ * --------
+ */
+void
+pgstat_report_recovery_conflict(int reason)
+{
+       PgStat_MsgRecoveryConflict msg;
+
+       if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
+               return;
+
+       pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
+       msg.m_databaseid = MyDatabaseId;
+       msg.m_reason = reason;
+       pgstat_send(&msg, sizeof(msg));
+}
 
 /* ----------
  * pgstat_ping() -
@@ -1254,7 +1344,7 @@ pgstat_ping(void)
 {
        PgStat_MsgDummy msg;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
@@ -1288,7 +1378,7 @@ pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
                                                   PgStat_FunctionCallUsage *fcu)
 {
        PgStat_BackendFunctionEntry *htabent;
-       bool            found;
+       bool            found;
 
        if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
        {
@@ -1330,6 +1420,23 @@ pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
        INSTR_TIME_SET_CURRENT(fcu->f_start);
 }
 
+/*
+ * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
+ *             for specified function
+ *
+ * If no entry, return NULL, don't create a new one
+ */
+PgStat_BackendFunctionEntry *
+find_funcstat_entry(Oid func_id)
+{
+       if (pgStatFunctions == NULL)
+               return NULL;
+
+       return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
+                                                                                                          (void *) &func_id,
+                                                                                                          HASH_FIND, NULL);
+}
+
 /*
  * Calculate function call usage and update stat counters.
  * Called by the executor after invoking a function.
@@ -1368,8 +1475,8 @@ pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
         * Compute the new total f_time as the total elapsed time added to the
         * pre-call value of f_time.  This is necessary to avoid double-counting
         * any time taken by recursive calls of myself.  (We do not need any
-        * similar kluge for self time, since that already excludes any
-        * recursive calls.)
+        * similar kluge for self time, since that already excludes any recursive
+        * calls.)
         */
        INSTR_TIME_ADD(f_total, fcu->save_f_time);
 
@@ -1405,13 +1512,14 @@ pgstat_initstats(Relation rel)
        /* We only count stats for things that have storage */
        if (!(relkind == RELKIND_RELATION ||
                  relkind == RELKIND_INDEX ||
-                 relkind == RELKIND_TOASTVALUE))
+                 relkind == RELKIND_TOASTVALUE ||
+                 relkind == RELKIND_SEQUENCE))
        {
                rel->pgstat_info = NULL;
                return;
        }
 
-       if (pgStatSock < 0 || !pgstat_track_counts)
+       if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
        {
                /* We're not counting at all */
                rel->pgstat_info = NULL;
@@ -1487,6 +1595,32 @@ get_tabstat_entry(Oid rel_id, bool isshared)
        return entry;
 }
 
+/*
+ * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
+ *
+ * If no entry, return NULL, don't create a new one
+ */
+PgStat_TableStatus *
+find_tabstat_entry(Oid rel_id)
+{
+       PgStat_TableStatus *entry;
+       TabStatusArray *tsa;
+       int                     i;
+
+       for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
+       {
+               for (i = 0; i < tsa->tsa_used; i++)
+               {
+                       entry = &tsa->tsa_entries[i];
+                       if (entry->t_id == rel_id)
+                               return entry;
+               }
+       }
+
+       /* Not present */
+       return NULL;
+}
+
 /*
  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
  */
@@ -1544,14 +1678,11 @@ pgstat_count_heap_insert(Relation rel)
 {
        PgStat_TableStatus *pgstat_info = rel->pgstat_info;
 
-       if (pgstat_track_counts && pgstat_info != NULL)
+       if (pgstat_info != NULL)
        {
+               /* We have to log the effect at the proper transactional level */
                int                     nest_level = GetCurrentTransactionNestLevel();
 
-               /* t_tuples_inserted is nontransactional, so just advance it */
-               pgstat_info->t_counts.t_tuples_inserted++;
-
-               /* We have to log the transactional effect at the proper level */
                if (pgstat_info->trans == NULL ||
                        pgstat_info->trans->nest_level != nest_level)
                        add_tabstat_xact_level(pgstat_info, nest_level);
@@ -1568,24 +1699,20 @@ pgstat_count_heap_update(Relation rel, bool hot)
 {
        PgStat_TableStatus *pgstat_info = rel->pgstat_info;
 
-       if (pgstat_track_counts && pgstat_info != NULL)
+       if (pgstat_info != NULL)
        {
+               /* We have to log the effect at the proper transactional level */
                int                     nest_level = GetCurrentTransactionNestLevel();
 
-               /* t_tuples_updated is nontransactional, so just advance it */
-               pgstat_info->t_counts.t_tuples_updated++;
-               /* ditto for the hot_update counter */
-               if (hot)
-                       pgstat_info->t_counts.t_tuples_hot_updated++;
-
-               /* We have to log the transactional effect at the proper level */
                if (pgstat_info->trans == NULL ||
                        pgstat_info->trans->nest_level != nest_level)
                        add_tabstat_xact_level(pgstat_info, nest_level);
 
-               /* An UPDATE both inserts a new tuple and deletes the old */
-               pgstat_info->trans->tuples_inserted++;
-               pgstat_info->trans->tuples_deleted++;
+               pgstat_info->trans->tuples_updated++;
+
+               /* t_tuples_hot_updated is nontransactional, so just advance it */
+               if (hot)
+                       pgstat_info->t_counts.t_tuples_hot_updated++;
        }
 }
 
@@ -1597,14 +1724,11 @@ pgstat_count_heap_delete(Relation rel)
 {
        PgStat_TableStatus *pgstat_info = rel->pgstat_info;
 
-       if (pgstat_track_counts && pgstat_info != NULL)
+       if (pgstat_info != NULL)
        {
+               /* We have to log the effect at the proper transactional level */
                int                     nest_level = GetCurrentTransactionNestLevel();
 
-               /* t_tuples_deleted is nontransactional, so just advance it */
-               pgstat_info->t_counts.t_tuples_deleted++;
-
-               /* We have to log the transactional effect at the proper level */
                if (pgstat_info->trans == NULL ||
                        pgstat_info->trans->nest_level != nest_level)
                        add_tabstat_xact_level(pgstat_info, nest_level);
@@ -1617,7 +1741,7 @@ pgstat_count_heap_delete(Relation rel)
  * pgstat_update_heap_dead_tuples - update dead-tuples count
  *
  * The semantics of this are that we are reporting the nontransactional
- * recovery of "delta" dead tuples; so t_new_dead_tuples decreases
+ * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
  * rather than increasing, and the change goes straight into the per-table
  * counter, not into transactional state.
  */
@@ -1626,8 +1750,8 @@ pgstat_update_heap_dead_tuples(Relation rel, int delta)
 {
        PgStat_TableStatus *pgstat_info = rel->pgstat_info;
 
-       if (pgstat_track_counts && pgstat_info != NULL)
-               pgstat_info->t_counts.t_new_dead_tuples -= delta;
+       if (pgstat_info != NULL)
+               pgstat_info->t_counts.t_delta_dead_tuples -= delta;
 }
 
 
@@ -1671,16 +1795,29 @@ AtEOXact_PgStat(bool isCommit)
                        Assert(trans->upper == NULL);
                        tabstat = trans->parent;
                        Assert(tabstat->trans == trans);
+                       /* count attempted actions regardless of commit/abort */
+                       tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
+                       tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
+                       tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
                        if (isCommit)
                        {
-                               tabstat->t_counts.t_new_live_tuples +=
+                               /* insert adds a live tuple, delete removes one */
+                               tabstat->t_counts.t_delta_live_tuples +=
                                        trans->tuples_inserted - trans->tuples_deleted;
-                               tabstat->t_counts.t_new_dead_tuples += trans->tuples_deleted;
+                               /* update and delete each create a dead tuple */
+                               tabstat->t_counts.t_delta_dead_tuples +=
+                                       trans->tuples_updated + trans->tuples_deleted;
+                               /* insert, update, delete each count as one change event */
+                               tabstat->t_counts.t_changed_tuples +=
+                                       trans->tuples_inserted + trans->tuples_updated +
+                                       trans->tuples_deleted;
                        }
                        else
                        {
                                /* inserted tuples are dead, deleted tuples are unaffected */
-                               tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
+                               tabstat->t_counts.t_delta_dead_tuples +=
+                                       trans->tuples_inserted + trans->tuples_updated;
+                               /* an aborted xact generates no changed_tuple events */
                        }
                        tabstat->trans = NULL;
                }
@@ -1729,6 +1866,7 @@ AtEOSubXact_PgStat(bool isCommit, int nestDepth)
                                if (trans->upper && trans->upper->nest_level == nestDepth - 1)
                                {
                                        trans->upper->tuples_inserted += trans->tuples_inserted;
+                                       trans->upper->tuples_updated += trans->tuples_updated;
                                        trans->upper->tuples_deleted += trans->tuples_deleted;
                                        tabstat->trans = trans->upper;
                                        pfree(trans);
@@ -1754,10 +1892,17 @@ AtEOSubXact_PgStat(bool isCommit, int nestDepth)
                        else
                        {
                                /*
-                                * On abort, inserted tuples are dead (and can be bounced out
-                                * to the top-level tabstat), deleted tuples are unaffected
+                                * On abort, update top-level tabstat counts, then forget the
+                                * subtransaction
                                 */
-                               tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
+
+                               /* count attempted actions regardless of commit/abort */
+                               tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
+                               tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
+                               tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
+                               /* inserted tuples are dead, deleted tuples are unaffected */
+                               tabstat->t_counts.t_delta_dead_tuples +=
+                                       trans->tuples_inserted + trans->tuples_updated;
                                tabstat->trans = trans->upper;
                                pfree(trans);
                        }
@@ -1797,6 +1942,7 @@ AtPrepare_PgStat(void)
                        Assert(tabstat->trans == trans);
 
                        record.tuples_inserted = trans->tuples_inserted;
+                       record.tuples_updated = trans->tuples_updated;
                        record.tuples_deleted = trans->tuples_deleted;
                        record.t_id = tabstat->t_id;
                        record.t_shared = tabstat->t_shared;
@@ -1861,9 +2007,17 @@ pgstat_twophase_postcommit(TransactionId xid, uint16 info,
        /* Find or create a tabstat entry for the rel */
        pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
 
-       pgstat_info->t_counts.t_new_live_tuples +=
+       /* Same math as in AtEOXact_PgStat, commit case */
+       pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
+       pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
+       pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
+       pgstat_info->t_counts.t_delta_live_tuples +=
                rec->tuples_inserted - rec->tuples_deleted;
-       pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_deleted;
+       pgstat_info->t_counts.t_delta_dead_tuples +=
+               rec->tuples_updated + rec->tuples_deleted;
+       pgstat_info->t_counts.t_changed_tuples +=
+               rec->tuples_inserted + rec->tuples_updated +
+               rec->tuples_deleted;
 }
 
 /*
@@ -1882,8 +2036,12 @@ pgstat_twophase_postabort(TransactionId xid, uint16 info,
        /* Find or create a tabstat entry for the rel */
        pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
 
-       /* inserted tuples are dead, deleted tuples are no-ops */
-       pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_inserted;
+       /* Same math as in AtEOXact_PgStat, abort case */
+       pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
+       pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
+       pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
+       pgstat_info->t_counts.t_delta_dead_tuples +=
+               rec->tuples_inserted + rec->tuples_updated;
 }
 
 
@@ -2062,7 +2220,9 @@ pgstat_fetch_global(void)
 
 static PgBackendStatus *BackendStatusArray = NULL;
 static PgBackendStatus *MyBEEntry = NULL;
-static char                       *BackendActivityBuffer = NULL;
+static char *BackendClientHostnameBuffer = NULL;
+static char *BackendAppnameBuffer = NULL;
+static char *BackendActivityBuffer = NULL;
 
 
 /*
@@ -2073,14 +2233,19 @@ BackendStatusShmemSize(void)
 {
        Size            size;
 
-       size = add_size(mul_size(sizeof(PgBackendStatus), MaxBackends),
+       size = mul_size(sizeof(PgBackendStatus), MaxBackends);
+       size = add_size(size,
+                                       mul_size(NAMEDATALEN, MaxBackends));
+       size = add_size(size,
                                        mul_size(pgstat_track_activity_query_size, MaxBackends));
+       size = add_size(size,
+                                       mul_size(NAMEDATALEN, MaxBackends));
        return size;
 }
 
 /*
- * Initialize the shared status array and activity string buffer during
- * postmaster startup.
+ * Initialize the shared status array and several string buffers
+ * during postmaster startup.
  */
 void
 CreateSharedBackendStatus(void)
@@ -2103,9 +2268,45 @@ CreateSharedBackendStatus(void)
                MemSet(BackendStatusArray, 0, size);
        }
 
+       /* Create or attach to the shared appname buffer */
+       size = mul_size(NAMEDATALEN, MaxBackends);
+       BackendAppnameBuffer = (char *)
+               ShmemInitStruct("Backend Application Name Buffer", size, &found);
+
+       if (!found)
+       {
+               MemSet(BackendAppnameBuffer, 0, size);
+
+               /* Initialize st_appname pointers. */
+               buffer = BackendAppnameBuffer;
+               for (i = 0; i < MaxBackends; i++)
+               {
+                       BackendStatusArray[i].st_appname = buffer;
+                       buffer += NAMEDATALEN;
+               }
+       }
+
+       /* Create or attach to the shared client hostname buffer */
+       size = mul_size(NAMEDATALEN, MaxBackends);
+       BackendClientHostnameBuffer = (char *)
+               ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
+
+       if (!found)
+       {
+               MemSet(BackendClientHostnameBuffer, 0, size);
+
+               /* Initialize st_clienthostname pointers. */
+               buffer = BackendClientHostnameBuffer;
+               for (i = 0; i < MaxBackends; i++)
+               {
+                       BackendStatusArray[i].st_clienthostname = buffer;
+                       buffer += NAMEDATALEN;
+               }
+       }
+
        /* Create or attach to the shared activity buffer */
        size = mul_size(pgstat_track_activity_query_size, MaxBackends);
-       BackendActivityBuffer = (char*)
+       BackendActivityBuffer = (char *)
                ShmemInitStruct("Backend Activity Buffer", size, &found);
 
        if (!found)
@@ -2114,7 +2315,8 @@ CreateSharedBackendStatus(void)
 
                /* Initialize st_activity pointers. */
                buffer = BackendActivityBuffer;
-               for (i = 0; i < MaxBackends; i++) {
+               for (i = 0; i < MaxBackends; i++)
+               {
                        BackendStatusArray[i].st_activity = buffer;
                        buffer += pgstat_track_activity_query_size;
                }
@@ -2129,6 +2331,7 @@ CreateSharedBackendStatus(void)
  *     Called from InitPostgres.  MyBackendId must be set,
  *     but we must not have started any transaction yet (since the
  *     exit hook must run after the last transaction exit).
+ *     NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
  * ----------
  */
 void
@@ -2146,7 +2349,8 @@ pgstat_initialize(void)
  * pgstat_bestart() -
  *
  *     Initialize this backend's entry in the PgBackendStatus array.
- *     Called from InitPostgres.  MyDatabaseId and session userid must be set
+ *     Called from InitPostgres.
+ *     MyDatabaseId, session userid, and application_name must be set
  *     (hence, this cannot be combined with pgstat_initialize).
  * ----------
  */
@@ -2200,13 +2404,24 @@ pgstat_bestart(void)
        beentry->st_databaseid = MyDatabaseId;
        beentry->st_userid = userid;
        beentry->st_clientaddr = clientaddr;
+       beentry->st_clienthostname[0] = '\0';
        beentry->st_waiting = false;
+       beentry->st_appname[0] = '\0';
        beentry->st_activity[0] = '\0';
-       /* Also make sure the last byte in the string area is always 0 */
+       /* Also make sure the last byte in each string area is always 0 */
+       beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
+       beentry->st_appname[NAMEDATALEN - 1] = '\0';
        beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
 
        beentry->st_changecount++;
        Assert((beentry->st_changecount & 1) == 0);
+
+       if (MyProcPort && MyProcPort->remote_hostname)
+               strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname, NAMEDATALEN);
+
+       /* Update app name to current GUC setting */
+       if (application_name)
+               pgstat_report_appname(application_name);
 }
 
 /*
@@ -2223,7 +2438,14 @@ pgstat_beshutdown_hook(int code, Datum arg)
 {
        volatile PgBackendStatus *beentry = MyBEEntry;
 
-       pgstat_report_stat(true);
+       /*
+        * If we got as far as discovering our own database ID, we can report what
+        * we did to the collector.  Otherwise, we'd be sending an invalid
+        * database ID, so forget it.  (This means that accesses to pg_database
+        * during failed backend starts might never get counted.)
+        */
+       if (OidIsValid(MyDatabaseId))
+               pgstat_report_stat(true);
 
        /*
         * Clear my status entry, following the protocol of bumping st_changecount
@@ -2282,6 +2504,38 @@ pgstat_report_activity(const char *cmd_str)
        Assert((beentry->st_changecount & 1) == 0);
 }
 
+/* ----------
+ * pgstat_report_appname() -
+ *
+ *     Called to update our application name.
+ * ----------
+ */
+void
+pgstat_report_appname(const char *appname)
+{
+       volatile PgBackendStatus *beentry = MyBEEntry;
+       int                     len;
+
+       if (!beentry)
+               return;
+
+       /* This should be unnecessary if GUC did its job, but be safe */
+       len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
+
+       /*
+        * Update my status entry, following the protocol of bumping
+        * st_changecount before and after.  We use a volatile pointer here to
+        * ensure the compiler doesn't try to get cute.
+        */
+       beentry->st_changecount++;
+
+       memcpy((char *) beentry->st_appname, appname, len);
+       beentry->st_appname[len] = '\0';
+
+       beentry->st_changecount++;
+       Assert((beentry->st_changecount & 1) == 0);
+}
+
 /*
  * Report current transaction start timestamp as the specified value.
  * Zero means there is no active transaction.
@@ -2344,7 +2598,8 @@ pgstat_read_current_status(void)
        volatile PgBackendStatus *beentry;
        PgBackendStatus *localtable;
        PgBackendStatus *localentry;
-       char                    *localactivity;
+       char       *localappname,
+                          *localactivity;
        int                     i;
 
        Assert(!pgStatRunningInCollector);
@@ -2356,6 +2611,9 @@ pgstat_read_current_status(void)
        localtable = (PgBackendStatus *)
                MemoryContextAlloc(pgStatLocalContext,
                                                   sizeof(PgBackendStatus) * MaxBackends);
+       localappname = (char *)
+               MemoryContextAlloc(pgStatLocalContext,
+                                                  NAMEDATALEN * MaxBackends);
        localactivity = (char *)
                MemoryContextAlloc(pgStatLocalContext,
                                                   pgstat_track_activity_query_size * MaxBackends);
@@ -2380,10 +2638,13 @@ pgstat_read_current_status(void)
                        if (localentry->st_procpid > 0)
                        {
                                memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
+
                                /*
                                 * strcpy is safe even if the string is modified concurrently,
                                 * because there's always a \0 at the end of the buffer.
                                 */
+                               strcpy(localappname, (char *) beentry->st_appname);
+                               localentry->st_appname = localappname;
                                strcpy(localactivity, (char *) beentry->st_activity);
                                localentry->st_activity = localactivity;
                        }
@@ -2401,6 +2662,7 @@ pgstat_read_current_status(void)
                if (localentry->st_procpid > 0)
                {
                        localentry++;
+                       localappname += NAMEDATALEN;
                        localactivity += pgstat_track_activity_query_size;
                        localNumBackends++;
                }
@@ -2415,12 +2677,12 @@ pgstat_read_current_status(void)
  * pgstat_get_backend_current_activity() -
  *
  *     Return a string representing the current activity of the backend with
- *     the specified PID.  This looks directly at the BackendStatusArray,
+ *     the specified PID.      This looks directly at the BackendStatusArray,
  *     and so will provide current information regardless of the age of our
  *     transaction's snapshot of the status array.
  *
  *     It is the caller's responsibility to invoke this only for backends whose
- *     state is expected to remain stable while the result is in use.  The
+ *     state is expected to remain stable while the result is in use.  The
  *     only current use is in deadlock reporting, where we can expect that
  *     the target backend is blocked on a lock.  (There are corner cases
  *     where the target's wait could get aborted while we are looking at it,
@@ -2446,11 +2708,11 @@ pgstat_get_backend_current_activity(int pid, bool checkUser)
                 * must follow the protocol of retrying if st_changecount changes
                 * while we examine the entry, or if it's odd.  (This might be
                 * unnecessary, since fetching or storing an int is almost certainly
-                * atomic, but let's play it safe.)  We use a volatile pointer here
-                * to ensure the compiler doesn't try to get cute.
+                * atomic, but let's play it safe.)  We use a volatile pointer here to
+                * ensure the compiler doesn't try to get cute.
                 */
                volatile PgBackendStatus *vbeentry = beentry;
-               bool    found;
+               bool            found;
 
                for (;;)
                {
@@ -2515,7 +2777,7 @@ pgstat_send(void *msg, int len)
 {
        int                     rc;
 
-       if (pgStatSock < 0)
+       if (pgStatSock == PGINVALID_SOCKET)
                return;
 
        ((PgStat_MsgHdr *) msg)->m_size = len;
@@ -2658,7 +2920,7 @@ PgstatCollectorMain(int argc, char *argv[])
         *
         * For performance reasons, we don't want to do a PostmasterIsAlive() test
         * after every message; instead, do it only when select()/poll() is
-        * interrupted by timeout.  In essence, we'll stay alive as long as
+        * interrupted by timeout.      In essence, we'll stay alive as long as
         * backends keep sending us stuff often, even if the postmaster is gone.
         */
        for (;;)
@@ -2799,6 +3061,18 @@ PgstatCollectorMain(int argc, char *argv[])
                                                                                         len);
                                        break;
 
+                               case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
+                                       pgstat_recv_resetsharedcounter(
+                                                                          (PgStat_MsgResetsharedcounter *) &msg,
+                                                                                                  len);
+                                       break;
+
+                               case PGSTAT_MTYPE_RESETSINGLECOUNTER:
+                                       pgstat_recv_resetsinglecounter(
+                                                                          (PgStat_MsgResetsinglecounter *) &msg,
+                                                                                                  len);
+                                       break;
+
                                case PGSTAT_MTYPE_AUTOVAC_START:
                                        pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
                                        break;
@@ -2815,14 +3089,18 @@ PgstatCollectorMain(int argc, char *argv[])
                                        pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
                                        break;
 
-                               case PGSTAT_MTYPE_FUNCSTAT:
-                                       pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
-                                       break;
+                               case PGSTAT_MTYPE_FUNCSTAT:
+                                       pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
+                                       break;
 
                                case PGSTAT_MTYPE_FUNCPURGE:
                                        pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
                                        break;
 
+                               case PGSTAT_MTYPE_RECOVERYCONFLICT:
+                                       pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
+                                       break;
+
                                default:
                                        break;
                        }
@@ -2899,6 +3177,13 @@ pgstat_get_db_entry(Oid databaseid, bool create)
                result->n_tuples_updated = 0;
                result->n_tuples_deleted = 0;
                result->last_autovac_time = 0;
+               result->n_conflict_tablespace = 0;
+               result->n_conflict_lock = 0;
+               result->n_conflict_snapshot = 0;
+               result->n_conflict_bufferpin = 0;
+               result->n_conflict_startup_deadlock = 0;
+
+               result->stat_reset_timestamp = GetCurrentTimestamp();
 
                memset(&hash_ctl, 0, sizeof(hash_ctl));
                hash_ctl.keysize = sizeof(Oid);
@@ -2922,6 +3207,55 @@ pgstat_get_db_entry(Oid databaseid, bool create)
 }
 
 
+/*
+ * Lookup the hash table entry for the specified table. If no hash
+ * table entry exists, initialize it, if the create parameter is true.
+ * Else, return NULL.
+ */
+static PgStat_StatTabEntry *
+pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
+{
+       PgStat_StatTabEntry *result;
+       bool            found;
+       HASHACTION      action = (create ? HASH_ENTER : HASH_FIND);
+
+       /* Lookup or create the hash table entry for this table */
+       result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
+                                                                                                &tableoid,
+                                                                                                action, &found);
+
+       if (!create && !found)
+               return NULL;
+
+       /* If not found, initialize the new one. */
+       if (!found)
+       {
+               result->numscans = 0;
+               result->tuples_returned = 0;
+               result->tuples_fetched = 0;
+               result->tuples_inserted = 0;
+               result->tuples_updated = 0;
+               result->tuples_deleted = 0;
+               result->tuples_hot_updated = 0;
+               result->n_live_tuples = 0;
+               result->n_dead_tuples = 0;
+               result->changes_since_analyze = 0;
+               result->blocks_fetched = 0;
+               result->blocks_hit = 0;
+               result->vacuum_timestamp = 0;
+               result->vacuum_count = 0;
+               result->autovac_vacuum_timestamp = 0;
+               result->autovac_vacuum_count = 0;
+               result->analyze_timestamp = 0;
+               result->analyze_count = 0;
+               result->autovac_analyze_timestamp = 0;
+               result->autovac_analyze_count = 0;
+       }
+
+       return result;
+}
+
+
 /* ----------
  * pgstat_write_statsfile() -
  *
@@ -2943,8 +3277,8 @@ pgstat_write_statsfile(bool permanent)
        PgStat_StatFuncEntry *funcentry;
        FILE       *fpout;
        int32           format_id;
-       const char *tmpfile = permanent?PGSTAT_STAT_PERMANENT_TMPFILE:pgstat_stat_tmpname;
-       const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:pgstat_stat_filename;
+       const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
+       const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
 
        /*
         * Open the statistics temp file to write out the current values.
@@ -2983,8 +3317,8 @@ pgstat_write_statsfile(bool permanent)
        {
                /*
                 * Write out the DB entry including the number of live backends. We
-                * don't write the tables or functions pointers, since they're of
-                * no use to any other process.
+                * don't write the tables or functions pointers, since they're of no
+                * use to any other process.
                 */
                fputc('D', fpout);
                fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
@@ -3055,13 +3389,26 @@ pgstat_write_statsfile(bool permanent)
                last_statwrite = globalStats.stats_timestamp;
 
                /*
-                * It's not entirely clear whether there could be clock skew between
-                * backends and the collector; but just in case someone manages to
-                * send us a stats request time that's far in the future, reset it.
-                * This ensures that no inquiry message can cause more than one stats
-                * file write to occur.
+                * If there is clock skew between backends and the collector, we could
+                * receive a stats request time that's in the future.  If so, complain
+                * and reset last_statrequest.  Resetting ensures that no inquiry
+                * message can cause more than one stats file write to occur.
                 */
-               last_statrequest = last_statwrite;
+               if (last_statrequest > last_statwrite)
+               {
+                       char       *reqtime;
+                       char       *mytime;
+
+                       /* Copy because timestamptz_to_str returns a static buffer */
+                       reqtime = pstrdup(timestamptz_to_str(last_statrequest));
+                       mytime = pstrdup(timestamptz_to_str(last_statwrite));
+                       elog(LOG, "last_statrequest %s is later than collector's time %s",
+                                reqtime, mytime);
+                       pfree(reqtime);
+                       pfree(mytime);
+
+                       last_statrequest = last_statwrite;
+               }
        }
 
        if (permanent)
@@ -3092,7 +3439,7 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
        FILE       *fpin;
        int32           format_id;
        bool            found;
-       const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:pgstat_stat_filename;
+       const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
 
        /*
         * The tables will live in pgStatLocalContext.
@@ -3116,13 +3463,30 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
         */
        memset(&globalStats, 0, sizeof(globalStats));
 
+       /*
+        * Set the current timestamp (will be kept only in case we can't load an
+        * existing statsfile.
+        */
+       globalStats.stat_reset_timestamp = GetCurrentTimestamp();
+
        /*
         * Try to open the status file. If it doesn't exist, the backends simply
         * return zero for anything and the collector simply starts from scratch
         * with empty counters.
+        *
+        * ENOENT is a possibility if the stats collector is not running or has
+        * not yet written the stats file the first time.  Any other failure
+        * condition is suspicious.
         */
        if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
+       {
+               if (errno != ENOENT)
+                       ereport(pgStatRunningInCollector ? LOG : WARNING,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not open statistics file \"%s\": %m",
+                                                       statfile)));
                return dbhash;
+       }
 
        /*
         * Verify it's of the expected format.
@@ -3131,7 +3495,7 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                || format_id != PGSTAT_FILE_FORMAT_ID)
        {
                ereport(pgStatRunningInCollector ? LOG : WARNING,
-                               (errmsg("corrupted pgstat.stat file")));
+                               (errmsg("corrupted statistics file \"%s\"", statfile)));
                goto done;
        }
 
@@ -3141,7 +3505,7 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
        if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
        {
                ereport(pgStatRunningInCollector ? LOG : WARNING,
-                               (errmsg("corrupted pgstat.stat file")));
+                               (errmsg("corrupted statistics file \"%s\"", statfile)));
                goto done;
        }
 
@@ -3163,7 +3527,8 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                                  fpin) != offsetof(PgStat_StatDBEntry, tables))
                                {
                                        ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                                       (errmsg("corrupted pgstat.stat file")));
+                                                       (errmsg("corrupted statistics file \"%s\"",
+                                                                       statfile)));
                                        goto done;
                                }
 
@@ -3177,7 +3542,8 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                if (found)
                                {
                                        ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                                       (errmsg("corrupted pgstat.stat file")));
+                                                       (errmsg("corrupted statistics file \"%s\"",
+                                                                       statfile)));
                                        goto done;
                                }
 
@@ -3214,6 +3580,7 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                                                                                 PGSTAT_FUNCTION_HASH_SIZE,
                                                                                                 &hash_ctl,
                                                                   HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
+
                                /*
                                 * Arrange that following records add entries to this
                                 * database's hash tables.
@@ -3238,7 +3605,8 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                                  fpin) != sizeof(PgStat_StatTabEntry))
                                {
                                        ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                                       (errmsg("corrupted pgstat.stat file")));
+                                                       (errmsg("corrupted statistics file \"%s\"",
+                                                                       statfile)));
                                        goto done;
                                }
 
@@ -3255,7 +3623,8 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                if (found)
                                {
                                        ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                                       (errmsg("corrupted pgstat.stat file")));
+                                                       (errmsg("corrupted statistics file \"%s\"",
+                                                                       statfile)));
                                        goto done;
                                }
 
@@ -3270,7 +3639,8 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                                  fpin) != sizeof(PgStat_StatFuncEntry))
                                {
                                        ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                                       (errmsg("corrupted pgstat.stat file")));
+                                                       (errmsg("corrupted statistics file \"%s\"",
+                                                                       statfile)));
                                        goto done;
                                }
 
@@ -3281,13 +3651,14 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
                                        break;
 
                                funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
-                                                                                                       (void *) &funcbuf.functionid,
+                                                                                               (void *) &funcbuf.functionid,
                                                                                                                 HASH_ENTER, &found);
 
                                if (found)
                                {
                                        ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                                       (errmsg("corrupted pgstat.stat file")));
+                                                       (errmsg("corrupted statistics file \"%s\"",
+                                                                       statfile)));
                                        goto done;
                                }
 
@@ -3302,7 +3673,8 @@ pgstat_read_statsfile(Oid onlydb, bool permanent)
 
                        default:
                                ereport(pgStatRunningInCollector ? LOG : WARNING,
-                                               (errmsg("corrupted pgstat.stat file")));
+                                               (errmsg("corrupted statistics file \"%s\"",
+                                                               statfile)));
                                goto done;
                }
        }
@@ -3329,13 +3701,21 @@ pgstat_read_statsfile_timestamp(bool permanent, TimestampTz *ts)
        PgStat_GlobalStats myGlobalStats;
        FILE       *fpin;
        int32           format_id;
-       const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:pgstat_stat_filename;
+       const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
 
        /*
-        * Try to open the status file.
+        * Try to open the status file.  As above, anything but ENOENT is worthy
+        * of complaining about.
         */
        if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
+       {
+               if (errno != ENOENT)
+                       ereport(pgStatRunningInCollector ? LOG : WARNING,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not open statistics file \"%s\": %m",
+                                                       statfile)));
                return false;
+       }
 
        /*
         * Verify it's of the expected format.
@@ -3343,6 +3723,8 @@ pgstat_read_statsfile_timestamp(bool permanent, TimestampTz *ts)
        if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
                || format_id != PGSTAT_FILE_FORMAT_ID)
        {
+               ereport(pgStatRunningInCollector ? LOG : WARNING,
+                               (errmsg("corrupted statistics file \"%s\"", statfile)));
                FreeFile(fpin);
                return false;
        }
@@ -3352,6 +3734,8 @@ pgstat_read_statsfile_timestamp(bool permanent, TimestampTz *ts)
         */
        if (fread(&myGlobalStats, 1, sizeof(myGlobalStats), fpin) != sizeof(myGlobalStats))
        {
+               ereport(pgStatRunningInCollector ? LOG : WARNING,
+                               (errmsg("corrupted statistics file \"%s\"", statfile)));
                FreeFile(fpin);
                return false;
        }
@@ -3380,25 +3764,33 @@ backend_read_statsfile(void)
 
        /*
         * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL msec
-        * before now.  This indirectly ensures that the collector needn't write
-        * the file more often than PGSTAT_STAT_INTERVAL.
+        * before now.  This indirectly ensures that the collector needn't write
+        * the file more often than PGSTAT_STAT_INTERVAL.  In an autovacuum
+        * worker, however, we want a lower delay to avoid using stale data, so we
+        * use PGSTAT_RETRY_DELAY (since the number of worker is low, this
+        * shouldn't be a problem).
         *
         * Note that we don't recompute min_ts after sleeping; so we might end up
-        * accepting a file a bit older than PGSTAT_STAT_INTERVAL.  In practice
+        * accepting a file a bit older than PGSTAT_STAT_INTERVAL.      In practice
         * that shouldn't happen, though, as long as the sleep time is less than
         * PGSTAT_STAT_INTERVAL; and we don't want to lie to the collector about
         * what our cutoff time really is.
         */
-       min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
-                                                                                -PGSTAT_STAT_INTERVAL);
+       if (IsAutoVacuumWorkerProcess())
+               min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
+                                                                                        -PGSTAT_RETRY_DELAY);
+       else
+               min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
+                                                                                        -PGSTAT_STAT_INTERVAL);
 
        /*
         * Loop until fresh enough stats file is available or we ran out of time.
-        * The stats inquiry message is sent repeatedly in case collector drops it.
+        * The stats inquiry message is sent repeatedly in case collector drops
+        * it.
         */
        for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
        {
-               TimestampTz file_ts;
+               TimestampTz file_ts = 0;
 
                CHECK_FOR_INTERRUPTS();
 
@@ -3488,7 +3880,6 @@ pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
 static void
 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
 {
-       PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
        PgStat_StatDBEntry *dbentry;
        PgStat_StatTabEntry *tabentry;
        int                     i;
@@ -3507,8 +3898,10 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
         */
        for (i = 0; i < msg->m_nentries; i++)
        {
+               PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
+
                tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
-                                                                                                 (void *) &(tabmsg[i].t_id),
+                                                                                                       (void *) &(tabmsg->t_id),
                                                                                                           HASH_ENTER, &found);
 
                if (!found)
@@ -3517,43 +3910,48 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
                         * If it's a new table entry, initialize counters to the values we
                         * just got.
                         */
-                       tabentry->numscans = tabmsg[i].t_counts.t_numscans;
-                       tabentry->tuples_returned = tabmsg[i].t_counts.t_tuples_returned;
-                       tabentry->tuples_fetched = tabmsg[i].t_counts.t_tuples_fetched;
-                       tabentry->tuples_inserted = tabmsg[i].t_counts.t_tuples_inserted;
-                       tabentry->tuples_updated = tabmsg[i].t_counts.t_tuples_updated;
-                       tabentry->tuples_deleted = tabmsg[i].t_counts.t_tuples_deleted;
-                       tabentry->tuples_hot_updated = tabmsg[i].t_counts.t_tuples_hot_updated;
-                       tabentry->n_live_tuples = tabmsg[i].t_counts.t_new_live_tuples;
-                       tabentry->n_dead_tuples = tabmsg[i].t_counts.t_new_dead_tuples;
-                       tabentry->blocks_fetched = tabmsg[i].t_counts.t_blocks_fetched;
-                       tabentry->blocks_hit = tabmsg[i].t_counts.t_blocks_hit;
-
-                       tabentry->last_anl_tuples = 0;
+                       tabentry->numscans = tabmsg->t_counts.t_numscans;
+                       tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
+                       tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
+                       tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
+                       tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
+                       tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
+                       tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
+                       tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
+                       tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
+                       tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
+                       tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
+                       tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
+
                        tabentry->vacuum_timestamp = 0;
+                       tabentry->vacuum_count = 0;
                        tabentry->autovac_vacuum_timestamp = 0;
+                       tabentry->autovac_vacuum_count = 0;
                        tabentry->analyze_timestamp = 0;
+                       tabentry->analyze_count = 0;
                        tabentry->autovac_analyze_timestamp = 0;
+                       tabentry->autovac_analyze_count = 0;
                }
                else
                {
                        /*
                         * Otherwise add the values to the existing entry.
                         */
-                       tabentry->numscans += tabmsg[i].t_counts.t_numscans;
-                       tabentry->tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
-                       tabentry->tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
-                       tabentry->tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
-                       tabentry->tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
-                       tabentry->tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
-                       tabentry->tuples_hot_updated += tabmsg[i].t_counts.t_tuples_hot_updated;
-                       tabentry->n_live_tuples += tabmsg[i].t_counts.t_new_live_tuples;
-                       tabentry->n_dead_tuples += tabmsg[i].t_counts.t_new_dead_tuples;
-                       tabentry->blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
-                       tabentry->blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
+                       tabentry->numscans += tabmsg->t_counts.t_numscans;
+                       tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
+                       tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
+                       tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
+                       tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
+                       tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
+                       tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
+                       tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
+                       tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
+                       tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
+                       tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
+                       tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
                }
 
-               /* Clamp n_live_tuples in case of negative new_live_tuples */
+               /* Clamp n_live_tuples in case of negative delta_live_tuples */
                tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
                /* Likewise for n_dead_tuples */
                tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
@@ -3561,13 +3959,13 @@ pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
                /*
                 * Add per-table stats to the per-database entry, too.
                 */
-               dbentry->n_tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
-               dbentry->n_tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
-               dbentry->n_tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
-               dbentry->n_tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
-               dbentry->n_tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
-               dbentry->n_blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
-               dbentry->n_blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
+               dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
+               dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
+               dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
+               dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
+               dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
+               dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
+               dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
        }
 }
 
@@ -3672,10 +4070,23 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
 
        dbentry->tables = NULL;
        dbentry->functions = NULL;
+
+       /*
+        * Reset database-level stats too.      This should match the initialization
+        * code in pgstat_get_db_entry().
+        */
        dbentry->n_xact_commit = 0;
        dbentry->n_xact_rollback = 0;
        dbentry->n_blocks_fetched = 0;
        dbentry->n_blocks_hit = 0;
+       dbentry->n_tuples_returned = 0;
+       dbentry->n_tuples_fetched = 0;
+       dbentry->n_tuples_inserted = 0;
+       dbentry->n_tuples_updated = 0;
+       dbentry->n_tuples_deleted = 0;
+       dbentry->last_autovac_time = 0;
+
+       dbentry->stat_reset_timestamp = GetCurrentTimestamp();
 
        memset(&hash_ctl, 0, sizeof(hash_ctl));
        hash_ctl.keysize = sizeof(Oid);
@@ -3696,30 +4107,71 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
 }
 
 /* ----------
- * pgstat_recv_autovac() -
+ * pgstat_recv_resetshared() -
  *
- *     Process an autovacuum signalling message.
+ *     Reset some shared statistics of the cluster.
  * ----------
  */
 static void
-pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
+pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
 {
-       PgStat_StatDBEntry *dbentry;
+       if (msg->m_resettarget == RESET_BGWRITER)
+       {
+               /* Reset the global background writer statistics for the cluster. */
+               memset(&globalStats, 0, sizeof(globalStats));
+               globalStats.stat_reset_timestamp = GetCurrentTimestamp();
+       }
 
        /*
-        * Lookup the database in the hashtable.  Don't create the entry if it
-        * doesn't exist, because autovacuum may be processing a template
-        * database.  If this isn't the case, the database is most likely to have
-        * an entry already.  (If it doesn't, not much harm is done anyway --
-        * it'll get created as soon as somebody actually uses the database.)
+        * Presumably the sender of this message validated the target, don't
+        * complain here if it's not valid
         */
+}
+
+/* ----------
+ * pgstat_recv_resetsinglecounter() -
+ *
+ *     Reset a statistics for a single object
+ * ----------
+ */
+static void
+pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
+{
+       PgStat_StatDBEntry *dbentry;
+
        dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
-       if (dbentry == NULL)
+
+       if (!dbentry)
                return;
 
+       /* Set the reset timestamp for the whole database */
+       dbentry->stat_reset_timestamp = GetCurrentTimestamp();
+
+       /* Remove object if it exists, ignore it if not */
+       if (msg->m_resettype == RESET_TABLE)
+               (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
+                                                  HASH_REMOVE, NULL);
+       else if (msg->m_resettype == RESET_FUNCTION)
+               (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
+                                                  HASH_REMOVE, NULL);
+}
+
+/* ----------
+ * pgstat_recv_autovac() -
+ *
+ *     Process an autovacuum signalling message.
+ * ----------
+ */
+static void
+pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
+{
+       PgStat_StatDBEntry *dbentry;
+
        /*
-        * Store the last autovacuum time in the database entry.
+        * Store the last autovacuum time in the database's hashtable entry.
         */
+       dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
+
        dbentry->last_autovac_time = msg->m_start_time;
 }
 
@@ -3736,39 +4188,25 @@ pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
        PgStat_StatTabEntry *tabentry;
 
        /*
-        * Don't create either the database or table entry if it doesn't already
-        * exist.  This avoids bloating the stats with entries for stuff that is
-        * only touched by vacuum and not by live operations.
+        * Store the data in the table's hashtable entry.
         */
-       dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
-       if (dbentry == NULL)
-               return;
+       dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
 
-       tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
-                                                  HASH_FIND, NULL);
-       if (tabentry == NULL)
-               return;
+       tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
 
-       if (msg->m_autovacuum)
-               tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
-       else
-               tabentry->vacuum_timestamp = msg->m_vacuumtime;
        tabentry->n_live_tuples = msg->m_tuples;
        /* Resetting dead_tuples to 0 is an approximation ... */
        tabentry->n_dead_tuples = 0;
-       if (msg->m_analyze)
+
+       if (msg->m_autovacuum)
        {
-               tabentry->last_anl_tuples = msg->m_tuples;
-               if (msg->m_autovacuum)
-                       tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
-               else
-                       tabentry->analyze_timestamp = msg->m_vacuumtime;
+               tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
+               tabentry->autovac_vacuum_count++;
        }
        else
        {
-               /* last_anl_tuples must never exceed n_live_tuples+n_dead_tuples */
-               tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
-                                                                               msg->m_tuples);
+               tabentry->vacuum_timestamp = msg->m_vacuumtime;
+               tabentry->vacuum_count++;
        }
 }
 
@@ -3785,26 +4223,31 @@ pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
        PgStat_StatTabEntry *tabentry;
 
        /*
-        * Don't create either the database or table entry if it doesn't already
-        * exist.  This avoids bloating the stats with entries for stuff that is
-        * only touched by analyze and not by live operations.
+        * Store the data in the table's hashtable entry.
         */
-       dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
-       if (dbentry == NULL)
-               return;
+       dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
 
-       tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
-                                                  HASH_FIND, NULL);
-       if (tabentry == NULL)
-               return;
+       tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
+
+       tabentry->n_live_tuples = msg->m_live_tuples;
+       tabentry->n_dead_tuples = msg->m_dead_tuples;
+
+       /*
+        * We reset changes_since_analyze to zero, forgetting any changes that
+        * occurred while the ANALYZE was in progress.
+        */
+       tabentry->changes_since_analyze = 0;
 
        if (msg->m_autovacuum)
+       {
                tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
+               tabentry->autovac_analyze_count++;
+       }
        else
+       {
                tabentry->analyze_timestamp = msg->m_analyzetime;
-       tabentry->n_live_tuples = msg->m_live_tuples;
-       tabentry->n_dead_tuples = msg->m_dead_tuples;
-       tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
+               tabentry->analyze_count++;
+       }
 }
 
 
@@ -3823,9 +4266,50 @@ pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
        globalStats.buf_written_clean += msg->m_buf_written_clean;
        globalStats.maxwritten_clean += msg->m_maxwritten_clean;
        globalStats.buf_written_backend += msg->m_buf_written_backend;
+       globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
        globalStats.buf_alloc += msg->m_buf_alloc;
 }
 
+/* ----------
+ * pgstat_recv_recoveryconflict() -
+ *
+ *     Process as RECOVERYCONFLICT message.
+ * ----------
+ */
+static void
+pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
+{
+       PgStat_StatDBEntry *dbentry;
+
+       dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
+
+       switch (msg->m_reason)
+       {
+               case PROCSIG_RECOVERY_CONFLICT_DATABASE:
+
+                       /*
+                        * Since we drop the information about the database as soon as it
+                        * replicates, there is no point in counting these conflicts.
+                        */
+                       break;
+               case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
+                       dbentry->n_conflict_tablespace++;
+                       break;
+               case PROCSIG_RECOVERY_CONFLICT_LOCK:
+                       dbentry->n_conflict_lock++;
+                       break;
+               case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
+                       dbentry->n_conflict_snapshot++;
+                       break;
+               case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
+                       dbentry->n_conflict_bufferpin++;
+                       break;
+               case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
+                       dbentry->n_conflict_startup_deadlock++;
+                       break;
+       }
+}
+
 /* ----------
  * pgstat_recv_funcstat() -
  *
@@ -3849,8 +4333,8 @@ pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
        for (i = 0; i < msg->m_nentries; i++, funcmsg++)
        {
                funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
-                                                                                                 (void *) &(funcmsg->f_id),
-                                                                                                          HASH_ENTER, &found);
+                                                                                                  (void *) &(funcmsg->f_id),
+                                                                                                                HASH_ENTER, &found);
 
                if (!found)
                {