PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
vacuumlazy.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * vacuumlazy.c
4  * Concurrent ("lazy") vacuuming.
5  *
6  *
7  * The major space usage for LAZY VACUUM is storage for the array of dead tuple
8  * TIDs. We want to ensure we can vacuum even the very largest relations with
9  * finite memory space usage. To do that, we set upper bounds on the number of
10  * tuples we will keep track of at once.
11  *
12  * We are willing to use at most maintenance_work_mem (or perhaps
13  * autovacuum_work_mem) memory space to keep track of dead tuples. We
14  * initially allocate an array of TIDs of that size, with an upper limit that
15  * depends on table size (this limit ensures we don't allocate a huge area
16  * uselessly for vacuuming small tables). If the array threatens to overflow,
17  * we suspend the heap scan phase and perform a pass of index cleanup and page
18  * compaction, then resume the heap scan with an empty TID array.
19  *
20  * If we're processing a table with no indexes, we can just vacuum each page
21  * as we go; there's no need to save up multiple tuples to minimize the number
22  * of index scans performed. So we don't use maintenance_work_mem memory for
23  * the TID array, just enough to hold as many heap tuples as fit on one page.
24  *
25  *
26  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
27  * Portions Copyright (c) 1994, Regents of the University of California
28  *
29  *
30  * IDENTIFICATION
31  * src/backend/commands/vacuumlazy.c
32  *
33  *-------------------------------------------------------------------------
34  */
35 #include "postgres.h"
36 
37 #include <math.h>
38 
39 #include "access/genam.h"
40 #include "access/heapam.h"
41 #include "access/heapam_xlog.h"
42 #include "access/htup_details.h"
43 #include "access/multixact.h"
44 #include "access/transam.h"
45 #include "access/visibilitymap.h"
46 #include "access/xlog.h"
47 #include "catalog/catalog.h"
48 #include "catalog/storage.h"
49 #include "commands/dbcommands.h"
50 #include "commands/progress.h"
51 #include "commands/vacuum.h"
52 #include "miscadmin.h"
53 #include "pgstat.h"
54 #include "portability/instr_time.h"
55 #include "postmaster/autovacuum.h"
56 #include "storage/bufmgr.h"
57 #include "storage/freespace.h"
58 #include "storage/lmgr.h"
59 #include "utils/lsyscache.h"
60 #include "utils/memutils.h"
61 #include "utils/pg_rusage.h"
62 #include "utils/timestamp.h"
63 #include "utils/tqual.h"
64 
65 
66 /*
67  * Space/time tradeoff parameters: do these need to be user-tunable?
68  *
69  * To consider truncating the relation, we want there to be at least
70  * REL_TRUNCATE_MINIMUM or (relsize / REL_TRUNCATE_FRACTION) (whichever
71  * is less) potentially-freeable pages.
72  */
73 #define REL_TRUNCATE_MINIMUM 1000
74 #define REL_TRUNCATE_FRACTION 16
75 
76 /*
77  * Timing parameters for truncate locking heuristics.
78  *
79  * These were not exposed as user tunable GUC values because it didn't seem
80  * that the potential for improvement was great enough to merit the cost of
81  * supporting them.
82  */
83 #define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL 20 /* ms */
84 #define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL 50 /* ms */
85 #define VACUUM_TRUNCATE_LOCK_TIMEOUT 5000 /* ms */
86 
87 /*
88  * Guesstimation of number of dead tuples per page. This is used to
89  * provide an upper limit to memory allocated when vacuuming small
90  * tables.
91  */
92 #define LAZY_ALLOC_TUPLES MaxHeapTuplesPerPage
93 
94 /*
95  * Before we consider skipping a page that's marked as clean in
96  * visibility map, we must've seen at least this many clean pages.
97  */
98 #define SKIP_PAGES_THRESHOLD ((BlockNumber) 32)
99 
100 /*
101  * Size of the prefetch window for lazy vacuum backwards truncation scan.
102  * Needs to be a power of 2.
103  */
104 #define PREFETCH_SIZE ((BlockNumber) 32)
105 
106 typedef struct LVRelStats
107 {
108  /* hasindex = true means two-pass strategy; false means one-pass */
109  bool hasindex;
110  /* Overall statistics about rel */
111  BlockNumber old_rel_pages; /* previous value of pg_class.relpages */
112  BlockNumber rel_pages; /* total number of pages */
113  BlockNumber scanned_pages; /* number of pages we examined */
114  BlockNumber pinskipped_pages; /* # of pages we skipped due to a pin */
115  BlockNumber frozenskipped_pages; /* # of frozen pages we skipped */
116  BlockNumber tupcount_pages; /* pages whose tuples we counted */
117  double scanned_tuples; /* counts only tuples on tupcount_pages */
118  double old_rel_tuples; /* previous value of pg_class.reltuples */
119  double new_rel_tuples; /* new estimated total # of tuples */
120  double new_dead_tuples; /* new estimated total # of dead tuples */
123  BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
124  /* List of TIDs of tuples we intend to delete */
125  /* NB: this list is ordered by TID address */
126  int num_dead_tuples; /* current # of entries */
127  int max_dead_tuples; /* # slots allocated in array */
128  ItemPointer dead_tuples; /* array of ItemPointerData */
132 } LVRelStats;
133 
134 
135 /* A few variables that don't seem worth passing around as parameters */
136 static int elevel = -1;
137 
141 
143 
144 
145 /* non-export function prototypes */
146 static void lazy_scan_heap(Relation onerel, int options,
147  LVRelStats *vacrelstats, Relation *Irel, int nindexes,
148  bool aggressive);
149 static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats);
150 static bool lazy_check_needs_freeze(Buffer buf, bool *hastup);
151 static void lazy_vacuum_index(Relation indrel,
152  IndexBulkDeleteResult **stats,
153  LVRelStats *vacrelstats);
154 static void lazy_cleanup_index(Relation indrel,
155  IndexBulkDeleteResult *stats,
156  LVRelStats *vacrelstats);
157 static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer,
158  int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer);
159 static bool should_attempt_truncation(LVRelStats *vacrelstats);
160 static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats);
162  LVRelStats *vacrelstats);
163 static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks);
164 static void lazy_record_dead_tuple(LVRelStats *vacrelstats,
165  ItemPointer itemptr);
166 static bool lazy_tid_reaped(ItemPointer itemptr, void *state);
167 static int vac_cmp_itemptr(const void *left, const void *right);
169  TransactionId *visibility_cutoff_xid, bool *all_frozen);
170 
171 
172 /*
173  * lazy_vacuum_rel() -- perform LAZY VACUUM for one heap relation
174  *
175  * This routine vacuums a single heap, cleans out its indexes, and
176  * updates its relpages and reltuples statistics.
177  *
178  * At entry, we have already established a transaction and opened
179  * and locked the relation.
180  */
181 void
183  BufferAccessStrategy bstrategy)
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);
242  if (options & VACOPT_DISABLE_PAGE_SKIPPING)
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 
359  TimestampDifference(starttime, endtime, &secs, &usecs);
360 
361  read_rate = 0;
362  write_rate = 0;
363  if ((secs > 0) || (usecs > 0))
364  {
365  read_rate = (double) BLCKSZ * VacuumPageMiss / (1024 * 1024) /
366  (secs + usecs / 1000000.0);
367  write_rate = (double) BLCKSZ * VacuumPageDirty / (1024 * 1024) /
368  (secs + usecs / 1000000.0);
369  }
370 
371  /*
372  * This is pretty messy, but we split it up so that we can skip
373  * emitting individual parts of the message when not applicable.
374  */
375  initStringInfo(&buf);
376  appendStringInfo(&buf, _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n"),
379  RelationGetRelationName(onerel),
380  vacrelstats->num_index_scans);
381  appendStringInfo(&buf, _("pages: %u removed, %u remain, %u skipped due to pins, %u skipped frozen\n"),
382  vacrelstats->pages_removed,
383  vacrelstats->rel_pages,
384  vacrelstats->pinskipped_pages,
385  vacrelstats->frozenskipped_pages);
386  appendStringInfo(&buf,
387  _("tuples: %.0f removed, %.0f remain, %.0f are dead but not yet removable, oldest xmin: %u\n"),
388  vacrelstats->tuples_deleted,
389  vacrelstats->new_rel_tuples,
390  vacrelstats->new_dead_tuples,
391  OldestXmin);
392  appendStringInfo(&buf,
393  _("buffer usage: %d hits, %d misses, %d dirtied\n"),
397  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
398  read_rate, write_rate);
399  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
400 
401  ereport(LOG,
402  (errmsg_internal("%s", buf.data)));
403  pfree(buf.data);
404  }
405  }
406 }
407 
408 /*
409  * For Hot Standby we need to know the highest transaction id that will
410  * be removed by any change. VACUUM proceeds in a number of passes so
411  * we need to consider how each pass operates. The first phase runs
412  * heap_page_prune(), which can issue XLOG_HEAP2_CLEAN records as it
413  * progresses - these will have a latestRemovedXid on each record.
414  * In some cases this removes all of the tuples to be removed, though
415  * often we have dead tuples with index pointers so we must remember them
416  * for removal in phase 3. Index records for those rows are removed
417  * in phase 2 and index blocks do not have MVCC information attached.
418  * So before we can allow removal of any index tuples we need to issue
419  * a WAL record containing the latestRemovedXid of rows that will be
420  * removed in phase three. This allows recovery queries to block at the
421  * correct place, i.e. before phase two, rather than during phase three
422  * which would be after the rows have become inaccessible.
423  */
424 static void
426 {
427  /*
428  * Skip this for relations for which no WAL is to be written, or if we're
429  * not trying to support archive recovery.
430  */
431  if (!RelationNeedsWAL(rel) || !XLogIsNeeded())
432  return;
433 
434  /*
435  * No need to write the record at all unless it contains a valid value
436  */
437  if (TransactionIdIsValid(vacrelstats->latestRemovedXid))
438  (void) log_heap_cleanup_info(rel->rd_node, vacrelstats->latestRemovedXid);
439 }
440 
441 /*
442  * lazy_scan_heap() -- scan an open heap relation
443  *
444  * This routine prunes each page in the heap, which will among other
445  * things truncate dead tuples to dead line pointers, defragment the
446  * page, and set commit status bits (see heap_page_prune). It also builds
447  * lists of dead tuples and pages with free space, calculates statistics
448  * on the number of live tuples in the heap, and marks pages as
449  * all-visible if appropriate. When done, or when we run low on space for
450  * dead-tuple TIDs, invoke vacuuming of indexes and call lazy_vacuum_heap
451  * to reclaim dead line pointers.
452  *
453  * If there are no indexes then we can reclaim line pointers on the fly;
454  * dead line pointers need only be retained until all index pointers that
455  * reference them have been killed.
456  */
457 static void
458 lazy_scan_heap(Relation onerel, int options, LVRelStats *vacrelstats,
459  Relation *Irel, int nindexes, bool aggressive)
460 {
461  BlockNumber nblocks,
462  blkno;
463  HeapTupleData tuple;
464  char *relname;
465  BlockNumber empty_pages,
466  vacuumed_pages;
467  double num_tuples,
468  tups_vacuumed,
469  nkeep,
470  nunused;
471  IndexBulkDeleteResult **indstats;
472  int i;
473  PGRUsage ru0;
474  Buffer vmbuffer = InvalidBuffer;
475  BlockNumber next_unskippable_block;
476  bool skipping_blocks;
477  xl_heap_freeze_tuple *frozen;
479  const int initprog_index[] = {
483  };
484  int64 initprog_val[3];
485 
486  pg_rusage_init(&ru0);
487 
488  relname = RelationGetRelationName(onerel);
489  ereport(elevel,
490  (errmsg("vacuuming \"%s.%s\"",
492  relname)));
493 
494  empty_pages = vacuumed_pages = 0;
495  num_tuples = tups_vacuumed = nkeep = nunused = 0;
496 
497  indstats = (IndexBulkDeleteResult **)
498  palloc0(nindexes * sizeof(IndexBulkDeleteResult *));
499 
500  nblocks = RelationGetNumberOfBlocks(onerel);
501  vacrelstats->rel_pages = nblocks;
502  vacrelstats->scanned_pages = 0;
503  vacrelstats->tupcount_pages = 0;
504  vacrelstats->nonempty_pages = 0;
505  vacrelstats->latestRemovedXid = InvalidTransactionId;
506 
507  lazy_space_alloc(vacrelstats, nblocks);
509 
510  /* Report that we're scanning the heap, advertising total # of blocks */
511  initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
512  initprog_val[1] = nblocks;
513  initprog_val[2] = vacrelstats->max_dead_tuples;
514  pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
515 
516  /*
517  * Except when aggressive is set, we want to skip pages that are
518  * all-visible according to the visibility map, but only when we can skip
519  * at least SKIP_PAGES_THRESHOLD consecutive pages. Since we're reading
520  * sequentially, the OS should be doing readahead for us, so there's no
521  * gain in skipping a page now and then; that's likely to disable
522  * readahead and so be counterproductive. Also, skipping even a single
523  * page means that we can't update relfrozenxid, so we only want to do it
524  * if we can skip a goodly number of pages.
525  *
526  * When aggressive is set, we can't skip pages just because they are
527  * all-visible, but we can still skip pages that are all-frozen, since
528  * such pages do not need freezing and do not affect the value that we can
529  * safely set for relfrozenxid or relminmxid.
530  *
531  * Before entering the main loop, establish the invariant that
532  * next_unskippable_block is the next block number >= blkno that we
533  * can't skip based on the visibility map, either all-visible for a
534  * regular scan or all-frozen for an aggressive scan. We set it to
535  * nblocks if there's no such block. We also set up the skipping_blocks
536  * flag correctly at this stage.
537  *
538  * Note: The value returned by visibilitymap_get_status could be slightly
539  * out-of-date, since we make this test before reading the corresponding
540  * heap page or locking the buffer. This is OK. If we mistakenly think
541  * that the page is all-visible or all-frozen when in fact the flag's just
542  * been cleared, we might fail to vacuum the page. It's easy to see that
543  * skipping a page when aggressive is not set is not a very big deal; we
544  * might leave some dead tuples lying around, but the next vacuum will
545  * find them. But even when aggressive *is* set, it's still OK if we miss
546  * a page whose all-frozen marking has just been cleared. Any new XIDs
547  * just added to that page are necessarily newer than the GlobalXmin we
548  * computed, so they'll have no effect on the value to which we can safely
549  * set relfrozenxid. A similar argument applies for MXIDs and relminmxid.
550  *
551  * We will scan the table's last page, at least to the extent of
552  * determining whether it has tuples or not, even if it should be skipped
553  * according to the above rules; except when we've already determined that
554  * it's not worth trying to truncate the table. This avoids having
555  * lazy_truncate_heap() take access-exclusive lock on the table to attempt
556  * a truncation that just fails immediately because there are tuples in
557  * the last page. This is worth avoiding mainly because such a lock must
558  * be replayed on any hot standby, where it can be disruptive.
559  */
560  next_unskippable_block = 0;
561  if ((options & VACOPT_DISABLE_PAGE_SKIPPING) == 0)
562  {
563  while (next_unskippable_block < nblocks)
564  {
565  uint8 vmstatus;
566 
567  vmstatus = visibilitymap_get_status(onerel, next_unskippable_block,
568  &vmbuffer);
569  if (aggressive)
570  {
571  if ((vmstatus & VISIBILITYMAP_ALL_FROZEN) == 0)
572  break;
573  }
574  else
575  {
576  if ((vmstatus & VISIBILITYMAP_ALL_VISIBLE) == 0)
577  break;
578  }
580  next_unskippable_block++;
581  }
582  }
583 
584  if (next_unskippable_block >= SKIP_PAGES_THRESHOLD)
585  skipping_blocks = true;
586  else
587  skipping_blocks = false;
588 
589  for (blkno = 0; blkno < nblocks; blkno++)
590  {
591  Buffer buf;
592  Page page;
593  OffsetNumber offnum,
594  maxoff;
595  bool tupgone,
596  hastup;
597  int prev_dead_count;
598  int nfrozen;
599  Size freespace;
600  bool all_visible_according_to_vm = false;
601  bool all_visible;
602  bool all_frozen = true; /* provided all_visible is also true */
603  bool has_dead_tuples;
604  TransactionId visibility_cutoff_xid = InvalidTransactionId;
605 
606  /* see note above about forcing scanning of last page */
607 #define FORCE_CHECK_PAGE() \
608  (blkno == nblocks - 1 && should_attempt_truncation(vacrelstats))
609 
611 
612  if (blkno == next_unskippable_block)
613  {
614  /* Time to advance next_unskippable_block */
615  next_unskippable_block++;
616  if ((options & VACOPT_DISABLE_PAGE_SKIPPING) == 0)
617  {
618  while (next_unskippable_block < nblocks)
619  {
620  uint8 vmskipflags;
621 
622  vmskipflags = visibilitymap_get_status(onerel,
623  next_unskippable_block,
624  &vmbuffer);
625  if (aggressive)
626  {
627  if ((vmskipflags & VISIBILITYMAP_ALL_FROZEN) == 0)
628  break;
629  }
630  else
631  {
632  if ((vmskipflags & VISIBILITYMAP_ALL_VISIBLE) == 0)
633  break;
634  }
636  next_unskippable_block++;
637  }
638  }
639 
640  /*
641  * We know we can't skip the current block. But set up
642  * skipping_all_visible_blocks to do the right thing at the
643  * following blocks.
644  */
645  if (next_unskippable_block - blkno > SKIP_PAGES_THRESHOLD)
646  skipping_blocks = true;
647  else
648  skipping_blocks = false;
649 
650  /*
651  * Normally, the fact that we can't skip this block must mean that
652  * it's not all-visible. But in an aggressive vacuum we know only
653  * that it's not all-frozen, so it might still be all-visible.
654  */
655  if (aggressive && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer))
656  all_visible_according_to_vm = true;
657  }
658  else
659  {
660  /*
661  * The current block is potentially skippable; if we've seen a
662  * long enough run of skippable blocks to justify skipping it, and
663  * we're not forced to check it, then go ahead and skip.
664  * Otherwise, the page must be at least all-visible if not
665  * all-frozen, so we can set all_visible_according_to_vm = true.
666  */
667  if (skipping_blocks && !FORCE_CHECK_PAGE())
668  {
669  /*
670  * Tricky, tricky. If this is in aggressive vacuum, the page
671  * must have been all-frozen at the time we checked whether it
672  * was skippable, but it might not be any more. We must be
673  * careful to count it as a skipped all-frozen page in that
674  * case, or else we'll think we can't update relfrozenxid and
675  * relminmxid. If it's not an aggressive vacuum, we don't
676  * know whether it was all-frozen, so we have to recheck; but
677  * in this case an approximate answer is OK.
678  */
679  if (aggressive || VM_ALL_FROZEN(onerel, blkno, &vmbuffer))
680  vacrelstats->frozenskipped_pages++;
681  continue;
682  }
683  all_visible_according_to_vm = true;
684  }
685 
687 
688  /*
689  * If we are close to overrunning the available space for dead-tuple
690  * TIDs, pause and do a cycle of vacuuming before we tackle this page.
691  */
692  if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MaxHeapTuplesPerPage &&
693  vacrelstats->num_dead_tuples > 0)
694  {
695  const int hvp_index[] = {
698  };
699  int64 hvp_val[2];
700 
701  /*
702  * Before beginning index vacuuming, we release any pin we may
703  * hold on the visibility map page. This isn't necessary for
704  * correctness, but we do it anyway to avoid holding the pin
705  * across a lengthy, unrelated operation.
706  */
707  if (BufferIsValid(vmbuffer))
708  {
709  ReleaseBuffer(vmbuffer);
710  vmbuffer = InvalidBuffer;
711  }
712 
713  /* Log cleanup info before we touch indexes */
714  vacuum_log_cleanup_info(onerel, vacrelstats);
715 
716  /* Report that we are now vacuuming indexes */
719 
720  /* Remove index entries */
721  for (i = 0; i < nindexes; i++)
722  lazy_vacuum_index(Irel[i],
723  &indstats[i],
724  vacrelstats);
725 
726  /*
727  * Report that we are now vacuuming the heap. We also increase
728  * the number of index scans here; note that by using
729  * pgstat_progress_update_multi_param we can update both
730  * parameters atomically.
731  */
733  hvp_val[1] = vacrelstats->num_index_scans + 1;
734  pgstat_progress_update_multi_param(2, hvp_index, hvp_val);
735 
736  /* Remove tuples from heap */
737  lazy_vacuum_heap(onerel, vacrelstats);
738 
739  /*
740  * Forget the now-vacuumed tuples, and press on, but be careful
741  * not to reset latestRemovedXid since we want that value to be
742  * valid.
743  */
744  vacrelstats->num_dead_tuples = 0;
745  vacrelstats->num_index_scans++;
746 
747  /* Report that we are once again scanning the heap */
750  }
751 
752  /*
753  * Pin the visibility map page in case we need to mark the page
754  * all-visible. In most cases this will be very cheap, because we'll
755  * already have the correct page pinned anyway. However, it's
756  * possible that (a) next_unskippable_block is covered by a different
757  * VM page than the current block or (b) we released our pin and did a
758  * cycle of index vacuuming.
759  *
760  */
761  visibilitymap_pin(onerel, blkno, &vmbuffer);
762 
763  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno,
764  RBM_NORMAL, vac_strategy);
765 
766  /* We need buffer cleanup lock so that we can prune HOT chains. */
768  {
769  /*
770  * If we're not performing an aggressive scan to guard against XID
771  * wraparound, and we don't want to forcibly check the page, then
772  * it's OK to skip vacuuming pages we get a lock conflict on. They
773  * will be dealt with in some future vacuum.
774  */
775  if (!aggressive && !FORCE_CHECK_PAGE())
776  {
777  ReleaseBuffer(buf);
778  vacrelstats->pinskipped_pages++;
779  continue;
780  }
781 
782  /*
783  * Read the page with share lock to see if any xids on it need to
784  * be frozen. If not we just skip the page, after updating our
785  * scan statistics. If there are some, we wait for cleanup lock.
786  *
787  * We could defer the lock request further by remembering the page
788  * and coming back to it later, or we could even register
789  * ourselves for multiple buffers and then service whichever one
790  * is received first. For now, this seems good enough.
791  *
792  * If we get here with aggressive false, then we're just forcibly
793  * checking the page, and so we don't want to insist on getting
794  * the lock; we only need to know if the page contains tuples, so
795  * that we can update nonempty_pages correctly. It's convenient
796  * to use lazy_check_needs_freeze() for both situations, though.
797  */
799  if (!lazy_check_needs_freeze(buf, &hastup))
800  {
801  UnlockReleaseBuffer(buf);
802  vacrelstats->scanned_pages++;
803  vacrelstats->pinskipped_pages++;
804  if (hastup)
805  vacrelstats->nonempty_pages = blkno + 1;
806  continue;
807  }
808  if (!aggressive)
809  {
810  /*
811  * Here, we must not advance scanned_pages; that would amount
812  * to claiming that the page contains no freezable tuples.
813  */
814  UnlockReleaseBuffer(buf);
815  vacrelstats->pinskipped_pages++;
816  if (hastup)
817  vacrelstats->nonempty_pages = blkno + 1;
818  continue;
819  }
822  /* drop through to normal processing */
823  }
824 
825  vacrelstats->scanned_pages++;
826  vacrelstats->tupcount_pages++;
827 
828  page = BufferGetPage(buf);
829 
830  if (PageIsNew(page))
831  {
832  /*
833  * An all-zeroes page could be left over if a backend extends the
834  * relation but crashes before initializing the page. Reclaim such
835  * pages for use.
836  *
837  * We have to be careful here because we could be looking at a
838  * page that someone has just added to the relation and not yet
839  * been able to initialize (see RelationGetBufferForTuple). To
840  * protect against that, release the buffer lock, grab the
841  * relation extension lock momentarily, and re-lock the buffer. If
842  * the page is still uninitialized by then, it must be left over
843  * from a crashed backend, and we can initialize it.
844  *
845  * We don't really need the relation lock when this is a new or
846  * temp relation, but it's probably not worth the code space to
847  * check that, since this surely isn't a critical path.
848  *
849  * Note: the comparable code in vacuum.c need not worry because
850  * it's got exclusive lock on the whole relation.
851  */
856  if (PageIsNew(page))
857  {
859  (errmsg("relation \"%s\" page %u is uninitialized --- fixing",
860  relname, blkno)));
861  PageInit(page, BufferGetPageSize(buf), 0);
862  empty_pages++;
863  }
864  freespace = PageGetHeapFreeSpace(page);
865  MarkBufferDirty(buf);
866  UnlockReleaseBuffer(buf);
867 
868  RecordPageWithFreeSpace(onerel, blkno, freespace);
869  continue;
870  }
871 
872  if (PageIsEmpty(page))
873  {
874  empty_pages++;
875  freespace = PageGetHeapFreeSpace(page);
876 
877  /* empty pages are always all-visible and all-frozen */
878  if (!PageIsAllVisible(page))
879  {
881 
882  /* mark buffer dirty before writing a WAL record */
883  MarkBufferDirty(buf);
884 
885  /*
886  * It's possible that another backend has extended the heap,
887  * initialized the page, and then failed to WAL-log the page
888  * due to an ERROR. Since heap extension is not WAL-logged,
889  * recovery might try to replay our record setting the page
890  * all-visible and find that the page isn't initialized, which
891  * will cause a PANIC. To prevent that, check whether the
892  * page has been previously WAL-logged, and if not, do that
893  * now.
894  */
895  if (RelationNeedsWAL(onerel) &&
896  PageGetLSN(page) == InvalidXLogRecPtr)
897  log_newpage_buffer(buf, true);
898 
899  PageSetAllVisible(page);
900  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
901  vmbuffer, InvalidTransactionId,
904  }
905 
906  UnlockReleaseBuffer(buf);
907  RecordPageWithFreeSpace(onerel, blkno, freespace);
908  continue;
909  }
910 
911  /*
912  * Prune all HOT-update chains in this page.
913  *
914  * We count tuples removed by the pruning step as removed by VACUUM.
915  */
916  tups_vacuumed += heap_page_prune(onerel, buf, OldestXmin, false,
917  &vacrelstats->latestRemovedXid);
918 
919  /*
920  * Now scan the page to collect vacuumable items and check for tuples
921  * requiring freezing.
922  */
923  all_visible = true;
924  has_dead_tuples = false;
925  nfrozen = 0;
926  hastup = false;
927  prev_dead_count = vacrelstats->num_dead_tuples;
928  maxoff = PageGetMaxOffsetNumber(page);
929 
930  /*
931  * Note: If you change anything in the loop below, also look at
932  * heap_page_is_all_visible to see if that needs to be changed.
933  */
934  for (offnum = FirstOffsetNumber;
935  offnum <= maxoff;
936  offnum = OffsetNumberNext(offnum))
937  {
938  ItemId itemid;
939 
940  itemid = PageGetItemId(page, offnum);
941 
942  /* Unused items require no processing, but we count 'em */
943  if (!ItemIdIsUsed(itemid))
944  {
945  nunused += 1;
946  continue;
947  }
948 
949  /* Redirect items mustn't be touched */
950  if (ItemIdIsRedirected(itemid))
951  {
952  hastup = true; /* this page won't be truncatable */
953  continue;
954  }
955 
956  ItemPointerSet(&(tuple.t_self), blkno, offnum);
957 
958  /*
959  * DEAD item pointers are to be vacuumed normally; but we don't
960  * count them in tups_vacuumed, else we'd be double-counting (at
961  * least in the common case where heap_page_prune() just freed up
962  * a non-HOT tuple).
963  */
964  if (ItemIdIsDead(itemid))
965  {
966  lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
967  all_visible = false;
968  continue;
969  }
970 
971  Assert(ItemIdIsNormal(itemid));
972 
973  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
974  tuple.t_len = ItemIdGetLength(itemid);
975  tuple.t_tableOid = RelationGetRelid(onerel);
976 
977  tupgone = false;
978 
979  switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
980  {
981  case HEAPTUPLE_DEAD:
982 
983  /*
984  * Ordinarily, DEAD tuples would have been removed by
985  * heap_page_prune(), but it's possible that the tuple
986  * state changed since heap_page_prune() looked. In
987  * particular an INSERT_IN_PROGRESS tuple could have
988  * changed to DEAD if the inserter aborted. So this
989  * cannot be considered an error condition.
990  *
991  * If the tuple is HOT-updated then it must only be
992  * removed by a prune operation; so we keep it just as if
993  * it were RECENTLY_DEAD. Also, if it's a heap-only
994  * tuple, we choose to keep it, because it'll be a lot
995  * cheaper to get rid of it in the next pruning pass than
996  * to treat it like an indexed tuple.
997  */
998  if (HeapTupleIsHotUpdated(&tuple) ||
999  HeapTupleIsHeapOnly(&tuple))
1000  nkeep += 1;
1001  else
1002  tupgone = true; /* we can delete the tuple */
1003  all_visible = false;
1004  break;
1005  case HEAPTUPLE_LIVE:
1006  /* Tuple is good --- but let's do some validity checks */
1007  if (onerel->rd_rel->relhasoids &&
1008  !OidIsValid(HeapTupleGetOid(&tuple)))
1009  elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid",
1010  relname, blkno, offnum);
1011 
1012  /*
1013  * Is the tuple definitely visible to all transactions?
1014  *
1015  * NB: Like with per-tuple hint bits, we can't set the
1016  * PD_ALL_VISIBLE flag if the inserter committed
1017  * asynchronously. See SetHintBits for more info. Check
1018  * that the tuple is hinted xmin-committed because of
1019  * that.
1020  */
1021  if (all_visible)
1022  {
1023  TransactionId xmin;
1024 
1026  {
1027  all_visible = false;
1028  break;
1029  }
1030 
1031  /*
1032  * The inserter definitely committed. But is it old
1033  * enough that everyone sees it as committed?
1034  */
1035  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
1036  if (!TransactionIdPrecedes(xmin, OldestXmin))
1037  {
1038  all_visible = false;
1039  break;
1040  }
1041 
1042  /* Track newest xmin on page. */
1043  if (TransactionIdFollows(xmin, visibility_cutoff_xid))
1044  visibility_cutoff_xid = xmin;
1045  }
1046  break;
1048 
1049  /*
1050  * If tuple is recently deleted then we must not remove it
1051  * from relation.
1052  */
1053  nkeep += 1;
1054  all_visible = false;
1055  break;
1057  /* This is an expected case during concurrent vacuum */
1058  all_visible = false;
1059  break;
1061  /* This is an expected case during concurrent vacuum */
1062  all_visible = false;
1063  break;
1064  default:
1065  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1066  break;
1067  }
1068 
1069  if (tupgone)
1070  {
1071  lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
1073  &vacrelstats->latestRemovedXid);
1074  tups_vacuumed += 1;
1075  has_dead_tuples = true;
1076  }
1077  else
1078  {
1079  bool tuple_totally_frozen;
1080 
1081  num_tuples += 1;
1082  hastup = true;
1083 
1084  /*
1085  * Each non-removable tuple must be checked to see if it needs
1086  * freezing. Note we already have exclusive buffer lock.
1087  */
1089  MultiXactCutoff, &frozen[nfrozen],
1090  &tuple_totally_frozen))
1091  frozen[nfrozen++].offset = offnum;
1092 
1093  if (!tuple_totally_frozen)
1094  all_frozen = false;
1095  }
1096  } /* scan along page */
1097 
1098  /*
1099  * If we froze any tuples, mark the buffer dirty, and write a WAL
1100  * record recording the changes. We must log the changes to be
1101  * crash-safe against future truncation of CLOG.
1102  */
1103  if (nfrozen > 0)
1104  {
1106 
1107  MarkBufferDirty(buf);
1108 
1109  /* execute collected freezes */
1110  for (i = 0; i < nfrozen; i++)
1111  {
1112  ItemId itemid;
1113  HeapTupleHeader htup;
1114 
1115  itemid = PageGetItemId(page, frozen[i].offset);
1116  htup = (HeapTupleHeader) PageGetItem(page, itemid);
1117 
1118  heap_execute_freeze_tuple(htup, &frozen[i]);
1119  }
1120 
1121  /* Now WAL-log freezing if necessary */
1122  if (RelationNeedsWAL(onerel))
1123  {
1124  XLogRecPtr recptr;
1125 
1126  recptr = log_heap_freeze(onerel, buf, FreezeLimit,
1127  frozen, nfrozen);
1128  PageSetLSN(page, recptr);
1129  }
1130 
1131  END_CRIT_SECTION();
1132  }
1133 
1134  /*
1135  * If there are no indexes then we can vacuum the page right now
1136  * instead of doing a second scan.
1137  */
1138  if (nindexes == 0 &&
1139  vacrelstats->num_dead_tuples > 0)
1140  {
1141  /* Remove tuples from heap */
1142  lazy_vacuum_page(onerel, blkno, buf, 0, vacrelstats, &vmbuffer);
1143  has_dead_tuples = false;
1144 
1145  /*
1146  * Forget the now-vacuumed tuples, and press on, but be careful
1147  * not to reset latestRemovedXid since we want that value to be
1148  * valid.
1149  */
1150  vacrelstats->num_dead_tuples = 0;
1151  vacuumed_pages++;
1152  }
1153 
1154  freespace = PageGetHeapFreeSpace(page);
1155 
1156  /* mark page all-visible, if appropriate */
1157  if (all_visible && !all_visible_according_to_vm)
1158  {
1160 
1161  if (all_frozen)
1162  flags |= VISIBILITYMAP_ALL_FROZEN;
1163 
1164  /*
1165  * It should never be the case that the visibility map page is set
1166  * while the page-level bit is clear, but the reverse is allowed
1167  * (if checksums are not enabled). Regardless, set the both bits
1168  * so that we get back in sync.
1169  *
1170  * NB: If the heap page is all-visible but the VM bit is not set,
1171  * we don't need to dirty the heap page. However, if checksums
1172  * are enabled, we do need to make sure that the heap page is
1173  * dirtied before passing it to visibilitymap_set(), because it
1174  * may be logged. Given that this situation should only happen in
1175  * rare cases after a crash, it is not worth optimizing.
1176  */
1177  PageSetAllVisible(page);
1178  MarkBufferDirty(buf);
1179  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1180  vmbuffer, visibility_cutoff_xid, flags);
1181  }
1182 
1183  /*
1184  * As of PostgreSQL 9.2, the visibility map bit should never be set if
1185  * the page-level bit is clear. However, it's possible that the bit
1186  * got cleared after we checked it and before we took the buffer
1187  * content lock, so we must recheck before jumping to the conclusion
1188  * that something bad has happened.
1189  */
1190  else if (all_visible_according_to_vm && !PageIsAllVisible(page)
1191  && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer))
1192  {
1193  elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
1194  relname, blkno);
1195  visibilitymap_clear(onerel, blkno, vmbuffer,
1197  }
1198 
1199  /*
1200  * It's possible for the value returned by GetOldestXmin() to move
1201  * backwards, so it's not wrong for us to see tuples that appear to
1202  * not be visible to everyone yet, while PD_ALL_VISIBLE is already
1203  * set. The real safe xmin value never moves backwards, but
1204  * GetOldestXmin() is conservative and sometimes returns a value
1205  * that's unnecessarily small, so if we see that contradiction it just
1206  * means that the tuples that we think are not visible to everyone yet
1207  * actually are, and the PD_ALL_VISIBLE flag is correct.
1208  *
1209  * There should never be dead tuples on a page with PD_ALL_VISIBLE
1210  * set, however.
1211  */
1212  else if (PageIsAllVisible(page) && has_dead_tuples)
1213  {
1214  elog(WARNING, "page containing dead tuples is marked as all-visible in relation \"%s\" page %u",
1215  relname, blkno);
1216  PageClearAllVisible(page);
1217  MarkBufferDirty(buf);
1218  visibilitymap_clear(onerel, blkno, vmbuffer,
1220  }
1221 
1222  /*
1223  * If the all-visible page is turned out to be all-frozen but not
1224  * marked, we should so mark it. Note that all_frozen is only valid
1225  * if all_visible is true, so we must check both.
1226  */
1227  else if (all_visible_according_to_vm && all_visible && all_frozen &&
1228  !VM_ALL_FROZEN(onerel, blkno, &vmbuffer))
1229  {
1230  /*
1231  * We can pass InvalidTransactionId as the cutoff XID here,
1232  * because setting the all-frozen bit doesn't cause recovery
1233  * conflicts.
1234  */
1235  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1236  vmbuffer, InvalidTransactionId,
1238  }
1239 
1240  UnlockReleaseBuffer(buf);
1241 
1242  /* Remember the location of the last page with nonremovable tuples */
1243  if (hastup)
1244  vacrelstats->nonempty_pages = blkno + 1;
1245 
1246  /*
1247  * If we remembered any tuples for deletion, then the page will be
1248  * visited again by lazy_vacuum_heap, which will compute and record
1249  * its post-compaction free space. If not, then we're done with this
1250  * page, so remember its free space as-is. (This path will always be
1251  * taken if there are no indexes.)
1252  */
1253  if (vacrelstats->num_dead_tuples == prev_dead_count)
1254  RecordPageWithFreeSpace(onerel, blkno, freespace);
1255  }
1256 
1257  /* report that everything is scanned and vacuumed */
1259 
1260  pfree(frozen);
1261 
1262  /* save stats for use later */
1263  vacrelstats->scanned_tuples = num_tuples;
1264  vacrelstats->tuples_deleted = tups_vacuumed;
1265  vacrelstats->new_dead_tuples = nkeep;
1266 
1267  /* now we can compute the new value for pg_class.reltuples */
1268  vacrelstats->new_rel_tuples = vac_estimate_reltuples(onerel, false,
1269  nblocks,
1270  vacrelstats->tupcount_pages,
1271  num_tuples);
1272 
1273  /*
1274  * Release any remaining pin on visibility map page.
1275  */
1276  if (BufferIsValid(vmbuffer))
1277  {
1278  ReleaseBuffer(vmbuffer);
1279  vmbuffer = InvalidBuffer;
1280  }
1281 
1282  /* If any tuples need to be deleted, perform final vacuum cycle */
1283  /* XXX put a threshold on min number of tuples here? */
1284  if (vacrelstats->num_dead_tuples > 0)
1285  {
1286  const int hvp_index[] = {
1289  };
1290  int64 hvp_val[2];
1291 
1292  /* Log cleanup info before we touch indexes */
1293  vacuum_log_cleanup_info(onerel, vacrelstats);
1294 
1295  /* Report that we are now vacuuming indexes */
1298 
1299  /* Remove index entries */
1300  for (i = 0; i < nindexes; i++)
1301  lazy_vacuum_index(Irel[i],
1302  &indstats[i],
1303  vacrelstats);
1304 
1305  /* Report that we are now vacuuming the heap */
1306  hvp_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_HEAP;
1307  hvp_val[1] = vacrelstats->num_index_scans + 1;
1308  pgstat_progress_update_multi_param(2, hvp_index, hvp_val);
1309 
1310  /* Remove tuples from heap */
1313  lazy_vacuum_heap(onerel, vacrelstats);
1314  vacrelstats->num_index_scans++;
1315  }
1316 
1317  /* report all blocks vacuumed; and that we're cleaning up */
1321 
1322  /* Do post-vacuum cleanup and statistics update for each index */
1323  for (i = 0; i < nindexes; i++)
1324  lazy_cleanup_index(Irel[i], indstats[i], vacrelstats);
1325 
1326  /* If no indexes, make log report that lazy_vacuum_heap would've made */
1327  if (vacuumed_pages)
1328  ereport(elevel,
1329  (errmsg("\"%s\": removed %.0f row versions in %u pages",
1330  RelationGetRelationName(onerel),
1331  tups_vacuumed, vacuumed_pages)));
1332 
1333  /*
1334  * This is pretty messy, but we split it up so that we can skip emitting
1335  * individual parts of the message when not applicable.
1336  */
1337  initStringInfo(&buf);
1338  appendStringInfo(&buf,
1339  _("%.0f dead row versions cannot be removed yet, oldest xmin: %u\n"),
1340  nkeep, OldestXmin);
1341  appendStringInfo(&buf, _("There were %.0f unused item pointers.\n"),
1342  nunused);
1343  appendStringInfo(&buf, ngettext("Skipped %u page due to buffer pins, ",
1344  "Skipped %u pages due to buffer pins, ",
1345  vacrelstats->pinskipped_pages),
1346  vacrelstats->pinskipped_pages);
1347  appendStringInfo(&buf, ngettext("%u frozen page.\n",
1348  "%u frozen pages.\n",
1349  vacrelstats->frozenskipped_pages),
1350  vacrelstats->frozenskipped_pages);
1351  appendStringInfo(&buf, ngettext("%u page is entirely empty.\n",
1352  "%u pages are entirely empty.\n",
1353  empty_pages),
1354  empty_pages);
1355  appendStringInfo(&buf, "%s.", pg_rusage_show(&ru0));
1356 
1357  ereport(elevel,
1358  (errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u out of %u pages",
1359  RelationGetRelationName(onerel),
1360  tups_vacuumed, num_tuples,
1361  vacrelstats->scanned_pages, nblocks),
1362  errdetail_internal("%s", buf.data)));
1363  pfree(buf.data);
1364 }
1365 
1366 
1367 /*
1368  * lazy_vacuum_heap() -- second pass over the heap
1369  *
1370  * This routine marks dead tuples as unused and compacts out free
1371  * space on their pages. Pages not having dead tuples recorded from
1372  * lazy_scan_heap are not visited at all.
1373  *
1374  * Note: the reason for doing this as a second pass is we cannot remove
1375  * the tuples until we've removed their index entries, and we want to
1376  * process index entry removal in batches as large as possible.
1377  */
1378 static void
1379 lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats)
1380 {
1381  int tupindex;
1382  int npages;
1383  PGRUsage ru0;
1384  Buffer vmbuffer = InvalidBuffer;
1385 
1386  pg_rusage_init(&ru0);
1387  npages = 0;
1388 
1389  tupindex = 0;
1390  while (tupindex < vacrelstats->num_dead_tuples)
1391  {
1392  BlockNumber tblk;
1393  Buffer buf;
1394  Page page;
1395  Size freespace;
1396 
1398 
1399  tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
1400  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, tblk, RBM_NORMAL,
1401  vac_strategy);
1403  {
1404  ReleaseBuffer(buf);
1405  ++tupindex;
1406  continue;
1407  }
1408  tupindex = lazy_vacuum_page(onerel, tblk, buf, tupindex, vacrelstats,
1409  &vmbuffer);
1410 
1411  /* Now that we've compacted the page, record its available space */
1412  page = BufferGetPage(buf);
1413  freespace = PageGetHeapFreeSpace(page);
1414 
1415  UnlockReleaseBuffer(buf);
1416  RecordPageWithFreeSpace(onerel, tblk, freespace);
1417  npages++;
1418  }
1419 
1420  if (BufferIsValid(vmbuffer))
1421  {
1422  ReleaseBuffer(vmbuffer);
1423  vmbuffer = InvalidBuffer;
1424  }
1425 
1426  ereport(elevel,
1427  (errmsg("\"%s\": removed %d row versions in %d pages",
1428  RelationGetRelationName(onerel),
1429  tupindex, npages),
1430  errdetail_internal("%s", pg_rusage_show(&ru0))));
1431 }
1432 
1433 /*
1434  * lazy_vacuum_page() -- free dead tuples on a page
1435  * and repair its fragmentation.
1436  *
1437  * Caller must hold pin and buffer cleanup lock on the buffer.
1438  *
1439  * tupindex is the index in vacrelstats->dead_tuples of the first dead
1440  * tuple for this page. We assume the rest follow sequentially.
1441  * The return value is the first tupindex after the tuples of this page.
1442  */
1443 static int
1445  int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
1446 {
1447  Page page = BufferGetPage(buffer);
1448  OffsetNumber unused[MaxOffsetNumber];
1449  int uncnt = 0;
1450  TransactionId visibility_cutoff_xid;
1451  bool all_frozen;
1452 
1454 
1456 
1457  for (; tupindex < vacrelstats->num_dead_tuples; tupindex++)
1458  {
1459  BlockNumber tblk;
1460  OffsetNumber toff;
1461  ItemId itemid;
1462 
1463  tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
1464  if (tblk != blkno)
1465  break; /* past end of tuples for this block */
1466  toff = ItemPointerGetOffsetNumber(&vacrelstats->dead_tuples[tupindex]);
1467  itemid = PageGetItemId(page, toff);
1468  ItemIdSetUnused(itemid);
1469  unused[uncnt++] = toff;
1470  }
1471 
1473 
1474  /*
1475  * Mark buffer dirty before we write WAL.
1476  */
1477  MarkBufferDirty(buffer);
1478 
1479  /* XLOG stuff */
1480  if (RelationNeedsWAL(onerel))
1481  {
1482  XLogRecPtr recptr;
1483 
1484  recptr = log_heap_clean(onerel, buffer,
1485  NULL, 0, NULL, 0,
1486  unused, uncnt,
1487  vacrelstats->latestRemovedXid);
1488  PageSetLSN(page, recptr);
1489  }
1490 
1491  /*
1492  * End critical section, so we safely can do visibility tests (which
1493  * possibly need to perform IO and allocate memory!). If we crash now the
1494  * page (including the corresponding vm bit) might not be marked all
1495  * visible, but that's fine. A later vacuum will fix that.
1496  */
1497  END_CRIT_SECTION();
1498 
1499  /*
1500  * Now that we have removed the dead tuples from the page, once again
1501  * check if the page has become all-visible. The page is already marked
1502  * dirty, exclusively locked, and, if needed, a full page image has been
1503  * emitted in the log_heap_clean() above.
1504  */
1505  if (heap_page_is_all_visible(onerel, buffer, &visibility_cutoff_xid,
1506  &all_frozen))
1507  PageSetAllVisible(page);
1508 
1509  /*
1510  * All the changes to the heap page have been done. If the all-visible
1511  * flag is now set, also set the VM all-visible bit (and, if possible, the
1512  * all-frozen bit) unless this has already been done previously.
1513  */
1514  if (PageIsAllVisible(page))
1515  {
1516  uint8 vm_status = visibilitymap_get_status(onerel, blkno, vmbuffer);
1517  uint8 flags = 0;
1518 
1519  /* Set the VM all-frozen bit to flag, if needed */
1520  if ((vm_status & VISIBILITYMAP_ALL_VISIBLE) == 0)
1521  flags |= VISIBILITYMAP_ALL_VISIBLE;
1522  if ((vm_status & VISIBILITYMAP_ALL_FROZEN) == 0 && all_frozen)
1523  flags |= VISIBILITYMAP_ALL_FROZEN;
1524 
1525  Assert(BufferIsValid(*vmbuffer));
1526  if (flags != 0)
1527  visibilitymap_set(onerel, blkno, buffer, InvalidXLogRecPtr,
1528  *vmbuffer, visibility_cutoff_xid, flags);
1529  }
1530 
1531  return tupindex;
1532 }
1533 
1534 /*
1535  * lazy_check_needs_freeze() -- scan page to see if any tuples
1536  * need to be cleaned to avoid wraparound
1537  *
1538  * Returns true if the page needs to be vacuumed using cleanup lock.
1539  * Also returns a flag indicating whether page contains any tuples at all.
1540  */
1541 static bool
1543 {
1544  Page page = BufferGetPage(buf);
1545  OffsetNumber offnum,
1546  maxoff;
1547  HeapTupleHeader tupleheader;
1548 
1549  *hastup = false;
1550 
1551  /* If we hit an uninitialized page, we want to force vacuuming it. */
1552  if (PageIsNew(page))
1553  return true;
1554 
1555  /* Quick out for ordinary empty page. */
1556  if (PageIsEmpty(page))
1557  return false;
1558 
1559  maxoff = PageGetMaxOffsetNumber(page);
1560  for (offnum = FirstOffsetNumber;
1561  offnum <= maxoff;
1562  offnum = OffsetNumberNext(offnum))
1563  {
1564  ItemId itemid;
1565 
1566  itemid = PageGetItemId(page, offnum);
1567 
1568  /* this should match hastup test in count_nondeletable_pages() */
1569  if (ItemIdIsUsed(itemid))
1570  *hastup = true;
1571 
1572  /* dead and redirect items never need freezing */
1573  if (!ItemIdIsNormal(itemid))
1574  continue;
1575 
1576  tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
1577 
1578  if (heap_tuple_needs_freeze(tupleheader, FreezeLimit,
1579  MultiXactCutoff, buf))
1580  return true;
1581  } /* scan along page */
1582 
1583  return false;
1584 }
1585 
1586 
1587 /*
1588  * lazy_vacuum_index() -- vacuum one index relation.
1589  *
1590  * Delete all the index entries pointing to tuples listed in
1591  * vacrelstats->dead_tuples, and update running statistics.
1592  */
1593 static void
1595  IndexBulkDeleteResult **stats,
1596  LVRelStats *vacrelstats)
1597 {
1598  IndexVacuumInfo ivinfo;
1599  PGRUsage ru0;
1600 
1601  pg_rusage_init(&ru0);
1602 
1603  ivinfo.index = indrel;
1604  ivinfo.analyze_only = false;
1605  ivinfo.estimated_count = true;
1606  ivinfo.message_level = elevel;
1607  ivinfo.num_heap_tuples = vacrelstats->old_rel_tuples;
1608  ivinfo.strategy = vac_strategy;
1609 
1610  /* Do bulk deletion */
1611  *stats = index_bulk_delete(&ivinfo, *stats,
1612  lazy_tid_reaped, (void *) vacrelstats);
1613 
1614  ereport(elevel,
1615  (errmsg("scanned index \"%s\" to remove %d row versions",
1616  RelationGetRelationName(indrel),
1617  vacrelstats->num_dead_tuples),
1618  errdetail_internal("%s", pg_rusage_show(&ru0))));
1619 }
1620 
1621 /*
1622  * lazy_cleanup_index() -- do post-vacuum cleanup for one index relation.
1623  */
1624 static void
1626  IndexBulkDeleteResult *stats,
1627  LVRelStats *vacrelstats)
1628 {
1629  IndexVacuumInfo ivinfo;
1630  PGRUsage ru0;
1631 
1632  pg_rusage_init(&ru0);
1633 
1634  ivinfo.index = indrel;
1635  ivinfo.analyze_only = false;
1636  ivinfo.estimated_count = (vacrelstats->tupcount_pages < vacrelstats->rel_pages);
1637  ivinfo.message_level = elevel;
1638  ivinfo.num_heap_tuples = vacrelstats->new_rel_tuples;
1639  ivinfo.strategy = vac_strategy;
1640 
1641  stats = index_vacuum_cleanup(&ivinfo, stats);
1642 
1643  if (!stats)
1644  return;
1645 
1646  /*
1647  * Now update statistics in pg_class, but only if the index says the count
1648  * is accurate.
1649  */
1650  if (!stats->estimated_count)
1651  vac_update_relstats(indrel,
1652  stats->num_pages,
1653  stats->num_index_tuples,
1654  0,
1655  false,
1658  false);
1659 
1660  ereport(elevel,
1661  (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
1662  RelationGetRelationName(indrel),
1663  stats->num_index_tuples,
1664  stats->num_pages),
1665  errdetail("%.0f index row versions were removed.\n"
1666  "%u index pages have been deleted, %u are currently reusable.\n"
1667  "%s.",
1668  stats->tuples_removed,
1669  stats->pages_deleted, stats->pages_free,
1670  pg_rusage_show(&ru0))));
1671 
1672  pfree(stats);
1673 }
1674 
1675 /*
1676  * should_attempt_truncation - should we attempt to truncate the heap?
1677  *
1678  * Don't even think about it unless we have a shot at releasing a goodly
1679  * number of pages. Otherwise, the time taken isn't worth it.
1680  *
1681  * Also don't attempt it if we are doing early pruning/vacuuming, because a
1682  * scan which cannot find a truncated heap page cannot determine that the
1683  * snapshot is too old to read that page. We might be able to get away with
1684  * truncating all except one of the pages, setting its LSN to (at least) the
1685  * maximum of the truncated range if we also treated an index leaf tuple
1686  * pointing to a missing heap page as something to trigger the "snapshot too
1687  * old" error, but that seems fragile and seems like it deserves its own patch
1688  * if we consider it.
1689  *
1690  * This is split out so that we can test whether truncation is going to be
1691  * called for before we actually do it. If you change the logic here, be
1692  * careful to depend only on fields that lazy_scan_heap updates on-the-fly.
1693  */
1694 static bool
1696 {
1697  BlockNumber possibly_freeable;
1698 
1699  possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
1700  if (possibly_freeable > 0 &&
1701  (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
1702  possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) &&
1704  return true;
1705  else
1706  return false;
1707 }
1708 
1709 /*
1710  * lazy_truncate_heap - try to truncate off any empty pages at the end
1711  */
1712 static void
1714 {
1715  BlockNumber old_rel_pages = vacrelstats->rel_pages;
1716  BlockNumber new_rel_pages;
1717  PGRUsage ru0;
1718  int lock_retry;
1719 
1720  pg_rusage_init(&ru0);
1721 
1722  /* Report that we are now truncating */
1725 
1726  /*
1727  * Loop until no more truncating can be done.
1728  */
1729  do
1730  {
1731  /*
1732  * We need full exclusive lock on the relation in order to do
1733  * truncation. If we can't get it, give up rather than waiting --- we
1734  * don't want to block other backends, and we don't want to deadlock
1735  * (which is quite possible considering we already hold a lower-grade
1736  * lock).
1737  */
1738  vacrelstats->lock_waiter_detected = false;
1739  lock_retry = 0;
1740  while (true)
1741  {
1743  break;
1744 
1745  /*
1746  * Check for interrupts while trying to (re-)acquire the exclusive
1747  * lock.
1748  */
1750 
1751  if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT /
1753  {
1754  /*
1755  * We failed to establish the lock in the specified number of
1756  * retries. This means we give up truncating.
1757  */
1758  vacrelstats->lock_waiter_detected = true;
1759  ereport(elevel,
1760  (errmsg("\"%s\": stopping truncate due to conflicting lock request",
1761  RelationGetRelationName(onerel))));
1762  return;
1763  }
1764 
1766  }
1767 
1768  /*
1769  * Now that we have exclusive lock, look to see if the rel has grown
1770  * whilst we were vacuuming with non-exclusive lock. If so, give up;
1771  * the newly added pages presumably contain non-deletable tuples.
1772  */
1773  new_rel_pages = RelationGetNumberOfBlocks(onerel);
1774  if (new_rel_pages != old_rel_pages)
1775  {
1776  /*
1777  * Note: we intentionally don't update vacrelstats->rel_pages with
1778  * the new rel size here. If we did, it would amount to assuming
1779  * that the new pages are empty, which is unlikely. Leaving the
1780  * numbers alone amounts to assuming that the new pages have the
1781  * same tuple density as existing ones, which is less unlikely.
1782  */
1784  return;
1785  }
1786 
1787  /*
1788  * Scan backwards from the end to verify that the end pages actually
1789  * contain no tuples. This is *necessary*, not optional, because
1790  * other backends could have added tuples to these pages whilst we
1791  * were vacuuming.
1792  */
1793  new_rel_pages = count_nondeletable_pages(onerel, vacrelstats);
1794 
1795  if (new_rel_pages >= old_rel_pages)
1796  {
1797  /* can't do anything after all */
1799  return;
1800  }
1801 
1802  /*
1803  * Okay to truncate.
1804  */
1805  RelationTruncate(onerel, new_rel_pages);
1806 
1807  /*
1808  * We can release the exclusive lock as soon as we have truncated.
1809  * Other backends can't safely access the relation until they have
1810  * processed the smgr invalidation that smgrtruncate sent out ... but
1811  * that should happen as part of standard invalidation processing once
1812  * they acquire lock on the relation.
1813  */
1815 
1816  /*
1817  * Update statistics. Here, it *is* correct to adjust rel_pages
1818  * without also touching reltuples, since the tuple count wasn't
1819  * changed by the truncation.
1820  */
1821  vacrelstats->pages_removed += old_rel_pages - new_rel_pages;
1822  vacrelstats->rel_pages = new_rel_pages;
1823 
1824  ereport(elevel,
1825  (errmsg("\"%s\": truncated %u to %u pages",
1826  RelationGetRelationName(onerel),
1827  old_rel_pages, new_rel_pages),
1828  errdetail_internal("%s",
1829  pg_rusage_show(&ru0))));
1830  old_rel_pages = new_rel_pages;
1831  } while (new_rel_pages > vacrelstats->nonempty_pages &&
1832  vacrelstats->lock_waiter_detected);
1833 }
1834 
1835 /*
1836  * Rescan end pages to verify that they are (still) empty of tuples.
1837  *
1838  * Returns number of nondeletable pages (last nonempty page + 1).
1839  */
1840 static BlockNumber
1842 {
1843  BlockNumber blkno;
1844  BlockNumber prefetchedUntil;
1845  instr_time starttime;
1846 
1847  /* Initialize the starttime if we check for conflicting lock requests */
1848  INSTR_TIME_SET_CURRENT(starttime);
1849 
1850  /*
1851  * Start checking blocks at what we believe relation end to be and move
1852  * backwards. (Strange coding of loop control is needed because blkno is
1853  * unsigned.) To make the scan faster, we prefetch a few blocks at a time
1854  * in forward direction, so that OS-level readahead can kick in.
1855  */
1856  blkno = vacrelstats->rel_pages;
1858  "prefetch size must be power of 2");
1859  prefetchedUntil = InvalidBlockNumber;
1860  while (blkno > vacrelstats->nonempty_pages)
1861  {
1862  Buffer buf;
1863  Page page;
1864  OffsetNumber offnum,
1865  maxoff;
1866  bool hastup;
1867 
1868  /*
1869  * Check if another process requests a lock on our relation. We are
1870  * holding an AccessExclusiveLock here, so they will be waiting. We
1871  * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
1872  * only check if that interval has elapsed once every 32 blocks to
1873  * keep the number of system calls and actual shared lock table
1874  * lookups to a minimum.
1875  */
1876  if ((blkno % 32) == 0)
1877  {
1878  instr_time currenttime;
1879  instr_time elapsed;
1880 
1881  INSTR_TIME_SET_CURRENT(currenttime);
1882  elapsed = currenttime;
1883  INSTR_TIME_SUBTRACT(elapsed, starttime);
1884  if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
1886  {
1888  {
1889  ereport(elevel,
1890  (errmsg("\"%s\": suspending truncate due to conflicting lock request",
1891  RelationGetRelationName(onerel))));
1892 
1893  vacrelstats->lock_waiter_detected = true;
1894  return blkno;
1895  }
1896  starttime = currenttime;
1897  }
1898  }
1899 
1900  /*
1901  * We don't insert a vacuum delay point here, because we have an
1902  * exclusive lock on the table which we want to hold for as short a
1903  * time as possible. We still need to check for interrupts however.
1904  */
1906 
1907  blkno--;
1908 
1909  /* If we haven't prefetched this lot yet, do so now. */
1910  if (prefetchedUntil > blkno)
1911  {
1912  BlockNumber prefetchStart;
1913  BlockNumber pblkno;
1914 
1915  prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
1916  for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
1917  {
1918  PrefetchBuffer(onerel, MAIN_FORKNUM, pblkno);
1920  }
1921  prefetchedUntil = prefetchStart;
1922  }
1923 
1924  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno,
1925  RBM_NORMAL, vac_strategy);
1926 
1927  /* In this phase we only need shared access to the buffer */
1929 
1930  page = BufferGetPage(buf);
1931 
1932  if (PageIsNew(page) || PageIsEmpty(page))
1933  {
1934  /* PageIsNew probably shouldn't happen... */
1935  UnlockReleaseBuffer(buf);
1936  continue;
1937  }
1938 
1939  hastup = false;
1940  maxoff = PageGetMaxOffsetNumber(page);
1941  for (offnum = FirstOffsetNumber;
1942  offnum <= maxoff;
1943  offnum = OffsetNumberNext(offnum))
1944  {
1945  ItemId itemid;
1946 
1947  itemid = PageGetItemId(page, offnum);
1948 
1949  /*
1950  * Note: any non-unused item should be taken as a reason to keep
1951  * this page. We formerly thought that DEAD tuples could be
1952  * thrown away, but that's not so, because we'd not have cleaned
1953  * out their index entries.
1954  */
1955  if (ItemIdIsUsed(itemid))
1956  {
1957  hastup = true;
1958  break; /* can stop scanning */
1959  }
1960  } /* scan along page */
1961 
1962  UnlockReleaseBuffer(buf);
1963 
1964  /* Done scanning if we found a tuple here */
1965  if (hastup)
1966  return blkno + 1;
1967  }
1968 
1969  /*
1970  * If we fall out of the loop, all the previously-thought-to-be-empty
1971  * pages still are; we need not bother to look at the last known-nonempty
1972  * page.
1973  */
1974  return vacrelstats->nonempty_pages;
1975 }
1976 
1977 /*
1978  * lazy_space_alloc - space allocation decisions for lazy vacuum
1979  *
1980  * See the comments at the head of this file for rationale.
1981  */
1982 static void
1983 lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks)
1984 {
1985  long maxtuples;
1986  int vac_work_mem = IsAutoVacuumWorkerProcess() &&
1987  autovacuum_work_mem != -1 ?
1989 
1990  if (vacrelstats->hasindex)
1991  {
1992  maxtuples = (vac_work_mem * 1024L) / sizeof(ItemPointerData);
1993  maxtuples = Min(maxtuples, INT_MAX);
1994  maxtuples = Min(maxtuples, MaxAllocSize / sizeof(ItemPointerData));
1995 
1996  /* curious coding here to ensure the multiplication can't overflow */
1997  if ((BlockNumber) (maxtuples / LAZY_ALLOC_TUPLES) > relblocks)
1998  maxtuples = relblocks * LAZY_ALLOC_TUPLES;
1999 
2000  /* stay sane if small maintenance_work_mem */
2001  maxtuples = Max(maxtuples, MaxHeapTuplesPerPage);
2002  }
2003  else
2004  {
2005  maxtuples = MaxHeapTuplesPerPage;
2006  }
2007 
2008  vacrelstats->num_dead_tuples = 0;
2009  vacrelstats->max_dead_tuples = (int) maxtuples;
2010  vacrelstats->dead_tuples = (ItemPointer)
2011  palloc(maxtuples * sizeof(ItemPointerData));
2012 }
2013 
2014 /*
2015  * lazy_record_dead_tuple - remember one deletable tuple
2016  */
2017 static void
2019  ItemPointer itemptr)
2020 {
2021  /*
2022  * The array shouldn't overflow under normal behavior, but perhaps it
2023  * could if we are given a really small maintenance_work_mem. In that
2024  * case, just forget the last few tuples (we'll get 'em next time).
2025  */
2026  if (vacrelstats->num_dead_tuples < vacrelstats->max_dead_tuples)
2027  {
2028  vacrelstats->dead_tuples[vacrelstats->num_dead_tuples] = *itemptr;
2029  vacrelstats->num_dead_tuples++;
2031  vacrelstats->num_dead_tuples);
2032  }
2033 }
2034 
2035 /*
2036  * lazy_tid_reaped() -- is a particular tid deletable?
2037  *
2038  * This has the right signature to be an IndexBulkDeleteCallback.
2039  *
2040  * Assumes dead_tuples array is in sorted order.
2041  */
2042 static bool
2044 {
2045  LVRelStats *vacrelstats = (LVRelStats *) state;
2046  ItemPointer res;
2047 
2048  res = (ItemPointer) bsearch((void *) itemptr,
2049  (void *) vacrelstats->dead_tuples,
2050  vacrelstats->num_dead_tuples,
2051  sizeof(ItemPointerData),
2052  vac_cmp_itemptr);
2053 
2054  return (res != NULL);
2055 }
2056 
2057 /*
2058  * Comparator routines for use with qsort() and bsearch().
2059  */
2060 static int
2061 vac_cmp_itemptr(const void *left, const void *right)
2062 {
2063  BlockNumber lblk,
2064  rblk;
2065  OffsetNumber loff,
2066  roff;
2067 
2068  lblk = ItemPointerGetBlockNumber((ItemPointer) left);
2069  rblk = ItemPointerGetBlockNumber((ItemPointer) right);
2070 
2071  if (lblk < rblk)
2072  return -1;
2073  if (lblk > rblk)
2074  return 1;
2075 
2076  loff = ItemPointerGetOffsetNumber((ItemPointer) left);
2077  roff = ItemPointerGetOffsetNumber((ItemPointer) right);
2078 
2079  if (loff < roff)
2080  return -1;
2081  if (loff > roff)
2082  return 1;
2083 
2084  return 0;
2085 }
2086 
2087 /*
2088  * Check if every tuple in the given page is visible to all current and future
2089  * transactions. Also return the visibility_cutoff_xid which is the highest
2090  * xmin amongst the visible tuples. Set *all_frozen to true if every tuple
2091  * on this page is frozen.
2092  */
2093 static bool
2095  TransactionId *visibility_cutoff_xid,
2096  bool *all_frozen)
2097 {
2098  Page page = BufferGetPage(buf);
2099  BlockNumber blockno = BufferGetBlockNumber(buf);
2100  OffsetNumber offnum,
2101  maxoff;
2102  bool all_visible = true;
2103 
2104  *visibility_cutoff_xid = InvalidTransactionId;
2105  *all_frozen = true;
2106 
2107  /*
2108  * This is a stripped down version of the line pointer scan in
2109  * lazy_scan_heap(). So if you change anything here, also check that code.
2110  */
2111  maxoff = PageGetMaxOffsetNumber(page);
2112  for (offnum = FirstOffsetNumber;
2113  offnum <= maxoff && all_visible;
2114  offnum = OffsetNumberNext(offnum))
2115  {
2116  ItemId itemid;
2117  HeapTupleData tuple;
2118 
2119  itemid = PageGetItemId(page, offnum);
2120 
2121  /* Unused or redirect line pointers are of no interest */
2122  if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
2123  continue;
2124 
2125  ItemPointerSet(&(tuple.t_self), blockno, offnum);
2126 
2127  /*
2128  * Dead line pointers can have index pointers pointing to them. So
2129  * they can't be treated as visible
2130  */
2131  if (ItemIdIsDead(itemid))
2132  {
2133  all_visible = false;
2134  *all_frozen = false;
2135  break;
2136  }
2137 
2138  Assert(ItemIdIsNormal(itemid));
2139 
2140  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2141  tuple.t_len = ItemIdGetLength(itemid);
2142  tuple.t_tableOid = RelationGetRelid(rel);
2143 
2144  switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
2145  {
2146  case HEAPTUPLE_LIVE:
2147  {
2148  TransactionId xmin;
2149 
2150  /* Check comments in lazy_scan_heap. */
2152  {
2153  all_visible = false;
2154  *all_frozen = false;
2155  break;
2156  }
2157 
2158  /*
2159  * The inserter definitely committed. But is it old enough
2160  * that everyone sees it as committed?
2161  */
2162  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
2163  if (!TransactionIdPrecedes(xmin, OldestXmin))
2164  {
2165  all_visible = false;
2166  *all_frozen = false;
2167  break;
2168  }
2169 
2170  /* Track newest xmin on page. */
2171  if (TransactionIdFollows(xmin, *visibility_cutoff_xid))
2172  *visibility_cutoff_xid = xmin;
2173 
2174  /* Check whether this tuple is already frozen or not */
2175  if (all_visible && *all_frozen &&
2177  *all_frozen = false;
2178  }
2179  break;
2180 
2181  case HEAPTUPLE_DEAD:
2185  {
2186  all_visible = false;
2187  *all_frozen = false;
2188  break;
2189  }
2190  default:
2191  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
2192  break;
2193  }
2194  } /* scan along page */
2195 
2196  return all_visible;
2197 }
int autovacuum_work_mem
Definition: autovacuum.c:114
double new_rel_tuples
Definition: vacuumlazy.c:119
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:7280
XLogRecPtr log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
Definition: heapam.c:7319
int multixact_freeze_table_age
Definition: vacuum.h:142
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1539
#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:1444
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:7399
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition: progress.h:24
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define PageIsEmpty(page)
Definition: bufpage.h:218
static BlockNumber count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1841
double tuples_removed
Definition: genam.h:77
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:1379
static bool lazy_tid_reaped(ItemPointer itemptr, void *state)
Definition: vacuumlazy.c:2043
#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:685
static void lazy_record_dead_tuple(LVRelStats *vacrelstats, ItemPointer itemptr)
Definition: vacuumlazy.c:2018
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
#define PageIsAllVisible(page)
Definition: bufpage.h:381
uint32 TransactionId
Definition: c.h:397
void UnlockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:257
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3068
#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)
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
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
int64 TimestampTz
Definition: timestamp.h:39
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define MaxOffsetNumber
Definition: off.h:28
int VacuumPageHit
Definition: globals.c:135
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3089
double old_rel_tuples
Definition: vacuumlazy.c:118
#define VISIBILITYMAP_ALL_FROZEN
Definition: visibilitymap.h:27
bool analyze_only
Definition: genam.h:47
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
#define XLogIsNeeded()
Definition: xlog.h:145
struct timeval instr_time
Definition: instr_time.h:147
#define Min(x, y)
Definition: c.h:806
BlockNumber tupcount_pages
Definition: vacuumlazy.c:116
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
BufferAccessStrategy strategy
Definition: genam.h:51
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
#define MaxHeapTuplesPerPage
Definition: htup_details.h:575
#define VM_ALL_FROZEN(r, b, v)
Definition: visibilitymap.h:34
unsigned char uint8
Definition: c.h:266
#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:1625
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
Relation index
Definition: genam.h:46
static void lazy_scan_heap(Relation onerel, int options, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive)
Definition: vacuumlazy.c:458
BlockNumber scanned_pages
Definition: vacuumlazy.c:113
#define INFO
Definition: elog.h:33
#define VACUUM_TRUNCATE_LOCK_TIMEOUT
Definition: vacuumlazy.c:85
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:501
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
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
#define ItemIdIsDead(itemId)
Definition: itemid.h:112
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
#define OidIsValid(objectId)
Definition: c.h:538
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
int freeze_table_age
Definition: vacuum.h:139
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData * ItemPointer
Definition: itemptr.h:49
#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
#define FORCE_CHECK_PAGE()
#define PROGRESS_VACUUM_PHASE_TRUNCATE
Definition: progress.h:34
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:677
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:757
BlockNumber old_rel_pages
Definition: vacuumlazy.c:111
void pg_usleep(long microsec)
Definition: signal.c:53
#define PREFETCH_SIZE
Definition: vacuumlazy.c:104
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition: heapam.c:7148
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
void pfree(void *pointer)
Definition: mcxt.c:950
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3718
#define ERROR
Definition: elog.h:43
#define REL_TRUNCATE_MINIMUM
Definition: vacuumlazy.c:73
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:666
int max_dead_tuples
Definition: vacuumlazy.c:127
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:167
int freeze_min_age
Definition: vacuum.h:138
void lazy_vacuum_rel(Relation onerel, int options, VacuumParams *params, BufferAccessStrategy bstrategy)
Definition: vacuumlazy.c:182
BlockNumber num_pages
Definition: genam.h:73
BlockNumber pages_free
Definition: genam.h:79
ItemPointer dead_tuples
Definition: vacuumlazy.c:128
ItemPointerData t_self
Definition: htup.h:65
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
#define DEBUG2
Definition: elog.h:24
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:318
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:6748
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:66
#define PageSetAllVisible(page)
Definition: bufpage.h:383
#define FirstOffsetNumber
Definition: off.h:27
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:140
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:226
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:436
static TransactionId OldestXmin
Definition: vacuumlazy.c:138
Oid t_tableOid
Definition: htup.h:66
BlockNumber pages_deleted
Definition: genam.h:78
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
int num_dead_tuples
Definition: vacuumlazy.c:126
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3361
#define ereport(elevel, rest)
Definition: elog.h:122
bool heap_tuple_needs_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, Buffer buf)
Definition: heapam.c:7201
#define PROGRESS_VACUUM_NUM_DEAD_TUPLES
Definition: progress.h:27
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static bool heap_page_is_all_visible(Relation rel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen)
Definition: vacuumlazy.c:2094
#define SKIP_PAGES_THRESHOLD
Definition: vacuumlazy.c:98
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL
Definition: vacuumlazy.c:84
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:379
#define MaxAllocSize
Definition: memutils.h:40
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define WARNING
Definition: elog.h:40
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1496
#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:127
bool hasindex
Definition: vacuumlazy.c:109
int VacuumPageDirty
Definition: globals.c:137
void * palloc0(Size size)
Definition: mcxt.c:878
void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:382
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL
Definition: vacuumlazy.c:83
void pgstat_progress_end_command(void)
Definition: pgstat.c:3140
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:743
#define BufferGetPageSize(buffer)
Definition: bufmgr.h:147
Oid MyDatabaseId
Definition: globals.c:77
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define InvalidMultiXactId
Definition: multixact.h:23
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen_p)
Definition: heapam.c:6570
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
static bool should_attempt_truncation(LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1695
#define PROGRESS_VACUUM_PHASE_FINAL_CLEANUP
Definition: progress.h:35
void PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:529
int num_index_scans
Definition: vacuumlazy.c:129
int maintenance_work_mem
Definition: globals.c:114
bool LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:275
static void vacuum_log_cleanup_info(Relation rel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:425
int message_level
Definition: genam.h:49
TransactionId MultiXactId
Definition: c.h:407
RelFileNode rd_node
Definition: rel.h:85
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
double num_heap_tuples
Definition: genam.h:50
#define Max(x, y)
Definition: c.h:800
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:142
#define PageClearAllVisible(page)
Definition: bufpage.h:385
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:686
#define Assert(condition)
Definition: c.h:675
double new_dead_tuples
Definition: vacuumlazy.c:120
Definition: regguts.h:298
TransactionId latestRemovedXid
Definition: vacuumlazy.c:130
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define INSTR_TIME_GET_MICROSEC(t)
Definition: instr_time.h:202
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
static void lazy_vacuum_index(Relation indrel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1594
#define PROGRESS_VACUUM_PHASE_INDEX_CLEANUP
Definition: progress.h:33
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
#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:3111
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
size_t Size
Definition: c.h:356
#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 InvalidBlockNumber
Definition: block.h:33
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:7348
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
int log_min_duration
Definition: vacuum.h:145
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:95
#define RelationNeedsWAL(relation)
Definition: rel.h:505
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:764
#define VISIBILITYMAP_ALL_VISIBLE
Definition: visibilitymap.h:26
struct LVRelStats LVRelStats
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
Definition: pgstat.c:1405
#define PageGetLSN(page)
Definition: bufpage.h:362
#define AccessExclusiveLock
Definition: lockdefs.h:45
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2605
BlockNumber pages_removed
Definition: vacuumlazy.c:121
BlockNumber nonempty_pages
Definition: vacuumlazy.c:123
void PageRepairFragmentation(Page page)
Definition: bufpage.c:479
#define PageIsNew(page)
Definition: bufpage.h:225
void * palloc(Size size)
Definition: mcxt.c:849
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 old_snapshot_threshold
Definition: snapmgr.c:75
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3154
int i
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
static bool lazy_check_needs_freeze(Buffer buf, bool *hastup)
Definition: vacuumlazy.c:1542
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
int VacuumPageMiss
Definition: globals.c:136
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define ItemIdSetUnused(itemId)
Definition: itemid.h:127
static int vac_cmp_itemptr(const void *left, const void *right)
Definition: vacuumlazy.c:2061
void vacuum_delay_point(void)
Definition: vacuum.c:1560
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:785
#define PageSetLSN(page, lsn)
Definition: bufpage.h:364
#define LAZY_ALLOC_TUPLES
Definition: vacuumlazy.c:92
double num_index_tuples
Definition: genam.h:76
int Buffer
Definition: buf.h:23
#define _(x)
Definition: elog.c:84
#define RelationGetRelid(relation)
Definition: rel.h:416
int multixact_freeze_min_age
Definition: vacuum.h:140
bool estimated_count
Definition: genam.h:75
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1713
#define PROGRESS_VACUUM_PHASE_VACUUM_HEAP
Definition: progress.h:32
#define REL_TRUNCATE_FRACTION
Definition: vacuumlazy.c:74
#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:1983
bool estimated_count
Definition: genam.h:48
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:227
#define RelationGetNamespace(relation)
Definition: rel.h:443
void PageInit(Page page, Size pageSize, Size specialSize)
Definition: bufpage.c:41
bool lock_waiter_detected
Definition: vacuumlazy.c:131