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