PostgreSQL Source Code  git master
vacuumlazy.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/storage.h"
#include "commands/dbcommands.h"
#include "commands/progress.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "portability/instr_time.h"
#include "postmaster/autovacuum.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "storage/lmgr.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/timestamp.h"
#include "utils/tqual.h"
Include dependency graph for vacuumlazy.c:

Go to the source code of this file.

Data Structures

struct  LVRelStats
 

Macros

#define REL_TRUNCATE_MINIMUM   1000
 
#define REL_TRUNCATE_FRACTION   16
 
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL   20 /* ms */
 
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL   50 /* ms */
 
#define VACUUM_TRUNCATE_LOCK_TIMEOUT   5000 /* ms */
 
#define LAZY_ALLOC_TUPLES   MaxHeapTuplesPerPage
 
#define SKIP_PAGES_THRESHOLD   ((BlockNumber) 32)
 
#define PREFETCH_SIZE   ((BlockNumber) 32)
 
#define FORCE_CHECK_PAGE()   (blkno == nblocks - 1 && should_attempt_truncation(vacrelstats))
 

Typedefs

typedef struct LVRelStats LVRelStats
 

Functions

static void lazy_scan_heap (Relation onerel, int options, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive)
 
static void lazy_vacuum_heap (Relation onerel, LVRelStats *vacrelstats)
 
static bool lazy_check_needs_freeze (Buffer buf, bool *hastup)
 
static void lazy_vacuum_index (Relation indrel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats)
 
static void lazy_cleanup_index (Relation indrel, IndexBulkDeleteResult *stats, LVRelStats *vacrelstats)
 
static int lazy_vacuum_page (Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
 
static bool should_attempt_truncation (LVRelStats *vacrelstats)
 
static void lazy_truncate_heap (Relation onerel, LVRelStats *vacrelstats)
 
static BlockNumber count_nondeletable_pages (Relation onerel, LVRelStats *vacrelstats)
 
static void lazy_space_alloc (LVRelStats *vacrelstats, BlockNumber relblocks)
 
static void lazy_record_dead_tuple (LVRelStats *vacrelstats, ItemPointer itemptr)
 
static bool lazy_tid_reaped (ItemPointer itemptr, void *state)
 
static int vac_cmp_itemptr (const void *left, const void *right)
 
static bool heap_page_is_all_visible (Relation rel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen)
 
void lazy_vacuum_rel (Relation onerel, int options, VacuumParams *params, BufferAccessStrategy bstrategy)
 
static void vacuum_log_cleanup_info (Relation rel, LVRelStats *vacrelstats)
 

Variables

static int elevel = -1
 
static TransactionId OldestXmin
 
static TransactionId FreezeLimit
 
static MultiXactId MultiXactCutoff
 
static BufferAccessStrategy vac_strategy
 

Macro Definition Documentation

◆ FORCE_CHECK_PAGE

#define FORCE_CHECK_PAGE ( )    (blkno == nblocks - 1 && should_attempt_truncation(vacrelstats))

Referenced by lazy_scan_heap().

◆ LAZY_ALLOC_TUPLES

#define LAZY_ALLOC_TUPLES   MaxHeapTuplesPerPage

Definition at line 92 of file vacuumlazy.c.

Referenced by lazy_space_alloc().

◆ PREFETCH_SIZE

#define PREFETCH_SIZE   ((BlockNumber) 32)

Definition at line 104 of file vacuumlazy.c.

Referenced by count_nondeletable_pages().

◆ REL_TRUNCATE_FRACTION

#define REL_TRUNCATE_FRACTION   16

Definition at line 74 of file vacuumlazy.c.

Referenced by should_attempt_truncation().

◆ REL_TRUNCATE_MINIMUM

#define REL_TRUNCATE_MINIMUM   1000

Definition at line 73 of file vacuumlazy.c.

Referenced by should_attempt_truncation().

◆ SKIP_PAGES_THRESHOLD

#define SKIP_PAGES_THRESHOLD   ((BlockNumber) 32)

Definition at line 98 of file vacuumlazy.c.

Referenced by lazy_scan_heap().

◆ VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL

#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL   20 /* ms */

Definition at line 83 of file vacuumlazy.c.

Referenced by count_nondeletable_pages().

◆ VACUUM_TRUNCATE_LOCK_TIMEOUT

#define VACUUM_TRUNCATE_LOCK_TIMEOUT   5000 /* ms */

Definition at line 85 of file vacuumlazy.c.

Referenced by lazy_truncate_heap().

◆ VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL

#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL   50 /* ms */

Definition at line 84 of file vacuumlazy.c.

Referenced by lazy_truncate_heap().

Typedef Documentation

◆ LVRelStats

Function Documentation

◆ count_nondeletable_pages()

static BlockNumber count_nondeletable_pages ( Relation  onerel,
LVRelStats vacrelstats 
)
static

Definition at line 1862 of file vacuumlazy.c.

References AccessExclusiveLock, buf, BUFFER_LOCK_SHARE, BufferGetPage, CHECK_FOR_INTERRUPTS, elevel, ereport, errmsg(), FirstOffsetNumber, INSTR_TIME_GET_MICROSEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, InvalidBlockNumber, ItemIdIsUsed, LVRelStats::lock_waiter_detected, LockBuffer(), LockHasWaitersRelation(), MAIN_FORKNUM, LVRelStats::nonempty_pages, OffsetNumberNext, PageGetItemId, PageGetMaxOffsetNumber, PageIsEmpty, PageIsNew, PREFETCH_SIZE, PrefetchBuffer(), RBM_NORMAL, ReadBufferExtended(), LVRelStats::rel_pages, RelationGetRelationName, StaticAssertStmt, UnlockReleaseBuffer(), and VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL.

Referenced by lazy_truncate_heap().

1863 {
1864  BlockNumber blkno;
1865  BlockNumber prefetchedUntil;
1866  instr_time starttime;
1867 
1868  /* Initialize the starttime if we check for conflicting lock requests */
1869  INSTR_TIME_SET_CURRENT(starttime);
1870 
1871  /*
1872  * Start checking blocks at what we believe relation end to be and move
1873  * backwards. (Strange coding of loop control is needed because blkno is
1874  * unsigned.) To make the scan faster, we prefetch a few blocks at a time
1875  * in forward direction, so that OS-level readahead can kick in.
1876  */
1877  blkno = vacrelstats->rel_pages;
1879  "prefetch size must be power of 2");
1880  prefetchedUntil = InvalidBlockNumber;
1881  while (blkno > vacrelstats->nonempty_pages)
1882  {
1883  Buffer buf;
1884  Page page;
1885  OffsetNumber offnum,
1886  maxoff;
1887  bool hastup;
1888 
1889  /*
1890  * Check if another process requests a lock on our relation. We are
1891  * holding an AccessExclusiveLock here, so they will be waiting. We
1892  * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
1893  * only check if that interval has elapsed once every 32 blocks to
1894  * keep the number of system calls and actual shared lock table
1895  * lookups to a minimum.
1896  */
1897  if ((blkno % 32) == 0)
1898  {
1899  instr_time currenttime;
1900  instr_time elapsed;
1901 
1902  INSTR_TIME_SET_CURRENT(currenttime);
1903  elapsed = currenttime;
1904  INSTR_TIME_SUBTRACT(elapsed, starttime);
1905  if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
1907  {
1909  {
1910  ereport(elevel,
1911  (errmsg("\"%s\": suspending truncate due to conflicting lock request",
1912  RelationGetRelationName(onerel))));
1913 
1914  vacrelstats->lock_waiter_detected = true;
1915  return blkno;
1916  }
1917  starttime = currenttime;
1918  }
1919  }
1920 
1921  /*
1922  * We don't insert a vacuum delay point here, because we have an
1923  * exclusive lock on the table which we want to hold for as short a
1924  * time as possible. We still need to check for interrupts however.
1925  */
1927 
1928  blkno--;
1929 
1930  /* If we haven't prefetched this lot yet, do so now. */
1931  if (prefetchedUntil > blkno)
1932  {
1933  BlockNumber prefetchStart;
1934  BlockNumber pblkno;
1935 
1936  prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
1937  for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
1938  {
1939  PrefetchBuffer(onerel, MAIN_FORKNUM, pblkno);
1941  }
1942  prefetchedUntil = prefetchStart;
1943  }
1944 
1945  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno,
1947 
1948  /* In this phase we only need shared access to the buffer */
1950 
1951  page = BufferGetPage(buf);
1952 
1953  if (PageIsNew(page) || PageIsEmpty(page))
1954  {
1955  /* PageIsNew probably shouldn't happen... */
1956  UnlockReleaseBuffer(buf);
1957  continue;
1958  }
1959 
1960  hastup = false;
1961  maxoff = PageGetMaxOffsetNumber(page);
1962  for (offnum = FirstOffsetNumber;
1963  offnum <= maxoff;
1964  offnum = OffsetNumberNext(offnum))
1965  {
1966  ItemId itemid;
1967 
1968  itemid = PageGetItemId(page, offnum);
1969 
1970  /*
1971  * Note: any non-unused item should be taken as a reason to keep
1972  * this page. We formerly thought that DEAD tuples could be
1973  * thrown away, but that's not so, because we'd not have cleaned
1974  * out their index entries.
1975  */
1976  if (ItemIdIsUsed(itemid))
1977  {
1978  hastup = true;
1979  break; /* can stop scanning */
1980  }
1981  } /* scan along page */
1982 
1983  UnlockReleaseBuffer(buf);
1984 
1985  /* Done scanning if we found a tuple here */
1986  if (hastup)
1987  return blkno + 1;
1988  }
1989 
1990  /*
1991  * If we fall out of the loop, all the previously-thought-to-be-empty
1992  * pages still are; we need not bother to look at the last known-nonempty
1993  * page.
1994  */
1995  return vacrelstats->nonempty_pages;
1996 }
#define PageIsEmpty(page)
Definition: bufpage.h:218
BlockNumber rel_pages
Definition: vacuumlazy.c:112
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
struct timeval instr_time
Definition: instr_time.h:147
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
uint16 OffsetNumber
Definition: off.h:24
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:784
#define PREFETCH_SIZE
Definition: vacuumlazy.c:104
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:167
static char * buf
Definition: pg_test_fsync.c:67
#define FirstOffsetNumber
Definition: off.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:122
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
static int elevel
Definition: vacuumlazy.c:136
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL
Definition: vacuumlazy.c:83
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
void PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:529
bool LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:275
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
#define INSTR_TIME_GET_MICROSEC(t)
Definition: instr_time.h:202
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
#define InvalidBlockNumber
Definition: block.h:33
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
#define AccessExclusiveLock
Definition: lockdefs.h:45
BlockNumber nonempty_pages
Definition: vacuumlazy.c:123
#define PageIsNew(page)
Definition: bufpage.h:225
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:74
bool lock_waiter_detected
Definition: vacuumlazy.c:131

◆ heap_page_is_all_visible()

static bool heap_page_is_all_visible ( Relation  rel,
Buffer  buf,
TransactionId visibility_cutoff_xid,
bool all_frozen 
)
static

Definition at line 2115 of file vacuumlazy.c.

References Assert, BufferGetBlockNumber(), BufferGetPage, elog, ERROR, FirstOffsetNumber, heap_tuple_needs_eventual_freeze(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetXmin, HeapTupleHeaderXminCommitted, HeapTupleSatisfiesVacuum(), InvalidTransactionId, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet, OffsetNumberNext, OldestXmin, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, RelationGetRelid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdFollows(), and TransactionIdPrecedes().

Referenced by lazy_vacuum_page().

2118 {
2119  Page page = BufferGetPage(buf);
2121  OffsetNumber offnum,
2122  maxoff;
2123  bool all_visible = true;
2124 
2125  *visibility_cutoff_xid = InvalidTransactionId;
2126  *all_frozen = true;
2127 
2128  /*
2129  * This is a stripped down version of the line pointer scan in
2130  * lazy_scan_heap(). So if you change anything here, also check that code.
2131  */
2132  maxoff = PageGetMaxOffsetNumber(page);
2133  for (offnum = FirstOffsetNumber;
2134  offnum <= maxoff && all_visible;
2135  offnum = OffsetNumberNext(offnum))
2136  {
2137  ItemId itemid;
2138  HeapTupleData tuple;
2139 
2140  itemid = PageGetItemId(page, offnum);
2141 
2142  /* Unused or redirect line pointers are of no interest */
2143  if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
2144  continue;
2145 
2146  ItemPointerSet(&(tuple.t_self), blockno, offnum);
2147 
2148  /*
2149  * Dead line pointers can have index pointers pointing to them. So
2150  * they can't be treated as visible
2151  */
2152  if (ItemIdIsDead(itemid))
2153  {
2154  all_visible = false;
2155  *all_frozen = false;
2156  break;
2157  }
2158 
2159  Assert(ItemIdIsNormal(itemid));
2160 
2161  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2162  tuple.t_len = ItemIdGetLength(itemid);
2163  tuple.t_tableOid = RelationGetRelid(rel);
2164 
2165  switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
2166  {
2167  case HEAPTUPLE_LIVE:
2168  {
2169  TransactionId xmin;
2170 
2171  /* Check comments in lazy_scan_heap. */
2173  {
2174  all_visible = false;
2175  *all_frozen = false;
2176  break;
2177  }
2178 
2179  /*
2180  * The inserter definitely committed. But is it old enough
2181  * that everyone sees it as committed?
2182  */
2183  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
2184  if (!TransactionIdPrecedes(xmin, OldestXmin))
2185  {
2186  all_visible = false;
2187  *all_frozen = false;
2188  break;
2189  }
2190 
2191  /* Track newest xmin on page. */
2192  if (TransactionIdFollows(xmin, *visibility_cutoff_xid))
2193  *visibility_cutoff_xid = xmin;
2194 
2195  /* Check whether this tuple is already frozen or not */
2196  if (all_visible && *all_frozen &&
2198  *all_frozen = false;
2199  }
2200  break;
2201 
2202  case HEAPTUPLE_DEAD:
2206  {
2207  all_visible = false;
2208  *all_frozen = false;
2209  break;
2210  }
2211  default:
2212  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
2213  break;
2214  }
2215  } /* scan along page */
2216 
2217  return all_visible;
2218 }
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:105
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:463
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
Definition: tqual.c:1164
uint32 BlockNumber
Definition: block.h:31
#define ItemIdIsDead(itemId)
Definition: itemid.h:112
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition: heapam.c:7296
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:323
uint32 t_len
Definition: htup.h:64
static char * buf
Definition: pg_test_fsync.c:67
#define FirstOffsetNumber
Definition: off.h:27
#define InvalidTransactionId
Definition: transam.h:31
static TransactionId OldestXmin
Definition: vacuumlazy.c:138
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
#define Assert(condition)
Definition: c.h:688
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:312
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2605
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:425
#define PageGetItem(page, itemId)
Definition: bufpage.h:336
Pointer Page
Definition: bufpage.h:74
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:105

◆ lazy_check_needs_freeze()

static bool lazy_check_needs_freeze ( Buffer  buf,
bool hastup 
)
static

Definition at line 1563 of file vacuumlazy.c.

References BufferGetPage, FirstOffsetNumber, FreezeLimit, heap_tuple_needs_freeze(), ItemIdIsNormal, ItemIdIsUsed, MultiXactCutoff, OffsetNumberNext, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageIsEmpty, and PageIsNew.

Referenced by lazy_scan_heap().

1564 {
1565  Page page = BufferGetPage(buf);
1566  OffsetNumber offnum,
1567  maxoff;
1568  HeapTupleHeader tupleheader;
1569 
1570  *hastup = false;
1571 
1572  /* If we hit an uninitialized page, we want to force vacuuming it. */
1573  if (PageIsNew(page))
1574  return true;
1575 
1576  /* Quick out for ordinary empty page. */
1577  if (PageIsEmpty(page))
1578  return false;
1579 
1580  maxoff = PageGetMaxOffsetNumber(page);
1581  for (offnum = FirstOffsetNumber;
1582  offnum <= maxoff;
1583  offnum = OffsetNumberNext(offnum))
1584  {
1585  ItemId itemid;
1586 
1587  itemid = PageGetItemId(page, offnum);
1588 
1589  /* this should match hastup test in count_nondeletable_pages() */
1590  if (ItemIdIsUsed(itemid))
1591  *hastup = true;
1592 
1593  /* dead and redirect items never need freezing */
1594  if (!ItemIdIsNormal(itemid))
1595  continue;
1596 
1597  tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
1598 
1599  if (heap_tuple_needs_freeze(tupleheader, FreezeLimit,
1600  MultiXactCutoff, buf))
1601  return true;
1602  } /* scan along page */
1603 
1604  return false;
1605 }
#define PageIsEmpty(page)
Definition: bufpage.h:218
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
uint16 OffsetNumber
Definition: off.h:24
static TransactionId FreezeLimit
Definition: vacuumlazy.c:139
static char * buf
Definition: pg_test_fsync.c:67
#define FirstOffsetNumber
Definition: off.h:27
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:140
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
bool heap_tuple_needs_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, Buffer buf)
Definition: heapam.c:7349
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
#define PageIsNew(page)
Definition: bufpage.h:225
#define PageGetItem(page, itemId)
Definition: bufpage.h:336
Pointer Page
Definition: bufpage.h:74

◆ lazy_cleanup_index()

static void lazy_cleanup_index ( Relation  indrel,
IndexBulkDeleteResult stats,
LVRelStats vacrelstats 
)
static

Definition at line 1646 of file vacuumlazy.c.

References IndexVacuumInfo::analyze_only, elevel, ereport, errdetail(), errmsg(), IndexVacuumInfo::estimated_count, IndexBulkDeleteResult::estimated_count, IndexVacuumInfo::index, index_vacuum_cleanup(), InvalidMultiXactId, InvalidTransactionId, IndexVacuumInfo::message_level, LVRelStats::new_rel_tuples, IndexVacuumInfo::num_heap_tuples, IndexBulkDeleteResult::num_index_tuples, IndexBulkDeleteResult::num_pages, IndexBulkDeleteResult::pages_deleted, IndexBulkDeleteResult::pages_free, pfree(), pg_rusage_init(), pg_rusage_show(), LVRelStats::rel_pages, RelationGetRelationName, IndexVacuumInfo::strategy, LVRelStats::tupcount_pages, IndexBulkDeleteResult::tuples_removed, vac_strategy, and vac_update_relstats().

Referenced by lazy_scan_heap().

1649 {
1650  IndexVacuumInfo ivinfo;
1651  PGRUsage ru0;
1652 
1653  pg_rusage_init(&ru0);
1654 
1655  ivinfo.index = indrel;
1656  ivinfo.analyze_only = false;
1657  ivinfo.estimated_count = (vacrelstats->tupcount_pages < vacrelstats->rel_pages);
1658  ivinfo.message_level = elevel;
1659  ivinfo.num_heap_tuples = vacrelstats->new_rel_tuples;
1660  ivinfo.strategy = vac_strategy;
1661 
1662  stats = index_vacuum_cleanup(&ivinfo, stats);
1663 
1664  if (!stats)
1665  return;
1666 
1667  /*
1668  * Now update statistics in pg_class, but only if the index says the count
1669  * is accurate.
1670  */
1671  if (!stats->estimated_count)
1672  vac_update_relstats(indrel,
1673  stats->num_pages,
1674  stats->num_index_tuples,
1675  0,
1676  false,
1679  false);
1680 
1681  ereport(elevel,
1682  (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
1683  RelationGetRelationName(indrel),
1684  stats->num_index_tuples,
1685  stats->num_pages),
1686  errdetail("%.0f index row versions were removed.\n"
1687  "%u index pages have been deleted, %u are currently reusable.\n"
1688  "%s.",
1689  stats->tuples_removed,
1690  stats->pages_deleted, stats->pages_free,
1691  pg_rusage_show(&ru0))));
1692 
1693  pfree(stats);
1694 }
double new_rel_tuples
Definition: vacuumlazy.c:119
double tuples_removed
Definition: genam.h:77
BlockNumber rel_pages
Definition: vacuumlazy.c:112
bool analyze_only
Definition: genam.h:47
BlockNumber tupcount_pages
Definition: vacuumlazy.c:116
BufferAccessStrategy strategy
Definition: genam.h:51
Relation index
Definition: genam.h:46
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void pfree(void *pointer)
Definition: mcxt.c:936
BlockNumber num_pages
Definition: genam.h:73
BlockNumber pages_free
Definition: genam.h:79
int errdetail(const char *fmt,...)
Definition: elog.c:873
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:445
BlockNumber pages_deleted
Definition: genam.h:78
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
#define InvalidMultiXactId
Definition: multixact.h:23
int message_level
Definition: genam.h:49
double num_heap_tuples
Definition: genam.h:50
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:765
int errmsg(const char *fmt,...)
Definition: elog.c:797
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:878
double num_index_tuples
Definition: genam.h:76
bool estimated_count
Definition: genam.h:75
bool estimated_count
Definition: genam.h:48

◆ lazy_record_dead_tuple()

static void lazy_record_dead_tuple ( LVRelStats vacrelstats,
ItemPointer  itemptr 
)
static

Definition at line 2039 of file vacuumlazy.c.

References LVRelStats::dead_tuples, LVRelStats::max_dead_tuples, LVRelStats::num_dead_tuples, pgstat_progress_update_param(), and PROGRESS_VACUUM_NUM_DEAD_TUPLES.

Referenced by lazy_scan_heap().

2041 {
2042  /*
2043  * The array shouldn't overflow under normal behavior, but perhaps it
2044  * could if we are given a really small maintenance_work_mem. In that
2045  * case, just forget the last few tuples (we'll get 'em next time).
2046  */
2047  if (vacrelstats->num_dead_tuples < vacrelstats->max_dead_tuples)
2048  {
2049  vacrelstats->dead_tuples[vacrelstats->num_dead_tuples] = *itemptr;
2050  vacrelstats->num_dead_tuples++;
2052  vacrelstats->num_dead_tuples);
2053  }
2054 }
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3093
int max_dead_tuples
Definition: vacuumlazy.c:127
ItemPointer dead_tuples
Definition: vacuumlazy.c:128
int num_dead_tuples
Definition: vacuumlazy.c:126
#define PROGRESS_VACUUM_NUM_DEAD_TUPLES
Definition: progress.h:27

◆ lazy_scan_heap()

static void lazy_scan_heap ( Relation  onerel,
int  options,
LVRelStats vacrelstats,
Relation Irel,
int  nindexes,
bool  aggressive 
)
static

Definition at line 463 of file vacuumlazy.c.

References _, appendStringInfo(), Assert, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, BufferGetPageSize, BufferIsValid, ConditionalLockBufferForCleanup(), StringInfoData::data, elevel, elog, END_CRIT_SECTION, ereport, errdetail_internal(), errmsg(), ERROR, ExclusiveLock, FirstOffsetNumber, FORCE_CHECK_PAGE, FreezeLimit, LVRelStats::frozenskipped_pages, get_namespace_name(), heap_execute_freeze_tuple(), heap_page_prune(), heap_prepare_freeze_tuple(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleGetOid, HeapTupleHeaderAdvanceLatestRemovedXid(), HeapTupleHeaderGetXmin, HeapTupleHeaderXminCommitted, HeapTupleIsHeapOnly, HeapTupleIsHotUpdated, HeapTupleSatisfiesVacuum(), i, initStringInfo(), InvalidBuffer, InvalidTransactionId, InvalidXLogRecPtr, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet, LVRelStats::latestRemovedXid, lazy_check_needs_freeze(), lazy_cleanup_index(), lazy_record_dead_tuple(), lazy_space_alloc(), lazy_vacuum_heap(), lazy_vacuum_index(), lazy_vacuum_page(), LockBuffer(), LockBufferForCleanup(), LockRelationForExtension(), log_heap_freeze(), log_newpage_buffer(), MAIN_FORKNUM, MarkBufferDirty(), LVRelStats::max_dead_tuples, MaxHeapTuplesPerPage, MultiXactCutoff, LVRelStats::new_dead_tuples, LVRelStats::new_rel_tuples, ngettext, LVRelStats::nonempty_pages, LVRelStats::num_dead_tuples, LVRelStats::num_index_scans, xl_heap_freeze_tuple::offset, OffsetNumberNext, OidIsValid, OldestXmin, PageClearAllVisible, PageGetHeapFreeSpace(), PageGetItem, PageGetItemId, PageGetLSN, PageGetMaxOffsetNumber, PageInit(), PageIsAllVisible, PageIsEmpty, PageIsNew, PageSetAllVisible, PageSetLSN, palloc(), palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), LVRelStats::pinskipped_pages, PROGRESS_VACUUM_HEAP_BLKS_SCANNED, PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, PROGRESS_VACUUM_MAX_DEAD_TUPLES, PROGRESS_VACUUM_NUM_INDEX_VACUUMS, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_INDEX_CLEANUP, PROGRESS_VACUUM_PHASE_SCAN_HEAP, PROGRESS_VACUUM_PHASE_VACUUM_HEAP, PROGRESS_VACUUM_PHASE_VACUUM_INDEX, PROGRESS_VACUUM_TOTAL_HEAP_BLKS, RBM_NORMAL, RelationData::rd_rel, ReadBufferExtended(), RecordPageWithFreeSpace(), LVRelStats::rel_pages, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), LVRelStats::scanned_pages, LVRelStats::scanned_tuples, SKIP_PAGES_THRESHOLD, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdFollows(), TransactionIdPrecedes(), LVRelStats::tupcount_pages, LVRelStats::tuples_deleted, UnlockRelationForExtension(), UnlockReleaseBuffer(), vac_estimate_reltuples(), VACOPT_DISABLE_PAGE_SKIPPING, vacuum_delay_point(), vacuum_log_cleanup_info(), VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_set(), VISIBILITYMAP_VALID_BITS, VM_ALL_FROZEN, VM_ALL_VISIBLE, and WARNING.

Referenced by lazy_vacuum_rel().

465 {
466  BlockNumber nblocks,
467  blkno;
468  HeapTupleData tuple;
469  char *relname;
470  TransactionId relfrozenxid = onerel->rd_rel->relfrozenxid;
471  TransactionId relminmxid = onerel->rd_rel->relminmxid;
472  BlockNumber empty_pages,
473  vacuumed_pages;
474  double num_tuples,
475  tups_vacuumed,
476  nkeep,
477  nunused;
478  IndexBulkDeleteResult **indstats;
479  int i;
480  PGRUsage ru0;
481  Buffer vmbuffer = InvalidBuffer;
482  BlockNumber next_unskippable_block;
483  bool skipping_blocks;
484  xl_heap_freeze_tuple *frozen;
486  const int initprog_index[] = {
490  };
491  int64 initprog_val[3];
492 
493  pg_rusage_init(&ru0);
494 
495  relname = RelationGetRelationName(onerel);
496  if (aggressive)
497  ereport(elevel,
498  (errmsg("aggressively vacuuming \"%s.%s\"",
500  relname)));
501  else
502  ereport(elevel,
503  (errmsg("vacuuming \"%s.%s\"",
505  relname)));
506 
507  empty_pages = vacuumed_pages = 0;
508  num_tuples = tups_vacuumed = nkeep = nunused = 0;
509 
510  indstats = (IndexBulkDeleteResult **)
511  palloc0(nindexes * sizeof(IndexBulkDeleteResult *));
512 
513  nblocks = RelationGetNumberOfBlocks(onerel);
514  vacrelstats->rel_pages = nblocks;
515  vacrelstats->scanned_pages = 0;
516  vacrelstats->tupcount_pages = 0;
517  vacrelstats->nonempty_pages = 0;
518  vacrelstats->latestRemovedXid = InvalidTransactionId;
519 
520  lazy_space_alloc(vacrelstats, nblocks);
522 
523  /* Report that we're scanning the heap, advertising total # of blocks */
524  initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
525  initprog_val[1] = nblocks;
526  initprog_val[2] = vacrelstats->max_dead_tuples;
527  pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
528 
529  /*
530  * Except when aggressive is set, we want to skip pages that are
531  * all-visible according to the visibility map, but only when we can skip
532  * at least SKIP_PAGES_THRESHOLD consecutive pages. Since we're reading
533  * sequentially, the OS should be doing readahead for us, so there's no
534  * gain in skipping a page now and then; that's likely to disable
535  * readahead and so be counterproductive. Also, skipping even a single
536  * page means that we can't update relfrozenxid, so we only want to do it
537  * if we can skip a goodly number of pages.
538  *
539  * When aggressive is set, we can't skip pages just because they are
540  * all-visible, but we can still skip pages that are all-frozen, since
541  * such pages do not need freezing and do not affect the value that we can
542  * safely set for relfrozenxid or relminmxid.
543  *
544  * Before entering the main loop, establish the invariant that
545  * next_unskippable_block is the next block number >= blkno that we can't
546  * skip based on the visibility map, either all-visible for a regular scan
547  * or all-frozen for an aggressive scan. We set it to nblocks if there's
548  * no such block. We also set up the skipping_blocks flag correctly at
549  * this stage.
550  *
551  * Note: The value returned by visibilitymap_get_status could be slightly
552  * out-of-date, since we make this test before reading the corresponding
553  * heap page or locking the buffer. This is OK. If we mistakenly think
554  * that the page is all-visible or all-frozen when in fact the flag's just
555  * been cleared, we might fail to vacuum the page. It's easy to see that
556  * skipping a page when aggressive is not set is not a very big deal; we
557  * might leave some dead tuples lying around, but the next vacuum will
558  * find them. But even when aggressive *is* set, it's still OK if we miss
559  * a page whose all-frozen marking has just been cleared. Any new XIDs
560  * just added to that page are necessarily newer than the GlobalXmin we
561  * computed, so they'll have no effect on the value to which we can safely
562  * set relfrozenxid. A similar argument applies for MXIDs and relminmxid.
563  *
564  * We will scan the table's last page, at least to the extent of
565  * determining whether it has tuples or not, even if it should be skipped
566  * according to the above rules; except when we've already determined that
567  * it's not worth trying to truncate the table. This avoids having
568  * lazy_truncate_heap() take access-exclusive lock on the table to attempt
569  * a truncation that just fails immediately because there are tuples in
570  * the last page. This is worth avoiding mainly because such a lock must
571  * be replayed on any hot standby, where it can be disruptive.
572  */
573  next_unskippable_block = 0;
575  {
576  while (next_unskippable_block < nblocks)
577  {
578  uint8 vmstatus;
579 
580  vmstatus = visibilitymap_get_status(onerel, next_unskippable_block,
581  &vmbuffer);
582  if (aggressive)
583  {
584  if ((vmstatus & VISIBILITYMAP_ALL_FROZEN) == 0)
585  break;
586  }
587  else
588  {
589  if ((vmstatus & VISIBILITYMAP_ALL_VISIBLE) == 0)
590  break;
591  }
593  next_unskippable_block++;
594  }
595  }
596 
597  if (next_unskippable_block >= SKIP_PAGES_THRESHOLD)
598  skipping_blocks = true;
599  else
600  skipping_blocks = false;
601 
602  for (blkno = 0; blkno < nblocks; blkno++)
603  {
604  Buffer buf;
605  Page page;
606  OffsetNumber offnum,
607  maxoff;
608  bool tupgone,
609  hastup;
610  int prev_dead_count;
611  int nfrozen;
612  Size freespace;
613  bool all_visible_according_to_vm = false;
614  bool all_visible;
615  bool all_frozen = true; /* provided all_visible is also true */
616  bool has_dead_tuples;
617  TransactionId visibility_cutoff_xid = InvalidTransactionId;
618 
619  /* see note above about forcing scanning of last page */
620 #define FORCE_CHECK_PAGE() \
621  (blkno == nblocks - 1 && should_attempt_truncation(vacrelstats))
622 
624 
625  if (blkno == next_unskippable_block)
626  {
627  /* Time to advance next_unskippable_block */
628  next_unskippable_block++;
629  if ((options & VACOPT_DISABLE_PAGE_SKIPPING) == 0)
630  {
631  while (next_unskippable_block < nblocks)
632  {
633  uint8 vmskipflags;
634 
635  vmskipflags = visibilitymap_get_status(onerel,
636  next_unskippable_block,
637  &vmbuffer);
638  if (aggressive)
639  {
640  if ((vmskipflags & VISIBILITYMAP_ALL_FROZEN) == 0)
641  break;
642  }
643  else
644  {
645  if ((vmskipflags & VISIBILITYMAP_ALL_VISIBLE) == 0)
646  break;
647  }
649  next_unskippable_block++;
650  }
651  }
652 
653  /*
654  * We know we can't skip the current block. But set up
655  * skipping_blocks to do the right thing at the following blocks.
656  */
657  if (next_unskippable_block - blkno > SKIP_PAGES_THRESHOLD)
658  skipping_blocks = true;
659  else
660  skipping_blocks = false;
661 
662  /*
663  * Normally, the fact that we can't skip this block must mean that
664  * it's not all-visible. But in an aggressive vacuum we know only
665  * that it's not all-frozen, so it might still be all-visible.
666  */
667  if (aggressive && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer))
668  all_visible_according_to_vm = true;
669  }
670  else
671  {
672  /*
673  * The current block is potentially skippable; if we've seen a
674  * long enough run of skippable blocks to justify skipping it, and
675  * we're not forced to check it, then go ahead and skip.
676  * Otherwise, the page must be at least all-visible if not
677  * all-frozen, so we can set all_visible_according_to_vm = true.
678  */
679  if (skipping_blocks && !FORCE_CHECK_PAGE())
680  {
681  /*
682  * Tricky, tricky. If this is in aggressive vacuum, the page
683  * must have been all-frozen at the time we checked whether it
684  * was skippable, but it might not be any more. We must be
685  * careful to count it as a skipped all-frozen page in that
686  * case, or else we'll think we can't update relfrozenxid and
687  * relminmxid. If it's not an aggressive vacuum, we don't
688  * know whether it was all-frozen, so we have to recheck; but
689  * in this case an approximate answer is OK.
690  */
691  if (aggressive || VM_ALL_FROZEN(onerel, blkno, &vmbuffer))
692  vacrelstats->frozenskipped_pages++;
693  continue;
694  }
695  all_visible_according_to_vm = true;
696  }
697 
699 
700  /*
701  * If we are close to overrunning the available space for dead-tuple
702  * TIDs, pause and do a cycle of vacuuming before we tackle this page.
703  */
704  if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MaxHeapTuplesPerPage &&
705  vacrelstats->num_dead_tuples > 0)
706  {
707  const int hvp_index[] = {
710  };
711  int64 hvp_val[2];
712 
713  /*
714  * Before beginning index vacuuming, we release any pin we may
715  * hold on the visibility map page. This isn't necessary for
716  * correctness, but we do it anyway to avoid holding the pin
717  * across a lengthy, unrelated operation.
718  */
719  if (BufferIsValid(vmbuffer))
720  {
721  ReleaseBuffer(vmbuffer);
722  vmbuffer = InvalidBuffer;
723  }
724 
725  /* Log cleanup info before we touch indexes */
726  vacuum_log_cleanup_info(onerel, vacrelstats);
727 
728  /* Report that we are now vacuuming indexes */
731 
732  /* Remove index entries */
733  for (i = 0; i < nindexes; i++)
734  lazy_vacuum_index(Irel[i],
735  &indstats[i],
736  vacrelstats);
737 
738  /*
739  * Report that we are now vacuuming the heap. We also increase
740  * the number of index scans here; note that by using
741  * pgstat_progress_update_multi_param we can update both
742  * parameters atomically.
743  */
745  hvp_val[1] = vacrelstats->num_index_scans + 1;
746  pgstat_progress_update_multi_param(2, hvp_index, hvp_val);
747 
748  /* Remove tuples from heap */
749  lazy_vacuum_heap(onerel, vacrelstats);
750 
751  /*
752  * Forget the now-vacuumed tuples, and press on, but be careful
753  * not to reset latestRemovedXid since we want that value to be
754  * valid.
755  */
756  vacrelstats->num_dead_tuples = 0;
757  vacrelstats->num_index_scans++;
758 
759  /* Report that we are once again scanning the heap */
762  }
763 
764  /*
765  * Pin the visibility map page in case we need to mark the page
766  * all-visible. In most cases this will be very cheap, because we'll
767  * already have the correct page pinned anyway. However, it's
768  * possible that (a) next_unskippable_block is covered by a different
769  * VM page than the current block or (b) we released our pin and did a
770  * cycle of index vacuuming.
771  *
772  */
773  visibilitymap_pin(onerel, blkno, &vmbuffer);
774 
775  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno,
777 
778  /* We need buffer cleanup lock so that we can prune HOT chains. */
780  {
781  /*
782  * If we're not performing an aggressive scan to guard against XID
783  * wraparound, and we don't want to forcibly check the page, then
784  * it's OK to skip vacuuming pages we get a lock conflict on. They
785  * will be dealt with in some future vacuum.
786  */
787  if (!aggressive && !FORCE_CHECK_PAGE())
788  {
789  ReleaseBuffer(buf);
790  vacrelstats->pinskipped_pages++;
791  continue;
792  }
793 
794  /*
795  * Read the page with share lock to see if any xids on it need to
796  * be frozen. If not we just skip the page, after updating our
797  * scan statistics. If there are some, we wait for cleanup lock.
798  *
799  * We could defer the lock request further by remembering the page
800  * and coming back to it later, or we could even register
801  * ourselves for multiple buffers and then service whichever one
802  * is received first. For now, this seems good enough.
803  *
804  * If we get here with aggressive false, then we're just forcibly
805  * checking the page, and so we don't want to insist on getting
806  * the lock; we only need to know if the page contains tuples, so
807  * that we can update nonempty_pages correctly. It's convenient
808  * to use lazy_check_needs_freeze() for both situations, though.
809  */
811  if (!lazy_check_needs_freeze(buf, &hastup))
812  {
813  UnlockReleaseBuffer(buf);
814  vacrelstats->scanned_pages++;
815  vacrelstats->pinskipped_pages++;
816  if (hastup)
817  vacrelstats->nonempty_pages = blkno + 1;
818  continue;
819  }
820  if (!aggressive)
821  {
822  /*
823  * Here, we must not advance scanned_pages; that would amount
824  * to claiming that the page contains no freezable tuples.
825  */
826  UnlockReleaseBuffer(buf);
827  vacrelstats->pinskipped_pages++;
828  if (hastup)
829  vacrelstats->nonempty_pages = blkno + 1;
830  continue;
831  }
834  /* drop through to normal processing */
835  }
836 
837  vacrelstats->scanned_pages++;
838  vacrelstats->tupcount_pages++;
839 
840  page = BufferGetPage(buf);
841 
842  if (PageIsNew(page))
843  {
844  /*
845  * An all-zeroes page could be left over if a backend extends the
846  * relation but crashes before initializing the page. Reclaim such
847  * pages for use.
848  *
849  * We have to be careful here because we could be looking at a
850  * page that someone has just added to the relation and not yet
851  * been able to initialize (see RelationGetBufferForTuple). To
852  * protect against that, release the buffer lock, grab the
853  * relation extension lock momentarily, and re-lock the buffer. If
854  * the page is still uninitialized by then, it must be left over
855  * from a crashed backend, and we can initialize it.
856  *
857  * We don't really need the relation lock when this is a new or
858  * temp relation, but it's probably not worth the code space to
859  * check that, since this surely isn't a critical path.
860  *
861  * Note: the comparable code in vacuum.c need not worry because
862  * it's got exclusive lock on the whole relation.
863  */
868  if (PageIsNew(page))
869  {
871  (errmsg("relation \"%s\" page %u is uninitialized --- fixing",
872  relname, blkno)));
873  PageInit(page, BufferGetPageSize(buf), 0);
874  empty_pages++;
875  }
876  freespace = PageGetHeapFreeSpace(page);
877  MarkBufferDirty(buf);
878  UnlockReleaseBuffer(buf);
879 
880  RecordPageWithFreeSpace(onerel, blkno, freespace);
881  continue;
882  }
883 
884  if (PageIsEmpty(page))
885  {
886  empty_pages++;
887  freespace = PageGetHeapFreeSpace(page);
888 
889  /* empty pages are always all-visible and all-frozen */
890  if (!PageIsAllVisible(page))
891  {
893 
894  /* mark buffer dirty before writing a WAL record */
895  MarkBufferDirty(buf);
896 
897  /*
898  * It's possible that another backend has extended the heap,
899  * initialized the page, and then failed to WAL-log the page
900  * due to an ERROR. Since heap extension is not WAL-logged,
901  * recovery might try to replay our record setting the page
902  * all-visible and find that the page isn't initialized, which
903  * will cause a PANIC. To prevent that, check whether the
904  * page has been previously WAL-logged, and if not, do that
905  * now.
906  */
907  if (RelationNeedsWAL(onerel) &&
908  PageGetLSN(page) == InvalidXLogRecPtr)
909  log_newpage_buffer(buf, true);
910 
911  PageSetAllVisible(page);
912  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
913  vmbuffer, InvalidTransactionId,
916  }
917 
918  UnlockReleaseBuffer(buf);
919  RecordPageWithFreeSpace(onerel, blkno, freespace);
920  continue;
921  }
922 
923  /*
924  * Prune all HOT-update chains in this page.
925  *
926  * We count tuples removed by the pruning step as removed by VACUUM.
927  */
928  tups_vacuumed += heap_page_prune(onerel, buf, OldestXmin, false,
929  &vacrelstats->latestRemovedXid);
930 
931  /*
932  * Now scan the page to collect vacuumable items and check for tuples
933  * requiring freezing.
934  */
935  all_visible = true;
936  has_dead_tuples = false;
937  nfrozen = 0;
938  hastup = false;
939  prev_dead_count = vacrelstats->num_dead_tuples;
940  maxoff = PageGetMaxOffsetNumber(page);
941 
942  /*
943  * Note: If you change anything in the loop below, also look at
944  * heap_page_is_all_visible to see if that needs to be changed.
945  */
946  for (offnum = FirstOffsetNumber;
947  offnum <= maxoff;
948  offnum = OffsetNumberNext(offnum))
949  {
950  ItemId itemid;
951 
952  itemid = PageGetItemId(page, offnum);
953 
954  /* Unused items require no processing, but we count 'em */
955  if (!ItemIdIsUsed(itemid))
956  {
957  nunused += 1;
958  continue;
959  }
960 
961  /* Redirect items mustn't be touched */
962  if (ItemIdIsRedirected(itemid))
963  {
964  hastup = true; /* this page won't be truncatable */
965  continue;
966  }
967 
968  ItemPointerSet(&(tuple.t_self), blkno, offnum);
969 
970  /*
971  * DEAD item pointers are to be vacuumed normally; but we don't
972  * count them in tups_vacuumed, else we'd be double-counting (at
973  * least in the common case where heap_page_prune() just freed up
974  * a non-HOT tuple).
975  */
976  if (ItemIdIsDead(itemid))
977  {
978  lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
979  all_visible = false;
980  continue;
981  }
982 
983  Assert(ItemIdIsNormal(itemid));
984 
985  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
986  tuple.t_len = ItemIdGetLength(itemid);
987  tuple.t_tableOid = RelationGetRelid(onerel);
988 
989  tupgone = false;
990 
991  switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
992  {
993  case HEAPTUPLE_DEAD:
994 
995  /*
996  * Ordinarily, DEAD tuples would have been removed by
997  * heap_page_prune(), but it's possible that the tuple
998  * state changed since heap_page_prune() looked. In
999  * particular an INSERT_IN_PROGRESS tuple could have
1000  * changed to DEAD if the inserter aborted. So this
1001  * cannot be considered an error condition.
1002  *
1003  * If the tuple is HOT-updated then it must only be
1004  * removed by a prune operation; so we keep it just as if
1005  * it were RECENTLY_DEAD. Also, if it's a heap-only
1006  * tuple, we choose to keep it, because it'll be a lot
1007  * cheaper to get rid of it in the next pruning pass than
1008  * to treat it like an indexed tuple.
1009  *
1010  * If this were to happen for a tuple that actually needed
1011  * to be deleted, we'd be in trouble, because it'd
1012  * possibly leave a tuple below the relation's xmin
1013  * horizon alive. heap_prepare_freeze_tuple() is prepared
1014  * to detect that case and abort the transaction,
1015  * preventing corruption.
1016  */
1017  if (HeapTupleIsHotUpdated(&tuple) ||
1018  HeapTupleIsHeapOnly(&tuple))
1019  nkeep += 1;
1020  else
1021  tupgone = true; /* we can delete the tuple */
1022  all_visible = false;
1023  break;
1024  case HEAPTUPLE_LIVE:
1025  /* Tuple is good --- but let's do some validity checks */
1026  if (onerel->rd_rel->relhasoids &&
1027  !OidIsValid(HeapTupleGetOid(&tuple)))
1028  elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid",
1029  relname, blkno, offnum);
1030 
1031  /*
1032  * Is the tuple definitely visible to all transactions?
1033  *
1034  * NB: Like with per-tuple hint bits, we can't set the
1035  * PD_ALL_VISIBLE flag if the inserter committed
1036  * asynchronously. See SetHintBits for more info. Check
1037  * that the tuple is hinted xmin-committed because of
1038  * that.
1039  */
1040  if (all_visible)
1041  {
1042  TransactionId xmin;
1043 
1045  {
1046  all_visible = false;
1047  break;
1048  }
1049 
1050  /*
1051  * The inserter definitely committed. But is it old
1052  * enough that everyone sees it as committed?
1053  */
1054  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
1055  if (!TransactionIdPrecedes(xmin, OldestXmin))
1056  {
1057  all_visible = false;
1058  break;
1059  }
1060 
1061  /* Track newest xmin on page. */
1062  if (TransactionIdFollows(xmin, visibility_cutoff_xid))
1063  visibility_cutoff_xid = xmin;
1064  }
1065  break;
1067 
1068  /*
1069  * If tuple is recently deleted then we must not remove it
1070  * from relation.
1071  */
1072  nkeep += 1;
1073  all_visible = false;
1074  break;
1076  /* This is an expected case during concurrent vacuum */
1077  all_visible = false;
1078  break;
1080  /* This is an expected case during concurrent vacuum */
1081  all_visible = false;
1082  break;
1083  default:
1084  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1085  break;
1086  }
1087 
1088  if (tupgone)
1089  {
1090  lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
1092  &vacrelstats->latestRemovedXid);
1093  tups_vacuumed += 1;
1094  has_dead_tuples = true;
1095  }
1096  else
1097  {
1098  bool tuple_totally_frozen;
1099 
1100  num_tuples += 1;
1101  hastup = true;
1102 
1103  /*
1104  * Each non-removable tuple must be checked to see if it needs
1105  * freezing. Note we already have exclusive buffer lock.
1106  */
1108  relfrozenxid, relminmxid,
1110  &frozen[nfrozen],
1111  &tuple_totally_frozen))
1112  frozen[nfrozen++].offset = offnum;
1113 
1114  if (!tuple_totally_frozen)
1115  all_frozen = false;
1116  }
1117  } /* scan along page */
1118 
1119  /*
1120  * If we froze any tuples, mark the buffer dirty, and write a WAL
1121  * record recording the changes. We must log the changes to be
1122  * crash-safe against future truncation of CLOG.
1123  */
1124  if (nfrozen > 0)
1125  {
1127 
1128  MarkBufferDirty(buf);
1129 
1130  /* execute collected freezes */
1131  for (i = 0; i < nfrozen; i++)
1132  {
1133  ItemId itemid;
1134  HeapTupleHeader htup;
1135 
1136  itemid = PageGetItemId(page, frozen[i].offset);
1137  htup = (HeapTupleHeader) PageGetItem(page, itemid);
1138 
1139  heap_execute_freeze_tuple(htup, &frozen[i]);
1140  }
1141 
1142  /* Now WAL-log freezing if necessary */
1143  if (RelationNeedsWAL(onerel))
1144  {
1145  XLogRecPtr recptr;
1146 
1147  recptr = log_heap_freeze(onerel, buf, FreezeLimit,
1148  frozen, nfrozen);
1149  PageSetLSN(page, recptr);
1150  }
1151 
1152  END_CRIT_SECTION();
1153  }
1154 
1155  /*
1156  * If there are no indexes then we can vacuum the page right now
1157  * instead of doing a second scan.
1158  */
1159  if (nindexes == 0 &&
1160  vacrelstats->num_dead_tuples > 0)
1161  {
1162  /* Remove tuples from heap */
1163  lazy_vacuum_page(onerel, blkno, buf, 0, vacrelstats, &vmbuffer);
1164  has_dead_tuples = false;
1165 
1166  /*
1167  * Forget the now-vacuumed tuples, and press on, but be careful
1168  * not to reset latestRemovedXid since we want that value to be
1169  * valid.
1170  */
1171  vacrelstats->num_dead_tuples = 0;
1172  vacuumed_pages++;
1173  }
1174 
1175  freespace = PageGetHeapFreeSpace(page);
1176 
1177  /* mark page all-visible, if appropriate */
1178  if (all_visible && !all_visible_according_to_vm)
1179  {
1181 
1182  if (all_frozen)
1183  flags |= VISIBILITYMAP_ALL_FROZEN;
1184 
1185  /*
1186  * It should never be the case that the visibility map page is set
1187  * while the page-level bit is clear, but the reverse is allowed
1188  * (if checksums are not enabled). Regardless, set the both bits
1189  * so that we get back in sync.
1190  *
1191  * NB: If the heap page is all-visible but the VM bit is not set,
1192  * we don't need to dirty the heap page. However, if checksums
1193  * are enabled, we do need to make sure that the heap page is
1194  * dirtied before passing it to visibilitymap_set(), because it
1195  * may be logged. Given that this situation should only happen in
1196  * rare cases after a crash, it is not worth optimizing.
1197  */
1198  PageSetAllVisible(page);
1199  MarkBufferDirty(buf);
1200  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1201  vmbuffer, visibility_cutoff_xid, flags);
1202  }
1203 
1204  /*
1205  * As of PostgreSQL 9.2, the visibility map bit should never be set if
1206  * the page-level bit is clear. However, it's possible that the bit
1207  * got cleared after we checked it and before we took the buffer
1208  * content lock, so we must recheck before jumping to the conclusion
1209  * that something bad has happened.
1210  */
1211  else if (all_visible_according_to_vm && !PageIsAllVisible(page)
1212  && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer))
1213  {
1214  elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
1215  relname, blkno);
1216  visibilitymap_clear(onerel, blkno, vmbuffer,
1218  }
1219 
1220  /*
1221  * It's possible for the value returned by GetOldestXmin() to move
1222  * backwards, so it's not wrong for us to see tuples that appear to
1223  * not be visible to everyone yet, while PD_ALL_VISIBLE is already
1224  * set. The real safe xmin value never moves backwards, but
1225  * GetOldestXmin() is conservative and sometimes returns a value
1226  * that's unnecessarily small, so if we see that contradiction it just
1227  * means that the tuples that we think are not visible to everyone yet
1228  * actually are, and the PD_ALL_VISIBLE flag is correct.
1229  *
1230  * There should never be dead tuples on a page with PD_ALL_VISIBLE
1231  * set, however.
1232  */
1233  else if (PageIsAllVisible(page) && has_dead_tuples)
1234  {
1235  elog(WARNING, "page containing dead tuples is marked as all-visible in relation \"%s\" page %u",
1236  relname, blkno);
1237  PageClearAllVisible(page);
1238  MarkBufferDirty(buf);
1239  visibilitymap_clear(onerel, blkno, vmbuffer,
1241  }
1242 
1243  /*
1244  * If the all-visible page is turned out to be all-frozen but not
1245  * marked, we should so mark it. Note that all_frozen is only valid
1246  * if all_visible is true, so we must check both.
1247  */
1248  else if (all_visible_according_to_vm && all_visible && all_frozen &&
1249  !VM_ALL_FROZEN(onerel, blkno, &vmbuffer))
1250  {
1251  /*
1252  * We can pass InvalidTransactionId as the cutoff XID here,
1253  * because setting the all-frozen bit doesn't cause recovery
1254  * conflicts.
1255  */
1256  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1257  vmbuffer, InvalidTransactionId,
1259  }
1260 
1261  UnlockReleaseBuffer(buf);
1262 
1263  /* Remember the location of the last page with nonremovable tuples */
1264  if (hastup)
1265  vacrelstats->nonempty_pages = blkno + 1;
1266 
1267  /*
1268  * If we remembered any tuples for deletion, then the page will be
1269  * visited again by lazy_vacuum_heap, which will compute and record
1270  * its post-compaction free space. If not, then we're done with this
1271  * page, so remember its free space as-is. (This path will always be
1272  * taken if there are no indexes.)
1273  */
1274  if (vacrelstats->num_dead_tuples == prev_dead_count)
1275  RecordPageWithFreeSpace(onerel, blkno, freespace);
1276  }
1277 
1278  /* report that everything is scanned and vacuumed */
1280 
1281  pfree(frozen);
1282 
1283  /* save stats for use later */
1284  vacrelstats->scanned_tuples = num_tuples;
1285  vacrelstats->tuples_deleted = tups_vacuumed;
1286  vacrelstats->new_dead_tuples = nkeep;
1287 
1288  /* now we can compute the new value for pg_class.reltuples */
1289  vacrelstats->new_rel_tuples = vac_estimate_reltuples(onerel, false,
1290  nblocks,
1291  vacrelstats->tupcount_pages,
1292  num_tuples);
1293 
1294  /*
1295  * Release any remaining pin on visibility map page.
1296  */
1297  if (BufferIsValid(vmbuffer))
1298  {
1299  ReleaseBuffer(vmbuffer);
1300  vmbuffer = InvalidBuffer;
1301  }
1302 
1303  /* If any tuples need to be deleted, perform final vacuum cycle */
1304  /* XXX put a threshold on min number of tuples here? */
1305  if (vacrelstats->num_dead_tuples > 0)
1306  {
1307  const int hvp_index[] = {
1309  PROGRESS_VACUUM_NUM_INDEX_VACUUMS
1310  };
1311  int64 hvp_val[2];
1312 
1313  /* Log cleanup info before we touch indexes */
1314  vacuum_log_cleanup_info(onerel, vacrelstats);
1315 
1316  /* Report that we are now vacuuming indexes */
1319 
1320  /* Remove index entries */
1321  for (i = 0; i < nindexes; i++)
1322  lazy_vacuum_index(Irel[i],
1323  &indstats[i],
1324  vacrelstats);
1325 
1326  /* Report that we are now vacuuming the heap */
1327  hvp_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_HEAP;
1328  hvp_val[1] = vacrelstats->num_index_scans + 1;
1329  pgstat_progress_update_multi_param(2, hvp_index, hvp_val);
1330 
1331  /* Remove tuples from heap */
1334  lazy_vacuum_heap(onerel, vacrelstats);
1335  vacrelstats->num_index_scans++;
1336  }
1337 
1338  /* report all blocks vacuumed; and that we're cleaning up */
1342 
1343  /* Do post-vacuum cleanup and statistics update for each index */
1344  for (i = 0; i < nindexes; i++)
1345  lazy_cleanup_index(Irel[i], indstats[i], vacrelstats);
1346 
1347  /* If no indexes, make log report that lazy_vacuum_heap would've made */
1348  if (vacuumed_pages)
1349  ereport(elevel,
1350  (errmsg("\"%s\": removed %.0f row versions in %u pages",
1351  RelationGetRelationName(onerel),
1352  tups_vacuumed, vacuumed_pages)));
1353 
1354  /*
1355  * This is pretty messy, but we split it up so that we can skip emitting
1356  * individual parts of the message when not applicable.
1357  */
1358  initStringInfo(&buf);
1359  appendStringInfo(&buf,
1360  _("%.0f dead row versions cannot be removed yet, oldest xmin: %u\n"),
1361  nkeep, OldestXmin);
1362  appendStringInfo(&buf, _("There were %.0f unused item pointers.\n"),
1363  nunused);
1364  appendStringInfo(&buf, ngettext("Skipped %u page due to buffer pins, ",
1365  "Skipped %u pages due to buffer pins, ",
1366  vacrelstats->pinskipped_pages),
1367  vacrelstats->pinskipped_pages);
1368  appendStringInfo(&buf, ngettext("%u frozen page.\n",
1369  "%u frozen pages.\n",
1370  vacrelstats->frozenskipped_pages),
1371  vacrelstats->frozenskipped_pages);
1372  appendStringInfo(&buf, ngettext("%u page is entirely empty.\n",
1373  "%u pages are entirely empty.\n",
1374  empty_pages),
1375  empty_pages);
1376  appendStringInfo(&buf, _("%s."), pg_rusage_show(&ru0));
1377 
1378  ereport(elevel,
1379  (errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u out of %u pages",
1380  RelationGetRelationName(onerel),
1381  tups_vacuumed, num_tuples,
1382  vacrelstats->scanned_pages, nblocks),
1383  errdetail_internal("%s", buf.data)));
1384  pfree(buf.data);
1385 }
double new_rel_tuples
Definition: vacuumlazy.c:119
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:7428
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
Definition: vacuumlazy.c:1465
int heap_page_prune(Relation relation, Buffer buffer, TransactionId OldestXmin, bool report_stats, TransactionId *latestRemovedXid)
Definition: pruneheap.c:181
void LockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3603
XLogRecPtr log_heap_freeze(Relation reln, Buffer buffer, TransactionId cutoff_xid, xl_heap_freeze_tuple *tuples, int ntuples)
Definition: heapam.c:7547
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition: progress.h:24
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define PageIsEmpty(page)
Definition: bufpage.h:218
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1009
BlockNumber rel_pages
Definition: vacuumlazy.c:112
OffsetNumber offset
Definition: heapam_xlog.h:299
static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1400
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:105
double vac_estimate_reltuples(Relation relation, bool is_analyze, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
Definition: vacuum.c:778
static void lazy_record_dead_tuple(LVRelStats *vacrelstats, ItemPointer itemptr)
Definition: vacuumlazy.c:2039
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
#define PageIsAllVisible(page)
Definition: bufpage.h:381
uint32 TransactionId
Definition: c.h:463
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
#define PROGRESS_VACUUM_MAX_DEAD_TUPLES
Definition: progress.h:26
#define PROGRESS_VACUUM_PHASE_VACUUM_INDEX
Definition: progress.h:31
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *buf)
double tuples_deleted
Definition: vacuumlazy.c:122
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
#define ExclusiveLock
Definition: lockdefs.h:44
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3093
#define VISIBILITYMAP_ALL_FROZEN
Definition: visibilitymap.h:27
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
BlockNumber tupcount_pages
Definition: vacuumlazy.c:116
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
#define MaxHeapTuplesPerPage
Definition: htup_details.h:580
#define VM_ALL_FROZEN(r, b, v)
Definition: visibilitymap.h:34
unsigned char uint8
Definition: c.h:312
#define PROGRESS_VACUUM_HEAP_BLKS_SCANNED
Definition: progress.h:23
#define InvalidBuffer
Definition: buf.h:25
static void lazy_cleanup_index(Relation indrel, IndexBulkDeleteResult *stats, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1646
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
Definition: tqual.c:1164
#define PROGRESS_VACUUM_TOTAL_HEAP_BLKS
Definition: progress.h:22
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
BlockNumber scanned_pages
Definition: vacuumlazy.c:113
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
BlockNumber pinskipped_pages
Definition: vacuumlazy.c:114
Form_pg_class rd_rel
Definition: rel.h:114
#define ItemIdIsDead(itemId)
Definition: itemid.h:112
#define OidIsValid(objectId)
Definition: c.h:594
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
uint16 OffsetNumber
Definition: off.h:24
#define VISIBILITYMAP_VALID_BITS
Definition: visibilitymap.h:28
HeapTupleHeader t_data
Definition: htup.h:67
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen_p)
Definition: heapam.c:6681
#define FORCE_CHECK_PAGE()
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:682
void pfree(void *pointer)
Definition: mcxt.c:936
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3718
#define ERROR
Definition: elog.h:43
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:662
int max_dead_tuples
Definition: vacuumlazy.c:127
ItemPointerData t_self
Definition: htup.h:65
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:323
static TransactionId FreezeLimit
Definition: vacuumlazy.c:139
uint32 t_len
Definition: htup.h:64
void heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
Definition: heapam.c:6893
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
static char * buf
Definition: pg_test_fsync.c:67
#define PageSetAllVisible(page)
Definition: bufpage.h:383
#define FirstOffsetNumber
Definition: off.h:27
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:140
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:445
static TransactionId OldestXmin
Definition: vacuumlazy.c:138
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
int num_dead_tuples
Definition: vacuumlazy.c:126
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define SKIP_PAGES_THRESHOLD
Definition: vacuumlazy.c:98
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define WARNING
Definition: elog.h:40
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
void LockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:332
static int elevel
Definition: vacuumlazy.c:136
#define ngettext(s, p, n)
Definition: c.h:1011
void * palloc0(Size size)
Definition: mcxt.c:864
void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:382
#define BufferGetPageSize(buffer)
Definition: bufmgr.h:147
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
int num_index_scans
Definition: vacuumlazy.c:129
static void vacuum_log_cleanup_info(Relation rel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:430
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
#define PageClearAllVisible(page)
Definition: bufpage.h:385
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:691
#define Assert(condition)
Definition: c.h:688
double new_dead_tuples
Definition: vacuumlazy.c:120
TransactionId latestRemovedXid
Definition: vacuumlazy.c:130
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
static void lazy_vacuum_index(Relation indrel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1615
#define PROGRESS_VACUUM_PHASE_INDEX_CLEANUP
Definition: progress.h:33
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:312
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:32
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3115
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
size_t Size
Definition: c.h:422
#define PROGRESS_VACUUM_NUM_INDEX_VACUUMS
Definition: progress.h:25
#define PROGRESS_VACUUM_PHASE_SCAN_HEAP
Definition: progress.h:30
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define RelationNeedsWAL(relation)
Definition: rel.h:514
#define VISIBILITYMAP_ALL_VISIBLE
Definition: visibilitymap.h:26
#define PageGetLSN(page)
Definition: bufpage.h:362
BlockNumber nonempty_pages
Definition: vacuumlazy.c:123
#define PageIsNew(page)
Definition: bufpage.h:225
void * palloc(Size size)
Definition: mcxt.c:835
int errmsg(const char *fmt,...)
Definition: elog.c:797
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *buf)
BlockNumber frozenskipped_pages
Definition: vacuumlazy.c:115
double scanned_tuples
Definition: vacuumlazy.c:117
int i
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
static bool lazy_check_needs_freeze(Buffer buf, bool *hastup)
Definition: vacuumlazy.c:1563
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
void vacuum_delay_point(void)
Definition: vacuum.c:1696
#define PageSetLSN(page, lsn)
Definition: bufpage.h:364
int Buffer
Definition: buf.h:23
#define _(x)
Definition: elog.c:84
#define RelationGetRelid(relation)
Definition: rel.h:425
#define PROGRESS_VACUUM_PHASE_VACUUM_HEAP
Definition: progress.h:32
#define PageGetItem(page, itemId)
Definition: bufpage.h:336
Pointer Page
Definition: bufpage.h:74
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:105
static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks)
Definition: vacuumlazy.c:2004
#define RelationGetNamespace(relation)
Definition: rel.h:452
void PageInit(Page page, Size pageSize, Size specialSize)
Definition: bufpage.c:41

◆ lazy_space_alloc()

static void lazy_space_alloc ( LVRelStats vacrelstats,
BlockNumber  relblocks 
)
static

Definition at line 2004 of file vacuumlazy.c.

References autovacuum_work_mem, LVRelStats::dead_tuples, LVRelStats::hasindex, IsAutoVacuumWorkerProcess(), LAZY_ALLOC_TUPLES, maintenance_work_mem, Max, LVRelStats::max_dead_tuples, MaxAllocSize, MaxHeapTuplesPerPage, Min, LVRelStats::num_dead_tuples, and palloc().

Referenced by lazy_scan_heap().

2005 {
2006  long maxtuples;
2007  int vac_work_mem = IsAutoVacuumWorkerProcess() &&
2008  autovacuum_work_mem != -1 ?
2010 
2011  if (vacrelstats->hasindex)
2012  {
2013  maxtuples = (vac_work_mem * 1024L) / sizeof(ItemPointerData);
2014  maxtuples = Min(maxtuples, INT_MAX);
2015  maxtuples = Min(maxtuples, MaxAllocSize / sizeof(ItemPointerData));
2016 
2017  /* curious coding here to ensure the multiplication can't overflow */
2018  if ((BlockNumber) (maxtuples / LAZY_ALLOC_TUPLES) > relblocks)
2019  maxtuples = relblocks * LAZY_ALLOC_TUPLES;
2020 
2021  /* stay sane if small maintenance_work_mem */
2022  maxtuples = Max(maxtuples, MaxHeapTuplesPerPage);
2023  }
2024  else
2025  {
2026  maxtuples = MaxHeapTuplesPerPage;
2027  }
2028 
2029  vacrelstats->num_dead_tuples = 0;
2030  vacrelstats->max_dead_tuples = (int) maxtuples;
2031  vacrelstats->dead_tuples = (ItemPointer)
2032  palloc(maxtuples * sizeof(ItemPointerData));
2033 }
int autovacuum_work_mem
Definition: autovacuum.c:115
#define Min(x, y)
Definition: c.h:846
#define MaxHeapTuplesPerPage
Definition: htup_details.h:580
uint32 BlockNumber
Definition: block.h:31
ItemPointerData * ItemPointer
Definition: itemptr.h:49
int max_dead_tuples
Definition: vacuumlazy.c:127
ItemPointer dead_tuples
Definition: vacuumlazy.c:128
int num_dead_tuples
Definition: vacuumlazy.c:126
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define MaxAllocSize
Definition: memutils.h:40
bool hasindex
Definition: vacuumlazy.c:109
int maintenance_work_mem
Definition: globals.c:114
#define Max(x, y)
Definition: c.h:840
void * palloc(Size size)
Definition: mcxt.c:835
#define LAZY_ALLOC_TUPLES
Definition: vacuumlazy.c:92

◆ lazy_tid_reaped()

static bool lazy_tid_reaped ( ItemPointer  itemptr,
void *  state 
)
static

Definition at line 2064 of file vacuumlazy.c.

References LVRelStats::dead_tuples, LVRelStats::num_dead_tuples, and vac_cmp_itemptr().

Referenced by lazy_vacuum_index().

2065 {
2066  LVRelStats *vacrelstats = (LVRelStats *) state;
2067  ItemPointer res;
2068 
2069  res = (ItemPointer) bsearch((void *) itemptr,
2070  (void *) vacrelstats->dead_tuples,
2071  vacrelstats->num_dead_tuples,
2072  sizeof(ItemPointerData),
2073  vac_cmp_itemptr);
2074 
2075  return (res != NULL);
2076 }
ItemPointerData * ItemPointer
Definition: itemptr.h:49
ItemPointer dead_tuples
Definition: vacuumlazy.c:128
int num_dead_tuples
Definition: vacuumlazy.c:126
Definition: regguts.h:298
static int vac_cmp_itemptr(const void *left, const void *right)
Definition: vacuumlazy.c:2082

◆ lazy_truncate_heap()

static void lazy_truncate_heap ( Relation  onerel,
LVRelStats vacrelstats 
)
static

Definition at line 1734 of file vacuumlazy.c.

References AccessExclusiveLock, CHECK_FOR_INTERRUPTS, ConditionalLockRelation(), count_nondeletable_pages(), elevel, ereport, errdetail_internal(), errmsg(), LVRelStats::lock_waiter_detected, LVRelStats::nonempty_pages, LVRelStats::old_rel_pages, LVRelStats::pages_removed, pg_rusage_init(), pg_rusage_show(), pg_usleep(), pgstat_progress_update_param(), PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_TRUNCATE, LVRelStats::rel_pages, RelationGetNumberOfBlocks, RelationGetRelationName, RelationTruncate(), UnlockRelation(), VACUUM_TRUNCATE_LOCK_TIMEOUT, and VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL.

Referenced by lazy_vacuum_rel().

1735 {
1736  BlockNumber old_rel_pages = vacrelstats->rel_pages;
1737  BlockNumber new_rel_pages;
1738  PGRUsage ru0;
1739  int lock_retry;
1740 
1741  pg_rusage_init(&ru0);
1742 
1743  /* Report that we are now truncating */
1746 
1747  /*
1748  * Loop until no more truncating can be done.
1749  */
1750  do
1751  {
1752  /*
1753  * We need full exclusive lock on the relation in order to do
1754  * truncation. If we can't get it, give up rather than waiting --- we
1755  * don't want to block other backends, and we don't want to deadlock
1756  * (which is quite possible considering we already hold a lower-grade
1757  * lock).
1758  */
1759  vacrelstats->lock_waiter_detected = false;
1760  lock_retry = 0;
1761  while (true)
1762  {
1764  break;
1765 
1766  /*
1767  * Check for interrupts while trying to (re-)acquire the exclusive
1768  * lock.
1769  */
1771 
1772  if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT /
1774  {
1775  /*
1776  * We failed to establish the lock in the specified number of
1777  * retries. This means we give up truncating.
1778  */
1779  vacrelstats->lock_waiter_detected = true;
1780  ereport(elevel,
1781  (errmsg("\"%s\": stopping truncate due to conflicting lock request",
1782  RelationGetRelationName(onerel))));
1783  return;
1784  }
1785 
1787  }
1788 
1789  /*
1790  * Now that we have exclusive lock, look to see if the rel has grown
1791  * whilst we were vacuuming with non-exclusive lock. If so, give up;
1792  * the newly added pages presumably contain non-deletable tuples.
1793  */
1794  new_rel_pages = RelationGetNumberOfBlocks(onerel);
1795  if (new_rel_pages != old_rel_pages)
1796  {
1797  /*
1798  * Note: we intentionally don't update vacrelstats->rel_pages with
1799  * the new rel size here. If we did, it would amount to assuming
1800  * that the new pages are empty, which is unlikely. Leaving the
1801  * numbers alone amounts to assuming that the new pages have the
1802  * same tuple density as existing ones, which is less unlikely.
1803  */
1805  return;
1806  }
1807 
1808  /*
1809  * Scan backwards from the end to verify that the end pages actually
1810  * contain no tuples. This is *necessary*, not optional, because
1811  * other backends could have added tuples to these pages whilst we
1812  * were vacuuming.
1813  */
1814  new_rel_pages = count_nondeletable_pages(onerel, vacrelstats);
1815 
1816  if (new_rel_pages >= old_rel_pages)
1817  {
1818  /* can't do anything after all */
1820  return;
1821  }
1822 
1823  /*
1824  * Okay to truncate.
1825  */
1826  RelationTruncate(onerel, new_rel_pages);
1827 
1828  /*
1829  * We can release the exclusive lock as soon as we have truncated.
1830  * Other backends can't safely access the relation until they have
1831  * processed the smgr invalidation that smgrtruncate sent out ... but
1832  * that should happen as part of standard invalidation processing once
1833  * they acquire lock on the relation.
1834  */
1836 
1837  /*
1838  * Update statistics. Here, it *is* correct to adjust rel_pages
1839  * without also touching reltuples, since the tuple count wasn't
1840  * changed by the truncation.
1841  */
1842  vacrelstats->pages_removed += old_rel_pages - new_rel_pages;
1843  vacrelstats->rel_pages = new_rel_pages;
1844 
1845  ereport(elevel,
1846  (errmsg("\"%s\": truncated %u to %u pages",
1847  RelationGetRelationName(onerel),
1848  old_rel_pages, new_rel_pages),
1849  errdetail_internal("%s",
1850  pg_rusage_show(&ru0))));
1851  old_rel_pages = new_rel_pages;
1852  } while (new_rel_pages > vacrelstats->nonempty_pages &&
1853  vacrelstats->lock_waiter_detected);
1854 }
static BlockNumber count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1862
BlockNumber rel_pages
Definition: vacuumlazy.c:112
void UnlockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:257
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3093
#define VACUUM_TRUNCATE_LOCK_TIMEOUT
Definition: vacuumlazy.c:85
uint32 BlockNumber
Definition: block.h:31
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_VACUUM_PHASE_TRUNCATE
Definition: progress.h:34
void pg_usleep(long microsec)
Definition: signal.c:53
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:226
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL
Definition: vacuumlazy.c:84
static int elevel
Definition: vacuumlazy.c:136
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
#define AccessExclusiveLock
Definition: lockdefs.h:45
BlockNumber pages_removed
Definition: vacuumlazy.c:121
BlockNumber nonempty_pages
Definition: vacuumlazy.c:123
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:227
bool lock_waiter_detected
Definition: vacuumlazy.c:131

◆ lazy_vacuum_heap()

static void lazy_vacuum_heap ( Relation  onerel,
LVRelStats vacrelstats 
)
static

Definition at line 1400 of file vacuumlazy.c.

References buf, BufferGetPage, BufferIsValid, ConditionalLockBufferForCleanup(), LVRelStats::dead_tuples, elevel, ereport, errdetail_internal(), errmsg(), InvalidBuffer, ItemPointerGetBlockNumber, lazy_vacuum_page(), MAIN_FORKNUM, LVRelStats::num_dead_tuples, PageGetHeapFreeSpace(), pg_rusage_init(), pg_rusage_show(), RBM_NORMAL, ReadBufferExtended(), RecordPageWithFreeSpace(), RelationGetRelationName, ReleaseBuffer(), UnlockReleaseBuffer(), and vacuum_delay_point().

Referenced by lazy_scan_heap().

1401 {
1402  int tupindex;
1403  int npages;
1404  PGRUsage ru0;
1405  Buffer vmbuffer = InvalidBuffer;
1406 
1407  pg_rusage_init(&ru0);
1408  npages = 0;
1409 
1410  tupindex = 0;
1411  while (tupindex < vacrelstats->num_dead_tuples)
1412  {
1413  BlockNumber tblk;
1414  Buffer buf;
1415  Page page;
1416  Size freespace;
1417 
1419 
1420  tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
1421  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, tblk, RBM_NORMAL,
1422  vac_strategy);
1424  {
1425  ReleaseBuffer(buf);
1426  ++tupindex;
1427  continue;
1428  }
1429  tupindex = lazy_vacuum_page(onerel, tblk, buf, tupindex, vacrelstats,
1430  &vmbuffer);
1431 
1432  /* Now that we've compacted the page, record its available space */
1433  page = BufferGetPage(buf);
1434  freespace = PageGetHeapFreeSpace(page);
1435 
1436  UnlockReleaseBuffer(buf);
1437  RecordPageWithFreeSpace(onerel, tblk, freespace);
1438  npages++;
1439  }
1440 
1441  if (BufferIsValid(vmbuffer))
1442  {
1443  ReleaseBuffer(vmbuffer);
1444  vmbuffer = InvalidBuffer;
1445  }
1446 
1447  ereport(elevel,
1448  (errmsg("\"%s\": removed %d row versions in %d pages",
1449  RelationGetRelationName(onerel),
1450  tupindex, npages),
1451  errdetail_internal("%s", pg_rusage_show(&ru0))));
1452 }
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
Definition: vacuumlazy.c:1465
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
#define InvalidBuffer
Definition: buf.h:25
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3718
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:662
ItemPointer dead_tuples
Definition: vacuumlazy.c:128
static char * buf
Definition: pg_test_fsync.c:67
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
size_t Size
Definition: c.h:422
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:76
void vacuum_delay_point(void)
Definition: vacuum.c:1696
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:74

◆ lazy_vacuum_index()

static void lazy_vacuum_index ( Relation  indrel,
IndexBulkDeleteResult **  stats,
LVRelStats vacrelstats 
)
static

Definition at line 1615 of file vacuumlazy.c.

References IndexVacuumInfo::analyze_only, elevel, ereport, errdetail_internal(), errmsg(), IndexVacuumInfo::estimated_count, IndexVacuumInfo::index, index_bulk_delete(), lazy_tid_reaped(), IndexVacuumInfo::message_level, IndexVacuumInfo::num_heap_tuples, LVRelStats::old_rel_tuples, pg_rusage_init(), pg_rusage_show(), RelationGetRelationName, IndexVacuumInfo::strategy, and vac_strategy.

Referenced by lazy_scan_heap().

1618 {
1619  IndexVacuumInfo ivinfo;
1620  PGRUsage ru0;
1621 
1622  pg_rusage_init(&ru0);
1623 
1624  ivinfo.index = indrel;
1625  ivinfo.analyze_only = false;
1626  ivinfo.estimated_count = true;
1627  ivinfo.message_level = elevel;
1628  ivinfo.num_heap_tuples = vacrelstats->old_rel_tuples;
1629  ivinfo.strategy = vac_strategy;
1630 
1631  /* Do bulk deletion */
1632  *stats = index_bulk_delete(&ivinfo, *stats,
1633  lazy_tid_reaped, (void *) vacrelstats);
1634 
1635  ereport(elevel,
1636  (errmsg("scanned index \"%s\" to remove %d row versions",
1637  RelationGetRelationName(indrel),
1638  vacrelstats->num_dead_tuples),
1639  errdetail_internal("%s", pg_rusage_show(&ru0))));
1640 }
static bool lazy_tid_reaped(ItemPointer itemptr, void *state)
Definition: vacuumlazy.c:2064
double old_rel_tuples
Definition: vacuumlazy.c:118
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:51
Relation index
Definition: genam.h:46
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define RelationGetRelationName(relation)
Definition: rel.h:445
int num_dead_tuples
Definition: vacuumlazy.c:126
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:744
int message_level
Definition: genam.h:49
double num_heap_tuples
Definition: genam.h:50
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool estimated_count
Definition: genam.h:48

◆ lazy_vacuum_page()

static int lazy_vacuum_page ( Relation  onerel,
BlockNumber  blkno,
Buffer  buffer,
int  tupindex,
LVRelStats vacrelstats,
Buffer vmbuffer 
)
static

Definition at line 1465 of file vacuumlazy.c.

References Assert, BufferGetPage, BufferIsValid, LVRelStats::dead_tuples, END_CRIT_SECTION, heap_page_is_all_visible(), InvalidXLogRecPtr, ItemIdSetUnused, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LVRelStats::latestRemovedXid, log_heap_clean(), MarkBufferDirty(), MaxOffsetNumber, LVRelStats::num_dead_tuples, PageGetItemId, PageIsAllVisible, PageRepairFragmentation(), PageSetAllVisible, PageSetLSN, pgstat_progress_update_param(), PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, RelationNeedsWAL, START_CRIT_SECTION, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_get_status(), and visibilitymap_set().

Referenced by lazy_scan_heap(), and lazy_vacuum_heap().

1467 {
1468  Page page = BufferGetPage(buffer);
1469  OffsetNumber unused[MaxOffsetNumber];
1470  int uncnt = 0;
1471  TransactionId visibility_cutoff_xid;
1472  bool all_frozen;
1473 
1475 
1477 
1478  for (; tupindex < vacrelstats->num_dead_tuples; tupindex++)
1479  {
1480  BlockNumber tblk;
1481  OffsetNumber toff;
1482  ItemId itemid;
1483 
1484  tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
1485  if (tblk != blkno)
1486  break; /* past end of tuples for this block */
1487  toff = ItemPointerGetOffsetNumber(&vacrelstats->dead_tuples[tupindex]);
1488  itemid = PageGetItemId(page, toff);
1489  ItemIdSetUnused(itemid);
1490  unused[uncnt++] = toff;
1491  }
1492 
1494 
1495  /*
1496  * Mark buffer dirty before we write WAL.
1497  */
1499 
1500  /* XLOG stuff */
1501  if (RelationNeedsWAL(onerel))
1502  {
1503  XLogRecPtr recptr;
1504 
1505  recptr = log_heap_clean(onerel, buffer,
1506  NULL, 0, NULL, 0,
1507  unused, uncnt,
1508  vacrelstats->latestRemovedXid);
1509  PageSetLSN(page, recptr);
1510  }
1511 
1512  /*
1513  * End critical section, so we safely can do visibility tests (which
1514  * possibly need to perform IO and allocate memory!). If we crash now the
1515  * page (including the corresponding vm bit) might not be marked all
1516  * visible, but that's fine. A later vacuum will fix that.
1517  */
1518  END_CRIT_SECTION();
1519 
1520  /*
1521  * Now that we have removed the dead tuples from the page, once again
1522  * check if the page has become all-visible. The page is already marked
1523  * dirty, exclusively locked, and, if needed, a full page image has been
1524  * emitted in the log_heap_clean() above.
1525  */
1526  if (heap_page_is_all_visible(onerel, buffer, &visibility_cutoff_xid,
1527  &all_frozen))
1528  PageSetAllVisible(page);
1529 
1530  /*
1531  * All the changes to the heap page have been done. If the all-visible
1532  * flag is now set, also set the VM all-visible bit (and, if possible, the
1533  * all-frozen bit) unless this has already been done previously.
1534  */
1535  if (PageIsAllVisible(page))
1536  {
1537  uint8 vm_status = visibilitymap_get_status(onerel, blkno, vmbuffer);
1538  uint8 flags = 0;
1539 
1540  /* Set the VM all-frozen bit to flag, if needed */
1541  if ((vm_status & VISIBILITYMAP_ALL_VISIBLE) == 0)
1542  flags |= VISIBILITYMAP_ALL_VISIBLE;
1543  if ((vm_status & VISIBILITYMAP_ALL_FROZEN) == 0 && all_frozen)
1544  flags |= VISIBILITYMAP_ALL_FROZEN;
1545 
1546  Assert(BufferIsValid(*vmbuffer));
1547  if (flags != 0)
1548  visibilitymap_set(onerel, blkno, buffer, InvalidXLogRecPtr,
1549  *vmbuffer, visibility_cutoff_xid, flags);
1550  }
1551 
1552  return tupindex;
1553 }
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition: progress.h:24
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define PageIsAllVisible(page)
Definition: bufpage.h:381
uint32 TransactionId
Definition: c.h:463
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
#define MaxOffsetNumber
Definition: off.h:28
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3093
#define VISIBILITYMAP_ALL_FROZEN
Definition: visibilitymap.h:27
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
unsigned char uint8
Definition: c.h:312
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
ItemPointer dead_tuples
Definition: vacuumlazy.c:128
#define PageSetAllVisible(page)
Definition: bufpage.h:383
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
int num_dead_tuples
Definition: vacuumlazy.c:126
static bool heap_page_is_all_visible(Relation rel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen)
Definition: vacuumlazy.c:2115
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:688
TransactionId latestRemovedXid
Definition: vacuumlazy.c:130
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
XLogRecPtr log_heap_clean(Relation reln, Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused, TransactionId latestRemovedXid)
Definition: heapam.c:7496
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:95
#define RelationNeedsWAL(relation)
Definition: rel.h:514
#define VISIBILITYMAP_ALL_VISIBLE
Definition: visibilitymap.h:26
void PageRepairFragmentation(Page page)
Definition: bufpage.c:479
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *buf)
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:76
#define ItemIdSetUnused(itemId)
Definition: itemid.h:127
#define PageSetLSN(page, lsn)
Definition: bufpage.h:364
Pointer Page
Definition: bufpage.h:74

◆ lazy_vacuum_rel()

void lazy_vacuum_rel ( Relation  onerel,
int  options,
VacuumParams params,
BufferAccessStrategy  bstrategy 
)

Definition at line 182 of file vacuumlazy.c.

References _, appendStringInfo(), Assert, buf, StringInfoData::data, DEBUG2, elevel, ereport, errmsg_internal(), FreeSpaceMapVacuum(), VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, FreezeLimit, LVRelStats::frozenskipped_pages, get_database_name(), get_namespace_name(), GetCurrentTimestamp(), LVRelStats::hasindex, INFO, initStringInfo(), InvalidMultiXactId, InvalidTransactionId, IsAutoVacuumWorkerProcess(), lazy_scan_heap(), lazy_truncate_heap(), LVRelStats::lock_waiter_detected, LOG, VacuumParams::log_min_duration, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, MultiXactCutoff, MultiXactIdPrecedesOrEquals(), MyDatabaseId, LVRelStats::new_dead_tuples, LVRelStats::new_rel_tuples, NoLock, LVRelStats::num_index_scans, LVRelStats::old_rel_pages, LVRelStats::old_rel_tuples, OldestXmin, LVRelStats::pages_removed, palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), pgstat_report_vacuum(), LVRelStats::pinskipped_pages, PROGRESS_COMMAND_VACUUM, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_FINAL_CLEANUP, RelationData::rd_rel, LVRelStats::rel_pages, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RowExclusiveLock, LVRelStats::scanned_pages, should_attempt_truncation(), TimestampDifference(), TimestampDifferenceExceeds(), TransactionIdPrecedesOrEquals(), LVRelStats::tupcount_pages, LVRelStats::tuples_deleted, vac_close_indexes(), vac_open_indexes(), vac_update_relstats(), VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_VERBOSE, vacuum_set_xid_limits(), VacuumPageDirty, VacuumPageHit, VacuumPageMiss, and visibilitymap_count().

Referenced by vacuum_rel().

184 {
185  LVRelStats *vacrelstats;
186  Relation *Irel;
187  int nindexes;
188  PGRUsage ru0;
189  TimestampTz starttime = 0;
190  long secs;
191  int usecs;
192  double read_rate,
193  write_rate;
194  bool aggressive; /* should we scan all unfrozen pages? */
195  bool scanned_all_unfrozen; /* actually scanned all such pages? */
196  TransactionId xidFullScanLimit;
197  MultiXactId mxactFullScanLimit;
198  BlockNumber new_rel_pages;
199  double new_rel_tuples;
200  BlockNumber new_rel_allvisible;
201  double new_live_tuples;
202  TransactionId new_frozen_xid;
203  MultiXactId new_min_multi;
204 
205  Assert(params != NULL);
206 
207  /* measure elapsed time iff autovacuum logging requires it */
208  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
209  {
210  pg_rusage_init(&ru0);
211  starttime = GetCurrentTimestamp();
212  }
213 
214  if (options & VACOPT_VERBOSE)
215  elevel = INFO;
216  else
217  elevel = DEBUG2;
218 
220  RelationGetRelid(onerel));
221 
222  vac_strategy = bstrategy;
223 
224  vacuum_set_xid_limits(onerel,
225  params->freeze_min_age,
226  params->freeze_table_age,
227  params->multixact_freeze_min_age,
229  &OldestXmin, &FreezeLimit, &xidFullScanLimit,
230  &MultiXactCutoff, &mxactFullScanLimit);
231 
232  /*
233  * We request an aggressive scan if the table's frozen Xid is now older
234  * than or equal to the requested Xid full-table scan limit; or if the
235  * table's minimum MultiXactId is older than or equal to the requested
236  * mxid full-table scan limit; or if DISABLE_PAGE_SKIPPING was specified.
237  */
238  aggressive = TransactionIdPrecedesOrEquals(onerel->rd_rel->relfrozenxid,
239  xidFullScanLimit);
240  aggressive |= MultiXactIdPrecedesOrEquals(onerel->rd_rel->relminmxid,
241  mxactFullScanLimit);
243  aggressive = true;
244 
245  vacrelstats = (LVRelStats *) palloc0(sizeof(LVRelStats));
246 
247  vacrelstats->old_rel_pages = onerel->rd_rel->relpages;
248  vacrelstats->old_rel_tuples = onerel->rd_rel->reltuples;
249  vacrelstats->num_index_scans = 0;
250  vacrelstats->pages_removed = 0;
251  vacrelstats->lock_waiter_detected = false;
252 
253  /* Open all indexes of the relation */
254  vac_open_indexes(onerel, RowExclusiveLock, &nindexes, &Irel);
255  vacrelstats->hasindex = (nindexes > 0);
256 
257  /* Do the vacuuming */
258  lazy_scan_heap(onerel, options, vacrelstats, Irel, nindexes, aggressive);
259 
260  /* Done with indexes */
261  vac_close_indexes(nindexes, Irel, NoLock);
262 
263  /*
264  * Compute whether we actually scanned the all unfrozen pages. If we did,
265  * we can adjust relfrozenxid and relminmxid.
266  *
267  * NB: We need to check this before truncating the relation, because that
268  * will change ->rel_pages.
269  */
270  if ((vacrelstats->scanned_pages + vacrelstats->frozenskipped_pages)
271  < vacrelstats->rel_pages)
272  {
273  Assert(!aggressive);
274  scanned_all_unfrozen = false;
275  }
276  else
277  scanned_all_unfrozen = true;
278 
279  /*
280  * Optionally truncate the relation.
281  */
282  if (should_attempt_truncation(vacrelstats))
283  lazy_truncate_heap(onerel, vacrelstats);
284 
285  /* Report that we are now doing final cleanup */
288 
289  /* Vacuum the Free Space Map */
290  FreeSpaceMapVacuum(onerel);
291 
292  /*
293  * Update statistics in pg_class.
294  *
295  * A corner case here is that if we scanned no pages at all because every
296  * page is all-visible, we should not update relpages/reltuples, because
297  * we have no new information to contribute. In particular this keeps us
298  * from replacing relpages=reltuples=0 (which means "unknown tuple
299  * density") with nonzero relpages and reltuples=0 (which means "zero
300  * tuple density") unless there's some actual evidence for the latter.
301  *
302  * It's important that we use tupcount_pages and not scanned_pages for the
303  * check described above; scanned_pages counts pages where we could not
304  * get cleanup lock, and which were processed only for frozenxid purposes.
305  *
306  * We do update relallvisible even in the corner case, since if the table
307  * is all-visible we'd definitely like to know that. But clamp the value
308  * to be not more than what we're setting relpages to.
309  *
310  * Also, don't change relfrozenxid/relminmxid if we skipped any pages,
311  * since then we don't know for certain that all tuples have a newer xmin.
312  */
313  new_rel_pages = vacrelstats->rel_pages;
314  new_rel_tuples = vacrelstats->new_rel_tuples;
315  if (vacrelstats->tupcount_pages == 0 && new_rel_pages > 0)
316  {
317  new_rel_pages = vacrelstats->old_rel_pages;
318  new_rel_tuples = vacrelstats->old_rel_tuples;
319  }
320 
321  visibilitymap_count(onerel, &new_rel_allvisible, NULL);
322  if (new_rel_allvisible > new_rel_pages)
323  new_rel_allvisible = new_rel_pages;
324 
325  new_frozen_xid = scanned_all_unfrozen ? FreezeLimit : InvalidTransactionId;
326  new_min_multi = scanned_all_unfrozen ? MultiXactCutoff : InvalidMultiXactId;
327 
328  vac_update_relstats(onerel,
329  new_rel_pages,
330  new_rel_tuples,
331  new_rel_allvisible,
332  vacrelstats->hasindex,
333  new_frozen_xid,
334  new_min_multi,
335  false);
336 
337  /* report results to the stats collector, too */
338  new_live_tuples = new_rel_tuples - vacrelstats->new_dead_tuples;
339  if (new_live_tuples < 0)
340  new_live_tuples = 0; /* just in case */
341 
343  onerel->rd_rel->relisshared,
344  new_live_tuples,
345  vacrelstats->new_dead_tuples);
347 
348  /* and log the action if appropriate */
349  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
350  {
351  TimestampTz endtime = GetCurrentTimestamp();
352 
353  if (params->log_min_duration == 0 ||
354  TimestampDifferenceExceeds(starttime, endtime,
355  params->log_min_duration))
356  {
358  char *msgfmt;
359 
360  TimestampDifference(starttime, endtime, &secs, &usecs);
361 
362  read_rate = 0;
363  write_rate = 0;
364  if ((secs > 0) || (usecs > 0))
365  {
366  read_rate = (double) BLCKSZ * VacuumPageMiss / (1024 * 1024) /
367  (secs + usecs / 1000000.0);
368  write_rate = (double) BLCKSZ * VacuumPageDirty / (1024 * 1024) /
369  (secs + usecs / 1000000.0);
370  }
371 
372  /*
373  * This is pretty messy, but we split it up so that we can skip
374  * emitting individual parts of the message when not applicable.
375  */
376  initStringInfo(&buf);
377  if (aggressive)
378  msgfmt = _("automatic aggressive vacuum of table \"%s.%s.%s\": index scans: %d\n");
379  else
380  msgfmt = _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n");
381  appendStringInfo(&buf, msgfmt,
384  RelationGetRelationName(onerel),
385  vacrelstats->num_index_scans);
386  appendStringInfo(&buf, _("pages: %u removed, %u remain, %u skipped due to pins, %u skipped frozen\n"),
387  vacrelstats->pages_removed,
388  vacrelstats->rel_pages,
389  vacrelstats->pinskipped_pages,
390  vacrelstats->frozenskipped_pages);
391  appendStringInfo(&buf,
392  _("tuples: %.0f removed, %.0f remain, %.0f are dead but not yet removable, oldest xmin: %u\n"),
393  vacrelstats->tuples_deleted,
394  vacrelstats->new_rel_tuples,
395  vacrelstats->new_dead_tuples,
396  OldestXmin);
397  appendStringInfo(&buf,
398  _("buffer usage: %d hits, %d misses, %d dirtied\n"),
402  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
403  read_rate, write_rate);
404  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
405 
406  ereport(LOG,
407  (errmsg_internal("%s", buf.data)));
408  pfree(buf.data);
409  }
410  }
411 }
double new_rel_tuples
Definition: vacuumlazy.c:119
int multixact_freeze_table_age
Definition: vacuum.h:142
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1675
BlockNumber rel_pages
Definition: vacuumlazy.c:112
uint32 TransactionId
Definition: c.h:463
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3072
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
double tuples_deleted
Definition: vacuumlazy.c:122
int64 TimestampTz
Definition: timestamp.h:39
int VacuumPageHit
Definition: globals.c:135
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3093
double old_rel_tuples
Definition: vacuumlazy.c:118
BlockNumber tupcount_pages
Definition: vacuumlazy.c:116
static void lazy_scan_heap(Relation onerel, int options, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive)
Definition: vacuumlazy.c:463
BlockNumber scanned_pages
Definition: vacuumlazy.c:113
#define INFO
Definition: elog.h:33
void vacuum_set_xid_limits(Relation rel, int freeze_min_age, int freeze_table_age, int multixact_freeze_min_age, int multixact_freeze_table_age, TransactionId *oldestXmin, TransactionId *freezeLimit, TransactionId *xidFullScanLimit, MultiXactId *multiXactCutoff, MultiXactId *mxactFullScanLimit)
Definition: vacuum.c:593
uint32 BlockNumber
Definition: block.h:31
BlockNumber pinskipped_pages
Definition: vacuumlazy.c:114
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:114
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
int freeze_table_age
Definition: vacuum.h:139
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
BlockNumber old_rel_pages
Definition: vacuumlazy.c:111
void pfree(void *pointer)
Definition: mcxt.c:936
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
int freeze_min_age
Definition: vacuum.h:138
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
#define DEBUG2
Definition: elog.h:24
static TransactionId FreezeLimit
Definition: vacuumlazy.c:139
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:67
#define RowExclusiveLock
Definition: lockdefs.h:38
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:140
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:445
static TransactionId OldestXmin
Definition: vacuumlazy.c:138
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define ereport(elevel, rest)
Definition: elog.h:122
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:379
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1632
static int elevel
Definition: vacuumlazy.c:136
bool hasindex
Definition: vacuumlazy.c:109
int VacuumPageDirty
Definition: globals.c:137
void * palloc0(Size size)
Definition: mcxt.c:864
void pgstat_progress_end_command(void)
Definition: pgstat.c:3144
Oid MyDatabaseId
Definition: globals.c:77
#define InvalidMultiXactId
Definition: multixact.h:23
static bool should_attempt_truncation(LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1716
#define PROGRESS_VACUUM_PHASE_FINAL_CLEANUP
Definition: progress.h:35
int num_index_scans
Definition: vacuumlazy.c:129
TransactionId MultiXactId
Definition: c.h:473
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
#define Assert(condition)
Definition: c.h:688
double new_dead_tuples
Definition: vacuumlazy.c:120
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
int log_min_duration
Definition: vacuum.h:145
void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
Definition: pgstat.c:1405
BlockNumber pages_removed
Definition: vacuumlazy.c:121
BlockNumber frozenskipped_pages
Definition: vacuumlazy.c:115
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3154
int VacuumPageMiss
Definition: globals.c:136
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:878
#define _(x)
Definition: elog.c:84
#define RelationGetRelid(relation)
Definition: rel.h:425
int multixact_freeze_min_age
Definition: vacuum.h:140
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1734
#define RelationGetNamespace(relation)
Definition: rel.h:452
bool lock_waiter_detected
Definition: vacuumlazy.c:131

◆ should_attempt_truncation()

static bool should_attempt_truncation ( LVRelStats vacrelstats)
static

Definition at line 1716 of file vacuumlazy.c.

References LVRelStats::nonempty_pages, old_snapshot_threshold, LVRelStats::rel_pages, REL_TRUNCATE_FRACTION, and REL_TRUNCATE_MINIMUM.

Referenced by lazy_vacuum_rel().

1717 {
1718  BlockNumber possibly_freeable;
1719 
1720  possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
1721  if (possibly_freeable > 0 &&
1722  (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
1723  possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) &&
1725  return true;
1726  else
1727  return false;
1728 }
BlockNumber rel_pages
Definition: vacuumlazy.c:112
uint32 BlockNumber
Definition: block.h:31
#define REL_TRUNCATE_MINIMUM
Definition: vacuumlazy.c:73
BlockNumber nonempty_pages
Definition: vacuumlazy.c:123
int old_snapshot_threshold
Definition: snapmgr.c:75
#define REL_TRUNCATE_FRACTION
Definition: vacuumlazy.c:74

◆ vac_cmp_itemptr()

static int vac_cmp_itemptr ( const void *  left,
const void *  right 
)
static

Definition at line 2082 of file vacuumlazy.c.

References ItemPointerGetBlockNumber, and ItemPointerGetOffsetNumber.

Referenced by lazy_tid_reaped().

2083 {
2084  BlockNumber lblk,
2085  rblk;
2086  OffsetNumber loff,
2087  roff;
2088 
2089  lblk = ItemPointerGetBlockNumber((ItemPointer) left);
2090  rblk = ItemPointerGetBlockNumber((ItemPointer) right);
2091 
2092  if (lblk < rblk)
2093  return -1;
2094  if (lblk > rblk)
2095  return 1;
2096 
2097  loff = ItemPointerGetOffsetNumber((ItemPointer) left);
2098  roff = ItemPointerGetOffsetNumber((ItemPointer) right);
2099 
2100  if (loff < roff)
2101  return -1;
2102  if (loff > roff)
2103  return 1;
2104 
2105  return 0;
2106 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:95
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:76

◆ vacuum_log_cleanup_info()

static void vacuum_log_cleanup_info ( Relation  rel,
LVRelStats vacrelstats 
)
static

Definition at line 430 of file vacuumlazy.c.

References LVRelStats::latestRemovedXid, log_heap_cleanup_info(), RelationData::rd_node, RelationNeedsWAL, TransactionIdIsValid, and XLogIsNeeded.

Referenced by lazy_scan_heap().

431 {
432  /*
433  * Skip this for relations for which no WAL is to be written, or if we're
434  * not trying to support archive recovery.
435  */
436  if (!RelationNeedsWAL(rel) || !XLogIsNeeded())
437  return;
438 
439  /*
440  * No need to write the record at all unless it contains a valid value
441  */
442  if (TransactionIdIsValid(vacrelstats->latestRemovedXid))
443  (void) log_heap_cleanup_info(rel->rd_node, vacrelstats->latestRemovedXid);
444 }
XLogRecPtr log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
Definition: heapam.c:7467
#define XLogIsNeeded()
Definition: xlog.h:146
RelFileNode rd_node
Definition: rel.h:85
TransactionId latestRemovedXid
Definition: vacuumlazy.c:130
#define RelationNeedsWAL(relation)
Definition: rel.h:514
#define TransactionIdIsValid(xid)
Definition: transam.h:41

Variable Documentation

◆ elevel

◆ FreezeLimit

TransactionId FreezeLimit
static

Definition at line 139 of file vacuumlazy.c.

Referenced by lazy_check_needs_freeze(), lazy_scan_heap(), and lazy_vacuum_rel().

◆ MultiXactCutoff

MultiXactId MultiXactCutoff
static

◆ OldestXmin

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 142 of file vacuumlazy.c.

Referenced by lazy_cleanup_index(), and lazy_vacuum_index().