PostgreSQL Source Code git master
Loading...
Searching...
No Matches
vacuumlazy.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * vacuumlazy.c
4 * Concurrent ("lazy") vacuuming.
5 *
6 * Heap relations are vacuumed in three main phases. In phase I, vacuum scans
7 * relation pages, pruning and freezing tuples and saving dead tuples' TIDs in
8 * a TID store. If that TID store fills up or vacuum finishes scanning the
9 * relation, it progresses to phase II: index vacuuming. Index vacuuming
10 * deletes the dead index entries referenced in the TID store. In phase III,
11 * vacuum scans the blocks of the relation referred to by the TIDs in the TID
12 * store and reaps the corresponding dead items, freeing that space for future
13 * tuples.
14 *
15 * If there are no indexes or index scanning is disabled, phase II may be
16 * skipped. If phase I identified very few dead index entries or if vacuum's
17 * failsafe mechanism has triggered (to avoid transaction ID wraparound),
18 * vacuum may skip phases II and III.
19 *
20 * If the TID store fills up in phase I, vacuum suspends phase I and proceeds
21 * to phases II and III, cleaning up the dead tuples referenced in the current
22 * TID store. This empties the TID store, allowing vacuum to resume phase I.
23 *
24 * In a way, the phases are more like states in a state machine, but they have
25 * been referred to colloquially as phases for so long that they are referred
26 * to as such here.
27 *
28 * Manually invoked VACUUMs may scan indexes during phase II in parallel. For
29 * more information on this, see the comment at the top of vacuumparallel.c.
30 *
31 * In between phases, vacuum updates the freespace map (every
32 * VACUUM_FSM_EVERY_PAGES).
33 *
34 * After completing all three phases, vacuum may truncate the relation if it
35 * has emptied pages at the end. Finally, vacuum updates relation statistics
36 * in pg_class and the cumulative statistics subsystem.
37 *
38 * Relation Scanning:
39 *
40 * Vacuum scans the heap relation, starting at the beginning and progressing
41 * to the end, skipping pages as permitted by their visibility status, vacuum
42 * options, and various other requirements.
43 *
44 * Vacuums are either aggressive or normal. Aggressive vacuums must scan every
45 * unfrozen tuple in order to advance relfrozenxid and avoid transaction ID
46 * wraparound. Normal vacuums may scan otherwise skippable pages for one of
47 * two reasons:
48 *
49 * When page skipping is not disabled, a normal vacuum may scan pages that are
50 * marked all-visible (and even all-frozen) in the visibility map if the range
51 * of skippable pages is below SKIP_PAGES_THRESHOLD. This is primarily for the
52 * benefit of kernel readahead (see comment in heap_vac_scan_next_block()).
53 *
54 * A normal vacuum may also scan skippable pages in an effort to freeze them
55 * and decrease the backlog of all-visible but not all-frozen pages that have
56 * to be processed by the next aggressive vacuum. These are referred to as
57 * eagerly scanned pages. Pages scanned due to SKIP_PAGES_THRESHOLD do not
58 * count as eagerly scanned pages.
59 *
60 * Eagerly scanned pages that are set all-frozen in the VM are successful
61 * eager freezes and those not set all-frozen in the VM are failed eager
62 * freezes.
63 *
64 * Because we want to amortize the overhead of freezing pages over multiple
65 * vacuums, normal vacuums cap the number of successful eager freezes to
66 * MAX_EAGER_FREEZE_SUCCESS_RATE of the number of all-visible but not
67 * all-frozen pages at the beginning of the vacuum. Since eagerly frozen pages
68 * may be unfrozen before the next aggressive vacuum, capping the number of
69 * successful eager freezes also caps the downside of eager freezing:
70 * potentially wasted work.
71 *
72 * Once the success cap has been hit, eager scanning is disabled for the
73 * remainder of the vacuum of the relation.
74 *
75 * Success is capped globally because we don't want to limit our successes if
76 * old data happens to be concentrated in a particular part of the table. This
77 * is especially likely to happen for append-mostly workloads where the oldest
78 * data is at the beginning of the unfrozen portion of the relation.
79 *
80 * On the assumption that different regions of the table are likely to contain
81 * similarly aged data, normal vacuums use a localized eager freeze failure
82 * cap. The failure count is reset for each region of the table -- comprised
83 * of EAGER_SCAN_REGION_SIZE blocks. In each region, we tolerate
84 * vacuum_max_eager_freeze_failure_rate of EAGER_SCAN_REGION_SIZE failures
85 * before suspending eager scanning until the end of the region.
86 * vacuum_max_eager_freeze_failure_rate is configurable both globally and per
87 * table.
88 *
89 * Aggressive vacuums must examine every unfrozen tuple and thus are not
90 * subject to any of the limits imposed by the eager scanning algorithm.
91 *
92 * Once vacuum has decided to scan a given block, it must read the block and
93 * obtain a cleanup lock to prune tuples on the page. A non-aggressive vacuum
94 * may choose to skip pruning and freezing if it cannot acquire a cleanup lock
95 * on the buffer right away. In this case, it may miss cleaning up dead tuples
96 * and their associated index entries (though it is free to reap any existing
97 * dead items on the page).
98 *
99 * After pruning and freezing, pages that are newly all-visible and all-frozen
100 * are marked as such in the visibility map.
101 *
102 * Dead TID Storage:
103 *
104 * The major space usage for vacuuming is storage for the dead tuple IDs that
105 * are to be removed from indexes. We want to ensure we can vacuum even the
106 * very largest relations with finite memory space usage. To do that, we set
107 * upper bounds on the memory that can be used for keeping track of dead TIDs
108 * at once.
109 *
110 * We are willing to use at most maintenance_work_mem (or perhaps
111 * autovacuum_work_mem) memory space to keep track of dead TIDs. If the
112 * TID store is full, we must call lazy_vacuum to vacuum indexes (and to vacuum
113 * the pages that we've pruned). This frees up the memory space dedicated to
114 * store dead TIDs.
115 *
116 * In practice VACUUM will often complete its initial pass over the target
117 * heap relation without ever running out of space to store TIDs. This means
118 * that there only needs to be one call to lazy_vacuum, after the initial pass
119 * completes.
120 *
121 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
122 * Portions Copyright (c) 1994, Regents of the University of California
123 *
124 *
125 * IDENTIFICATION
126 * src/backend/access/heap/vacuumlazy.c
127 *
128 *-------------------------------------------------------------------------
129 */
130#include "postgres.h"
131
132#include "access/genam.h"
133#include "access/heapam.h"
134#include "access/htup_details.h"
135#include "access/multixact.h"
136#include "access/tidstore.h"
137#include "access/transam.h"
138#include "access/visibilitymap.h"
139#include "access/xloginsert.h"
140#include "catalog/storage.h"
141#include "commands/progress.h"
142#include "commands/vacuum.h"
143#include "common/int.h"
144#include "common/pg_prng.h"
145#include "executor/instrument.h"
146#include "miscadmin.h"
147#include "pgstat.h"
150#include "storage/bufmgr.h"
151#include "storage/freespace.h"
152#include "storage/latch.h"
153#include "storage/lmgr.h"
154#include "storage/read_stream.h"
156#include "utils/lsyscache.h"
157#include "utils/pg_rusage.h"
158#include "utils/timestamp.h"
159#include "utils/wait_event.h"
160
161
162/*
163 * Space/time tradeoff parameters: do these need to be user-tunable?
164 *
165 * To consider truncating the relation, we want there to be at least
166 * REL_TRUNCATE_MINIMUM or (relsize / REL_TRUNCATE_FRACTION) (whichever
167 * is less) potentially-freeable pages.
168 */
169#define REL_TRUNCATE_MINIMUM 1000
170#define REL_TRUNCATE_FRACTION 16
171
172/*
173 * Timing parameters for truncate locking heuristics.
174 *
175 * These were not exposed as user tunable GUC values because it didn't seem
176 * that the potential for improvement was great enough to merit the cost of
177 * supporting them.
178 */
179#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL 20 /* ms */
180#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL 50 /* ms */
181#define VACUUM_TRUNCATE_LOCK_TIMEOUT 5000 /* ms */
182
183/*
184 * Threshold that controls whether we bypass index vacuuming and heap
185 * vacuuming as an optimization
186 */
187#define BYPASS_THRESHOLD_PAGES 0.02 /* i.e. 2% of rel_pages */
188
189/*
190 * Perform a failsafe check each time we scan another 4GB of pages.
191 * (Note that this is deliberately kept to a power-of-two, usually 2^19.)
192 */
193#define FAILSAFE_EVERY_PAGES \
194 ((BlockNumber) (((uint64) 4 * 1024 * 1024 * 1024) / BLCKSZ))
195
196/*
197 * When a table has no indexes, vacuum the FSM after every 8GB, approximately
198 * (it won't be exact because we only vacuum FSM after processing a heap page
199 * that has some removable tuples). When there are indexes, this is ignored,
200 * and we vacuum FSM after each index/heap cleaning pass.
201 */
202#define VACUUM_FSM_EVERY_PAGES \
203 ((BlockNumber) (((uint64) 8 * 1024 * 1024 * 1024) / BLCKSZ))
204
205/*
206 * Before we consider skipping a page that's marked as clean in
207 * visibility map, we must've seen at least this many clean pages.
208 */
209#define SKIP_PAGES_THRESHOLD ((BlockNumber) 32)
210
211/*
212 * Size of the prefetch window for lazy vacuum backwards truncation scan.
213 * Needs to be a power of 2.
214 */
215#define PREFETCH_SIZE ((BlockNumber) 32)
216
217/*
218 * Macro to check if we are in a parallel vacuum. If true, we are in the
219 * parallel mode and the DSM segment is initialized.
220 */
221#define ParallelVacuumIsActive(vacrel) ((vacrel)->pvs != NULL)
222
223/* Phases of vacuum during which we report error context. */
233
234/*
235 * An eager scan of a page that is set all-frozen in the VM is considered
236 * "successful". To spread out freezing overhead across multiple normal
237 * vacuums, we limit the number of successful eager page freezes. The maximum
238 * number of eager page freezes is calculated as a ratio of the all-visible
239 * but not all-frozen pages at the beginning of the vacuum.
240 */
241#define MAX_EAGER_FREEZE_SUCCESS_RATE 0.2
242
243/*
244 * On the assumption that different regions of the table tend to have
245 * similarly aged data, once vacuum fails to freeze
246 * vacuum_max_eager_freeze_failure_rate of the blocks in a region of size
247 * EAGER_SCAN_REGION_SIZE, it suspends eager scanning until it has progressed
248 * to another region of the table with potentially older data.
249 */
250#define EAGER_SCAN_REGION_SIZE 4096
251
252typedef struct LVRelState
253{
254 /* Target heap relation and its indexes */
258
259 /* Buffer access strategy and parallel vacuum state */
262
263 /* Aggressive VACUUM? (must set relfrozenxid >= FreezeLimit) */
265 /* Use visibility map to skip? (disabled by DISABLE_PAGE_SKIPPING) */
267 /* Consider index vacuuming bypass optimization? */
269
270 /* Doing index vacuuming, index cleanup, rel truncation? */
274
275 /* VACUUM operation's cutoffs for freezing and pruning */
278 /* Tracks oldest extant XID/MXID for setting relfrozenxid/relminmxid */
282
283 /* Error reporting state */
284 char *dbname;
286 char *relname;
287 char *indname; /* Current index name */
288 BlockNumber blkno; /* used only for heap operations */
289 OffsetNumber offnum; /* used only for heap operations */
291 bool verbose; /* VACUUM VERBOSE? */
292
293 /*
294 * dead_items stores TIDs whose index tuples are deleted by index
295 * vacuuming. Each TID points to an LP_DEAD line pointer from a heap page
296 * that has been processed by lazy_scan_prune. Also needed by
297 * lazy_vacuum_heap_rel, which marks the same LP_DEAD line pointers as
298 * LP_UNUSED during second heap pass.
299 *
300 * Both dead_items and dead_items_info are allocated in shared memory in
301 * parallel vacuum cases.
302 */
303 TidStore *dead_items; /* TIDs whose index tuples we'll delete */
305
306 BlockNumber rel_pages; /* total number of pages */
307 BlockNumber scanned_pages; /* # pages examined (not skipped via VM) */
308
309 /*
310 * Count of all-visible blocks eagerly scanned (for logging only). This
311 * does not include skippable blocks scanned due to SKIP_PAGES_THRESHOLD.
312 */
314
315 BlockNumber removed_pages; /* # pages removed by relation truncation */
316 BlockNumber new_frozen_tuple_pages; /* # pages with newly frozen tuples */
317
318 /* # pages newly set all-visible in the VM */
320
321 /*
322 * # pages newly set all-visible and all-frozen in the VM. This is a
323 * subset of new_all_visible_pages. That is, new_all_visible_pages
324 * includes all pages set all-visible, but
325 * new_all_visible_all_frozen_pages includes only those which were also
326 * set all-frozen.
327 */
329
330 /* # all-visible pages newly set all-frozen in the VM */
332
333 BlockNumber lpdead_item_pages; /* # pages with LP_DEAD items */
334 BlockNumber missed_dead_pages; /* # pages with missed dead tuples */
335 BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
336
337 /* Statistics output by us, for table */
338 double new_rel_tuples; /* new estimated total # of tuples */
339 double new_live_tuples; /* new estimated total # of live tuples */
340 /* Statistics output by index AMs */
342
343 /* Instrumentation counters */
347
348 /*
349 * Total number of planned and actually launched parallel workers for
350 * index vacuuming and index cleanup.
351 */
353
354 /* Counters that follow are only for scanned_pages */
355 int64 tuples_deleted; /* # deleted from table */
356 int64 tuples_frozen; /* # newly frozen */
357 int64 lpdead_items; /* # deleted from indexes */
358 int64 live_tuples; /* # live tuples remaining */
359 int64 recently_dead_tuples; /* # dead, but not yet removable */
360 int64 missed_dead_tuples; /* # removable, but not removed */
361
362 /* State maintained by heap_vac_scan_next_block() */
363 BlockNumber current_block; /* last block returned */
364 BlockNumber next_unskippable_block; /* next unskippable block */
365 bool next_unskippable_eager_scanned; /* if it was eagerly scanned */
366 Buffer next_unskippable_vmbuffer; /* buffer containing its VM bit */
367
368 /* State related to managing eager scanning of all-visible pages */
369
370 /*
371 * A normal vacuum that has failed to freeze too many eagerly scanned
372 * blocks in a region suspends eager scanning.
373 * next_eager_scan_region_start is the block number of the first block
374 * eligible for resumed eager scanning.
375 *
376 * When eager scanning is permanently disabled, either initially
377 * (including for aggressive vacuum) or due to hitting the success cap,
378 * this is set to InvalidBlockNumber.
379 */
381
382 /*
383 * The remaining number of blocks a normal vacuum will consider eager
384 * scanning when it is successful. When eager scanning is enabled, this is
385 * initialized to MAX_EAGER_FREEZE_SUCCESS_RATE of the total number of
386 * all-visible but not all-frozen pages. For each eager freeze success,
387 * this is decremented. Once it hits 0, eager scanning is permanently
388 * disabled. It is initialized to 0 if eager scanning starts out disabled
389 * (including for aggressive vacuum).
390 */
392
393 /*
394 * The maximum number of blocks which may be eagerly scanned and not
395 * frozen before eager scanning is temporarily suspended. This is
396 * configurable both globally, via the
397 * vacuum_max_eager_freeze_failure_rate GUC, and per table, with a table
398 * storage parameter of the same name. It is calculated as
399 * vacuum_max_eager_freeze_failure_rate of EAGER_SCAN_REGION_SIZE blocks.
400 * It is 0 when eager scanning is disabled.
401 */
403
404 /*
405 * The number of eagerly scanned blocks vacuum failed to freeze (due to
406 * age) in the current eager scan region. Vacuum resets it to
407 * eager_scan_max_fails_per_region each time it enters a new region of the
408 * relation. If eager_scan_remaining_fails hits 0, eager scanning is
409 * suspended until the next region. It is also 0 if eager scanning has
410 * been permanently disabled.
411 */
414
415
416/* Struct for saving and restoring vacuum error information. */
423
424
425/* non-export function prototypes */
426static void lazy_scan_heap(LVRelState *vacrel);
428 const VacuumParams *params);
430 void *callback_private_data,
431 void *per_buffer_data);
434 BlockNumber blkno, Page page,
435 bool sharelock, Buffer vmbuffer);
437 BlockNumber blkno, Page page,
438 Buffer vmbuffer,
439 bool *has_lpdead_items, bool *vm_page_frozen);
441 BlockNumber blkno, Page page,
442 bool *has_lpdead_items);
443static void lazy_vacuum(LVRelState *vacrel);
447 Buffer buffer, OffsetNumber *deadoffsets,
448 int num_offsets, Buffer vmbuffer);
453 double reltuples,
457 double reltuples,
458 bool estimated_count,
464static void dead_items_alloc(LVRelState *vacrel, int nworkers);
465static void dead_items_add(LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets,
466 int num_offsets);
469
471 GlobalVisState *vistest,
473 OffsetNumber *deadoffsets,
474 int ndeadoffsets,
475 bool *all_frozen,
476 TransactionId *newest_live_xid,
479static void vacuum_error_callback(void *arg);
482 int phase, BlockNumber blkno,
483 OffsetNumber offnum);
486
487
488
489/*
490 * Helper to set up the eager scanning state for vacuuming a single relation.
491 * Initializes the eager scan management related members of the LVRelState.
492 *
493 * Caller provides whether or not an aggressive vacuum is required due to
494 * vacuum options or for relfrozenxid/relminmxid advancement.
495 */
496static void
498{
502 float first_region_ratio;
504
505 /*
506 * Initialize eager scan management fields to their disabled values.
507 * Aggressive vacuums, normal vacuums of small tables, and normal vacuums
508 * of tables without sufficiently old tuples disable eager scanning.
509 */
510 vacrel->next_eager_scan_region_start = InvalidBlockNumber;
511 vacrel->eager_scan_max_fails_per_region = 0;
512 vacrel->eager_scan_remaining_fails = 0;
513 vacrel->eager_scan_remaining_successes = 0;
514
515 /* If eager scanning is explicitly disabled, just return. */
516 if (params->max_eager_freeze_failure_rate == 0)
517 return;
518
519 /*
520 * The caller will have determined whether or not an aggressive vacuum is
521 * required by either the vacuum parameters or the relative age of the
522 * oldest unfrozen transaction IDs. An aggressive vacuum must scan every
523 * all-visible page to safely advance the relfrozenxid and/or relminmxid,
524 * so scans of all-visible pages are not considered eager.
525 */
526 if (vacrel->aggressive)
527 return;
528
529 /*
530 * Aggressively vacuuming a small relation shouldn't take long, so it
531 * isn't worth amortizing. We use two times the region size as the size
532 * cutoff because the eager scan start block is a random spot somewhere in
533 * the first region, making the second region the first to be eager
534 * scanned normally.
535 */
536 if (vacrel->rel_pages < 2 * EAGER_SCAN_REGION_SIZE)
537 return;
538
539 /*
540 * We only want to enable eager scanning if we are likely to be able to
541 * freeze some of the pages in the relation.
542 *
543 * Tuples with XIDs older than OldestXmin or MXIDs older than OldestMxact
544 * are technically freezable, but we won't freeze them unless the criteria
545 * for opportunistic freezing is met. Only tuples with XIDs/MXIDs older
546 * than the FreezeLimit/MultiXactCutoff are frozen in the common case.
547 *
548 * So, as a heuristic, we wait until the FreezeLimit has advanced past the
549 * relfrozenxid or the MultiXactCutoff has advanced past the relminmxid to
550 * enable eager scanning.
551 */
552 if (TransactionIdIsNormal(vacrel->cutoffs.relfrozenxid) &&
553 TransactionIdPrecedes(vacrel->cutoffs.relfrozenxid,
554 vacrel->cutoffs.FreezeLimit))
556
558 MultiXactIdIsValid(vacrel->cutoffs.relminmxid) &&
559 MultiXactIdPrecedes(vacrel->cutoffs.relminmxid,
560 vacrel->cutoffs.MultiXactCutoff))
562
564 return;
565
566 /* We have met the criteria to eagerly scan some pages. */
567
568 /*
569 * Our success cap is MAX_EAGER_FREEZE_SUCCESS_RATE of the number of
570 * all-visible but not all-frozen blocks in the relation.
571 */
573
574 vacrel->eager_scan_remaining_successes =
577
578 /* If every all-visible page is frozen, eager scanning is disabled. */
579 if (vacrel->eager_scan_remaining_successes == 0)
580 return;
581
582 /*
583 * Now calculate the bounds of the first eager scan region. Its end block
584 * will be a random spot somewhere in the first EAGER_SCAN_REGION_SIZE
585 * blocks. This affects the bounds of all subsequent regions and avoids
586 * eager scanning and failing to freeze the same blocks each vacuum of the
587 * relation.
588 */
590
591 vacrel->next_eager_scan_region_start = randseed % EAGER_SCAN_REGION_SIZE;
592
594 params->max_eager_freeze_failure_rate <= 1);
595
596 vacrel->eager_scan_max_fails_per_region =
599
600 /*
601 * The first region will be smaller than subsequent regions. As such,
602 * adjust the eager freeze failures tolerated for this region.
603 */
604 first_region_ratio = 1 - (float) vacrel->next_eager_scan_region_start /
606
607 vacrel->eager_scan_remaining_fails =
608 vacrel->eager_scan_max_fails_per_region *
610}
611
612/*
613 * heap_vacuum_rel() -- perform VACUUM for one heap relation
614 *
615 * This routine sets things up for and then calls lazy_scan_heap, where
616 * almost all work actually takes place. Finalizes everything after call
617 * returns by managing relation truncation and updating rel's pg_class
618 * entry. (Also updates pg_class entries for any indexes that need it.)
619 *
620 * At entry, we have already established a transaction and opened
621 * and locked the relation.
622 */
623void
625 BufferAccessStrategy bstrategy)
626{
628 bool verbose,
629 instrument,
630 skipwithvm,
638 TimestampTz starttime = 0;
640 startwritetime = 0;
643 ErrorContextCallback errcallback;
644 char **indnames = NULL;
646
647 verbose = (params->options & VACOPT_VERBOSE) != 0;
648 instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
649 params->log_vacuum_min_duration >= 0));
650 if (instrument)
651 {
653 if (track_io_timing)
654 {
657 }
658 }
659
660 /* Used for instrumentation and stats report */
661 starttime = GetCurrentTimestamp();
662
664 RelationGetRelid(rel));
667 params->is_wraparound
670 else
673
674 /*
675 * Setup error traceback support for ereport() first. The idea is to set
676 * up an error context callback to display additional information on any
677 * error during a vacuum. During different phases of vacuum, we update
678 * the state so that the error context callback always display current
679 * information.
680 *
681 * Copy the names of heap rel into local memory for error reporting
682 * purposes, too. It isn't always safe to assume that we can get the name
683 * of each rel. It's convenient for code in lazy_scan_heap to always use
684 * these temp copies.
685 */
688 vacrel->relnamespace = get_namespace_name(RelationGetNamespace(rel));
689 vacrel->relname = pstrdup(RelationGetRelationName(rel));
690 vacrel->indname = NULL;
692 vacrel->verbose = verbose;
693 errcallback.callback = vacuum_error_callback;
694 errcallback.arg = vacrel;
695 errcallback.previous = error_context_stack;
696 error_context_stack = &errcallback;
697
698 /* Set up high level stuff about rel and its indexes */
699 vacrel->rel = rel;
701 &vacrel->indrels);
702 vacrel->bstrategy = bstrategy;
703 if (instrument && vacrel->nindexes > 0)
704 {
705 /* Copy index names used by instrumentation (not error reporting) */
706 indnames = palloc_array(char *, vacrel->nindexes);
707 for (int i = 0; i < vacrel->nindexes; i++)
709 }
710
711 /*
712 * The index_cleanup param either disables index vacuuming and cleanup or
713 * forces it to go ahead when we would otherwise apply the index bypass
714 * optimization. The default is 'auto', which leaves the final decision
715 * up to lazy_vacuum().
716 *
717 * The truncate param allows user to avoid attempting relation truncation,
718 * though it can't force truncation to happen.
719 */
722 params->truncate != VACOPTVALUE_AUTO);
723
724 /*
725 * While VacuumFailSafeActive is reset to false before calling this, we
726 * still need to reset it here due to recursive calls.
727 */
728 VacuumFailsafeActive = false;
729 vacrel->consider_bypass_optimization = true;
730 vacrel->do_index_vacuuming = true;
731 vacrel->do_index_cleanup = true;
732 vacrel->do_rel_truncate = (params->truncate != VACOPTVALUE_DISABLED);
733 if (params->index_cleanup == VACOPTVALUE_DISABLED)
734 {
735 /* Force disable index vacuuming up-front */
736 vacrel->do_index_vacuuming = false;
737 vacrel->do_index_cleanup = false;
738 }
739 else if (params->index_cleanup == VACOPTVALUE_ENABLED)
740 {
741 /* Force index vacuuming. Note that failsafe can still bypass. */
742 vacrel->consider_bypass_optimization = false;
743 }
744 else
745 {
746 /* Default/auto, make all decisions dynamically */
748 }
749
750 /* Initialize page counters explicitly (be tidy) */
751 vacrel->scanned_pages = 0;
752 vacrel->eager_scanned_pages = 0;
753 vacrel->removed_pages = 0;
754 vacrel->new_frozen_tuple_pages = 0;
755 vacrel->lpdead_item_pages = 0;
756 vacrel->missed_dead_pages = 0;
757 vacrel->nonempty_pages = 0;
758 /* dead_items_alloc allocates vacrel->dead_items later on */
759
760 /* Allocate/initialize output statistics state */
761 vacrel->new_rel_tuples = 0;
762 vacrel->new_live_tuples = 0;
763 vacrel->indstats = (IndexBulkDeleteResult **)
764 palloc0(vacrel->nindexes * sizeof(IndexBulkDeleteResult *));
765
766 /* Initialize remaining counters (be tidy) */
767 vacrel->num_index_scans = 0;
768 vacrel->num_dead_items_resets = 0;
769 vacrel->total_dead_items_bytes = 0;
770 vacrel->tuples_deleted = 0;
771 vacrel->tuples_frozen = 0;
772 vacrel->lpdead_items = 0;
773 vacrel->live_tuples = 0;
774 vacrel->recently_dead_tuples = 0;
775 vacrel->missed_dead_tuples = 0;
776
777 vacrel->new_all_visible_pages = 0;
778 vacrel->new_all_visible_all_frozen_pages = 0;
779 vacrel->new_all_frozen_pages = 0;
780
781 vacrel->worker_usage.vacuum.nlaunched = 0;
782 vacrel->worker_usage.vacuum.nplanned = 0;
783 vacrel->worker_usage.cleanup.nlaunched = 0;
784 vacrel->worker_usage.cleanup.nplanned = 0;
785
786 /*
787 * Get cutoffs that determine which deleted tuples are considered DEAD,
788 * not just RECENTLY_DEAD, and which XIDs/MXIDs to freeze. Then determine
789 * the extent of the blocks that we'll scan in lazy_scan_heap. It has to
790 * happen in this order to ensure that the OldestXmin cutoff field works
791 * as an upper bound on the XIDs stored in the pages we'll actually scan
792 * (NewRelfrozenXid tracking must never be allowed to miss unfrozen XIDs).
793 *
794 * Next acquire vistest, a related cutoff that's used in pruning. We use
795 * vistest in combination with OldestXmin to ensure that
796 * heap_page_prune_and_freeze() always removes any deleted tuple whose
797 * xmax is < OldestXmin. lazy_scan_prune must never become confused about
798 * whether a tuple should be frozen or removed. (In the future we might
799 * want to teach lazy_scan_prune to recompute vistest from time to time,
800 * to increase the number of dead tuples it can prune away.)
801 */
802 vacrel->aggressive = vacuum_get_cutoffs(rel, params, &vacrel->cutoffs);
804 vacrel->vistest = GlobalVisTestFor(rel);
805
806 /* Initialize state used to track oldest extant XID/MXID */
807 vacrel->NewRelfrozenXid = vacrel->cutoffs.OldestXmin;
808 vacrel->NewRelminMxid = vacrel->cutoffs.OldestMxact;
809
810 /*
811 * Initialize state related to tracking all-visible page skipping. This is
812 * very important to determine whether or not it is safe to advance the
813 * relfrozenxid/relminmxid.
814 */
815 vacrel->skippedallvis = false;
816 skipwithvm = true;
818 {
819 /*
820 * Force aggressive mode, and disable skipping blocks using the
821 * visibility map (even those set all-frozen)
822 */
823 vacrel->aggressive = true;
824 skipwithvm = false;
825 }
826
827 vacrel->skipwithvm = skipwithvm;
828
829 /*
830 * Set up eager scan tracking state. This must happen after determining
831 * whether or not the vacuum must be aggressive, because only normal
832 * vacuums use the eager scan algorithm.
833 */
835
836 /* Report the vacuum mode: 'normal' or 'aggressive' */
838 vacrel->aggressive
841
842 if (verbose)
843 {
844 if (vacrel->aggressive)
846 (errmsg("aggressively vacuuming \"%s.%s.%s\"",
847 vacrel->dbname, vacrel->relnamespace,
848 vacrel->relname)));
849 else
851 (errmsg("vacuuming \"%s.%s.%s\"",
852 vacrel->dbname, vacrel->relnamespace,
853 vacrel->relname)));
854 }
855
856 /*
857 * Allocate dead_items memory using dead_items_alloc. This handles
858 * parallel VACUUM initialization as part of allocating shared memory
859 * space used for dead_items. (But do a failsafe precheck first, to
860 * ensure that parallel VACUUM won't be attempted at all when relfrozenxid
861 * is already dangerously old.)
862 */
865
866#ifdef USE_INJECTION_POINTS
867
868 /*
869 * Used by tests to pause before parallel vacuum is launched, allowing
870 * test code to modify configuration that the leader then propagates to
871 * workers.
872 */
874 INJECTION_POINT("autovacuum-start-parallel-vacuum", NULL);
875#endif
876
877 /*
878 * Call lazy_scan_heap to perform all required heap pruning, index
879 * vacuuming, and heap vacuuming (plus related processing)
880 */
882
883 /*
884 * Save dead items max_bytes and update the memory usage statistics before
885 * cleanup, they are freed in parallel vacuum cases during
886 * dead_items_cleanup().
887 */
888 dead_items_max_bytes = vacrel->dead_items_info->max_bytes;
889 vacrel->total_dead_items_bytes += TidStoreMemoryUsage(vacrel->dead_items);
890
891 /*
892 * Free resources managed by dead_items_alloc. This ends parallel mode in
893 * passing when necessary.
894 */
897
898 /*
899 * Update pg_class entries for each of rel's indexes where appropriate.
900 *
901 * Unlike the later update to rel's pg_class entry, this is not critical.
902 * Maintains relpages/reltuples statistics used by the planner only.
903 */
904 if (vacrel->do_index_cleanup)
906
907 /* Done with rel's indexes */
908 vac_close_indexes(vacrel->nindexes, vacrel->indrels, NoLock);
909
910 /* Optionally truncate rel */
913
914 /* Pop the error context stack */
915 error_context_stack = errcallback.previous;
916
917 /* Report that we are now doing final cleanup */
920
921 /*
922 * Prepare to update rel's pg_class entry.
923 *
924 * Aggressive VACUUMs must always be able to advance relfrozenxid to a
925 * value >= FreezeLimit, and relminmxid to a value >= MultiXactCutoff.
926 * Non-aggressive VACUUMs may advance them by any amount, or not at all.
927 */
928 Assert(vacrel->NewRelfrozenXid == vacrel->cutoffs.OldestXmin ||
929 TransactionIdPrecedesOrEquals(vacrel->aggressive ? vacrel->cutoffs.FreezeLimit :
930 vacrel->cutoffs.relfrozenxid,
931 vacrel->NewRelfrozenXid));
932 Assert(vacrel->NewRelminMxid == vacrel->cutoffs.OldestMxact ||
933 MultiXactIdPrecedesOrEquals(vacrel->aggressive ? vacrel->cutoffs.MultiXactCutoff :
934 vacrel->cutoffs.relminmxid,
935 vacrel->NewRelminMxid));
936 if (vacrel->skippedallvis)
937 {
938 /*
939 * Must keep original relfrozenxid in a non-aggressive VACUUM that
940 * chose to skip an all-visible page range. The state that tracks new
941 * values will have missed unfrozen XIDs from the pages we skipped.
942 */
943 Assert(!vacrel->aggressive);
944 vacrel->NewRelfrozenXid = InvalidTransactionId;
945 vacrel->NewRelminMxid = InvalidMultiXactId;
946 }
947
948 /*
949 * For safety, clamp relallvisible to be not more than what we're setting
950 * pg_class.relpages to
951 */
952 new_rel_pages = vacrel->rel_pages; /* After possible rel truncation */
956
957 /*
958 * An all-frozen block _must_ be all-visible. As such, clamp the count of
959 * all-frozen blocks to the count of all-visible blocks. This matches the
960 * clamping of relallvisible above.
961 */
964
965 /*
966 * Now actually update rel's pg_class entry.
967 *
968 * In principle new_live_tuples could be -1 indicating that we (still)
969 * don't know the tuple count. In practice that can't happen, since we
970 * scan every page that isn't skipped using the visibility map.
971 */
972 vac_update_relstats(rel, new_rel_pages, vacrel->new_live_tuples,
974 vacrel->nindexes > 0,
975 vacrel->NewRelfrozenXid, vacrel->NewRelminMxid,
977
978 /*
979 * Report results to the cumulative stats system, too.
980 *
981 * Deliberately avoid telling the stats system about LP_DEAD items that
982 * remain in the table due to VACUUM bypassing index and heap vacuuming.
983 * ANALYZE will consider the remaining LP_DEAD items to be dead "tuples".
984 * It seems like a good idea to err on the side of not vacuuming again too
985 * soon in cases where the failsafe prevented significant amounts of heap
986 * vacuuming.
987 */
989 Max(vacrel->new_live_tuples, 0),
990 vacrel->recently_dead_tuples +
991 vacrel->missed_dead_tuples,
992 starttime);
994
995 if (instrument)
996 {
998
999 if (verbose || params->log_vacuum_min_duration == 0 ||
1001 params->log_vacuum_min_duration))
1002 {
1003 long secs_dur;
1004 int usecs_dur;
1005 WalUsage walusage;
1006 BufferUsage bufferusage;
1008 char *msgfmt;
1009 int32 diff;
1010 double read_rate = 0,
1011 write_rate = 0;
1015
1017 memset(&walusage, 0, sizeof(WalUsage));
1019 memset(&bufferusage, 0, sizeof(BufferUsage));
1021
1022 total_blks_hit = bufferusage.shared_blks_hit +
1023 bufferusage.local_blks_hit;
1024 total_blks_read = bufferusage.shared_blks_read +
1025 bufferusage.local_blks_read;
1027 bufferusage.local_blks_dirtied;
1028
1030 if (verbose)
1031 {
1032 /*
1033 * Aggressiveness already reported earlier, in dedicated
1034 * VACUUM VERBOSE ereport
1035 */
1036 Assert(!params->is_wraparound);
1037 msgfmt = _("finished vacuuming \"%s.%s.%s\": index scans: %d\n");
1038 }
1039 else if (params->is_wraparound)
1040 {
1041 /*
1042 * While it's possible for a VACUUM to be both is_wraparound
1043 * and !aggressive, that's just a corner-case -- is_wraparound
1044 * implies aggressive. Produce distinct output for the corner
1045 * case all the same, just in case.
1046 */
1047 if (vacrel->aggressive)
1048 msgfmt = _("automatic aggressive vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
1049 else
1050 msgfmt = _("automatic vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
1051 }
1052 else
1053 {
1054 if (vacrel->aggressive)
1055 msgfmt = _("automatic aggressive vacuum of table \"%s.%s.%s\": index scans: %d\n");
1056 else
1057 msgfmt = _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n");
1058 }
1060 vacrel->dbname,
1061 vacrel->relnamespace,
1062 vacrel->relname,
1063 vacrel->num_index_scans);
1064 appendStringInfo(&buf, _("pages: %u removed, %u remain, %u scanned (%.2f%% of total), %u eagerly scanned\n"),
1065 vacrel->removed_pages,
1067 vacrel->scanned_pages,
1068 orig_rel_pages == 0 ? 100.0 :
1069 100.0 * vacrel->scanned_pages /
1071 vacrel->eager_scanned_pages);
1073 _("tuples: %" PRId64 " removed, %" PRId64 " remain, %" PRId64 " are dead but not yet removable\n"),
1074 vacrel->tuples_deleted,
1075 (int64) vacrel->new_rel_tuples,
1076 vacrel->recently_dead_tuples);
1077 if (vacrel->missed_dead_tuples > 0)
1079 _("tuples missed: %" PRId64 " dead from %u pages not removed due to cleanup lock contention\n"),
1080 vacrel->missed_dead_tuples,
1081 vacrel->missed_dead_pages);
1083 vacrel->cutoffs.OldestXmin);
1085 _("removable cutoff: %u, which was %d XIDs old when operation ended\n"),
1086 vacrel->cutoffs.OldestXmin, diff);
1088 {
1089 diff = (int32) (vacrel->NewRelfrozenXid -
1090 vacrel->cutoffs.relfrozenxid);
1092 _("new relfrozenxid: %u, which is %d XIDs ahead of previous value\n"),
1093 vacrel->NewRelfrozenXid, diff);
1094 }
1095 if (minmulti_updated)
1096 {
1097 diff = (int32) (vacrel->NewRelminMxid -
1098 vacrel->cutoffs.relminmxid);
1100 _("new relminmxid: %u, which is %d MXIDs ahead of previous value\n"),
1101 vacrel->NewRelminMxid, diff);
1102 }
1103 appendStringInfo(&buf, _("frozen: %u pages from table (%.2f%% of total) had %" PRId64 " tuples frozen\n"),
1104 vacrel->new_frozen_tuple_pages,
1105 orig_rel_pages == 0 ? 100.0 :
1106 100.0 * vacrel->new_frozen_tuple_pages /
1108 vacrel->tuples_frozen);
1109
1111 _("visibility map: %u pages set all-visible, %u pages set all-frozen (%u were all-visible)\n"),
1112 vacrel->new_all_visible_pages,
1113 vacrel->new_all_visible_all_frozen_pages +
1114 vacrel->new_all_frozen_pages,
1115 vacrel->new_all_frozen_pages);
1116 if (vacrel->do_index_vacuuming)
1117 {
1118 if (vacrel->nindexes == 0 || vacrel->num_index_scans == 0)
1119 appendStringInfoString(&buf, _("index scan not needed: "));
1120 else
1121 appendStringInfoString(&buf, _("index scan needed: "));
1122
1123 msgfmt = _("%u pages from table (%.2f%% of total) had %" PRId64 " dead item identifiers removed\n");
1124 }
1125 else
1126 {
1128 appendStringInfoString(&buf, _("index scan bypassed: "));
1129 else
1130 appendStringInfoString(&buf, _("index scan bypassed by failsafe: "));
1131
1132 msgfmt = _("%u pages from table (%.2f%% of total) have %" PRId64 " dead item identifiers\n");
1133 }
1135 vacrel->lpdead_item_pages,
1136 orig_rel_pages == 0 ? 100.0 :
1137 100.0 * vacrel->lpdead_item_pages / orig_rel_pages,
1138 vacrel->lpdead_items);
1139
1140 if (vacrel->worker_usage.vacuum.nplanned > 0)
1142 _("parallel workers: index vacuum: %d planned, %d launched in total\n"),
1143 vacrel->worker_usage.vacuum.nplanned,
1144 vacrel->worker_usage.vacuum.nlaunched);
1145
1146 if (vacrel->worker_usage.cleanup.nplanned > 0)
1148 _("parallel workers: index cleanup: %d planned, %d launched\n"),
1149 vacrel->worker_usage.cleanup.nplanned,
1150 vacrel->worker_usage.cleanup.nlaunched);
1151
1152 for (int i = 0; i < vacrel->nindexes; i++)
1153 {
1154 IndexBulkDeleteResult *istat = vacrel->indstats[i];
1155
1156 if (!istat)
1157 continue;
1158
1160 _("index \"%s\": pages: %u in total, %u newly deleted, %u currently deleted, %u reusable\n"),
1161 indnames[i],
1162 istat->num_pages,
1163 istat->pages_newly_deleted,
1164 istat->pages_deleted,
1165 istat->pages_free);
1166 }
1168 {
1169 /*
1170 * We bypass the changecount mechanism because this value is
1171 * only updated by the calling process. We also rely on the
1172 * above call to pgstat_progress_end_command() to not clear
1173 * the st_progress_param array.
1174 */
1175 appendStringInfo(&buf, _("delay time: %.3f ms\n"),
1177 }
1178 if (track_io_timing)
1179 {
1180 double read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
1181 double write_ms = (double) (pgStatBlockWriteTime - startwritetime) / 1000;
1182
1183 appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
1184 read_ms, write_ms);
1185 }
1186 if (secs_dur > 0 || usecs_dur > 0)
1187 {
1189 (1024 * 1024) / (secs_dur + usecs_dur / 1000000.0);
1191 (1024 * 1024) / (secs_dur + usecs_dur / 1000000.0);
1192 }
1193 appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
1196 _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
1201 _("WAL usage: %" PRId64 " records, %" PRId64 " full page images, %" PRIu64 " bytes, %" PRIu64 " full page image bytes, %" PRId64 " buffers full\n"),
1202 walusage.wal_records,
1203 walusage.wal_fpi,
1204 walusage.wal_bytes,
1205 walusage.wal_fpi_bytes,
1206 walusage.wal_buffers_full);
1207
1208 /*
1209 * Report the dead items memory usage.
1210 *
1211 * The num_dead_items_resets counter increases when we reset the
1212 * collected dead items, so the counter is non-zero if at least
1213 * one dead items are collected, even if index vacuuming is
1214 * disabled.
1215 */
1217 ngettext("memory usage: dead item storage %.2f MB accumulated across %d reset (limit %.2f MB each)\n",
1218 "memory usage: dead item storage %.2f MB accumulated across %d resets (limit %.2f MB each)\n",
1219 vacrel->num_dead_items_resets),
1220 (double) vacrel->total_dead_items_bytes / (1024 * 1024),
1221 vacrel->num_dead_items_resets,
1222 (double) dead_items_max_bytes / (1024 * 1024));
1223 appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
1224
1225 ereport(verbose ? INFO : LOG,
1226 (errmsg_internal("%s", buf.data)));
1227 pfree(buf.data);
1228 }
1229 }
1230
1231 /* Cleanup index statistics and index names */
1232 for (int i = 0; i < vacrel->nindexes; i++)
1233 {
1234 if (vacrel->indstats[i])
1235 pfree(vacrel->indstats[i]);
1236
1237 if (instrument)
1238 pfree(indnames[i]);
1239 }
1240}
1241
1242/*
1243 * lazy_scan_heap() -- workhorse function for VACUUM
1244 *
1245 * This routine prunes each page in the heap, and considers the need to
1246 * freeze remaining tuples with storage (not including pages that can be
1247 * skipped using the visibility map). Also performs related maintenance
1248 * of the FSM and visibility map. These steps all take place during an
1249 * initial pass over the target heap relation.
1250 *
1251 * Also invokes lazy_vacuum_all_indexes to vacuum indexes, which largely
1252 * consists of deleting index tuples that point to LP_DEAD items left in
1253 * heap pages following pruning. Earlier initial pass over the heap will
1254 * have collected the TIDs whose index tuples need to be removed.
1255 *
1256 * Finally, invokes lazy_vacuum_heap_rel to vacuum heap pages, which
1257 * largely consists of marking LP_DEAD items (from vacrel->dead_items)
1258 * as LP_UNUSED. This has to happen in a second, final pass over the
1259 * heap, to preserve a basic invariant that all index AMs rely on: no
1260 * extant index tuple can ever be allowed to contain a TID that points to
1261 * an LP_UNUSED line pointer in the heap. We must disallow premature
1262 * recycling of line pointers to avoid index scans that get confused
1263 * about which TID points to which tuple immediately after recycling.
1264 * (Actually, this isn't a concern when target heap relation happens to
1265 * have no indexes, which allows us to safely apply the one-pass strategy
1266 * as an optimization).
1267 *
1268 * In practice we often have enough space to fit all TIDs, and so won't
1269 * need to call lazy_vacuum more than once, after our initial pass over
1270 * the heap has totally finished. Otherwise things are slightly more
1271 * complicated: our "initial pass" over the heap applies only to those
1272 * pages that were pruned before we needed to call lazy_vacuum, and our
1273 * "final pass" over the heap only vacuums these same heap pages.
1274 * However, we process indexes in full every time lazy_vacuum is called,
1275 * which makes index processing very inefficient when memory is in short
1276 * supply.
1277 */
1278static void
1280{
1281 ReadStream *stream;
1282 BlockNumber rel_pages = vacrel->rel_pages,
1283 blkno = 0,
1286 vacrel->eager_scan_remaining_successes; /* for logging */
1287 Buffer vmbuffer = InvalidBuffer;
1288 const int initprog_index[] = {
1292 };
1294
1295 /* Report that we're scanning the heap, advertising total # of blocks */
1297 initprog_val[1] = rel_pages;
1298 initprog_val[2] = vacrel->dead_items_info->max_bytes;
1300
1301 /* Initialize for the first heap_vac_scan_next_block() call */
1302 vacrel->current_block = InvalidBlockNumber;
1303 vacrel->next_unskippable_block = InvalidBlockNumber;
1304 vacrel->next_unskippable_eager_scanned = false;
1305 vacrel->next_unskippable_vmbuffer = InvalidBuffer;
1306
1307 /*
1308 * Set up the read stream for vacuum's first pass through the heap.
1309 *
1310 * This could be made safe for READ_STREAM_USE_BATCHING, but only with
1311 * explicit work in heap_vac_scan_next_block.
1312 */
1314 vacrel->bstrategy,
1315 vacrel->rel,
1318 vacrel,
1319 sizeof(bool));
1320
1321 while (true)
1322 {
1323 Buffer buf;
1324 Page page;
1325 bool was_eager_scanned = false;
1326 int ndeleted = 0;
1327 bool has_lpdead_items;
1328 void *per_buffer_data = NULL;
1329 bool vm_page_frozen = false;
1330 bool got_cleanup_lock = false;
1331
1332 vacuum_delay_point(false);
1333
1334 /*
1335 * Regularly check if wraparound failsafe should trigger.
1336 *
1337 * There is a similar check inside lazy_vacuum_all_indexes(), but
1338 * relfrozenxid might start to look dangerously old before we reach
1339 * that point. This check also provides failsafe coverage for the
1340 * one-pass strategy, and the two-pass strategy with the index_cleanup
1341 * param set to 'off'.
1342 */
1343 if (vacrel->scanned_pages > 0 &&
1344 vacrel->scanned_pages % FAILSAFE_EVERY_PAGES == 0)
1346
1347 /*
1348 * Consider if we definitely have enough space to process TIDs on page
1349 * already. If we are close to overrunning the available space for
1350 * dead_items TIDs, pause and do a cycle of vacuuming before we tackle
1351 * this page. However, let's force at least one page-worth of tuples
1352 * to be stored as to ensure we do at least some work when the memory
1353 * configured is so low that we run out before storing anything.
1354 */
1355 if (vacrel->dead_items_info->num_items > 0 &&
1356 TidStoreMemoryUsage(vacrel->dead_items) > vacrel->dead_items_info->max_bytes)
1357 {
1358 /*
1359 * Before beginning index vacuuming, we release any pin we may
1360 * hold on the visibility map page. This isn't necessary for
1361 * correctness, but we do it anyway to avoid holding the pin
1362 * across a lengthy, unrelated operation.
1363 */
1364 if (BufferIsValid(vmbuffer))
1365 {
1366 ReleaseBuffer(vmbuffer);
1367 vmbuffer = InvalidBuffer;
1368 }
1369
1370 /* Perform a round of index and heap vacuuming */
1371 vacrel->consider_bypass_optimization = false;
1373
1374 /*
1375 * Vacuum the Free Space Map to make newly-freed space visible on
1376 * upper-level FSM pages. Note that blkno is the previously
1377 * processed block.
1378 */
1380 blkno + 1);
1382
1383 /* Report that we are once again scanning the heap */
1386 }
1387
1388 buf = read_stream_next_buffer(stream, &per_buffer_data);
1389
1390 /* The relation is exhausted. */
1391 if (!BufferIsValid(buf))
1392 break;
1393
1394 was_eager_scanned = *((bool *) per_buffer_data);
1396 page = BufferGetPage(buf);
1397 blkno = BufferGetBlockNumber(buf);
1398
1399 vacrel->scanned_pages++;
1401 vacrel->eager_scanned_pages++;
1402
1403 /* Report as block scanned, update error traceback information */
1406 blkno, InvalidOffsetNumber);
1407
1408 /*
1409 * Pin the visibility map page in case we need to mark the page
1410 * all-visible. In most cases this will be very cheap, because we'll
1411 * already have the correct page pinned anyway.
1412 */
1413 visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
1414
1415 /*
1416 * We need a buffer cleanup lock to prune HOT chains and defragment
1417 * the page in lazy_scan_prune. But when it's not possible to acquire
1418 * a cleanup lock right away, we may be able to settle for reduced
1419 * processing using lazy_scan_noprune.
1420 */
1422
1423 if (!got_cleanup_lock)
1425
1426 /* Check for new or empty pages before lazy_scan_[no]prune call */
1428 vmbuffer))
1429 {
1430 /* Processed as new/empty page (lock and pin released) */
1431 continue;
1432 }
1433
1434 /*
1435 * If we didn't get the cleanup lock, we can still collect LP_DEAD
1436 * items in the dead_items area for later vacuuming, count live and
1437 * recently dead tuples for vacuum logging, and determine if this
1438 * block could later be truncated. If we encounter any xid/mxids that
1439 * require advancing the relfrozenxid/relminxid, we'll have to wait
1440 * for a cleanup lock and call lazy_scan_prune().
1441 */
1442 if (!got_cleanup_lock &&
1443 !lazy_scan_noprune(vacrel, buf, blkno, page, &has_lpdead_items))
1444 {
1445 /*
1446 * lazy_scan_noprune could not do all required processing. Wait
1447 * for a cleanup lock, and call lazy_scan_prune in the usual way.
1448 */
1449 Assert(vacrel->aggressive);
1452 got_cleanup_lock = true;
1453 }
1454
1455 /*
1456 * If we have a cleanup lock, we must now prune, freeze, and count
1457 * tuples. We may have acquired the cleanup lock originally, or we may
1458 * have gone back and acquired it after lazy_scan_noprune() returned
1459 * false. Either way, the page hasn't been processed yet.
1460 *
1461 * Like lazy_scan_noprune(), lazy_scan_prune() will count
1462 * recently_dead_tuples and live tuples for vacuum logging, determine
1463 * if the block can later be truncated, and accumulate the details of
1464 * remaining LP_DEAD line pointers on the page into dead_items. These
1465 * dead items include those pruned by lazy_scan_prune() as well as
1466 * line pointers previously marked LP_DEAD.
1467 */
1468 if (got_cleanup_lock)
1469 ndeleted = lazy_scan_prune(vacrel, buf, blkno, page,
1470 vmbuffer,
1472
1473 /*
1474 * Count an eagerly scanned page as a failure or a success.
1475 *
1476 * Only lazy_scan_prune() freezes pages, so if we didn't get the
1477 * cleanup lock, we won't have frozen the page. However, we only count
1478 * pages that were too new to require freezing as eager freeze
1479 * failures.
1480 *
1481 * We could gather more information from lazy_scan_noprune() about
1482 * whether or not there were tuples with XIDs or MXIDs older than the
1483 * FreezeLimit or MultiXactCutoff. However, for simplicity, we simply
1484 * exclude pages skipped due to cleanup lock contention from eager
1485 * freeze algorithm caps.
1486 */
1488 {
1489 /* Aggressive vacuums do not eager scan. */
1490 Assert(!vacrel->aggressive);
1491
1492 if (vm_page_frozen)
1493 {
1494 if (vacrel->eager_scan_remaining_successes > 0)
1495 vacrel->eager_scan_remaining_successes--;
1496
1497 if (vacrel->eager_scan_remaining_successes == 0)
1498 {
1499 /*
1500 * Report only once that we disabled eager scanning. We
1501 * may eagerly read ahead blocks in excess of the success
1502 * or failure caps before attempting to freeze them, so we
1503 * could reach here even after disabling additional eager
1504 * scanning.
1505 */
1506 if (vacrel->eager_scan_max_fails_per_region > 0)
1507 ereport(vacrel->verbose ? INFO : DEBUG2,
1508 (errmsg("disabling eager scanning after freezing %u eagerly scanned blocks of relation \"%s.%s.%s\"",
1510 vacrel->dbname, vacrel->relnamespace,
1511 vacrel->relname)));
1512
1513 /*
1514 * If we hit our success cap, permanently disable eager
1515 * scanning by setting the other eager scan management
1516 * fields to their disabled values.
1517 */
1518 vacrel->eager_scan_remaining_fails = 0;
1519 vacrel->next_eager_scan_region_start = InvalidBlockNumber;
1520 vacrel->eager_scan_max_fails_per_region = 0;
1521 }
1522 }
1523 else if (vacrel->eager_scan_remaining_fails > 0)
1524 vacrel->eager_scan_remaining_fails--;
1525 }
1526
1527 /*
1528 * Now drop the buffer lock and, potentially, update the FSM.
1529 *
1530 * Our goal is to update the freespace map the last time we touch the
1531 * page. If we'll process a block in the second pass, we may free up
1532 * additional space on the page, so it is better to update the FSM
1533 * after the second pass. If the relation has no indexes, or if index
1534 * vacuuming is disabled, there will be no second heap pass; if this
1535 * particular page has no dead items, the second heap pass will not
1536 * touch this page. So, in those cases, update the FSM now.
1537 *
1538 * Note: In corner cases, it's possible to miss updating the FSM
1539 * entirely. If index vacuuming is currently enabled, we'll skip the
1540 * FSM update now. But if failsafe mode is later activated, or there
1541 * are so few dead tuples that index vacuuming is bypassed, there will
1542 * also be no opportunity to update the FSM later, because we'll never
1543 * revisit this page. Since updating the FSM is desirable but not
1544 * absolutely required, that's OK.
1545 */
1546 if (vacrel->nindexes == 0
1547 || !vacrel->do_index_vacuuming
1548 || !has_lpdead_items)
1549 {
1550 Size freespace = PageGetHeapFreeSpace(page);
1551
1553 RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
1554
1555 /*
1556 * Periodically perform FSM vacuuming to make newly-freed space
1557 * visible on upper FSM pages. This is done after vacuuming if the
1558 * table has indexes. There will only be newly-freed space if we
1559 * held the cleanup lock and lazy_scan_prune() was called.
1560 */
1561 if (got_cleanup_lock && vacrel->nindexes == 0 && ndeleted > 0 &&
1563 {
1565 blkno);
1567 }
1568 }
1569 else
1571 }
1572
1573 vacrel->blkno = InvalidBlockNumber;
1574 if (BufferIsValid(vmbuffer))
1575 ReleaseBuffer(vmbuffer);
1576
1577 /*
1578 * Report that everything is now scanned. We never skip scanning the last
1579 * block in the relation, so we can pass rel_pages here.
1580 */
1582 rel_pages);
1583
1584 /* now we can compute the new value for pg_class.reltuples */
1585 vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
1586 vacrel->scanned_pages,
1587 vacrel->live_tuples);
1588
1589 /*
1590 * Also compute the total number of surviving heap entries. In the
1591 * (unlikely) scenario that new_live_tuples is -1, take it as zero.
1592 */
1593 vacrel->new_rel_tuples =
1594 Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
1595 vacrel->missed_dead_tuples;
1596
1597 read_stream_end(stream);
1598
1599 /*
1600 * Do index vacuuming (call each index's ambulkdelete routine), then do
1601 * related heap vacuuming
1602 */
1603 if (vacrel->dead_items_info->num_items > 0)
1605
1606 /*
1607 * Vacuum the remainder of the Free Space Map. We must do this whether or
1608 * not there were indexes, and whether or not we bypassed index vacuuming.
1609 * We can pass rel_pages here because we never skip scanning the last
1610 * block of the relation.
1611 */
1612 if (rel_pages > next_fsm_block_to_vacuum)
1614
1615 /* report all blocks vacuumed */
1617
1618 /* Do final index cleanup (call each index's amvacuumcleanup routine) */
1619 if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
1621}
1622
1623/*
1624 * heap_vac_scan_next_block() -- read stream callback to get the next block
1625 * for vacuum to process
1626 *
1627 * Every time lazy_scan_heap() needs a new block to process during its first
1628 * phase, it invokes read_stream_next_buffer() with a stream set up to call
1629 * heap_vac_scan_next_block() to get the next block.
1630 *
1631 * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
1632 * various thresholds to skip blocks which do not need to be processed and
1633 * returns the next block to process or InvalidBlockNumber if there are no
1634 * remaining blocks.
1635 *
1636 * The visibility status of the next block to process and whether or not it
1637 * was eager scanned is set in the per_buffer_data.
1638 *
1639 * callback_private_data contains a reference to the LVRelState, passed to the
1640 * read stream API during stream setup. The LVRelState is an in/out parameter
1641 * here (locally named `vacrel`). Vacuum options and information about the
1642 * relation are read from it. vacrel->skippedallvis is set if we skip a block
1643 * that's all-visible but not all-frozen (to ensure that we don't update
1644 * relfrozenxid in that case). vacrel also holds information about the next
1645 * unskippable block -- as bookkeeping for this function.
1646 */
1647static BlockNumber
1649 void *callback_private_data,
1650 void *per_buffer_data)
1651{
1653 LVRelState *vacrel = callback_private_data;
1654
1655 /* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
1657
1658 /* Have we reached the end of the relation? */
1659 if (next_block >= vacrel->rel_pages)
1660 {
1661 if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
1662 {
1663 ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
1664 vacrel->next_unskippable_vmbuffer = InvalidBuffer;
1665 }
1666 return InvalidBlockNumber;
1667 }
1668
1669 /*
1670 * We must be in one of the three following states:
1671 */
1672 if (next_block > vacrel->next_unskippable_block ||
1673 vacrel->next_unskippable_block == InvalidBlockNumber)
1674 {
1675 /*
1676 * 1. We have just processed an unskippable block (or we're at the
1677 * beginning of the scan). Find the next unskippable block using the
1678 * visibility map.
1679 */
1680 bool skipsallvis;
1681
1683
1684 /*
1685 * We now know the next block that we must process. It can be the
1686 * next block after the one we just processed, or something further
1687 * ahead. If it's further ahead, we can jump to it, but we choose to
1688 * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
1689 * pages. Since we're reading sequentially, the OS should be doing
1690 * readahead for us, so there's no gain in skipping a page now and
1691 * then. Skipping such a range might even discourage sequential
1692 * detection.
1693 *
1694 * This test also enables more frequent relfrozenxid advancement
1695 * during non-aggressive VACUUMs. If the range has any all-visible
1696 * pages then skipping makes updating relfrozenxid unsafe, which is a
1697 * real downside.
1698 */
1699 if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
1700 {
1701 next_block = vacrel->next_unskippable_block;
1702 if (skipsallvis)
1703 vacrel->skippedallvis = true;
1704 }
1705 }
1706
1707 /* Now we must be in one of the two remaining states: */
1708 if (next_block < vacrel->next_unskippable_block)
1709 {
1710 /*
1711 * 2. We are processing a range of blocks that we could have skipped
1712 * but chose not to. We know that they are all-visible in the VM,
1713 * otherwise they would've been unskippable.
1714 */
1715 vacrel->current_block = next_block;
1716 /* Block was not eager scanned */
1717 *((bool *) per_buffer_data) = false;
1718 return vacrel->current_block;
1719 }
1720 else
1721 {
1722 /*
1723 * 3. We reached the next unskippable block. Process it. On next
1724 * iteration, we will be back in state 1.
1725 */
1726 Assert(next_block == vacrel->next_unskippable_block);
1727
1728 vacrel->current_block = next_block;
1729 *((bool *) per_buffer_data) = vacrel->next_unskippable_eager_scanned;
1730 return vacrel->current_block;
1731 }
1732}
1733
1734/*
1735 * Find the next unskippable block in a vacuum scan using the visibility map.
1736 * The next unskippable block and its visibility information is updated in
1737 * vacrel.
1738 *
1739 * Note: our opinion of which blocks can be skipped can go stale immediately.
1740 * It's okay if caller "misses" a page whose all-visible or all-frozen marking
1741 * was concurrently cleared, though. All that matters is that caller scan all
1742 * pages whose tuples might contain XIDs < OldestXmin, or MXIDs < OldestMxact.
1743 * (Actually, non-aggressive VACUUMs can choose to skip all-visible pages with
1744 * older XIDs/MXIDs. The *skippedallvis flag will be set here when the choice
1745 * to skip such a range is actually made, making everything safe.)
1746 */
1747static void
1749{
1750 BlockNumber rel_pages = vacrel->rel_pages;
1751 BlockNumber next_unskippable_block = vacrel->next_unskippable_block + 1;
1752 Buffer next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
1753 bool next_unskippable_eager_scanned = false;
1754
1755 *skipsallvis = false;
1756
1757 for (;; next_unskippable_block++)
1758 {
1760 next_unskippable_block,
1761 &next_unskippable_vmbuffer);
1762
1763
1764 /*
1765 * At the start of each eager scan region, normal vacuums with eager
1766 * scanning enabled reset the failure counter, allowing vacuum to
1767 * resume eager scanning if it had been suspended in the previous
1768 * region.
1769 */
1770 if (next_unskippable_block >= vacrel->next_eager_scan_region_start)
1771 {
1772 vacrel->eager_scan_remaining_fails =
1773 vacrel->eager_scan_max_fails_per_region;
1774 vacrel->next_eager_scan_region_start += EAGER_SCAN_REGION_SIZE;
1775 }
1776
1777 /*
1778 * A block is unskippable if it is not all visible according to the
1779 * visibility map.
1780 */
1782 {
1784 break;
1785 }
1786
1787 /*
1788 * Caller must scan the last page to determine whether it has tuples
1789 * (caller must have the opportunity to set vacrel->nonempty_pages).
1790 * This rule avoids having lazy_truncate_heap() take access-exclusive
1791 * lock on rel to attempt a truncation that fails anyway, just because
1792 * there are tuples on the last page (it is likely that there will be
1793 * tuples on other nearby pages as well, but those can be skipped).
1794 *
1795 * Implement this by always treating the last block as unsafe to skip.
1796 */
1797 if (next_unskippable_block == rel_pages - 1)
1798 break;
1799
1800 /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
1801 if (!vacrel->skipwithvm)
1802 break;
1803
1804 /*
1805 * All-frozen pages cannot contain XIDs < OldestXmin (XIDs that aren't
1806 * already frozen by now), so this page can be skipped.
1807 */
1808 if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
1809 continue;
1810
1811 /*
1812 * Aggressive vacuums cannot skip any all-visible pages that are not
1813 * also all-frozen.
1814 */
1815 if (vacrel->aggressive)
1816 break;
1817
1818 /*
1819 * Normal vacuums with eager scanning enabled only skip all-visible
1820 * but not all-frozen pages if they have hit the failure limit for the
1821 * current eager scan region.
1822 */
1823 if (vacrel->eager_scan_remaining_fails > 0)
1824 {
1825 next_unskippable_eager_scanned = true;
1826 break;
1827 }
1828
1829 /*
1830 * All-visible blocks are safe to skip in a normal vacuum. But
1831 * remember that the final range contains such a block for later.
1832 */
1833 *skipsallvis = true;
1834 }
1835
1836 /* write the local variables back to vacrel */
1837 vacrel->next_unskippable_block = next_unskippable_block;
1838 vacrel->next_unskippable_eager_scanned = next_unskippable_eager_scanned;
1839 vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
1840}
1841
1842/*
1843 * lazy_scan_new_or_empty() -- lazy_scan_heap() new/empty page handling.
1844 *
1845 * Must call here to handle both new and empty pages before calling
1846 * lazy_scan_prune or lazy_scan_noprune, since they're not prepared to deal
1847 * with new or empty pages.
1848 *
1849 * It's necessary to consider new pages as a special case, since the rules for
1850 * maintaining the visibility map and FSM with empty pages are a little
1851 * different (though new pages can be truncated away during rel truncation).
1852 *
1853 * Empty pages are not really a special case -- they're just heap pages that
1854 * have no allocated tuples (including even LP_UNUSED items). You might
1855 * wonder why we need to handle them here all the same. It's only necessary
1856 * because of a corner-case involving a hard crash during heap relation
1857 * extension. If we ever make relation-extension crash safe, then it should
1858 * no longer be necessary to deal with empty pages here (or new pages, for
1859 * that matter).
1860 *
1861 * Caller must hold at least a shared lock. We might need to escalate the
1862 * lock in that case, so the type of lock caller holds needs to be specified
1863 * using 'sharelock' argument.
1864 *
1865 * Returns false in common case where caller should go on to call
1866 * lazy_scan_prune (or lazy_scan_noprune). Otherwise returns true, indicating
1867 * that lazy_scan_heap is done processing the page, releasing lock on caller's
1868 * behalf.
1869 *
1870 * No vm_page_frozen output parameter (like that passed to lazy_scan_prune())
1871 * is passed here because neither empty nor new pages can be eagerly frozen.
1872 * New pages are never frozen. Empty pages are always set frozen in the VM at
1873 * the same time that they are set all-visible, and we don't eagerly scan
1874 * frozen pages.
1875 */
1876static bool
1878 Page page, bool sharelock, Buffer vmbuffer)
1879{
1880 Size freespace;
1881
1882 if (PageIsNew(page))
1883 {
1884 /*
1885 * All-zeroes pages can be left over if either a backend extends the
1886 * relation by a single page, but crashes before the newly initialized
1887 * page has been written out, or when bulk-extending the relation
1888 * (which creates a number of empty pages at the tail end of the
1889 * relation), and then enters them into the FSM.
1890 *
1891 * Note we do not enter the page into the visibilitymap. That has the
1892 * downside that we repeatedly visit this page in subsequent vacuums,
1893 * but otherwise we'll never discover the space on a promoted standby.
1894 * The harm of repeated checking ought to normally not be too bad. The
1895 * space usually should be used at some point, otherwise there
1896 * wouldn't be any regular vacuums.
1897 *
1898 * Make sure these pages are in the FSM, to ensure they can be reused.
1899 * Do that by testing if there's any space recorded for the page. If
1900 * not, enter it. We do so after releasing the lock on the heap page,
1901 * the FSM is approximate, after all.
1902 */
1904
1905 if (GetRecordedFreeSpace(vacrel->rel, blkno) == 0)
1906 {
1907 freespace = BLCKSZ - SizeOfPageHeaderData;
1908
1909 RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
1910 }
1911
1912 return true;
1913 }
1914
1915 if (PageIsEmpty(page))
1916 {
1917 /*
1918 * It seems likely that caller will always be able to get a cleanup
1919 * lock on an empty page. But don't take any chances -- escalate to
1920 * an exclusive lock (still don't need a cleanup lock, though).
1921 */
1922 if (sharelock)
1923 {
1926
1927 if (!PageIsEmpty(page))
1928 {
1929 /* page isn't new or empty -- keep lock and pin for now */
1930 return false;
1931 }
1932 }
1933 else
1934 {
1935 /* Already have a full cleanup lock (which is more than enough) */
1936 }
1937
1938 /*
1939 * Unlike new pages, empty pages are always set all-visible and
1940 * all-frozen.
1941 */
1942 if (!PageIsAllVisible(page))
1943 {
1944 /* Lock vmbuffer before entering critical section */
1946
1948
1949 /* mark buffer dirty before writing a WAL record */
1951
1952 PageSetAllVisible(page);
1953 PageClearPrunable(page);
1954 visibilitymap_set(blkno,
1955 vmbuffer,
1958 vacrel->rel->rd_locator);
1959
1960 /*
1961 * Emit WAL for setting PD_ALL_VISIBLE on the heap page and
1962 * setting the VM.
1963 */
1964 if (RelationNeedsWAL(vacrel->rel))
1966 vmbuffer,
1969 InvalidTransactionId, /* conflict xid */
1970 false, /* cleanup lock */
1971 PRUNE_VACUUM_SCAN, /* reason */
1972 NULL, 0,
1973 NULL, 0,
1974 NULL, 0,
1975 NULL, 0);
1976
1978
1979 LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
1980
1981 /* Count the newly all-frozen pages for logging */
1982 vacrel->new_all_visible_pages++;
1983 vacrel->new_all_visible_all_frozen_pages++;
1984 }
1985
1986 freespace = PageGetHeapFreeSpace(page);
1988 RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
1989 return true;
1990 }
1991
1992 /* page isn't new or empty -- keep lock and pin */
1993 return false;
1994}
1995
1996/* qsort comparator for sorting OffsetNumbers */
1997static int
1998cmpOffsetNumbers(const void *a, const void *b)
1999{
2000 return pg_cmp_u16(*(const OffsetNumber *) a, *(const OffsetNumber *) b);
2001}
2002
2003/*
2004 * lazy_scan_prune() -- lazy_scan_heap() pruning and freezing.
2005 *
2006 * Caller must hold pin and buffer cleanup lock on the buffer.
2007 *
2008 * vmbuffer is the buffer containing the VM block with visibility information
2009 * for the heap block, blkno.
2010 *
2011 * *has_lpdead_items is set to true or false depending on whether, upon return
2012 * from this function, any LP_DEAD items are still present on the page.
2013 *
2014 * *vm_page_frozen is set to true if the page is newly set all-frozen in the
2015 * VM. The caller currently only uses this for determining whether an eagerly
2016 * scanned page was successfully set all-frozen.
2017 *
2018 * Returns the number of tuples deleted from the page during HOT pruning.
2019 */
2020static int
2022 Buffer buf,
2023 BlockNumber blkno,
2024 Page page,
2025 Buffer vmbuffer,
2026 bool *has_lpdead_items,
2027 bool *vm_page_frozen)
2028{
2029 Relation rel = vacrel->rel;
2031 PruneFreezeParams params = {
2032 .relation = rel,
2033 .buffer = buf,
2034 .vmbuffer = vmbuffer,
2035 .reason = PRUNE_VACUUM_SCAN,
2037 .vistest = vacrel->vistest,
2038 .cutoffs = &vacrel->cutoffs,
2039 };
2040
2041 Assert(BufferGetBlockNumber(buf) == blkno);
2042
2043 /*
2044 * Prune all HOT-update chains and potentially freeze tuples on this page.
2045 *
2046 * If the relation has no indexes, we can immediately mark would-be dead
2047 * items LP_UNUSED.
2048 *
2049 * The number of tuples removed from the page is returned in
2050 * presult.ndeleted. It should not be confused with presult.lpdead_items;
2051 * presult.lpdead_items's final value can be thought of as the number of
2052 * tuples that were deleted from indexes.
2053 *
2054 * We will update the VM after collecting LP_DEAD items and freezing
2055 * tuples. Pruning will have determined whether or not the page is
2056 * all-visible.
2057 */
2058 if (vacrel->nindexes == 0)
2060
2061 /*
2062 * Allow skipping full inspection of pages that the VM indicates are
2063 * already all-frozen (which may be scanned due to SKIP_PAGES_THRESHOLD).
2064 * However, if DISABLE_PAGE_SKIPPING was specified, we can't trust the VM,
2065 * so we must examine the page to make sure it is truly all-frozen and fix
2066 * it otherwise.
2067 */
2068 if (vacrel->skipwithvm)
2070
2072 &presult,
2073 &vacrel->offnum,
2074 &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid);
2075
2076 Assert(MultiXactIdIsValid(vacrel->NewRelminMxid));
2077 Assert(TransactionIdIsValid(vacrel->NewRelfrozenXid));
2078
2079 if (presult.nfrozen > 0)
2080 {
2081 /*
2082 * We don't increment the new_frozen_tuple_pages instrumentation
2083 * counter when nfrozen == 0, since it only counts pages with newly
2084 * frozen tuples (don't confuse that with pages newly set all-frozen
2085 * in VM).
2086 */
2087 vacrel->new_frozen_tuple_pages++;
2088 }
2089
2090 /*
2091 * Now save details of the LP_DEAD items from the page in vacrel
2092 */
2093 if (presult.lpdead_items > 0)
2094 {
2095 vacrel->lpdead_item_pages++;
2096
2097 /*
2098 * deadoffsets are collected incrementally in
2099 * heap_page_prune_and_freeze() as each dead line pointer is recorded,
2100 * with an indeterminate order, but dead_items_add requires them to be
2101 * sorted.
2102 */
2103 qsort(presult.deadoffsets, presult.lpdead_items, sizeof(OffsetNumber),
2105
2106 dead_items_add(vacrel, blkno, presult.deadoffsets, presult.lpdead_items);
2107 }
2108
2109 /* Finally, add page-local counts to whole-VACUUM counts */
2110 if (presult.newly_all_visible)
2111 vacrel->new_all_visible_pages++;
2112 if (presult.newly_all_visible_frozen)
2113 vacrel->new_all_visible_all_frozen_pages++;
2114 if (presult.newly_all_frozen)
2115 vacrel->new_all_frozen_pages++;
2116
2117 /* Capture if the page was newly set frozen */
2118 *vm_page_frozen = presult.newly_all_visible_frozen ||
2119 presult.newly_all_frozen;
2120
2121 vacrel->tuples_deleted += presult.ndeleted;
2122 vacrel->tuples_frozen += presult.nfrozen;
2123 vacrel->lpdead_items += presult.lpdead_items;
2124 vacrel->live_tuples += presult.live_tuples;
2125 vacrel->recently_dead_tuples += presult.recently_dead_tuples;
2126
2127 /* Can't truncate this page */
2128 if (presult.hastup)
2129 vacrel->nonempty_pages = blkno + 1;
2130
2131 /* Did we find LP_DEAD items? */
2132 *has_lpdead_items = (presult.lpdead_items > 0);
2133
2134 return presult.ndeleted;
2135}
2136
2137/*
2138 * lazy_scan_noprune() -- lazy_scan_prune() without pruning or freezing
2139 *
2140 * Caller need only hold a pin and share lock on the buffer, unlike
2141 * lazy_scan_prune, which requires a full cleanup lock. While pruning isn't
2142 * performed here, it's quite possible that an earlier opportunistic pruning
2143 * operation left LP_DEAD items behind. We'll at least collect any such items
2144 * in dead_items for removal from indexes.
2145 *
2146 * For aggressive VACUUM callers, we may return false to indicate that a full
2147 * cleanup lock is required for processing by lazy_scan_prune. This is only
2148 * necessary when the aggressive VACUUM needs to freeze some tuple XIDs from
2149 * one or more tuples on the page. We always return true for non-aggressive
2150 * callers.
2151 *
2152 * If this function returns true, *has_lpdead_items gets set to true or false
2153 * depending on whether, upon return from this function, any LP_DEAD items are
2154 * present on the page. If this function returns false, *has_lpdead_items
2155 * is not updated.
2156 */
2157static bool
2159 Buffer buf,
2160 BlockNumber blkno,
2161 Page page,
2162 bool *has_lpdead_items)
2163{
2164 OffsetNumber offnum,
2165 maxoff;
2166 int lpdead_items,
2167 live_tuples,
2168 recently_dead_tuples,
2169 missed_dead_tuples;
2170 bool hastup;
2172 TransactionId NoFreezePageRelfrozenXid = vacrel->NewRelfrozenXid;
2173 MultiXactId NoFreezePageRelminMxid = vacrel->NewRelminMxid;
2175
2176 Assert(BufferGetBlockNumber(buf) == blkno);
2177
2178 hastup = false; /* for now */
2179
2180 lpdead_items = 0;
2181 live_tuples = 0;
2182 recently_dead_tuples = 0;
2183 missed_dead_tuples = 0;
2184
2185 maxoff = PageGetMaxOffsetNumber(page);
2186 for (offnum = FirstOffsetNumber;
2187 offnum <= maxoff;
2188 offnum = OffsetNumberNext(offnum))
2189 {
2190 ItemId itemid;
2191 HeapTupleData tuple;
2192
2193 vacrel->offnum = offnum;
2194 itemid = PageGetItemId(page, offnum);
2195
2196 if (!ItemIdIsUsed(itemid))
2197 continue;
2198
2199 if (ItemIdIsRedirected(itemid))
2200 {
2201 hastup = true;
2202 continue;
2203 }
2204
2205 if (ItemIdIsDead(itemid))
2206 {
2207 /*
2208 * Deliberately don't set hastup=true here. See same point in
2209 * lazy_scan_prune for an explanation.
2210 */
2211 deadoffsets[lpdead_items++] = offnum;
2212 continue;
2213 }
2214
2215 hastup = true; /* page prevents rel truncation */
2216 tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
2218 &NoFreezePageRelfrozenXid,
2219 &NoFreezePageRelminMxid))
2220 {
2221 /* Tuple with XID < FreezeLimit (or MXID < MultiXactCutoff) */
2222 if (vacrel->aggressive)
2223 {
2224 /*
2225 * Aggressive VACUUMs must always be able to advance rel's
2226 * relfrozenxid to a value >= FreezeLimit (and be able to
2227 * advance rel's relminmxid to a value >= MultiXactCutoff).
2228 * The ongoing aggressive VACUUM won't be able to do that
2229 * unless it can freeze an XID (or MXID) from this tuple now.
2230 *
2231 * The only safe option is to have caller perform processing
2232 * of this page using lazy_scan_prune. Caller might have to
2233 * wait a while for a cleanup lock, but it can't be helped.
2234 */
2235 vacrel->offnum = InvalidOffsetNumber;
2236 return false;
2237 }
2238
2239 /*
2240 * Non-aggressive VACUUMs are under no obligation to advance
2241 * relfrozenxid (even by one XID). We can be much laxer here.
2242 *
2243 * Currently we always just accept an older final relfrozenxid
2244 * and/or relminmxid value. We never make caller wait or work a
2245 * little harder, even when it likely makes sense to do so.
2246 */
2247 }
2248
2249 ItemPointerSet(&(tuple.t_self), blkno, offnum);
2250 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2251 tuple.t_len = ItemIdGetLength(itemid);
2252 tuple.t_tableOid = RelationGetRelid(vacrel->rel);
2253
2254 switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
2255 buf))
2256 {
2258 case HEAPTUPLE_LIVE:
2259
2260 /*
2261 * Count both cases as live, just like lazy_scan_prune
2262 */
2263 live_tuples++;
2264
2265 break;
2266 case HEAPTUPLE_DEAD:
2267
2268 /*
2269 * There is some useful work for pruning to do, that won't be
2270 * done due to failure to get a cleanup lock.
2271 */
2272 missed_dead_tuples++;
2273 break;
2275
2276 /*
2277 * Count in recently_dead_tuples, just like lazy_scan_prune
2278 */
2279 recently_dead_tuples++;
2280 break;
2282
2283 /*
2284 * Do not count these rows as live, just like lazy_scan_prune
2285 */
2286 break;
2287 default:
2288 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
2289 break;
2290 }
2291 }
2292
2293 vacrel->offnum = InvalidOffsetNumber;
2294
2295 /*
2296 * By here we know for sure that caller can put off freezing and pruning
2297 * this particular page until the next VACUUM. Remember its details now.
2298 * (lazy_scan_prune expects a clean slate, so we have to do this last.)
2299 */
2300 vacrel->NewRelfrozenXid = NoFreezePageRelfrozenXid;
2301 vacrel->NewRelminMxid = NoFreezePageRelminMxid;
2302
2303 /* Save any LP_DEAD items found on the page in dead_items */
2304 if (vacrel->nindexes == 0)
2305 {
2306 /* Using one-pass strategy (since table has no indexes) */
2307 if (lpdead_items > 0)
2308 {
2309 /*
2310 * Perfunctory handling for the corner case where a single pass
2311 * strategy VACUUM cannot get a cleanup lock, and it turns out
2312 * that there is one or more LP_DEAD items: just count the LP_DEAD
2313 * items as missed_dead_tuples instead. (This is a bit dishonest,
2314 * but it beats having to maintain specialized heap vacuuming code
2315 * forever, for vanishingly little benefit.)
2316 */
2317 hastup = true;
2318 missed_dead_tuples += lpdead_items;
2319 }
2320 }
2321 else if (lpdead_items > 0)
2322 {
2323 /*
2324 * Page has LP_DEAD items, and so any references/TIDs that remain in
2325 * indexes will be deleted during index vacuuming (and then marked
2326 * LP_UNUSED in the heap)
2327 */
2328 vacrel->lpdead_item_pages++;
2329
2330 dead_items_add(vacrel, blkno, deadoffsets, lpdead_items);
2331
2332 vacrel->lpdead_items += lpdead_items;
2333 }
2334
2335 /*
2336 * Finally, add relevant page-local counts to whole-VACUUM counts
2337 */
2338 vacrel->live_tuples += live_tuples;
2339 vacrel->recently_dead_tuples += recently_dead_tuples;
2340 vacrel->missed_dead_tuples += missed_dead_tuples;
2341 if (missed_dead_tuples > 0)
2342 vacrel->missed_dead_pages++;
2343
2344 /* Can't truncate this page */
2345 if (hastup)
2346 vacrel->nonempty_pages = blkno + 1;
2347
2348 /* Did we find LP_DEAD items? */
2349 *has_lpdead_items = (lpdead_items > 0);
2350
2351 /* Caller won't need to call lazy_scan_prune with same page */
2352 return true;
2353}
2354
2355/*
2356 * Main entry point for index vacuuming and heap vacuuming.
2357 *
2358 * Removes items collected in dead_items from table's indexes, then marks the
2359 * same items LP_UNUSED in the heap. See the comments above lazy_scan_heap
2360 * for full details.
2361 *
2362 * Also empties dead_items, freeing up space for later TIDs.
2363 *
2364 * We may choose to bypass index vacuuming at this point, though only when the
2365 * ongoing VACUUM operation will definitely only have one index scan/round of
2366 * index vacuuming.
2367 */
2368static void
2370{
2371 bool bypass;
2372
2373 /* Should not end up here with no indexes */
2374 Assert(vacrel->nindexes > 0);
2375 Assert(vacrel->lpdead_item_pages > 0);
2376
2377 if (!vacrel->do_index_vacuuming)
2378 {
2379 Assert(!vacrel->do_index_cleanup);
2381 return;
2382 }
2383
2384 /*
2385 * Consider bypassing index vacuuming (and heap vacuuming) entirely.
2386 *
2387 * We currently only do this in cases where the number of LP_DEAD items
2388 * for the entire VACUUM operation is close to zero. This avoids sharp
2389 * discontinuities in the duration and overhead of successive VACUUM
2390 * operations that run against the same table with a fixed workload.
2391 * Ideally, successive VACUUM operations will behave as if there are
2392 * exactly zero LP_DEAD items in cases where there are close to zero.
2393 *
2394 * This is likely to be helpful with a table that is continually affected
2395 * by UPDATEs that can mostly apply the HOT optimization, but occasionally
2396 * have small aberrations that lead to just a few heap pages retaining
2397 * only one or two LP_DEAD items. This is pretty common; even when the
2398 * DBA goes out of their way to make UPDATEs use HOT, it is practically
2399 * impossible to predict whether HOT will be applied in 100% of cases.
2400 * It's far easier to ensure that 99%+ of all UPDATEs against a table use
2401 * HOT through careful tuning.
2402 */
2403 bypass = false;
2404 if (vacrel->consider_bypass_optimization && vacrel->rel_pages > 0)
2405 {
2407
2408 Assert(vacrel->num_index_scans == 0);
2409 Assert(vacrel->lpdead_items == vacrel->dead_items_info->num_items);
2410 Assert(vacrel->do_index_vacuuming);
2411 Assert(vacrel->do_index_cleanup);
2412
2413 /*
2414 * This crossover point at which we'll start to do index vacuuming is
2415 * expressed as a percentage of the total number of heap pages in the
2416 * table that are known to have at least one LP_DEAD item. This is
2417 * much more important than the total number of LP_DEAD items, since
2418 * it's a proxy for the number of heap pages whose visibility map bits
2419 * cannot be set on account of bypassing index and heap vacuuming.
2420 *
2421 * We apply one further precautionary test: the space currently used
2422 * to store the TIDs (TIDs that now all point to LP_DEAD items) must
2423 * not exceed 32MB. This limits the risk that we will bypass index
2424 * vacuuming again and again until eventually there is a VACUUM whose
2425 * dead_items space is not CPU cache resident.
2426 *
2427 * We don't take any special steps to remember the LP_DEAD items (such
2428 * as counting them in our final update to the stats system) when the
2429 * optimization is applied. Though the accounting used in analyze.c's
2430 * acquire_sample_rows() will recognize the same LP_DEAD items as dead
2431 * rows in its own stats report, that's okay. The discrepancy should
2432 * be negligible. If this optimization is ever expanded to cover more
2433 * cases then this may need to be reconsidered.
2434 */
2436 bypass = (vacrel->lpdead_item_pages < threshold &&
2437 TidStoreMemoryUsage(vacrel->dead_items) < 32 * 1024 * 1024);
2438 }
2439
2440 if (bypass)
2441 {
2442 /*
2443 * There are almost zero TIDs. Behave as if there were precisely
2444 * zero: bypass index vacuuming, but do index cleanup.
2445 *
2446 * We expect that the ongoing VACUUM operation will finish very
2447 * quickly, so there is no point in considering speeding up as a
2448 * failsafe against wraparound failure. (Index cleanup is expected to
2449 * finish very quickly in cases where there were no ambulkdelete()
2450 * calls.)
2451 */
2452 vacrel->do_index_vacuuming = false;
2453 }
2455 {
2456 /*
2457 * We successfully completed a round of index vacuuming. Do related
2458 * heap vacuuming now.
2459 */
2461 }
2462 else
2463 {
2464 /*
2465 * Failsafe case.
2466 *
2467 * We attempted index vacuuming, but didn't finish a full round/full
2468 * index scan. This happens when relfrozenxid or relminmxid is too
2469 * far in the past.
2470 *
2471 * From this point on the VACUUM operation will do no further index
2472 * vacuuming or heap vacuuming. This VACUUM operation won't end up
2473 * back here again.
2474 */
2476 }
2477
2478 /*
2479 * Forget the LP_DEAD items that we just vacuumed (or just decided to not
2480 * vacuum)
2481 */
2483}
2484
2485/*
2486 * lazy_vacuum_all_indexes() -- Main entry for index vacuuming
2487 *
2488 * Returns true in the common case when all indexes were successfully
2489 * vacuumed. Returns false in rare cases where we determined that the ongoing
2490 * VACUUM operation is at risk of taking too long to finish, leading to
2491 * wraparound failure.
2492 */
2493static bool
2495{
2496 bool allindexes = true;
2497 double old_live_tuples = vacrel->rel->rd_rel->reltuples;
2498 const int progress_start_index[] = {
2501 };
2502 const int progress_end_index[] = {
2506 };
2509
2510 Assert(vacrel->nindexes > 0);
2511 Assert(vacrel->do_index_vacuuming);
2512 Assert(vacrel->do_index_cleanup);
2513
2514 /* Precheck for XID wraparound emergencies */
2516 {
2517 /* Wraparound emergency -- don't even start an index scan */
2518 return false;
2519 }
2520
2521 /*
2522 * Report that we are now vacuuming indexes and the number of indexes to
2523 * vacuum.
2524 */
2526 progress_start_val[1] = vacrel->nindexes;
2528
2530 {
2531 for (int idx = 0; idx < vacrel->nindexes; idx++)
2532 {
2533 Relation indrel = vacrel->indrels[idx];
2534 IndexBulkDeleteResult *istat = vacrel->indstats[idx];
2535
2536 vacrel->indstats[idx] = lazy_vacuum_one_index(indrel, istat,
2538 vacrel);
2539
2540 /* Report the number of indexes vacuumed */
2542 idx + 1);
2543
2545 {
2546 /* Wraparound emergency -- end current index scan */
2547 allindexes = false;
2548 break;
2549 }
2550 }
2551 }
2552 else
2553 {
2554 /* Outsource everything to parallel variant */
2556 vacrel->num_index_scans,
2557 &(vacrel->worker_usage.vacuum));
2558
2559 /*
2560 * Do a postcheck to consider applying wraparound failsafe now. Note
2561 * that parallel VACUUM only gets the precheck and this postcheck.
2562 */
2564 allindexes = false;
2565 }
2566
2567 /*
2568 * We delete all LP_DEAD items from the first heap pass in all indexes on
2569 * each call here (except calls where we choose to do the failsafe). This
2570 * makes the next call to lazy_vacuum_heap_rel() safe (except in the event
2571 * of the failsafe triggering, which prevents the next call from taking
2572 * place).
2573 */
2574 Assert(vacrel->num_index_scans > 0 ||
2575 vacrel->dead_items_info->num_items == vacrel->lpdead_items);
2577
2578 /*
2579 * Increase and report the number of index scans. Also, we reset
2580 * PROGRESS_VACUUM_INDEXES_TOTAL and PROGRESS_VACUUM_INDEXES_PROCESSED.
2581 *
2582 * We deliberately include the case where we started a round of bulk
2583 * deletes that we weren't able to finish due to the failsafe triggering.
2584 */
2585 vacrel->num_index_scans++;
2586 progress_end_val[0] = 0;
2587 progress_end_val[1] = 0;
2588 progress_end_val[2] = vacrel->num_index_scans;
2590
2591 return allindexes;
2592}
2593
2594/*
2595 * Read stream callback for vacuum's third phase (second pass over the heap).
2596 * Gets the next block from the TID store and returns it or InvalidBlockNumber
2597 * if there are no further blocks to vacuum.
2598 *
2599 * NB: Assumed to be safe to use with READ_STREAM_USE_BATCHING.
2600 */
2601static BlockNumber
2603 void *callback_private_data,
2604 void *per_buffer_data)
2605{
2606 TidStoreIter *iter = callback_private_data;
2608
2610 if (iter_result == NULL)
2611 return InvalidBlockNumber;
2612
2613 /*
2614 * Save the TidStoreIterResult for later, so we can extract the offsets.
2615 * It is safe to copy the result, according to TidStoreIterateNext().
2616 */
2617 memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
2618
2619 return iter_result->blkno;
2620}
2621
2622/*
2623 * lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
2624 *
2625 * This routine marks LP_DEAD items in vacrel->dead_items as LP_UNUSED. Pages
2626 * that never had lazy_scan_prune record LP_DEAD items are not visited at all.
2627 *
2628 * We may also be able to truncate the line pointer array of the heap pages we
2629 * visit. If there is a contiguous group of LP_UNUSED items at the end of the
2630 * array, it can be reclaimed as free space. These LP_UNUSED items usually
2631 * start out as LP_DEAD items recorded by lazy_scan_prune (we set items from
2632 * each page to LP_UNUSED, and then consider if it's possible to truncate the
2633 * page's line pointer array).
2634 *
2635 * Note: the reason for doing this as a second pass is we cannot remove the
2636 * tuples until we've removed their index entries, and we want to process
2637 * index entry removal in batches as large as possible.
2638 */
2639static void
2641{
2642 ReadStream *stream;
2644 Buffer vmbuffer = InvalidBuffer;
2646 TidStoreIter *iter;
2647
2648 Assert(vacrel->do_index_vacuuming);
2649 Assert(vacrel->do_index_cleanup);
2650 Assert(vacrel->num_index_scans > 0);
2651
2652 /* Report that we are now vacuuming the heap */
2655
2656 /* Update error traceback information */
2660
2661 iter = TidStoreBeginIterate(vacrel->dead_items);
2662
2663 /*
2664 * Set up the read stream for vacuum's second pass through the heap.
2665 *
2666 * It is safe to use batchmode, as vacuum_reap_lp_read_stream_next() does
2667 * not need to wait for IO and does not perform locking. Once we support
2668 * parallelism it should still be fine, as presumably the holder of locks
2669 * would never be blocked by IO while holding the lock.
2670 */
2673 vacrel->bstrategy,
2674 vacrel->rel,
2677 iter,
2678 sizeof(TidStoreIterResult));
2679
2680 while (true)
2681 {
2682 BlockNumber blkno;
2683 Buffer buf;
2684 Page page;
2686 Size freespace;
2688 int num_offsets;
2689
2690 vacuum_delay_point(false);
2691
2692 buf = read_stream_next_buffer(stream, (void **) &iter_result);
2693
2694 /* The relation is exhausted */
2695 if (!BufferIsValid(buf))
2696 break;
2697
2698 vacrel->blkno = blkno = BufferGetBlockNumber(buf);
2699
2702 Assert(num_offsets <= lengthof(offsets));
2703
2704 /*
2705 * Pin the visibility map page in case we need to mark the page
2706 * all-visible. In most cases this will be very cheap, because we'll
2707 * already have the correct page pinned anyway.
2708 */
2709 visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
2710
2711 /* We need a non-cleanup exclusive lock to mark dead_items unused */
2713 lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
2714 num_offsets, vmbuffer);
2715
2716 /* Now that we've vacuumed the page, record its available space */
2717 page = BufferGetPage(buf);
2718 freespace = PageGetHeapFreeSpace(page);
2719
2721 RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
2723 }
2724
2725 read_stream_end(stream);
2726 TidStoreEndIterate(iter);
2727
2728 vacrel->blkno = InvalidBlockNumber;
2729 if (BufferIsValid(vmbuffer))
2730 ReleaseBuffer(vmbuffer);
2731
2732 /*
2733 * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
2734 * the second heap pass. No more, no less.
2735 */
2736 Assert(vacrel->num_index_scans > 1 ||
2737 (vacrel->dead_items_info->num_items == vacrel->lpdead_items &&
2738 vacuumed_pages == vacrel->lpdead_item_pages));
2739
2741 (errmsg("table \"%s\": removed %" PRId64 " dead item identifiers in %u pages",
2742 vacrel->relname, vacrel->dead_items_info->num_items,
2743 vacuumed_pages)));
2744
2745 /* Revert to the previous phase information for error traceback */
2747}
2748
2749/*
2750 * lazy_vacuum_heap_page() -- free page's LP_DEAD items listed in the
2751 * vacrel->dead_items store.
2752 *
2753 * Caller must have an exclusive buffer lock on the buffer (though a full
2754 * cleanup lock is also acceptable). vmbuffer must be valid and already have
2755 * a pin on blkno's visibility map page.
2756 */
2757static void
2759 OffsetNumber *deadoffsets, int num_offsets,
2760 Buffer vmbuffer)
2761{
2762 Page page = BufferGetPage(buffer);
2764 int nunused = 0;
2765 TransactionId newest_live_xid;
2767 bool all_frozen;
2769 uint8 vmflags = 0;
2770
2771 Assert(vacrel->do_index_vacuuming);
2772
2774
2775 /* Update error traceback information */
2779
2780 /*
2781 * Before marking dead items unused, check whether the page will become
2782 * all-visible once that change is applied. This lets us reap the tuples
2783 * and mark the page all-visible within the same critical section,
2784 * enabling both changes to be emitted in a single WAL record. Since the
2785 * visibility checks may perform I/O and allocate memory, they must be
2786 * done outside the critical section.
2787 */
2788 if (heap_page_would_be_all_visible(vacrel->rel, buffer,
2789 vacrel->vistest, true,
2790 deadoffsets, num_offsets,
2791 &all_frozen, &newest_live_xid,
2792 &vacrel->offnum))
2793 {
2795 if (all_frozen)
2796 {
2798 Assert(!TransactionIdIsValid(newest_live_xid));
2799 }
2800
2801 /*
2802 * Take the lock on the vmbuffer before entering a critical section.
2803 * The heap page lock must also be held while updating the VM to
2804 * ensure consistency.
2805 */
2807 }
2808
2810
2811 for (int i = 0; i < num_offsets; i++)
2812 {
2813 ItemId itemid;
2814 OffsetNumber toff = deadoffsets[i];
2815
2816 itemid = PageGetItemId(page, toff);
2817
2818 Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
2819 ItemIdSetUnused(itemid);
2820 unused[nunused++] = toff;
2821 }
2822
2823 Assert(nunused > 0);
2824
2825 /* Attempt to truncate line pointer array now */
2827
2828 if ((vmflags & VISIBILITYMAP_VALID_BITS) != 0)
2829 {
2830 /*
2831 * The page is guaranteed to have had dead line pointers, so we always
2832 * set PD_ALL_VISIBLE.
2833 */
2834 PageSetAllVisible(page);
2835 PageClearPrunable(page);
2836 visibilitymap_set(blkno,
2837 vmbuffer, vmflags,
2838 vacrel->rel->rd_locator);
2839 conflict_xid = newest_live_xid;
2840 }
2841
2842 /*
2843 * Mark buffer dirty before we write WAL.
2844 */
2845 MarkBufferDirty(buffer);
2846
2847 /* XLOG stuff */
2848 if (RelationNeedsWAL(vacrel->rel))
2849 {
2850 log_heap_prune_and_freeze(vacrel->rel, buffer,
2851 vmflags != 0 ? vmbuffer : InvalidBuffer,
2852 vmflags,
2854 false, /* no cleanup lock required */
2856 NULL, 0, /* frozen */
2857 NULL, 0, /* redirected */
2858 NULL, 0, /* dead */
2859 unused, nunused);
2860 }
2861
2863
2865 {
2866 /* Count the newly set VM page for logging */
2867 LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2868 vacrel->new_all_visible_pages++;
2869 if (all_frozen)
2870 vacrel->new_all_visible_all_frozen_pages++;
2871 }
2872
2873 /* Revert to the previous phase information for error traceback */
2875}
2876
2877/*
2878 * Trigger the failsafe to avoid wraparound failure when vacrel table has a
2879 * relfrozenxid and/or relminmxid that is dangerously far in the past.
2880 * Triggering the failsafe makes the ongoing VACUUM bypass any further index
2881 * vacuuming and heap vacuuming. Truncating the heap is also bypassed.
2882 *
2883 * Any remaining work (work that VACUUM cannot just bypass) is typically sped
2884 * up when the failsafe triggers. VACUUM stops applying any cost-based delay
2885 * that it started out with.
2886 *
2887 * Returns true when failsafe has been triggered.
2888 */
2889static bool
2891{
2892 /* Don't warn more than once per VACUUM */
2894 return true;
2895
2897 {
2898 const int progress_index[] = {
2902 };
2904
2905 VacuumFailsafeActive = true;
2906
2907 /*
2908 * Abandon use of a buffer access strategy to allow use of all of
2909 * shared buffers. We assume the caller who allocated the memory for
2910 * the BufferAccessStrategy will free it.
2911 */
2912 vacrel->bstrategy = NULL;
2913
2914 /* Disable index vacuuming, index cleanup, and heap rel truncation */
2915 vacrel->do_index_vacuuming = false;
2916 vacrel->do_index_cleanup = false;
2917 vacrel->do_rel_truncate = false;
2918
2919 /* Reset the progress counters and set the failsafe mode */
2921
2923 (errmsg("bypassing nonessential maintenance of table \"%s.%s.%s\" as a failsafe after %d index scans",
2924 vacrel->dbname, vacrel->relnamespace, vacrel->relname,
2925 vacrel->num_index_scans),
2926 errdetail("The table's relfrozenxid or relminmxid is too far in the past."),
2927 errhint("Consider increasing configuration parameter \"maintenance_work_mem\" or \"autovacuum_work_mem\".\n"
2928 "You might also need to consider other ways for VACUUM to keep up with the allocation of transaction IDs.")));
2929
2930 /* Stop applying cost limits from this point on */
2931 VacuumCostActive = false;
2933
2934 return true;
2935 }
2936
2937 return false;
2938}
2939
2940/*
2941 * lazy_cleanup_all_indexes() -- cleanup all indexes of relation.
2942 */
2943static void
2945{
2946 double reltuples = vacrel->new_rel_tuples;
2947 bool estimated_count = vacrel->scanned_pages < vacrel->rel_pages;
2948 const int progress_start_index[] = {
2951 };
2952 const int progress_end_index[] = {
2955 };
2957 int64 progress_end_val[2] = {0, 0};
2958
2959 Assert(vacrel->do_index_cleanup);
2960 Assert(vacrel->nindexes > 0);
2961
2962 /*
2963 * Report that we are now cleaning up indexes and the number of indexes to
2964 * cleanup.
2965 */
2967 progress_start_val[1] = vacrel->nindexes;
2969
2971 {
2972 for (int idx = 0; idx < vacrel->nindexes; idx++)
2973 {
2974 Relation indrel = vacrel->indrels[idx];
2975 IndexBulkDeleteResult *istat = vacrel->indstats[idx];
2976
2977 vacrel->indstats[idx] =
2978 lazy_cleanup_one_index(indrel, istat, reltuples,
2979 estimated_count, vacrel);
2980
2981 /* Report the number of indexes cleaned up */
2983 idx + 1);
2984 }
2985 }
2986 else
2987 {
2988 /* Outsource everything to parallel variant */
2990 vacrel->num_index_scans,
2991 estimated_count,
2992 &(vacrel->worker_usage.cleanup));
2993 }
2994
2995 /* Reset the progress counters */
2997}
2998
2999/*
3000 * lazy_vacuum_one_index() -- vacuum index relation.
3001 *
3002 * Delete all the index tuples containing a TID collected in
3003 * vacrel->dead_items. Also update running statistics. Exact
3004 * details depend on index AM's ambulkdelete routine.
3005 *
3006 * reltuples is the number of heap tuples to be passed to the
3007 * bulkdelete callback. It's always assumed to be estimated.
3008 * See indexam.sgml for more info.
3009 *
3010 * Returns bulk delete stats derived from input stats
3011 */
3012static IndexBulkDeleteResult *
3014 double reltuples, LVRelState *vacrel)
3015{
3018
3019 ivinfo.index = indrel;
3020 ivinfo.heaprel = vacrel->rel;
3021 ivinfo.analyze_only = false;
3022 ivinfo.report_progress = false;
3023 ivinfo.estimated_count = true;
3024 ivinfo.message_level = DEBUG2;
3025 ivinfo.num_heap_tuples = reltuples;
3026 ivinfo.strategy = vacrel->bstrategy;
3027
3028 /*
3029 * Update error traceback information.
3030 *
3031 * The index name is saved during this phase and restored immediately
3032 * after this phase. See vacuum_error_callback.
3033 */
3034 Assert(vacrel->indname == NULL);
3039
3040 /* Do bulk deletion */
3041 istat = vac_bulkdel_one_index(&ivinfo, istat, vacrel->dead_items,
3042 vacrel->dead_items_info);
3043
3044 /* Revert to the previous phase information for error traceback */
3046 pfree(vacrel->indname);
3047 vacrel->indname = NULL;
3048
3049 return istat;
3050}
3051
3052/*
3053 * lazy_cleanup_one_index() -- do post-vacuum cleanup for index relation.
3054 *
3055 * Calls index AM's amvacuumcleanup routine. reltuples is the number
3056 * of heap tuples and estimated_count is true if reltuples is an
3057 * estimated value. See indexam.sgml for more info.
3058 *
3059 * Returns bulk delete stats derived from input stats
3060 */
3061static IndexBulkDeleteResult *
3063 double reltuples, bool estimated_count,
3065{
3068
3069 ivinfo.index = indrel;
3070 ivinfo.heaprel = vacrel->rel;
3071 ivinfo.analyze_only = false;
3072 ivinfo.report_progress = false;
3073 ivinfo.estimated_count = estimated_count;
3074 ivinfo.message_level = DEBUG2;
3075
3076 ivinfo.num_heap_tuples = reltuples;
3077 ivinfo.strategy = vacrel->bstrategy;
3078
3079 /*
3080 * Update error traceback information.
3081 *
3082 * The index name is saved during this phase and restored immediately
3083 * after this phase. See vacuum_error_callback.
3084 */
3085 Assert(vacrel->indname == NULL);
3090
3091 istat = vac_cleanup_one_index(&ivinfo, istat);
3092
3093 /* Revert to the previous phase information for error traceback */
3095 pfree(vacrel->indname);
3096 vacrel->indname = NULL;
3097
3098 return istat;
3099}
3100
3101/*
3102 * should_attempt_truncation - should we attempt to truncate the heap?
3103 *
3104 * Don't even think about it unless we have a shot at releasing a goodly
3105 * number of pages. Otherwise, the time taken isn't worth it, mainly because
3106 * an AccessExclusive lock must be replayed on any hot standby, where it can
3107 * be particularly disruptive.
3108 *
3109 * Also don't attempt it if wraparound failsafe is in effect. The entire
3110 * system might be refusing to allocate new XIDs at this point. The system
3111 * definitely won't return to normal unless and until VACUUM actually advances
3112 * the oldest relfrozenxid -- which hasn't happened for target rel just yet.
3113 * If lazy_truncate_heap attempted to acquire an AccessExclusiveLock to
3114 * truncate the table under these circumstances, an XID exhaustion error might
3115 * make it impossible for VACUUM to fix the underlying XID exhaustion problem.
3116 * There is very little chance of truncation working out when the failsafe is
3117 * in effect in any case. lazy_scan_prune makes the optimistic assumption
3118 * that any LP_DEAD items it encounters will always be LP_UNUSED by the time
3119 * we're called.
3120 */
3121static bool
3123{
3125
3126 if (!vacrel->do_rel_truncate || VacuumFailsafeActive)
3127 return false;
3128
3129 possibly_freeable = vacrel->rel_pages - vacrel->nonempty_pages;
3130 if (possibly_freeable > 0 &&
3133 return true;
3134
3135 return false;
3136}
3137
3138/*
3139 * lazy_truncate_heap - try to truncate off any empty pages at the end
3140 */
3141static void
3143{
3144 BlockNumber orig_rel_pages = vacrel->rel_pages;
3147 int lock_retry;
3148
3149 /* Report that we are now truncating */
3152
3153 /* Update error traceback information one last time */
3155 vacrel->nonempty_pages, InvalidOffsetNumber);
3156
3157 /*
3158 * Loop until no more truncating can be done.
3159 */
3160 do
3161 {
3162 /*
3163 * We need full exclusive lock on the relation in order to do
3164 * truncation. If we can't get it, give up rather than waiting --- we
3165 * don't want to block other backends, and we don't want to deadlock
3166 * (which is quite possible considering we already hold a lower-grade
3167 * lock).
3168 */
3169 lock_waiter_detected = false;
3170 lock_retry = 0;
3171 while (true)
3172 {
3174 break;
3175
3176 /*
3177 * Check for interrupts while trying to (re-)acquire the exclusive
3178 * lock.
3179 */
3181
3184 {
3185 /*
3186 * We failed to establish the lock in the specified number of
3187 * retries. This means we give up truncating.
3188 */
3189 ereport(vacrel->verbose ? INFO : DEBUG2,
3190 (errmsg("\"%s\": stopping truncate due to conflicting lock request",
3191 vacrel->relname)));
3192 return;
3193 }
3194
3200 }
3201
3202 /*
3203 * Now that we have exclusive lock, look to see if the rel has grown
3204 * whilst we were vacuuming with non-exclusive lock. If so, give up;
3205 * the newly added pages presumably contain non-deletable tuples.
3206 */
3209 {
3210 /*
3211 * Note: we intentionally don't update vacrel->rel_pages with the
3212 * new rel size here. If we did, it would amount to assuming that
3213 * the new pages are empty, which is unlikely. Leaving the numbers
3214 * alone amounts to assuming that the new pages have the same
3215 * tuple density as existing ones, which is less unlikely.
3216 */
3218 return;
3219 }
3220
3221 /*
3222 * Scan backwards from the end to verify that the end pages actually
3223 * contain no tuples. This is *necessary*, not optional, because
3224 * other backends could have added tuples to these pages whilst we
3225 * were vacuuming.
3226 */
3228 vacrel->blkno = new_rel_pages;
3229
3231 {
3232 /* can't do anything after all */
3234 return;
3235 }
3236
3237 /*
3238 * Okay to truncate.
3239 */
3241
3242 /*
3243 * We can release the exclusive lock as soon as we have truncated.
3244 * Other backends can't safely access the relation until they have
3245 * processed the smgr invalidation that smgrtruncate sent out ... but
3246 * that should happen as part of standard invalidation processing once
3247 * they acquire lock on the relation.
3248 */
3250
3251 /*
3252 * Update statistics. Here, it *is* correct to adjust rel_pages
3253 * without also touching reltuples, since the tuple count wasn't
3254 * changed by the truncation.
3255 */
3256 vacrel->removed_pages += orig_rel_pages - new_rel_pages;
3257 vacrel->rel_pages = new_rel_pages;
3258
3259 ereport(vacrel->verbose ? INFO : DEBUG2,
3260 (errmsg("table \"%s\": truncated %u to %u pages",
3261 vacrel->relname,
3264 } while (new_rel_pages > vacrel->nonempty_pages && lock_waiter_detected);
3265}
3266
3267/*
3268 * Rescan end pages to verify that they are (still) empty of tuples.
3269 *
3270 * Returns number of nondeletable pages (last nonempty page + 1).
3271 */
3272static BlockNumber
3274{
3276 "prefetch size must be power of 2");
3277
3278 BlockNumber blkno;
3280 instr_time starttime;
3281
3282 /* Initialize the starttime if we check for conflicting lock requests */
3283 INSTR_TIME_SET_CURRENT(starttime);
3284
3285 /*
3286 * Start checking blocks at what we believe relation end to be and move
3287 * backwards. (Strange coding of loop control is needed because blkno is
3288 * unsigned.) To make the scan faster, we prefetch a few blocks at a time
3289 * in forward direction, so that OS-level readahead can kick in.
3290 */
3291 blkno = vacrel->rel_pages;
3293 while (blkno > vacrel->nonempty_pages)
3294 {
3295 Buffer buf;
3296 Page page;
3297 OffsetNumber offnum,
3298 maxoff;
3299 bool hastup;
3300
3301 /*
3302 * Check if another process requests a lock on our relation. We are
3303 * holding an AccessExclusiveLock here, so they will be waiting. We
3304 * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
3305 * only check if that interval has elapsed once every 32 blocks to
3306 * keep the number of system calls and actual shared lock table
3307 * lookups to a minimum.
3308 */
3309 if ((blkno % 32) == 0)
3310 {
3313
3316 INSTR_TIME_SUBTRACT(elapsed, starttime);
3317 if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
3319 {
3321 {
3322 ereport(vacrel->verbose ? INFO : DEBUG2,
3323 (errmsg("table \"%s\": suspending truncate due to conflicting lock request",
3324 vacrel->relname)));
3325
3326 *lock_waiter_detected = true;
3327 return blkno;
3328 }
3329 starttime = currenttime;
3330 }
3331 }
3332
3333 /*
3334 * We don't insert a vacuum delay point here, because we have an
3335 * exclusive lock on the table which we want to hold for as short a
3336 * time as possible. We still need to check for interrupts however.
3337 */
3339
3340 blkno--;
3341
3342 /* If we haven't prefetched this lot yet, do so now. */
3343 if (prefetchedUntil > blkno)
3344 {
3347
3348 prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
3349 for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
3350 {
3353 }
3355 }
3356
3358 vacrel->bstrategy);
3359
3360 /* In this phase we only need shared access to the buffer */
3362
3363 page = BufferGetPage(buf);
3364
3365 if (PageIsNew(page) || PageIsEmpty(page))
3366 {
3368 continue;
3369 }
3370
3371 hastup = false;
3372 maxoff = PageGetMaxOffsetNumber(page);
3373 for (offnum = FirstOffsetNumber;
3374 offnum <= maxoff;
3375 offnum = OffsetNumberNext(offnum))
3376 {
3377 ItemId itemid;
3378
3379 itemid = PageGetItemId(page, offnum);
3380
3381 /*
3382 * Note: any non-unused item should be taken as a reason to keep
3383 * this page. Even an LP_DEAD item makes truncation unsafe, since
3384 * we must not have cleaned out its index entries.
3385 */
3386 if (ItemIdIsUsed(itemid))
3387 {
3388 hastup = true;
3389 break; /* can stop scanning */
3390 }
3391 } /* scan along page */
3392
3394
3395 /* Done scanning if we found a tuple here */
3396 if (hastup)
3397 return blkno + 1;
3398 }
3399
3400 /*
3401 * If we fall out of the loop, all the previously-thought-to-be-empty
3402 * pages still are; we need not bother to look at the last known-nonempty
3403 * page.
3404 */
3405 return vacrel->nonempty_pages;
3406}
3407
3408/*
3409 * Allocate dead_items and dead_items_info (either using palloc, or in dynamic
3410 * shared memory). Sets both in vacrel for caller.
3411 *
3412 * Also handles parallel initialization as part of allocating dead_items in
3413 * DSM when required.
3414 */
3415static void
3417{
3418 VacDeadItemsInfo *dead_items_info;
3420 autovacuum_work_mem != -1 ?
3422
3423 /*
3424 * Initialize state for a parallel vacuum. As of now, only one worker can
3425 * be used for an index, so we invoke parallelism only if there are at
3426 * least two indexes on a table.
3427 */
3428 if (nworkers >= 0 && vacrel->nindexes > 1 && vacrel->do_index_vacuuming)
3429 {
3430 /*
3431 * Since parallel workers cannot access data in temporary tables, we
3432 * can't perform parallel vacuum on them.
3433 */
3435 {
3436 /*
3437 * Give warning only if the user explicitly tries to perform a
3438 * parallel vacuum on the temporary table.
3439 */
3440 if (nworkers > 0)
3442 (errmsg("disabling parallel option of vacuum on \"%s\" --- cannot vacuum temporary tables in parallel",
3443 vacrel->relname)));
3444 }
3445 else
3446 vacrel->pvs = parallel_vacuum_init(vacrel->rel, vacrel->indrels,
3447 vacrel->nindexes, nworkers,
3449 vacrel->verbose ? INFO : DEBUG2,
3450 vacrel->bstrategy);
3451
3452 /*
3453 * If parallel mode started, dead_items and dead_items_info spaces are
3454 * allocated in DSM.
3455 */
3457 {
3459 &vacrel->dead_items_info);
3460 return;
3461 }
3462 }
3463
3464 /*
3465 * Serial VACUUM case. Allocate both dead_items and dead_items_info
3466 * locally.
3467 */
3468
3469 dead_items_info = palloc_object(VacDeadItemsInfo);
3470 dead_items_info->max_bytes = vac_work_mem * (Size) 1024;
3471 dead_items_info->num_items = 0;
3472 vacrel->dead_items_info = dead_items_info;
3473
3474 vacrel->dead_items = TidStoreCreateLocal(dead_items_info->max_bytes, true);
3475}
3476
3477/*
3478 * Add the given block number and offset numbers to dead_items.
3479 */
3480static void
3482 int num_offsets)
3483{
3484 const int prog_index[2] = {
3487 };
3488 int64 prog_val[2];
3489
3490 TidStoreSetBlockOffsets(vacrel->dead_items, blkno, offsets, num_offsets);
3491 vacrel->dead_items_info->num_items += num_offsets;
3492
3493 /* update the progress information */
3494 prog_val[0] = vacrel->dead_items_info->num_items;
3495 prog_val[1] = TidStoreMemoryUsage(vacrel->dead_items);
3497}
3498
3499/*
3500 * Forget all collected dead items.
3501 */
3502static void
3504{
3505 /* Update statistics for dead items */
3506 vacrel->num_dead_items_resets++;
3507 vacrel->total_dead_items_bytes += TidStoreMemoryUsage(vacrel->dead_items);
3508
3510 {
3512 vacrel->dead_items = parallel_vacuum_get_dead_items(vacrel->pvs,
3513 &vacrel->dead_items_info);
3514 return;
3515 }
3516
3517 /* Recreate the tidstore with the same max_bytes limitation */
3518 TidStoreDestroy(vacrel->dead_items);
3519 vacrel->dead_items = TidStoreCreateLocal(vacrel->dead_items_info->max_bytes, true);
3520
3521 /* Reset the counter */
3522 vacrel->dead_items_info->num_items = 0;
3523}
3524
3525/*
3526 * Perform cleanup for resources allocated in dead_items_alloc
3527 */
3528static void
3530{
3532 {
3533 /* Don't bother with pfree here */
3534 return;
3535 }
3536
3537 /* End parallel mode */
3538 parallel_vacuum_end(vacrel->pvs, vacrel->indstats);
3539 vacrel->pvs = NULL;
3540}
3541
3542#ifdef USE_ASSERT_CHECKING
3543
3544/*
3545 * Wrapper for heap_page_would_be_all_visible() which can be used for callers
3546 * that expect no LP_DEAD on the page. Currently assert-only, but there is no
3547 * reason not to use it outside of asserts.
3548 */
3549bool
3551 GlobalVisState *vistest,
3552 bool *all_frozen,
3553 TransactionId *newest_live_xid,
3555{
3556 /*
3557 * Pass allow_update_vistest as false so that the GlobalVisState
3558 * boundaries used here match those used by the pruning code we are
3559 * cross-checking. Allowing an update could move the boundaries between
3560 * the two calls, causing a spurious assertion failure.
3561 */
3563 vistest, false,
3564 NULL, 0,
3565 all_frozen,
3566 newest_live_xid,
3568}
3569#endif
3570
3571/*
3572 * Check whether the heap page in buf is all-visible except for the dead
3573 * tuples referenced in the deadoffsets array.
3574 *
3575 * Vacuum uses this to check if a page would become all-visible after reaping
3576 * known dead tuples. This function does not remove the dead items.
3577 *
3578 * This cannot be called in a critical section, as the visibility checks may
3579 * perform IO and allocate memory.
3580 *
3581 * Returns true if the page is all-visible other than the provided
3582 * deadoffsets and false otherwise.
3583 *
3584 * vistest is used to determine visibility. If allow_update_vistest is true,
3585 * the boundaries of the GlobalVisState may be updated when checking the
3586 * visibility of the newest live XID on the page.
3587 *
3588 * Output parameters:
3589 *
3590 * - *all_frozen: true if every tuple on the page is frozen
3591 * - *newest_live_xid: newest xmin of live tuples on the page
3592 * - *logging_offnum: OffsetNumber of current tuple being processed;
3593 * used by vacuum's error callback system.
3594 *
3595 * Callers looking to verify that the page is already all-visible can call
3596 * heap_page_is_all_visible().
3597 *
3598 * This logic is closely related to heap_prune_record_unchanged_lp_normal().
3599 * If you modify this function, ensure consistency with that code. An
3600 * assertion cross-checks that both remain in agreement. Do not introduce new
3601 * side-effects.
3602 */
3603static bool
3605 GlobalVisState *vistest,
3607 OffsetNumber *deadoffsets,
3608 int ndeadoffsets,
3609 bool *all_frozen,
3610 TransactionId *newest_live_xid,
3612{
3613 Page page = BufferGetPage(buf);
3615 OffsetNumber offnum,
3616 maxoff;
3617 bool all_visible = true;
3618 int matched_dead_count = 0;
3619
3620 *newest_live_xid = InvalidTransactionId;
3621 *all_frozen = true;
3622
3623 Assert(ndeadoffsets == 0 || deadoffsets);
3624
3625#ifdef USE_ASSERT_CHECKING
3626 /* Confirm input deadoffsets[] is strictly sorted */
3627 if (ndeadoffsets > 1)
3628 {
3629 for (int i = 1; i < ndeadoffsets; i++)
3630 Assert(deadoffsets[i - 1] < deadoffsets[i]);
3631 }
3632#endif
3633
3634 maxoff = PageGetMaxOffsetNumber(page);
3635 for (offnum = FirstOffsetNumber;
3636 offnum <= maxoff && all_visible;
3637 offnum = OffsetNumberNext(offnum))
3638 {
3639 ItemId itemid;
3640 HeapTupleData tuple;
3642
3643 /*
3644 * Set the offset number so that we can display it along with any
3645 * error that occurred while processing this tuple.
3646 */
3647 *logging_offnum = offnum;
3648 itemid = PageGetItemId(page, offnum);
3649
3650 /* Unused or redirect line pointers are of no interest */
3651 if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
3652 continue;
3653
3654 ItemPointerSet(&(tuple.t_self), blockno, offnum);
3655
3656 /*
3657 * Dead line pointers can have index pointers pointing to them. So
3658 * they can't be treated as visible
3659 */
3660 if (ItemIdIsDead(itemid))
3661 {
3662 if (!deadoffsets ||
3664 deadoffsets[matched_dead_count] != offnum)
3665 {
3666 *all_frozen = all_visible = false;
3667 break;
3668 }
3670 continue;
3671 }
3672
3673 Assert(ItemIdIsNormal(itemid));
3674
3675 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
3676 tuple.t_len = ItemIdGetLength(itemid);
3677 tuple.t_tableOid = RelationGetRelid(rel);
3678
3679 /* Visibility checks may do IO or allocate memory */
3682 {
3683 case HEAPTUPLE_LIVE:
3684 {
3685 TransactionId xmin;
3686
3687 /* Check heap_prune_record_unchanged_lp_normal comments */
3689 {
3690 all_visible = false;
3691 *all_frozen = false;
3692 break;
3693 }
3694
3695 /*
3696 * The inserter definitely committed. But we don't know if
3697 * it is old enough that everyone sees it as committed.
3698 * Don't check that now.
3699 *
3700 * If we scan all tuples without finding one that prevents
3701 * the page from being all-visible, we then check whether
3702 * any snapshot still considers the newest XID on the page
3703 * to be running. In that case, the page is not considered
3704 * all-visible.
3705 */
3706 xmin = HeapTupleHeaderGetXmin(tuple.t_data);
3707
3708 /* Track newest xmin on page. */
3709 if (TransactionIdFollows(xmin, *newest_live_xid) &&
3711 *newest_live_xid = xmin;
3712
3713 /* Check whether this tuple is already frozen or not */
3714 if (all_visible && *all_frozen &&
3716 *all_frozen = false;
3717 }
3718 break;
3719
3720 case HEAPTUPLE_DEAD:
3724 {
3725 all_visible = false;
3726 *all_frozen = false;
3727 break;
3728 }
3729 default:
3730 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
3731 break;
3732 }
3733 } /* scan along page */
3734
3735 /*
3736 * After processing all the live tuples on the page, if the newest xmin
3737 * among them may still be considered running by any snapshot, the page
3738 * cannot be all-visible.
3739 */
3740 if (all_visible &&
3741 TransactionIdIsNormal(*newest_live_xid) &&
3742 GlobalVisTestXidConsideredRunning(vistest, *newest_live_xid,
3744 {
3745 all_visible = false;
3746 *all_frozen = false;
3747 }
3748
3749 /* Clear the offset information once we have processed the given page. */
3751
3752 return all_visible;
3753}
3754
3755/*
3756 * Update index statistics in pg_class if the statistics are accurate.
3757 */
3758static void
3760{
3761 Relation *indrels = vacrel->indrels;
3762 int nindexes = vacrel->nindexes;
3763 IndexBulkDeleteResult **indstats = vacrel->indstats;
3764
3765 Assert(vacrel->do_index_cleanup);
3766
3767 for (int idx = 0; idx < nindexes; idx++)
3768 {
3769 Relation indrel = indrels[idx];
3770 IndexBulkDeleteResult *istat = indstats[idx];
3771
3772 if (istat == NULL || istat->estimated_count)
3773 continue;
3774
3775 /* Update index statistics */
3777 istat->num_pages,
3778 istat->num_index_tuples,
3779 0, 0,
3780 false,
3783 NULL, NULL, false);
3784 }
3785}
3786
3787/*
3788 * Error context callback for errors occurring during vacuum. The error
3789 * context messages for index phases should match the messages set in parallel
3790 * vacuum. If you change this function for those phases, change
3791 * parallel_vacuum_error_callback() as well.
3792 */
3793static void
3795{
3797
3798 switch (errinfo->phase)
3799 {
3801 if (BlockNumberIsValid(errinfo->blkno))
3802 {
3803 if (OffsetNumberIsValid(errinfo->offnum))
3804 errcontext("while scanning block %u offset %u of relation \"%s.%s\"",
3805 errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
3806 else
3807 errcontext("while scanning block %u of relation \"%s.%s\"",
3808 errinfo->blkno, errinfo->relnamespace, errinfo->relname);
3809 }
3810 else
3811 errcontext("while scanning relation \"%s.%s\"",
3812 errinfo->relnamespace, errinfo->relname);
3813 break;
3814
3816 if (BlockNumberIsValid(errinfo->blkno))
3817 {
3818 if (OffsetNumberIsValid(errinfo->offnum))
3819 errcontext("while vacuuming block %u offset %u of relation \"%s.%s\"",
3820 errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
3821 else
3822 errcontext("while vacuuming block %u of relation \"%s.%s\"",
3823 errinfo->blkno, errinfo->relnamespace, errinfo->relname);
3824 }
3825 else
3826 errcontext("while vacuuming relation \"%s.%s\"",
3827 errinfo->relnamespace, errinfo->relname);
3828 break;
3829
3831 errcontext("while vacuuming index \"%s\" of relation \"%s.%s\"",
3832 errinfo->indname, errinfo->relnamespace, errinfo->relname);
3833 break;
3834
3836 errcontext("while cleaning up index \"%s\" of relation \"%s.%s\"",
3837 errinfo->indname, errinfo->relnamespace, errinfo->relname);
3838 break;
3839
3841 if (BlockNumberIsValid(errinfo->blkno))
3842 errcontext("while truncating relation \"%s.%s\" to %u blocks",
3843 errinfo->relnamespace, errinfo->relname, errinfo->blkno);
3844 break;
3845
3847 default:
3848 return; /* do nothing; the errinfo may not be
3849 * initialized */
3850 }
3851}
3852
3853/*
3854 * Updates the information required for vacuum error callback. This also saves
3855 * the current information which can be later restored via restore_vacuum_error_info.
3856 */
3857static void
3859 int phase, BlockNumber blkno, OffsetNumber offnum)
3860{
3861 if (saved_vacrel)
3862 {
3863 saved_vacrel->offnum = vacrel->offnum;
3864 saved_vacrel->blkno = vacrel->blkno;
3865 saved_vacrel->phase = vacrel->phase;
3866 }
3867
3868 vacrel->blkno = blkno;
3869 vacrel->offnum = offnum;
3870 vacrel->phase = phase;
3871}
3872
3873/*
3874 * Restores the vacuum information saved via a prior call to update_vacuum_error_info.
3875 */
3876static void
3879{
3880 vacrel->blkno = saved_vacrel->blkno;
3881 vacrel->offnum = saved_vacrel->offnum;
3882 vacrel->phase = saved_vacrel->phase;
3883}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:262
int autovacuum_work_mem
Definition autovacuum.c:126
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1715
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1775
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_VACUUM
PgBackendStatus * MyBEEntry
uint32 BlockNumber
Definition block.h:31
#define InvalidBlockNumber
Definition block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
int Buffer
Definition buf.h:23
#define InvalidBuffer
Definition buf.h:25
bool track_io_timing
Definition bufmgr.c:192
void CheckBufferIsPinnedOnce(Buffer buffer)
Definition bufmgr.c:6637
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition bufmgr.c:4446
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition bufmgr.c:787
void ReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5586
void UnlockReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5603
void MarkBufferDirty(Buffer buffer)
Definition bufmgr.c:3147
void LockBufferForCleanup(Buffer buffer)
Definition bufmgr.c:6670
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition bufmgr.c:926
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition bufmgr.c:6843
#define RelationGetNumberOfBlocks(reln)
Definition bufmgr.h:309
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:468
@ BUFFER_LOCK_SHARE
Definition bufmgr.h:212
@ BUFFER_LOCK_EXCLUSIVE
Definition bufmgr.h:222
@ BUFFER_LOCK_UNLOCK
Definition bufmgr.h:207
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:334
@ RBM_NORMAL
Definition bufmgr.h:46
static bool BufferIsValid(Buffer bufnum)
Definition bufmgr.h:419
Size PageGetHeapFreeSpace(const PageData *page)
Definition bufpage.c:1000
void PageTruncateLinePointerArray(Page page)
Definition bufpage.c:844
static bool PageIsEmpty(const PageData *page)
Definition bufpage.h:248
static bool PageIsAllVisible(const PageData *page)
Definition bufpage.h:454
static bool PageIsNew(const PageData *page)
Definition bufpage.h:258
#define SizeOfPageHeaderData
Definition bufpage.h:241
static void PageSetAllVisible(Page page)
Definition bufpage.h:459
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition bufpage.h:268
static void * PageGetItem(PageData *page, const ItemIdData *itemId)
Definition bufpage.h:378
PageData * Page
Definition bufpage.h:81
#define PageClearPrunable(page)
Definition bufpage.h:485
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition bufpage.h:396
uint8_t uint8
Definition c.h:622
#define ngettext(s, p, n)
Definition c.h:1270
#define Max(x, y)
Definition c.h:1085
#define Assert(condition)
Definition c.h:943
int64_t int64
Definition c.h:621
TransactionId MultiXactId
Definition c.h:746
int32_t int32
Definition c.h:620
#define unlikely(x)
Definition c.h:438
uint32_t uint32
Definition c.h:624
#define lengthof(array)
Definition c.h:873
#define StaticAssertDecl(condition, errmessage)
Definition c.h:1008
uint32 TransactionId
Definition c.h:736
size_t Size
Definition c.h:689
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
int64 TimestampTz
Definition timestamp.h:39
Datum arg
Definition elog.c:1322
ErrorContextCallback * error_context_stack
Definition elog.c:99
#define _(x)
Definition elog.c:95
#define LOG
Definition elog.h:31
#define errcontext
Definition elog.h:199
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:36
#define DEBUG2
Definition elog.h:29
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:227
#define INFO
Definition elog.h:34
#define ereport(elevel,...)
Definition elog.h:151
#define palloc_object(type)
Definition fe_memutils.h:74
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_object(type)
Definition fe_memutils.h:75
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition freespace.c:377
Size GetRecordedFreeSpace(Relation rel, BlockNumber heapBlk)
Definition freespace.c:244
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition freespace.c:194
bool VacuumCostActive
Definition globals.c:159
int VacuumCostBalance
Definition globals.c:158
int maintenance_work_mem
Definition globals.c:133
volatile uint32 CritSectionCount
Definition globals.c:45
struct Latch * MyLatch
Definition globals.c:63
Oid MyDatabaseId
Definition globals.c:94
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition heapam.c:7778
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition heapam.c:7833
#define HEAP_PAGE_PRUNE_FREEZE
Definition heapam.h:43
#define HEAP_PAGE_PRUNE_ALLOW_FAST_PATH
Definition heapam.h:44
@ HEAPTUPLE_RECENTLY_DEAD
Definition heapam.h:140
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition heapam.h:141
@ HEAPTUPLE_LIVE
Definition heapam.h:139
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition heapam.h:142
@ HEAPTUPLE_DEAD
Definition heapam.h:138
#define HEAP_PAGE_PRUNE_SET_VM
Definition heapam.h:45
@ PRUNE_VACUUM_CLEANUP
Definition heapam.h:254
@ PRUNE_VACUUM_SCAN
Definition heapam.h:253
#define HEAP_PAGE_PRUNE_MARK_UNUSED_NOW
Definition heapam.h:42
HTSV_Result HeapTupleSatisfiesVacuumHorizon(HeapTuple htup, Buffer buffer, TransactionId *dead_after)
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
HeapTupleHeaderData * HeapTupleHeader
Definition htup.h:23
static TransactionId HeapTupleHeaderGetXmin(const HeapTupleHeaderData *tup)
#define MaxHeapTuplesPerPage
static bool HeapTupleHeaderXminCommitted(const HeapTupleHeaderData *tup)
#define INJECTION_POINT(name, arg)
#define INSTR_TIME_SET_CURRENT(t)
Definition instr_time.h:124
#define INSTR_TIME_SUBTRACT(x, y)
Definition instr_time.h:185
#define INSTR_TIME_GET_MICROSEC(t)
Definition instr_time.h:200
WalUsage pgWalUsage
Definition instrument.c:22
void WalUsageAccumDiff(WalUsage *dst, const WalUsage *add, const WalUsage *sub)
Definition instrument.c:340
BufferUsage pgBufferUsage
Definition instrument.c:20
void BufferUsageAccumDiff(BufferUsage *dst, const BufferUsage *add, const BufferUsage *sub)
Definition instrument.c:300
static int pg_cmp_u16(uint16 a, uint16 b)
Definition int.h:707
int b
Definition isn.c:74
int a
Definition isn.c:73
int i
Definition isn.c:77
#define ItemIdGetLength(itemId)
Definition itemid.h:59
#define ItemIdIsNormal(itemId)
Definition itemid.h:99
#define ItemIdIsDead(itemId)
Definition itemid.h:113
#define ItemIdIsUsed(itemId)
Definition itemid.h:92
#define ItemIdSetUnused(itemId)
Definition itemid.h:128
#define ItemIdIsRedirected(itemId)
Definition itemid.h:106
#define ItemIdHasStorage(itemId)
Definition itemid.h:120
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition itemptr.h:135
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
void UnlockRelation(Relation relation, LOCKMODE lockmode)
Definition lmgr.c:314
bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
Definition lmgr.c:278
bool LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
Definition lmgr.c:367
#define NoLock
Definition lockdefs.h:34
#define AccessExclusiveLock
Definition lockdefs.h:43
#define RowExclusiveLock
Definition lockdefs.h:38
char * get_database_name(Oid dbid)
Definition lsyscache.c:1312
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3588
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
#define AmAutoVacuumWorkerProcess()
Definition miscadmin.h:396
#define START_CRIT_SECTION()
Definition miscadmin.h:150
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define END_CRIT_SECTION()
Definition miscadmin.h:152
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2865
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2879
#define MultiXactIdIsValid(multi)
Definition multixact.h:29
#define InvalidMultiXactId
Definition multixact.h:25
static char * errmsg
#define InvalidOffsetNumber
Definition off.h:26
#define OffsetNumberIsValid(offsetNumber)
Definition off.h:39
#define OffsetNumberNext(offsetNumber)
Definition off.h:52
uint16 OffsetNumber
Definition off.h:24
#define FirstOffsetNumber
Definition off.h:27
#define MaxOffsetNumber
Definition off.h:28
static int verbose
uint32 pg_prng_uint32(pg_prng_state *state)
Definition pg_prng.c:227
pg_prng_state pg_global_prng_state
Definition pg_prng.c:34
const char * pg_rusage_show(const PGRUsage *ru0)
Definition pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition pg_rusage.c:27
static char buf[DEFAULT_XLOG_SEG_SIZE]
int64 PgStat_Counter
Definition pgstat.h:71
PgStat_Counter pgStatBlockReadTime
PgStat_Counter pgStatBlockWriteTime
void pgstat_report_vacuum(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime)
#define qsort(a, b, c, d)
Definition port.h:495
static int fb(int x)
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition procarray.c:4127
bool GlobalVisTestXidConsideredRunning(GlobalVisState *state, TransactionId xid, bool allow_update)
Definition procarray.c:4328
#define PROGRESS_VACUUM_PHASE_FINAL_CLEANUP
Definition progress.h:41
#define PROGRESS_VACUUM_MODE
Definition progress.h:32
#define PROGRESS_VACUUM_MODE_NORMAL
Definition progress.h:44
#define PROGRESS_VACUUM_STARTED_BY_AUTOVACUUM
Definition progress.h:50
#define PROGRESS_VACUUM_DEAD_TUPLE_BYTES
Definition progress.h:27
#define PROGRESS_VACUUM_PHASE_SCAN_HEAP
Definition progress.h:36
#define PROGRESS_VACUUM_TOTAL_HEAP_BLKS
Definition progress.h:22
#define PROGRESS_VACUUM_PHASE
Definition progress.h:21
#define PROGRESS_VACUUM_DELAY_TIME
Definition progress.h:31
#define PROGRESS_VACUUM_STARTED_BY_AUTOVACUUM_WRAPAROUND
Definition progress.h:51
#define PROGRESS_VACUUM_NUM_INDEX_VACUUMS
Definition progress.h:25
#define PROGRESS_VACUUM_PHASE_VACUUM_HEAP
Definition progress.h:38
#define PROGRESS_VACUUM_NUM_DEAD_ITEM_IDS
Definition progress.h:28
#define PROGRESS_VACUUM_MAX_DEAD_TUPLE_BYTES
Definition progress.h:26
#define PROGRESS_VACUUM_STARTED_BY_MANUAL
Definition progress.h:49
#define PROGRESS_VACUUM_HEAP_BLKS_SCANNED
Definition progress.h:23
#define PROGRESS_VACUUM_STARTED_BY
Definition progress.h:33
#define PROGRESS_VACUUM_PHASE_INDEX_CLEANUP
Definition progress.h:39
#define PROGRESS_VACUUM_PHASE_VACUUM_INDEX
Definition progress.h:37
#define PROGRESS_VACUUM_MODE_FAILSAFE
Definition progress.h:46
#define PROGRESS_VACUUM_INDEXES_PROCESSED
Definition progress.h:30
#define PROGRESS_VACUUM_INDEXES_TOTAL
Definition progress.h:29
#define PROGRESS_VACUUM_MODE_AGGRESSIVE
Definition progress.h:45
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition progress.h:24
#define PROGRESS_VACUUM_PHASE_TRUNCATE
Definition progress.h:40
void heap_page_prune_and_freeze(PruneFreezeParams *params, PruneFreezeResult *presult, OffsetNumber *off_loc, TransactionId *new_relfrozen_xid, MultiXactId *new_relmin_mxid)
Definition pruneheap.c:1090
void log_heap_prune_and_freeze(Relation relation, Buffer buffer, Buffer vmbuffer, uint8 vmflags, TransactionId conflict_xid, bool cleanup_lock, PruneReason reason, HeapTupleFreeze *frozen, int nfrozen, OffsetNumber *redirected, int nredirected, OffsetNumber *dead, int ndead, OffsetNumber *unused, int nunused)
Definition pruneheap.c:2561
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
ReadStream * read_stream_begin_relation(int flags, BufferAccessStrategy strategy, Relation rel, ForkNumber forknum, ReadStreamBlockNumberCB callback, void *callback_private_data, size_t per_buffer_data_size)
void read_stream_end(ReadStream *stream)
#define READ_STREAM_MAINTENANCE
Definition read_stream.h:28
#define READ_STREAM_USE_BATCHING
Definition read_stream.h:64
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationNeedsWAL(relation)
Definition rel.h:639
#define RelationUsesLocalBuffers(relation)
Definition rel.h:648
#define RelationGetNamespace(relation)
Definition rel.h:557
@ MAIN_FORKNUM
Definition relpath.h:58
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition storage.c:289
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
int64 shared_blks_dirtied
Definition instrument.h:28
int64 local_blks_hit
Definition instrument.h:30
int64 shared_blks_read
Definition instrument.h:27
int64 local_blks_read
Definition instrument.h:31
int64 local_blks_dirtied
Definition instrument.h:32
int64 shared_blks_hit
Definition instrument.h:26
struct ErrorContextCallback * previous
Definition elog.h:298
void(* callback)(void *arg)
Definition elog.h:299
ItemPointerData t_self
Definition htup.h:65
uint32 t_len
Definition htup.h:64
HeapTupleHeader t_data
Definition htup.h:68
Oid t_tableOid
Definition htup.h:66
BlockNumber pages_deleted
Definition genam.h:90
BlockNumber pages_newly_deleted
Definition genam.h:89
BlockNumber pages_free
Definition genam.h:91
BlockNumber num_pages
Definition genam.h:85
double num_index_tuples
Definition genam.h:87
BlockNumber next_eager_scan_region_start
Definition vacuumlazy.c:380
ParallelVacuumState * pvs
Definition vacuumlazy.c:261
bool next_unskippable_eager_scanned
Definition vacuumlazy.c:365
VacDeadItemsInfo * dead_items_info
Definition vacuumlazy.c:304
PVWorkerUsage worker_usage
Definition vacuumlazy.c:352
Buffer next_unskippable_vmbuffer
Definition vacuumlazy.c:366
OffsetNumber offnum
Definition vacuumlazy.c:289
TidStore * dead_items
Definition vacuumlazy.c:303
int64 tuples_deleted
Definition vacuumlazy.c:355
BlockNumber nonempty_pages
Definition vacuumlazy.c:335
BlockNumber eager_scan_remaining_fails
Definition vacuumlazy.c:412
bool do_rel_truncate
Definition vacuumlazy.c:273
BlockNumber scanned_pages
Definition vacuumlazy.c:307
int num_dead_items_resets
Definition vacuumlazy.c:345
bool aggressive
Definition vacuumlazy.c:264
BlockNumber new_frozen_tuple_pages
Definition vacuumlazy.c:316
GlobalVisState * vistest
Definition vacuumlazy.c:277
BlockNumber removed_pages
Definition vacuumlazy.c:315
int num_index_scans
Definition vacuumlazy.c:344
IndexBulkDeleteResult ** indstats
Definition vacuumlazy.c:341
BlockNumber new_all_frozen_pages
Definition vacuumlazy.c:331
double new_live_tuples
Definition vacuumlazy.c:339
double new_rel_tuples
Definition vacuumlazy.c:338
BlockNumber new_all_visible_all_frozen_pages
Definition vacuumlazy.c:328
BlockNumber new_all_visible_pages
Definition vacuumlazy.c:319
TransactionId NewRelfrozenXid
Definition vacuumlazy.c:279
Relation rel
Definition vacuumlazy.c:255
bool consider_bypass_optimization
Definition vacuumlazy.c:268
BlockNumber rel_pages
Definition vacuumlazy.c:306
Size total_dead_items_bytes
Definition vacuumlazy.c:346
BlockNumber next_unskippable_block
Definition vacuumlazy.c:364
int64 recently_dead_tuples
Definition vacuumlazy.c:359
int64 tuples_frozen
Definition vacuumlazy.c:356
char * dbname
Definition vacuumlazy.c:284
BlockNumber missed_dead_pages
Definition vacuumlazy.c:334
BlockNumber current_block
Definition vacuumlazy.c:363
char * relnamespace
Definition vacuumlazy.c:285
int64 live_tuples
Definition vacuumlazy.c:358
int64 lpdead_items
Definition vacuumlazy.c:357
BufferAccessStrategy bstrategy
Definition vacuumlazy.c:260
BlockNumber eager_scan_remaining_successes
Definition vacuumlazy.c:391
bool skippedallvis
Definition vacuumlazy.c:281
BlockNumber lpdead_item_pages
Definition vacuumlazy.c:333
BlockNumber eager_scanned_pages
Definition vacuumlazy.c:313
Relation * indrels
Definition vacuumlazy.c:256
bool skipwithvm
Definition vacuumlazy.c:266
bool do_index_cleanup
Definition vacuumlazy.c:272
MultiXactId NewRelminMxid
Definition vacuumlazy.c:280
int64 missed_dead_tuples
Definition vacuumlazy.c:360
BlockNumber blkno
Definition vacuumlazy.c:288
struct VacuumCutoffs cutoffs
Definition vacuumlazy.c:276
char * relname
Definition vacuumlazy.c:286
BlockNumber eager_scan_max_fails_per_region
Definition vacuumlazy.c:402
VacErrPhase phase
Definition vacuumlazy.c:290
char * indname
Definition vacuumlazy.c:287
bool do_index_vacuuming
Definition vacuumlazy.c:271
BlockNumber blkno
Definition vacuumlazy.c:419
VacErrPhase phase
Definition vacuumlazy.c:421
OffsetNumber offnum
Definition vacuumlazy.c:420
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Relation relation
Definition heapam.h:262
size_t max_bytes
Definition vacuum.h:298
int64 num_items
Definition vacuum.h:299
int nworkers
Definition vacuum.h:250
VacOptValue truncate
Definition vacuum.h:235
int log_vacuum_min_duration
Definition vacuum.h:226
uint32 options
Definition vacuum.h:218
bool is_wraparound
Definition vacuum.h:225
VacOptValue index_cleanup
Definition vacuum.h:234
double max_eager_freeze_failure_rate
Definition vacuum.h:243
int64 wal_buffers_full
Definition instrument.h:57
uint64 wal_bytes
Definition instrument.h:55
int64 wal_fpi
Definition instrument.h:54
uint64 wal_fpi_bytes
Definition instrument.h:56
int64 wal_records
Definition instrument.h:53
TidStoreIter * TidStoreBeginIterate(TidStore *ts)
Definition tidstore.c:471
void TidStoreEndIterate(TidStoreIter *iter)
Definition tidstore.c:518
TidStoreIterResult * TidStoreIterateNext(TidStoreIter *iter)
Definition tidstore.c:493
TidStore * TidStoreCreateLocal(size_t max_bytes, bool insert_only)
Definition tidstore.c:162
void TidStoreDestroy(TidStore *ts)
Definition tidstore.c:317
int TidStoreGetBlockOffsets(TidStoreIterResult *result, OffsetNumber *offsets, int max_offsets)
Definition tidstore.c:566
void TidStoreSetBlockOffsets(TidStore *ts, BlockNumber blkno, OffsetNumber *offsets, int num_offsets)
Definition tidstore.c:345
size_t TidStoreMemoryUsage(TidStore *ts)
Definition tidstore.c:532
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
static TransactionId ReadNextTransactionId(void)
Definition transam.h:375
#define InvalidTransactionId
Definition transam.h:31
static bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition transam.h:282
#define TransactionIdIsValid(xid)
Definition transam.h:41
#define TransactionIdIsNormal(xid)
Definition transam.h:42
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
bool track_cost_delay_timing
Definition vacuum.c:83
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition vacuum.c:2369
IndexBulkDeleteResult * vac_cleanup_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat)
Definition vacuum.c:2679
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition vacuum.c:2412
void vacuum_delay_point(bool is_analyze)
Definition vacuum.c:2433
bool vacuum_get_cutoffs(Relation rel, const VacuumParams *params, struct VacuumCutoffs *cutoffs)
Definition vacuum.c:1101
bool vacuum_xid_failsafe_check(const struct VacuumCutoffs *cutoffs)
Definition vacuum.c:1269
bool VacuumFailsafeActive
Definition vacuum.c:111
double vac_estimate_reltuples(Relation relation, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
Definition vacuum.c:1331
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, BlockNumber num_all_frozen_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool *frozenxid_updated, bool *minmulti_updated, bool in_outer_xact)
Definition vacuum.c:1427
IndexBulkDeleteResult * vac_bulkdel_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat, TidStore *dead_items, VacDeadItemsInfo *dead_items_info)
Definition vacuum.c:2658
#define VACOPT_VERBOSE
Definition vacuum.h:181
@ VACOPTVALUE_AUTO
Definition vacuum.h:202
@ VACOPTVALUE_ENABLED
Definition vacuum.h:204
@ VACOPTVALUE_UNSPECIFIED
Definition vacuum.h:201
@ VACOPTVALUE_DISABLED
Definition vacuum.h:203
#define VACOPT_DISABLE_PAGE_SKIPPING
Definition vacuum.h:187
static int lazy_scan_prune(LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, Buffer vmbuffer, bool *has_lpdead_items, bool *vm_page_frozen)
static void dead_items_cleanup(LVRelState *vacrel)
static void update_relstats_all_indexes(LVRelState *vacrel)
static void dead_items_add(LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets, int num_offsets)
static BlockNumber heap_vac_scan_next_block(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL
Definition vacuumlazy.c:180
static void vacuum_error_callback(void *arg)
#define EAGER_SCAN_REGION_SIZE
Definition vacuumlazy.c:250
static void lazy_truncate_heap(LVRelState *vacrel)
static void lazy_vacuum(LVRelState *vacrel)
static void lazy_cleanup_all_indexes(LVRelState *vacrel)
#define MAX_EAGER_FREEZE_SUCCESS_RATE
Definition vacuumlazy.c:241
static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, bool *has_lpdead_items)
static BlockNumber vacuum_reap_lp_read_stream_next(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
#define REL_TRUNCATE_MINIMUM
Definition vacuumlazy.c:169
static bool should_attempt_truncation(LVRelState *vacrel)
static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, bool sharelock, Buffer vmbuffer)
VacErrPhase
Definition vacuumlazy.c:225
@ VACUUM_ERRCB_PHASE_SCAN_HEAP
Definition vacuumlazy.c:227
@ VACUUM_ERRCB_PHASE_VACUUM_INDEX
Definition vacuumlazy.c:228
@ VACUUM_ERRCB_PHASE_TRUNCATE
Definition vacuumlazy.c:231
@ VACUUM_ERRCB_PHASE_INDEX_CLEANUP
Definition vacuumlazy.c:230
@ VACUUM_ERRCB_PHASE_VACUUM_HEAP
Definition vacuumlazy.c:229
@ VACUUM_ERRCB_PHASE_UNKNOWN
Definition vacuumlazy.c:226
static void lazy_scan_heap(LVRelState *vacrel)
#define ParallelVacuumIsActive(vacrel)
Definition vacuumlazy.c:221
static void restore_vacuum_error_info(LVRelState *vacrel, const LVSavedErrInfo *saved_vacrel)
static IndexBulkDeleteResult * lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat, double reltuples, LVRelState *vacrel)
static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
static void dead_items_reset(LVRelState *vacrel)
#define REL_TRUNCATE_FRACTION
Definition vacuumlazy.c:170
static bool lazy_check_wraparound_failsafe(LVRelState *vacrel)
static IndexBulkDeleteResult * lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat, double reltuples, bool estimated_count, LVRelState *vacrel)
#define PREFETCH_SIZE
Definition vacuumlazy.c:215
static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer, OffsetNumber *deadoffsets, int num_offsets, Buffer vmbuffer)
static void heap_vacuum_eager_scan_setup(LVRelState *vacrel, const VacuumParams *params)
Definition vacuumlazy.c:497
static bool heap_page_would_be_all_visible(Relation rel, Buffer buf, GlobalVisState *vistest, bool allow_update_vistest, OffsetNumber *deadoffsets, int ndeadoffsets, bool *all_frozen, TransactionId *newest_live_xid, OffsetNumber *logging_offnum)
void heap_vacuum_rel(Relation rel, const VacuumParams *params, BufferAccessStrategy bstrategy)
Definition vacuumlazy.c:624
#define BYPASS_THRESHOLD_PAGES
Definition vacuumlazy.c:187
static void dead_items_alloc(LVRelState *vacrel, int nworkers)
#define VACUUM_TRUNCATE_LOCK_TIMEOUT
Definition vacuumlazy.c:181
static bool lazy_vacuum_all_indexes(LVRelState *vacrel)
static void update_vacuum_error_info(LVRelState *vacrel, LVSavedErrInfo *saved_vacrel, int phase, BlockNumber blkno, OffsetNumber offnum)
static BlockNumber count_nondeletable_pages(LVRelState *vacrel, bool *lock_waiter_detected)
#define SKIP_PAGES_THRESHOLD
Definition vacuumlazy.c:209
#define FAILSAFE_EVERY_PAGES
Definition vacuumlazy.c:193
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL
Definition vacuumlazy.c:179
static int cmpOffsetNumbers(const void *a, const void *b)
static void lazy_vacuum_heap_rel(LVRelState *vacrel)
#define VACUUM_FSM_EVERY_PAGES
Definition vacuumlazy.c:202
void parallel_vacuum_cleanup_all_indexes(ParallelVacuumState *pvs, long num_table_tuples, int num_index_scans, bool estimated_count, PVWorkerStats *wstats)
TidStore * parallel_vacuum_get_dead_items(ParallelVacuumState *pvs, VacDeadItemsInfo **dead_items_info_p)
void parallel_vacuum_bulkdel_all_indexes(ParallelVacuumState *pvs, long num_table_tuples, int num_index_scans, PVWorkerStats *wstats)
ParallelVacuumState * parallel_vacuum_init(Relation rel, Relation *indrels, int nindexes, int nrequested_workers, int vac_work_mem, int elevel, BufferAccessStrategy bstrategy)
void parallel_vacuum_reset_dead_items(ParallelVacuumState *pvs)
void parallel_vacuum_end(ParallelVacuumState *pvs, IndexBulkDeleteResult **istats)
void visibilitymap_set(BlockNumber heapBlk, Buffer vmBuf, uint8 flags, const RelFileLocator rlocator)
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
#define VISIBILITYMAP_VALID_BITS
#define VISIBILITYMAP_ALL_FROZEN
#define VISIBILITYMAP_ALL_VISIBLE
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
bool IsInParallelMode(void)
Definition xact.c:1119