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