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