PostgreSQL Source Code  git master
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-2018, 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  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 }
412 
413 /*
414  * For Hot Standby we need to know the highest transaction id that will
415  * be removed by any change. VACUUM proceeds in a number of passes so
416  * we need to consider how each pass operates. The first phase runs
417  * heap_page_prune(), which can issue XLOG_HEAP2_CLEAN records as it
418  * progresses - these will have a latestRemovedXid on each record.
419  * In some cases this removes all of the tuples to be removed, though
420  * often we have dead tuples with index pointers so we must remember them
421  * for removal in phase 3. Index records for those rows are removed
422  * in phase 2 and index blocks do not have MVCC information attached.
423  * So before we can allow removal of any index tuples we need to issue
424  * a WAL record containing the latestRemovedXid of rows that will be
425  * removed in phase three. This allows recovery queries to block at the
426  * correct place, i.e. before phase two, rather than during phase three
427  * which would be after the rows have become inaccessible.
428  */
429 static void
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 }
445 
446 /*
447  * lazy_scan_heap() -- scan an open heap relation
448  *
449  * This routine prunes each page in the heap, which will among other
450  * things truncate dead tuples to dead line pointers, defragment the
451  * page, and set commit status bits (see heap_page_prune). It also builds
452  * lists of dead tuples and pages with free space, calculates statistics
453  * on the number of live tuples in the heap, and marks pages as
454  * all-visible if appropriate. When done, or when we run low on space for
455  * dead-tuple TIDs, invoke vacuuming of indexes and call lazy_vacuum_heap
456  * to reclaim dead line pointers.
457  *
458  * If there are no indexes then we can reclaim line pointers on the fly;
459  * dead line pointers need only be retained until all index pointers that
460  * reference them have been killed.
461  */
462 static void
463 lazy_scan_heap(Relation onerel, int options, LVRelStats *vacrelstats,
464  Relation *Irel, int nindexes, bool aggressive)
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;
574  if ((options & VACOPT_DISABLE_PAGE_SKIPPING) == 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,
776  RBM_NORMAL, vac_strategy);
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[] = {
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 }
1386 
1387 
1388 /*
1389  * lazy_vacuum_heap() -- second pass over the heap
1390  *
1391  * This routine marks dead tuples as unused and compacts out free
1392  * space on their pages. Pages not having dead tuples recorded from
1393  * lazy_scan_heap are not visited at all.
1394  *
1395  * Note: the reason for doing this as a second pass is we cannot remove
1396  * the tuples until we've removed their index entries, and we want to
1397  * process index entry removal in batches as large as possible.
1398  */
1399 static void
1400 lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats)
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 }
1453 
1454 /*
1455  * lazy_vacuum_page() -- free dead tuples on a page
1456  * and repair its fragmentation.
1457  *
1458  * Caller must hold pin and buffer cleanup lock on the buffer.
1459  *
1460  * tupindex is the index in vacrelstats->dead_tuples of the first dead
1461  * tuple for this page. We assume the rest follow sequentially.
1462  * The return value is the first tupindex after the tuples of this page.
1463  */
1464 static int
1466  int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
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  */
1498  MarkBufferDirty(buffer);
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 }
1554 
1555 /*
1556  * lazy_check_needs_freeze() -- scan page to see if any tuples
1557  * need to be cleaned to avoid wraparound
1558  *
1559  * Returns true if the page needs to be vacuumed using cleanup lock.
1560  * Also returns a flag indicating whether page contains any tuples at all.
1561  */
1562 static bool
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 }
1606 
1607 
1608 /*
1609  * lazy_vacuum_index() -- vacuum one index relation.
1610  *
1611  * Delete all the index entries pointing to tuples listed in
1612  * vacrelstats->dead_tuples, and update running statistics.
1613  */
1614 static void
1616  IndexBulkDeleteResult **stats,
1617  LVRelStats *vacrelstats)
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 }
1641 
1642 /*
1643  * lazy_cleanup_index() -- do post-vacuum cleanup for one index relation.
1644  */
1645 static void
1647  IndexBulkDeleteResult *stats,
1648  LVRelStats *vacrelstats)
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 }
1695 
1696 /*
1697  * should_attempt_truncation - should we attempt to truncate the heap?
1698  *
1699  * Don't even think about it unless we have a shot at releasing a goodly
1700  * number of pages. Otherwise, the time taken isn't worth it.
1701  *
1702  * Also don't attempt it if we are doing early pruning/vacuuming, because a
1703  * scan which cannot find a truncated heap page cannot determine that the
1704  * snapshot is too old to read that page. We might be able to get away with
1705  * truncating all except one of the pages, setting its LSN to (at least) the
1706  * maximum of the truncated range if we also treated an index leaf tuple
1707  * pointing to a missing heap page as something to trigger the "snapshot too
1708  * old" error, but that seems fragile and seems like it deserves its own patch
1709  * if we consider it.
1710  *
1711  * This is split out so that we can test whether truncation is going to be
1712  * called for before we actually do it. If you change the logic here, be
1713  * careful to depend only on fields that lazy_scan_heap updates on-the-fly.
1714  */
1715 static bool
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 }
1729 
1730 /*
1731  * lazy_truncate_heap - try to truncate off any empty pages at the end
1732  */
1733 static void
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 }
1855 
1856 /*
1857  * Rescan end pages to verify that they are (still) empty of tuples.
1858  *
1859  * Returns number of nondeletable pages (last nonempty page + 1).
1860  */
1861 static BlockNumber
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,
1946  RBM_NORMAL, vac_strategy);
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 }
1997 
1998 /*
1999  * lazy_space_alloc - space allocation decisions for lazy vacuum
2000  *
2001  * See the comments at the head of this file for rationale.
2002  */
2003 static void
2004 lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks)
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 }
2034 
2035 /*
2036  * lazy_record_dead_tuple - remember one deletable tuple
2037  */
2038 static void
2040  ItemPointer itemptr)
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 }
2055 
2056 /*
2057  * lazy_tid_reaped() -- is a particular tid deletable?
2058  *
2059  * This has the right signature to be an IndexBulkDeleteCallback.
2060  *
2061  * Assumes dead_tuples array is in sorted order.
2062  */
2063 static bool
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 }
2077 
2078 /*
2079  * Comparator routines for use with qsort() and bsearch().
2080  */
2081 static int
2082 vac_cmp_itemptr(const void *left, const void *right)
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 }
2107 
2108 /*
2109  * Check if every tuple in the given page is visible to all current and future
2110  * transactions. Also return the visibility_cutoff_xid which is the highest
2111  * xmin amongst the visible tuples. Set *all_frozen to true if every tuple
2112  * on this page is frozen.
2113  */
2114 static bool
2116  TransactionId *visibility_cutoff_xid,
2117  bool *all_frozen)
2118 {
2119  Page page = BufferGetPage(buf);
2120  BlockNumber blockno = BufferGetBlockNumber(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 }
int autovacuum_work_mem
Definition: autovacuum.c:115
double new_rel_tuples
Definition: vacuumlazy.c:119
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:7428
XLogRecPtr log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
Definition: heapam.c:7467
int multixact_freeze_table_age
Definition: vacuum.h:142
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1675
#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
static BlockNumber count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1862
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:1400
static bool lazy_tid_reaped(ItemPointer itemptr, void *state)
Definition: vacuumlazy.c:2064
#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 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:3072
#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:3093
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:146
struct timeval instr_time
Definition: instr_time.h:147
#define Min(x, y)
Definition: c.h:846
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: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
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:463
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:593
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:594
#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
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 PROGRESS_VACUUM_PHASE_TRUNCATE
Definition: progress.h:34
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:682
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:784
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:7296
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
void pfree(void *pointer)
Definition: mcxt.c:936
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:662
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: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
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:67
#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:445
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:3255
#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:7349
#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:2115
#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:1632
#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
bool hasindex
Definition: vacuumlazy.c:109
int VacuumPageDirty
Definition: globals.c:137
void * palloc0(Size size)
Definition: mcxt.c:864
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:3144
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:744
#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
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
static bool should_attempt_truncation(LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1716
#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:430
int message_level
Definition: genam.h:49
TransactionId MultiXactId
Definition: c.h:473
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:840
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
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:215
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 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:7496
#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:514
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:765
#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: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 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:1563
#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:700
#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:2082
void vacuum_delay_point(void)
Definition: vacuum.c:1696
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 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:425
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:1734
#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:2004
bool estimated_count
Definition: genam.h:48
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:227
#define RelationGetNamespace(relation)
Definition: rel.h:452
void PageInit(Page page, Size pageSize, Size specialSize)
Definition: bufpage.c:41
bool lock_waiter_detected
Definition: vacuumlazy.c:131