Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pruneheap.c
4 : : * heap page pruning and HOT-chain management code
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/access/heap/pruneheap.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/heapam.h"
18 : : #include "access/heapam_xlog.h"
19 : : #include "access/htup_details.h"
20 : : #include "access/multixact.h"
21 : : #include "access/transam.h"
22 : : #include "access/visibilitymap.h"
23 : : #include "access/xlog.h"
24 : : #include "access/xloginsert.h"
25 : : #include "commands/vacuum.h"
26 : : #include "executor/instrument.h"
27 : : #include "miscadmin.h"
28 : : #include "pgstat.h"
29 : : #include "storage/bufmgr.h"
30 : : #include "storage/freespace.h"
31 : : #include "utils/rel.h"
32 : : #include "utils/snapmgr.h"
33 : :
34 : : /* Working data for heap_page_prune_and_freeze() and subroutines */
35 : : typedef struct
36 : : {
37 : : /*-------------------------------------------------------
38 : : * Arguments passed to heap_page_prune_and_freeze()
39 : : *-------------------------------------------------------
40 : : */
41 : :
42 : : /* tuple visibility test, initialized for the relation */
43 : : GlobalVisState *vistest;
44 : : /* whether or not dead items can be set LP_UNUSED during pruning */
45 : : bool mark_unused_now;
46 : : /* whether to attempt freezing tuples */
47 : : bool attempt_freeze;
48 : : /* whether to attempt setting the VM */
49 : : bool attempt_set_vm;
50 : : struct VacuumCutoffs *cutoffs;
51 : : Relation relation;
52 : :
53 : : /*
54 : : * Keep the buffer, block, and page handy so that helpers needing to
55 : : * access them don't need to make repeated calls to BufferGetBlockNumber()
56 : : * and BufferGetPage().
57 : : */
58 : : BlockNumber block;
59 : : Buffer buffer;
60 : : Page page;
61 : :
62 : : /*-------------------------------------------------------
63 : : * Fields describing what to do to the page
64 : : *-------------------------------------------------------
65 : : */
66 : : TransactionId new_prune_xid; /* new prune hint value */
67 : : TransactionId latest_xid_removed;
68 : : int nredirected; /* numbers of entries in arrays below */
69 : : int ndead;
70 : : int nunused;
71 : : int nfrozen;
72 : : /* arrays that accumulate indexes of items to be changed */
73 : : OffsetNumber redirected[MaxHeapTuplesPerPage * 2];
74 : : OffsetNumber nowdead[MaxHeapTuplesPerPage];
75 : : OffsetNumber nowunused[MaxHeapTuplesPerPage];
76 : : HeapTupleFreeze frozen[MaxHeapTuplesPerPage];
77 : :
78 : : /*
79 : : * set_all_visible and set_all_frozen indicate if the all-visible and
80 : : * all-frozen bits in the visibility map can be set for this page after
81 : : * pruning. They are only tracked when the caller requests VM updates
82 : : * (attempt_set_vm); otherwise they remain false throughout.
83 : : *
84 : : * NOTE: set_all_visible and set_all_frozen initially don't include
85 : : * LP_DEAD items. That's convenient for heap_page_prune_and_freeze() to
86 : : * use them to decide whether to opportunistically freeze the page or not.
87 : : * The set_all_visible and set_all_frozen values ultimately used to set
88 : : * the VM are adjusted to include LP_DEAD items after we determine whether
89 : : * or not to opportunistically freeze.
90 : : */
91 : : bool set_all_visible;
92 : : bool set_all_frozen;
93 : :
94 : : /*-------------------------------------------------------
95 : : * Working state for HOT chain processing
96 : : *-------------------------------------------------------
97 : : */
98 : :
99 : : /*
100 : : * 'root_items' contains offsets of all LP_REDIRECT line pointers and
101 : : * normal non-HOT tuples. They can be stand-alone items or the first item
102 : : * in a HOT chain. 'heaponly_items' contains heap-only tuples which can
103 : : * only be removed as part of a HOT chain.
104 : : */
105 : : int nroot_items;
106 : : OffsetNumber root_items[MaxHeapTuplesPerPage];
107 : : int nheaponly_items;
108 : : OffsetNumber heaponly_items[MaxHeapTuplesPerPage];
109 : :
110 : : /*
111 : : * processed[offnum] is true if item at offnum has been processed.
112 : : *
113 : : * This needs to be MaxHeapTuplesPerPage + 1 long as FirstOffsetNumber is
114 : : * 1. Otherwise every access would need to subtract 1.
115 : : */
116 : : bool processed[MaxHeapTuplesPerPage + 1];
117 : :
118 : : /*
119 : : * Tuple visibility is only computed once for each tuple, for correctness
120 : : * and efficiency reasons; see comment in heap_page_prune_and_freeze() for
121 : : * details. This is of type int8[], instead of HTSV_Result[], so we can
122 : : * use -1 to indicate no visibility has been computed, e.g. for LP_DEAD
123 : : * items.
124 : : *
125 : : * This needs to be MaxHeapTuplesPerPage + 1 long as FirstOffsetNumber is
126 : : * 1. Otherwise every access would need to subtract 1.
127 : : */
128 : : int8 htsv[MaxHeapTuplesPerPage + 1];
129 : :
130 : : /*-------------------------------------------------------
131 : : * Working state for freezing
132 : : *-------------------------------------------------------
133 : : */
134 : : HeapPageFreeze pagefrz;
135 : :
136 : : /*-------------------------------------------------------
137 : : * Working state for visibility map processing
138 : : *-------------------------------------------------------
139 : : */
140 : :
141 : : /*
142 : : * Caller must provide a pinned vmbuffer corresponding to the heap block
143 : : * passed to heap_page_prune_and_freeze(). We will fix any corruption
144 : : * found in the VM and set the VM if the page is all-visible/all-frozen.
145 : : */
146 : : Buffer vmbuffer;
147 : :
148 : : /*
149 : : * The state of the VM bits at the beginning of pruning and the state they
150 : : * will be in at the end.
151 : : */
152 : : uint8 old_vmbits;
153 : : uint8 new_vmbits;
154 : :
155 : : /* The newest xmin of live tuples on the page */
156 : : TransactionId newest_live_xid;
157 : :
158 : : /*-------------------------------------------------------
159 : : * Information about what was done
160 : : *
161 : : * These fields are not used by pruning itself for the most part, but are
162 : : * used to collect information about what was pruned and what state the
163 : : * page is in after pruning, for the benefit of the caller. They are
164 : : * copied to the caller's PruneFreezeResult at the end.
165 : : * -------------------------------------------------------
166 : : */
167 : :
168 : : int ndeleted; /* Number of tuples deleted from the page */
169 : :
170 : : /* Number of live and recently dead tuples, after pruning */
171 : : int live_tuples;
172 : : int recently_dead_tuples;
173 : :
174 : : /* Whether or not the page makes rel truncation unsafe */
175 : : bool hastup;
176 : :
177 : : /*
178 : : * LP_DEAD items on the page after pruning. Includes existing LP_DEAD
179 : : * items
180 : : */
181 : : int lpdead_items; /* number of items in the array */
182 : : OffsetNumber *deadoffsets; /* points directly to presult->deadoffsets */
183 : : } PruneState;
184 : :
185 : : /*
186 : : * Type of visibility map corruption detected on a heap page and its
187 : : * associated VM page. Passed to heap_page_fix_vm_corruption() so the caller
188 : : * can specify what it found rather than having the function rederive the
189 : : * corruption from page state.
190 : : */
191 : : typedef enum VMCorruptionType
192 : : {
193 : : /* VM bits are set but the heap page-level PD_ALL_VISIBLE flag is not */
194 : : VM_CORRUPT_MISSING_PAGE_HINT,
195 : : /* LP_DEAD line pointers found on a page marked all-visible */
196 : : VM_CORRUPT_LPDEAD,
197 : : /* Tuple not visible to all transactions on a page marked all-visible */
198 : : VM_CORRUPT_TUPLE_VISIBILITY,
199 : : } VMCorruptionType;
200 : :
201 : : /* Local functions */
202 : : static void prune_freeze_setup(PruneFreezeParams *params,
203 : : TransactionId *new_relfrozen_xid,
204 : : MultiXactId *new_relmin_mxid,
205 : : PruneFreezeResult *presult,
206 : : PruneState *prstate);
207 : : static void heap_page_fix_vm_corruption(PruneState *prstate,
208 : : OffsetNumber offnum,
209 : : VMCorruptionType corruption_type);
210 : : static void prune_freeze_fast_path(PruneState *prstate,
211 : : PruneFreezeResult *presult);
212 : : static void prune_freeze_plan(PruneState *prstate,
213 : : OffsetNumber *off_loc);
214 : : static HTSV_Result heap_prune_satisfies_vacuum(PruneState *prstate,
215 : : HeapTuple tup);
216 : : static inline HTSV_Result htsv_get_valid_status(int status);
217 : : static void heap_prune_chain(OffsetNumber maxoff,
218 : : OffsetNumber rootoffnum, PruneState *prstate);
219 : : static void heap_prune_record_prunable(PruneState *prstate, TransactionId xid,
220 : : OffsetNumber offnum);
221 : : static void heap_prune_record_redirect(PruneState *prstate,
222 : : OffsetNumber offnum, OffsetNumber rdoffnum,
223 : : bool was_normal);
224 : : static void heap_prune_record_dead(PruneState *prstate, OffsetNumber offnum,
225 : : bool was_normal);
226 : : static void heap_prune_record_dead_or_unused(PruneState *prstate, OffsetNumber offnum,
227 : : bool was_normal);
228 : : static void heap_prune_record_unused(PruneState *prstate, OffsetNumber offnum, bool was_normal);
229 : :
230 : : static void heap_prune_record_unchanged_lp_unused(PruneState *prstate, OffsetNumber offnum);
231 : : static void heap_prune_record_unchanged_lp_normal(PruneState *prstate, OffsetNumber offnum);
232 : : static void heap_prune_record_unchanged_lp_dead(PruneState *prstate, OffsetNumber offnum);
233 : : static void heap_prune_record_unchanged_lp_redirect(PruneState *prstate, OffsetNumber offnum);
234 : :
235 : : static void page_verify_redirects(Page page);
236 : :
237 : : static bool heap_page_will_freeze(bool did_tuple_hint_fpi, bool do_prune, bool do_hint_prune,
238 : : PruneState *prstate);
239 : : static bool heap_page_will_set_vm(PruneState *prstate, PruneReason reason,
240 : : bool do_prune, bool do_freeze);
241 : :
242 : :
243 : : /*
244 : : * Optionally prune and repair fragmentation in the specified page.
245 : : *
246 : : * This is an opportunistic function. It will perform housekeeping
247 : : * only if the page heuristically looks like a candidate for pruning and we
248 : : * can acquire buffer cleanup lock without blocking.
249 : : *
250 : : * Note: this is called quite often. It's important that it fall out quickly
251 : : * if there's not any use in pruning.
252 : : *
253 : : * Caller must have pin on the buffer, and must *not* have a lock on it.
254 : : *
255 : : * This function may pin *vmbuffer. It's passed by reference so the caller can
256 : : * reuse the pin across calls, avoiding repeated pin/unpin cycles. If we find
257 : : * VM corruption during pruning, we will fix it. Caller is responsible for
258 : : * unpinning *vmbuffer.
259 : : *
260 : : * rel_read_only is true if we determined at plan time that the query does not
261 : : * modify the relation. It is counterproductive to set the VM if the query
262 : : * will immediately clear it.
263 : : *
264 : : * As noted in ScanRelIsReadOnly(), INSERT ... SELECT from the same table will
265 : : * report the scan relation as read-only. This is usually harmless in
266 : : * practice. It is useful to set scanned pages all-visible that won't be
267 : : * inserted into. Pages it does insert to will rarely meet the criteria for
268 : : * pruning, and those that do are likely to contain in-progress inserts which
269 : : * make the page not fully all-visible.
270 : : */
271 : : void
272 : 20575263 : heap_page_prune_opt(Relation relation, Buffer buffer, Buffer *vmbuffer,
273 : : bool rel_read_only)
274 : : {
275 : 20575263 : Page page = BufferGetPage(buffer);
276 : : TransactionId prune_xid;
277 : : GlobalVisState *vistest;
278 : : Size minfree;
279 : :
280 : : /*
281 : : * We can't write WAL in recovery mode, so there's no point trying to
282 : : * clean the page. The primary will likely issue a cleaning WAL record
283 : : * soon anyway, so this is no particular loss.
284 : : */
285 [ + + ]: 20575263 : if (RecoveryInProgress())
286 : 271819 : return;
287 : :
288 : : /*
289 : : * First check whether there's any chance there's something to prune,
290 : : * determining the appropriate horizon is a waste if there's no prune_xid
291 : : * (i.e. no updates/deletes left potentially dead tuples around and no
292 : : * inserts inserted new tuples that may be visible to all).
293 : : */
294 : 20303444 : prune_xid = PageGetPruneXid(page);
295 [ + + ]: 20303444 : if (!TransactionIdIsValid(prune_xid))
296 : 8783053 : return;
297 : :
298 : : /*
299 : : * Check whether prune_xid indicates that there may be dead rows that can
300 : : * be cleaned up.
301 : : */
302 : 11520391 : vistest = GlobalVisTestFor(relation);
303 : :
304 [ + + ]: 11520391 : if (!GlobalVisTestIsRemovableXid(vistest, prune_xid, true))
305 : 9015518 : return;
306 : :
307 : : /*
308 : : * We prune when a previous UPDATE failed to find enough space on the page
309 : : * for a new tuple version, or when free space falls below the relation's
310 : : * fill-factor target (but not less than 10%).
311 : : *
312 : : * Checking free space here is questionable since we aren't holding any
313 : : * lock on the buffer; in the worst case we could get a bogus answer. It's
314 : : * unlikely to be *seriously* wrong, though, since reading either pd_lower
315 : : * or pd_upper is probably atomic. Avoiding taking a lock seems more
316 : : * important than sometimes getting a wrong answer in what is after all
317 : : * just a heuristic estimate.
318 : : */
319 [ + + ]: 2504873 : minfree = RelationGetTargetPageFreeSpace(relation,
320 : : HEAP_DEFAULT_FILLFACTOR);
321 : 2504873 : minfree = Max(minfree, BLCKSZ / 10);
322 : :
323 [ + + + + ]: 2504873 : if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
324 : : {
325 : 137736 : bool record_free_space = false;
326 : 137736 : Size freespace = 0;
327 : :
328 : : /* OK, try to get exclusive buffer lock */
329 [ + + ]: 137736 : if (!ConditionalLockBufferForCleanup(buffer))
330 : 2117 : return;
331 : :
332 : : /*
333 : : * Now that we have buffer lock, get accurate information about the
334 : : * page's free space, and recheck the heuristic about whether to
335 : : * prune.
336 : : */
337 [ + + + - ]: 135619 : if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
338 : : {
339 : : OffsetNumber dummy_off_loc;
340 : : PruneFreezeResult presult;
341 : : PruneFreezeParams params;
342 : :
343 : 135619 : visibilitymap_pin(relation, BufferGetBlockNumber(buffer),
344 : : vmbuffer);
345 : :
346 : 135619 : params.relation = relation;
347 : 135619 : params.buffer = buffer;
348 : 135619 : params.vmbuffer = *vmbuffer;
349 : 135619 : params.reason = PRUNE_ON_ACCESS;
350 : 135619 : params.vistest = vistest;
351 : 135619 : params.cutoffs = NULL;
352 : :
353 : : /*
354 : : * We don't pass the HEAP_PAGE_PRUNE_MARK_UNUSED_NOW option
355 : : * regardless of whether or not the relation has indexes, since we
356 : : * cannot safely determine that during on-access pruning with the
357 : : * current implementation.
358 : : */
359 : 135619 : params.options = HEAP_PAGE_PRUNE_ALLOW_FAST_PATH;
360 [ + + ]: 135619 : if (rel_read_only)
361 : 37897 : params.options |= HEAP_PAGE_PRUNE_SET_VM;
362 : :
363 : 135619 : heap_page_prune_and_freeze(¶ms, &presult, &dummy_off_loc,
364 : : NULL, NULL);
365 : :
366 : : /*
367 : : * Report the number of tuples reclaimed to pgstats. This is
368 : : * presult.ndeleted minus the number of newly-LP_DEAD-set items.
369 : : *
370 : : * We derive the number of dead tuples like this to avoid totally
371 : : * forgetting about items that were set to LP_DEAD, since they
372 : : * still need to be cleaned up by VACUUM. We only want to count
373 : : * heap-only tuples that just became LP_UNUSED in our report,
374 : : * which don't.
375 : : *
376 : : * VACUUM doesn't have to compensate in the same way when it
377 : : * tracks ndeleted, since it will set the same LP_DEAD items to
378 : : * LP_UNUSED separately.
379 : : */
380 [ + + ]: 135619 : if (presult.ndeleted > presult.nnewlpdead)
381 : 22225 : pgstat_update_heap_dead_tuples(relation,
382 : 22225 : presult.ndeleted - presult.nnewlpdead);
383 : :
384 : : /*
385 : : * If this prune newly set the page all-visible, VACUUM may later
386 : : * skip the page and not update the free space map (FSM) for it.
387 : : * Keep the FSM from going stale by recording it now. We do not
388 : : * want to update the freespace map otherwise, to reserve
389 : : * freespace on this page for HOT updates.
390 : : */
391 [ + + ]: 135619 : if (presult.newly_all_visible)
392 : : {
393 : 13704 : record_free_space = true;
394 : 13704 : freespace = PageGetHeapFreeSpace(page);
395 : : }
396 : : }
397 : :
398 : : /* And release buffer lock */
399 : 135619 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
400 : :
401 : : /*
402 : : * RecordPageWithFreeSpace() only dirties the FSM when the recorded
403 : : * free-space category actually changes. Note that vacuum will still
404 : : * do FreeSpaceMapVacuum() for ranges of pages that are skipped, so we
405 : : * don't have to worry about that here.
406 : : */
407 [ + + ]: 135619 : if (record_free_space)
408 : 13704 : RecordPageWithFreeSpace(relation, BufferGetBlockNumber(buffer), freespace);
409 : : }
410 : : }
411 : :
412 : : /*
413 : : * Helper for heap_page_prune_and_freeze() to initialize the PruneState using
414 : : * the provided parameters.
415 : : *
416 : : * params, new_relfrozen_xid, new_relmin_mxid, and presult are input
417 : : * parameters and are not modified by this function. Only prstate is modified.
418 : : */
419 : : static void
420 : 625602 : prune_freeze_setup(PruneFreezeParams *params,
421 : : TransactionId *new_relfrozen_xid,
422 : : MultiXactId *new_relmin_mxid,
423 : : PruneFreezeResult *presult,
424 : : PruneState *prstate)
425 : : {
426 : : /* Copy parameters to prstate */
427 : 625602 : prstate->vistest = params->vistest;
428 : 625602 : prstate->mark_unused_now =
429 : 625602 : (params->options & HEAP_PAGE_PRUNE_MARK_UNUSED_NOW) != 0;
430 : :
431 : : /* cutoffs must be provided if we will attempt freezing */
432 : : Assert(!(params->options & HEAP_PAGE_PRUNE_FREEZE) || params->cutoffs);
433 : 625602 : prstate->attempt_freeze = (params->options & HEAP_PAGE_PRUNE_FREEZE) != 0;
434 : 625602 : prstate->attempt_set_vm = (params->options & HEAP_PAGE_PRUNE_SET_VM) != 0;
435 : 625602 : prstate->cutoffs = params->cutoffs;
436 : 625602 : prstate->relation = params->relation;
437 : 625602 : prstate->block = BufferGetBlockNumber(params->buffer);
438 : 625602 : prstate->buffer = params->buffer;
439 : 625602 : prstate->page = BufferGetPage(params->buffer);
440 : :
441 : : Assert(BufferIsValid(params->vmbuffer));
442 : 625602 : prstate->vmbuffer = params->vmbuffer;
443 : 625602 : prstate->new_vmbits = 0;
444 : 625602 : prstate->old_vmbits = visibilitymap_get_status(prstate->relation,
445 : : prstate->block,
446 : : &prstate->vmbuffer);
447 : :
448 : : /*
449 : : * Our strategy is to scan the page and make lists of items to change,
450 : : * then apply the changes within a critical section. This keeps as much
451 : : * logic as possible out of the critical section, and also ensures that
452 : : * WAL replay will work the same as the normal case.
453 : : *
454 : : * First, initialize the new pd_prune_xid value to zero (indicating no
455 : : * prunable tuples). If we find any tuples which may soon become
456 : : * prunable, we will save the lowest relevant XID in new_prune_xid. Also
457 : : * initialize the rest of our working state.
458 : : */
459 : 625602 : prstate->new_prune_xid = InvalidTransactionId;
460 : 625602 : prstate->latest_xid_removed = InvalidTransactionId;
461 : 625602 : prstate->nredirected = prstate->ndead = prstate->nunused = 0;
462 : 625602 : prstate->nfrozen = 0;
463 : 625602 : prstate->nroot_items = 0;
464 : 625602 : prstate->nheaponly_items = 0;
465 : :
466 : : /* initialize page freezing working state */
467 : 625602 : prstate->pagefrz.freeze_required = false;
468 : 625602 : prstate->pagefrz.FreezePageConflictXid = InvalidTransactionId;
469 [ + + ]: 625602 : if (prstate->attempt_freeze)
470 : : {
471 : : Assert(new_relfrozen_xid && new_relmin_mxid);
472 : 489983 : prstate->pagefrz.FreezePageRelfrozenXid = *new_relfrozen_xid;
473 : 489983 : prstate->pagefrz.NoFreezePageRelfrozenXid = *new_relfrozen_xid;
474 : 489983 : prstate->pagefrz.FreezePageRelminMxid = *new_relmin_mxid;
475 : 489983 : prstate->pagefrz.NoFreezePageRelminMxid = *new_relmin_mxid;
476 : : }
477 : : else
478 : : {
479 : : Assert(!new_relfrozen_xid && !new_relmin_mxid);
480 : 135619 : prstate->pagefrz.FreezePageRelminMxid = InvalidMultiXactId;
481 : 135619 : prstate->pagefrz.NoFreezePageRelminMxid = InvalidMultiXactId;
482 : 135619 : prstate->pagefrz.FreezePageRelfrozenXid = InvalidTransactionId;
483 : 135619 : prstate->pagefrz.NoFreezePageRelfrozenXid = InvalidTransactionId;
484 : : }
485 : :
486 : 625602 : prstate->ndeleted = 0;
487 : 625602 : prstate->live_tuples = 0;
488 : 625602 : prstate->recently_dead_tuples = 0;
489 : 625602 : prstate->hastup = false;
490 : 625602 : prstate->lpdead_items = 0;
491 : :
492 : : /*
493 : : * deadoffsets are filled in during pruning but are only used to populate
494 : : * PruneFreezeResult->deadoffsets. To avoid needing two copies of the
495 : : * array, just save a pointer to the result offsets array in the
496 : : * PruneState.
497 : : */
498 : 625602 : prstate->deadoffsets = presult->deadoffsets;
499 : :
500 : : /*
501 : : * We track whether the page will be all-visible/all-frozen at the end of
502 : : * pruning and freezing. While examining tuple visibility, we'll set
503 : : * set_all_visible to false if there are tuples on the page not visible to
504 : : * all running and future transactions. If setting the VM is enabled for
505 : : * this scan, we will do so if the page ends up being all-visible.
506 : : *
507 : : * We also keep track of the newest live XID, which is used to calculate
508 : : * the snapshot conflict horizon for a WAL record setting the VM.
509 : : */
510 : 625602 : prstate->set_all_visible = prstate->attempt_set_vm;
511 : 625602 : prstate->newest_live_xid = InvalidTransactionId;
512 : :
513 : : /*
514 : : * Currently, only VACUUM performs freezing, but other callers may in the
515 : : * future. We must initialize set_all_frozen based on whether or not the
516 : : * caller passed HEAP_PAGE_PRUNE_FREEZE, because if they did not, we won't
517 : : * call heap_prepare_freeze_tuple() for each tuple, and set_all_frozen
518 : : * will never be cleared for tuples that need freezing. This would lead to
519 : : * incorrectly setting the visibility map all-frozen for this page. We
520 : : * can't set the page all-frozen in the VM if the caller didn't pass
521 : : * HEAP_PAGE_PRUNE_SET_VM.
522 : : *
523 : : * When freezing is not required (no XIDs/MXIDs older than the freeze
524 : : * cutoff), we may still choose to "opportunistically" freeze if doing so
525 : : * would make the page all-frozen.
526 : : *
527 : : * We will not be able to freeze the whole page at the end of vacuum if
528 : : * there are tuples present that are not visible to everyone or if there
529 : : * are dead tuples which will not be removable. However, dead tuples that
530 : : * will be removed by the end of vacuum should not prevent this
531 : : * opportunistic freezing.
532 : : *
533 : : * Therefore, we do not clear set_all_visible and set_all_frozen when we
534 : : * encounter LP_DEAD items. Instead, we correct them after deciding
535 : : * whether to freeze, but before updating the VM, to avoid setting the VM
536 : : * bits incorrectly.
537 : : */
538 [ + + + - ]: 625602 : prstate->set_all_frozen = prstate->attempt_freeze && prstate->attempt_set_vm;
539 : 625602 : }
540 : :
541 : : /*
542 : : * Helper for heap_page_prune_and_freeze(). Iterates over every tuple on the
543 : : * page, examines its visibility information, and determines the appropriate
544 : : * action for each tuple. All tuples are processed and classified during this
545 : : * phase, but no modifications are made to the page until the later execution
546 : : * stage.
547 : : *
548 : : * *off_loc is used for error callback and cleared before returning.
549 : : */
550 : : static void
551 : 427731 : prune_freeze_plan(PruneState *prstate, OffsetNumber *off_loc)
552 : : {
553 : 427731 : Page page = prstate->page;
554 : 427731 : BlockNumber blockno = prstate->block;
555 : 427731 : OffsetNumber maxoff = PageGetMaxOffsetNumber(prstate->page);
556 : : OffsetNumber offnum;
557 : : HeapTupleData tup;
558 : :
559 : 427731 : tup.t_tableOid = RelationGetRelid(prstate->relation);
560 : :
561 : : /*
562 : : * Determine HTSV for all tuples, and queue them up for processing as HOT
563 : : * chain roots or as heap-only items.
564 : : *
565 : : * Determining HTSV only once for each tuple is required for correctness,
566 : : * to deal with cases where running HTSV twice could result in different
567 : : * results. For example, RECENTLY_DEAD can turn to DEAD if another
568 : : * checked item causes GlobalVisTestIsRemovableFullXid() to update the
569 : : * horizon, or INSERT_IN_PROGRESS can change to DEAD if the inserting
570 : : * transaction aborts.
571 : : *
572 : : * It's also good for performance. Most commonly tuples within a page are
573 : : * stored at decreasing offsets (while the items are stored at increasing
574 : : * offsets). When processing all tuples on a page this leads to reading
575 : : * memory at decreasing offsets within a page, with a variable stride.
576 : : * That's hard for CPU prefetchers to deal with. Processing the items in
577 : : * reverse order (and thus the tuples in increasing order) increases
578 : : * prefetching efficiency significantly / decreases the number of cache
579 : : * misses.
580 : : */
581 : 427731 : for (offnum = maxoff;
582 [ + + ]: 29221105 : offnum >= FirstOffsetNumber;
583 : 28793374 : offnum = OffsetNumberPrev(offnum))
584 : : {
585 : 28793374 : ItemId itemid = PageGetItemId(page, offnum);
586 : : HeapTupleHeader htup;
587 : :
588 : : /*
589 : : * Set the offset number so that we can display it along with any
590 : : * error that occurred while processing this tuple.
591 : : */
592 : 28793374 : *off_loc = offnum;
593 : :
594 : 28793374 : prstate->processed[offnum] = false;
595 : 28793374 : prstate->htsv[offnum] = -1;
596 : :
597 : : /* Nothing to do if slot doesn't contain a tuple */
598 [ + + ]: 28793374 : if (!ItemIdIsUsed(itemid))
599 : : {
600 : 208727 : heap_prune_record_unchanged_lp_unused(prstate, offnum);
601 : 208727 : continue;
602 : : }
603 : :
604 [ + + ]: 28584647 : if (ItemIdIsDead(itemid))
605 : : {
606 : : /*
607 : : * If the caller set mark_unused_now true, we can set dead line
608 : : * pointers LP_UNUSED now.
609 : : */
610 [ + + ]: 1769941 : if (unlikely(prstate->mark_unused_now))
611 : 1766 : heap_prune_record_unused(prstate, offnum, false);
612 : : else
613 : 1768175 : heap_prune_record_unchanged_lp_dead(prstate, offnum);
614 : 1769941 : continue;
615 : : }
616 : :
617 [ + + ]: 26814706 : if (ItemIdIsRedirected(itemid))
618 : : {
619 : : /* This is the start of a HOT chain */
620 : 217845 : prstate->root_items[prstate->nroot_items++] = offnum;
621 : 217845 : continue;
622 : : }
623 : :
624 : : Assert(ItemIdIsNormal(itemid));
625 : :
626 : : /*
627 : : * Get the tuple's visibility status and queue it up for processing.
628 : : */
629 : 26596861 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
630 : 26596861 : tup.t_data = htup;
631 : 26596861 : tup.t_len = ItemIdGetLength(itemid);
632 : 26596861 : ItemPointerSet(&tup.t_self, blockno, offnum);
633 : :
634 : 26596861 : prstate->htsv[offnum] = heap_prune_satisfies_vacuum(prstate, &tup);
635 : :
636 [ + + ]: 26596861 : if (!HeapTupleHeaderIsHeapOnly(htup))
637 : 26230729 : prstate->root_items[prstate->nroot_items++] = offnum;
638 : : else
639 : 366132 : prstate->heaponly_items[prstate->nheaponly_items++] = offnum;
640 : : }
641 : :
642 : : /*
643 : : * Process HOT chains.
644 : : *
645 : : * We added the items to the array starting from 'maxoff', so by
646 : : * processing the array in reverse order, we process the items in
647 : : * ascending offset number order. The order doesn't matter for
648 : : * correctness, but some quick micro-benchmarking suggests that this is
649 : : * faster. (Earlier PostgreSQL versions, which scanned all the items on
650 : : * the page instead of using the root_items array, also did it in
651 : : * ascending offset number order.)
652 : : */
653 [ + + ]: 26876305 : for (int i = prstate->nroot_items - 1; i >= 0; i--)
654 : : {
655 : 26448574 : offnum = prstate->root_items[i];
656 : :
657 : : /* Ignore items already processed as part of an earlier chain */
658 [ - + ]: 26448574 : if (prstate->processed[offnum])
659 : 0 : continue;
660 : :
661 : : /* see preceding loop */
662 : 26448574 : *off_loc = offnum;
663 : :
664 : : /* Process this item or chain of items */
665 : 26448574 : heap_prune_chain(maxoff, offnum, prstate);
666 : : }
667 : :
668 : : /*
669 : : * Process any heap-only tuples that were not already processed as part of
670 : : * a HOT chain.
671 : : */
672 [ + + ]: 793863 : for (int i = prstate->nheaponly_items - 1; i >= 0; i--)
673 : : {
674 : 366132 : offnum = prstate->heaponly_items[i];
675 : :
676 [ + + ]: 366132 : if (prstate->processed[offnum])
677 : 348663 : continue;
678 : :
679 : : /* see preceding loop */
680 : 17469 : *off_loc = offnum;
681 : :
682 : : /*
683 : : * If the tuple is DEAD and doesn't chain to anything else, mark it
684 : : * unused. (If it does chain, we can only remove it as part of
685 : : * pruning its chain.)
686 : : *
687 : : * We need this primarily to handle aborted HOT updates, that is,
688 : : * XMIN_INVALID heap-only tuples. Those might not be linked to by any
689 : : * chain, since the parent tuple might be re-updated before any
690 : : * pruning occurs. So we have to be able to reap them separately from
691 : : * chain-pruning. (Note that HeapTupleHeaderIsHotUpdated will never
692 : : * return true for an XMIN_INVALID tuple, so this code will work even
693 : : * when there were sequential updates within the aborted transaction.)
694 : : */
695 [ + + ]: 17469 : if (prstate->htsv[offnum] == HEAPTUPLE_DEAD)
696 : : {
697 : 3456 : ItemId itemid = PageGetItemId(page, offnum);
698 : 3456 : HeapTupleHeader htup = (HeapTupleHeader) PageGetItem(page, itemid);
699 : :
700 [ + - ]: 3456 : if (likely(!HeapTupleHeaderIsHotUpdated(htup)))
701 : : {
702 : 3456 : HeapTupleHeaderAdvanceConflictHorizon(htup,
703 : : &prstate->latest_xid_removed);
704 : 3456 : heap_prune_record_unused(prstate, offnum, true);
705 : : }
706 : : else
707 : : {
708 : : /*
709 : : * This tuple should've been processed and removed as part of
710 : : * a HOT chain, so something's wrong. To preserve evidence,
711 : : * we don't dare to remove it. We cannot leave behind a DEAD
712 : : * tuple either, because that will cause VACUUM to error out.
713 : : * Throwing an error with a distinct error message seems like
714 : : * the least bad option.
715 : : */
716 [ # # ]: 0 : elog(ERROR, "dead heap-only tuple (%u, %d) is not linked to from any HOT chain",
717 : : blockno, offnum);
718 : : }
719 : : }
720 : : else
721 : 14013 : heap_prune_record_unchanged_lp_normal(prstate, offnum);
722 : : }
723 : :
724 : : /* We should now have processed every tuple exactly once */
725 : : #ifdef USE_ASSERT_CHECKING
726 : : for (offnum = FirstOffsetNumber;
727 : : offnum <= maxoff;
728 : : offnum = OffsetNumberNext(offnum))
729 : : {
730 : : *off_loc = offnum;
731 : :
732 : : Assert(prstate->processed[offnum]);
733 : : }
734 : : #endif
735 : :
736 : : /* Clear the offset information once we have processed the given page. */
737 : 427731 : *off_loc = InvalidOffsetNumber;
738 : 427731 : }
739 : :
740 : : /*
741 : : * Decide whether to proceed with freezing according to the freeze plans
742 : : * prepared for the current heap buffer. If freezing is chosen, this function
743 : : * performs several pre-freeze checks.
744 : : *
745 : : * The values of do_prune, do_hint_prune, and did_tuple_hint_fpi must be
746 : : * determined before calling this function.
747 : : *
748 : : * prstate is both an input and output parameter.
749 : : *
750 : : * Returns true if we should apply the freeze plans and freeze tuples on the
751 : : * page, and false otherwise.
752 : : */
753 : : static bool
754 : 427731 : heap_page_will_freeze(bool did_tuple_hint_fpi,
755 : : bool do_prune,
756 : : bool do_hint_prune,
757 : : PruneState *prstate)
758 : : {
759 : 427731 : bool do_freeze = false;
760 : :
761 : : /*
762 : : * If the caller specified we should not attempt to freeze any tuples,
763 : : * validate that everything is in the right state and return.
764 : : */
765 [ + + ]: 427731 : if (!prstate->attempt_freeze)
766 : : {
767 : : Assert(!prstate->set_all_frozen && prstate->nfrozen == 0);
768 : 135521 : return false;
769 : : }
770 : :
771 [ + + ]: 292210 : if (prstate->pagefrz.freeze_required)
772 : : {
773 : : /*
774 : : * heap_prepare_freeze_tuple indicated that at least one XID/MXID from
775 : : * before FreezeLimit/MultiXactCutoff is present. Must freeze to
776 : : * advance relfrozenxid/relminmxid.
777 : : */
778 : 23631 : do_freeze = true;
779 : : }
780 : : else
781 : : {
782 : : /*
783 : : * Opportunistically freeze the page if we are generating an FPI
784 : : * anyway and if doing so means that we can set the page all-frozen
785 : : * afterwards (might not happen until VACUUM's final heap pass).
786 : : *
787 : : * XXX: Previously, we knew if pruning emitted an FPI by checking
788 : : * pgWalUsage.wal_fpi before and after pruning. Once the freeze and
789 : : * prune records were combined, this heuristic couldn't be used
790 : : * anymore. The opportunistic freeze heuristic must be improved;
791 : : * however, for now, try to approximate the old logic.
792 : : */
793 [ + + + + ]: 268579 : if (prstate->set_all_frozen && prstate->nfrozen > 0)
794 : : {
795 : : Assert(prstate->set_all_visible);
796 : :
797 : : /*
798 : : * Freezing would make the page all-frozen. Have already emitted
799 : : * an FPI or will do so anyway?
800 : : */
801 [ + + + + : 23969 : if (RelationNeedsWAL(prstate->relation))
+ - + - ]
802 : : {
803 [ + + ]: 22284 : if (did_tuple_hint_fpi)
804 : 1292 : do_freeze = true;
805 [ + + ]: 20992 : else if (do_prune)
806 : : {
807 [ + + ]: 2501 : if (XLogCheckBufferNeedsBackup(prstate->buffer))
808 : 954 : do_freeze = true;
809 : : }
810 [ + + ]: 18491 : else if (do_hint_prune)
811 : : {
812 [ + + + - : 22260 : if (XLogHintBitIsNeeded() &&
+ + ]
813 : 11130 : XLogCheckBufferNeedsBackup(prstate->buffer))
814 : 2011 : do_freeze = true;
815 : : }
816 : : }
817 : : }
818 : : }
819 : :
820 [ + + ]: 292210 : if (do_freeze)
821 : : {
822 : : /*
823 : : * Validate the tuples we will be freezing before entering the
824 : : * critical section.
825 : : */
826 : 27888 : heap_pre_freeze_checks(prstate->buffer, prstate->frozen, prstate->nfrozen);
827 : : Assert(TransactionIdPrecedes(prstate->pagefrz.FreezePageConflictXid,
828 : : prstate->cutoffs->OldestXmin));
829 : : }
830 [ + + ]: 264322 : else if (prstate->nfrozen > 0)
831 : : {
832 : : /*
833 : : * The page contained some tuples that were not already frozen, and we
834 : : * chose not to freeze them now. The page won't be all-frozen then.
835 : : */
836 : : Assert(!prstate->pagefrz.freeze_required);
837 : :
838 : 20272 : prstate->set_all_frozen = false;
839 : 20272 : prstate->nfrozen = 0; /* avoid miscounts in instrumentation */
840 : : }
841 : : else
842 : : {
843 : : /*
844 : : * We have no freeze plans to execute. The page might already be
845 : : * all-frozen (perhaps only following pruning), though. Such pages
846 : : * can be marked all-frozen in the VM by our caller, even though none
847 : : * of its tuples were newly frozen here.
848 : : */
849 : : }
850 : :
851 : 292210 : return do_freeze;
852 : : }
853 : :
854 : : /*
855 : : * Emit a warning about and fix visibility map corruption on the given page.
856 : : *
857 : : * The caller specifies the type of corruption it has already detected via
858 : : * corruption_type, so that we can emit the appropriate warning. All cases
859 : : * result in the VM bits being cleared; corruption types where PD_ALL_VISIBLE
860 : : * is incorrectly set also clear PD_ALL_VISIBLE.
861 : : *
862 : : * Must be called while holding an exclusive lock on the heap buffer. Dead
863 : : * items and not all-visible tuples must have been discovered under that same
864 : : * lock. Although we do not hold a lock on the VM buffer, it is pinned, and
865 : : * the heap buffer is exclusively locked, ensuring that no other backend can
866 : : * update the VM bits corresponding to this heap page.
867 : : *
868 : : * This function makes changes to the VM and, potentially, the heap page, but
869 : : * it does not need to be done in a critical section.
870 : : */
871 : : static void
872 : 0 : heap_page_fix_vm_corruption(PruneState *prstate, OffsetNumber offnum,
873 : : VMCorruptionType corruption_type)
874 : : {
875 : 0 : const char *relname = RelationGetRelationName(prstate->relation);
876 : 0 : bool do_clear_vm = false;
877 : 0 : bool do_clear_heap = false;
878 : :
879 : : Assert(BufferIsLockedByMeInMode(prstate->buffer, BUFFER_LOCK_EXCLUSIVE));
880 : :
881 [ # # # # ]: 0 : switch (corruption_type)
882 : : {
883 : 0 : case VM_CORRUPT_LPDEAD:
884 [ # # ]: 0 : ereport(WARNING,
885 : : (errcode(ERRCODE_DATA_CORRUPTED),
886 : : errmsg("dead line pointer found on page marked all-visible"),
887 : : errcontext("relation \"%s\", page %u, tuple %u",
888 : : relname, prstate->block, offnum)));
889 : 0 : do_clear_vm = true;
890 : 0 : do_clear_heap = true;
891 : 0 : break;
892 : :
893 : 0 : case VM_CORRUPT_TUPLE_VISIBILITY:
894 : :
895 : : /*
896 : : * A HEAPTUPLE_LIVE tuple on an all-visible page can appear to not
897 : : * be visible to everyone when
898 : : * GetOldestNonRemovableTransactionId() returns a conservative
899 : : * value that's older than the real safe xmin. That is not
900 : : * corruption -- the PD_ALL_VISIBLE flag is still correct.
901 : : *
902 : : * However, dead tuple versions, in-progress inserts, and
903 : : * in-progress deletes should never appear on a page marked
904 : : * all-visible. That indicates real corruption. PD_ALL_VISIBLE
905 : : * should have been cleared by the DML operation that deleted or
906 : : * inserted the tuple.
907 : : */
908 [ # # ]: 0 : ereport(WARNING,
909 : : (errcode(ERRCODE_DATA_CORRUPTED),
910 : : errmsg("tuple not visible to all transactions found on page marked all-visible"),
911 : : errcontext("relation \"%s\", page %u, tuple %u",
912 : : relname, prstate->block, offnum)));
913 : 0 : do_clear_vm = true;
914 : 0 : do_clear_heap = true;
915 : 0 : break;
916 : :
917 : 0 : case VM_CORRUPT_MISSING_PAGE_HINT:
918 : :
919 : : /*
920 : : * As of PostgreSQL 9.2, the visibility map bit should never be
921 : : * set if the page-level bit is clear. However, for vacuum, it's
922 : : * possible that the bit got cleared after
923 : : * heap_vac_scan_next_block() was called, so we must recheck now
924 : : * that we have the buffer lock before concluding that the VM is
925 : : * corrupt.
926 : : */
927 : : Assert(!PageIsAllVisible(prstate->page));
928 : : Assert(prstate->old_vmbits & VISIBILITYMAP_VALID_BITS);
929 [ # # ]: 0 : ereport(WARNING,
930 : : (errcode(ERRCODE_DATA_CORRUPTED),
931 : : errmsg("page is not marked all-visible but visibility map bit is set"),
932 : : errcontext("relation \"%s\", page %u",
933 : : relname, prstate->block)));
934 : 0 : do_clear_vm = true;
935 : 0 : break;
936 : : }
937 : :
938 : : Assert(do_clear_heap || do_clear_vm);
939 : :
940 : : /* Avoid marking the buffer dirty if PD_ALL_VISIBLE is already clear */
941 [ # # ]: 0 : if (do_clear_heap)
942 : : {
943 : : Assert(PageIsAllVisible(prstate->page));
944 : 0 : PageClearAllVisible(prstate->page);
945 : 0 : MarkBufferDirtyHint(prstate->buffer, true);
946 : : }
947 : :
948 [ # # ]: 0 : if (do_clear_vm)
949 : : {
950 : 0 : LockBuffer(prstate->vmbuffer, BUFFER_LOCK_EXCLUSIVE);
951 : : /* This VM clear is not WAL-logged, so its return value is not needed. */
952 : 0 : (void) visibilitymap_clear(prstate->relation->rd_locator,
953 : : prstate->block, prstate->vmbuffer,
954 : : VISIBILITYMAP_VALID_BITS);
955 : 0 : LockBuffer(prstate->vmbuffer, BUFFER_LOCK_UNLOCK);
956 : 0 : prstate->old_vmbits = 0;
957 : : }
958 : 0 : }
959 : :
960 : : /*
961 : : * Decide whether to set the visibility map bits (all-visible and all-frozen)
962 : : * for the current page using information from the PruneState and VM.
963 : : *
964 : : * This function does not actually set the VM bits or page-level visibility
965 : : * hint, PD_ALL_VISIBLE.
966 : : *
967 : : * This should be called only after do_freeze has been decided (and do_prune
968 : : * has been set), as these factor into our heuristic-based decision.
969 : : *
970 : : * Returns true if one or both VM bits should be set and false otherwise.
971 : : */
972 : : static bool
973 : 427731 : heap_page_will_set_vm(PruneState *prstate, PruneReason reason,
974 : : bool do_prune, bool do_freeze)
975 : : {
976 [ + + ]: 427731 : if (!prstate->attempt_set_vm)
977 : 97722 : return false;
978 : :
979 [ + + ]: 330009 : if (!prstate->set_all_visible)
980 : 250683 : return false;
981 : :
982 : : /*
983 : : * If this is an on-access call and we're not actually pruning, avoid
984 : : * setting the visibility map if it would newly dirty the heap page or, if
985 : : * the page is already dirty, if doing so would require including a
986 : : * full-page image (FPI) of the heap page in the WAL.
987 : : */
988 [ + + + + : 79326 : if (reason == PRUNE_ON_ACCESS && !do_prune && !do_freeze &&
+ - ]
989 [ + + + + ]: 29170 : (!BufferIsDirty(prstate->buffer) || XLogCheckBufferNeedsBackup(prstate->buffer)))
990 : : {
991 : 15569 : prstate->set_all_visible = prstate->set_all_frozen = false;
992 : 15569 : return false;
993 : : }
994 : :
995 : 63757 : prstate->new_vmbits = VISIBILITYMAP_ALL_VISIBLE;
996 : :
997 [ + + ]: 63757 : if (prstate->set_all_frozen)
998 : 34872 : prstate->new_vmbits |= VISIBILITYMAP_ALL_FROZEN;
999 : :
1000 [ + + ]: 63757 : if (prstate->new_vmbits == prstate->old_vmbits)
1001 : : {
1002 : 1740 : prstate->new_vmbits = 0;
1003 : 1740 : return false;
1004 : : }
1005 : :
1006 : 62017 : return true;
1007 : : }
1008 : :
1009 : : /*
1010 : : * If the page is already all-frozen, or already all-visible and freezing
1011 : : * won't be attempted, there is no remaining work and we can use the fast path
1012 : : * to avoid the expensive overhead of heap_page_prune_and_freeze().
1013 : : *
1014 : : * This can happen when the page has a stale prune hint, or if VACUUM is
1015 : : * scanning an already all-frozen page due to SKIP_PAGES_THRESHOLD.
1016 : : *
1017 : : * The caller must already have examined the visibility map and saved the
1018 : : * status of the page's VM bits in prstate->old_vmbits. Caller must hold a
1019 : : * content lock on the heap page since it will examine line pointers.
1020 : : *
1021 : : * Before calling prune_freeze_fast_path(), the caller should first
1022 : : * check for and fix any discrepancy between the page-level visibility hint
1023 : : * and the visibility map. Otherwise, the fast path will always prevent us
1024 : : * from getting them in sync. Note that if there are tuples on the page that
1025 : : * are not visible to all but the VM is incorrectly marked
1026 : : * all-visible/all-frozen, we will not get the chance to fix that corruption
1027 : : * when using the fast path.
1028 : : */
1029 : : static void
1030 : 197871 : prune_freeze_fast_path(PruneState *prstate, PruneFreezeResult *presult)
1031 : : {
1032 : 197871 : OffsetNumber maxoff = PageGetMaxOffsetNumber(prstate->page);
1033 : 197871 : Page page = prstate->page;
1034 : :
1035 : : Assert((prstate->old_vmbits & VISIBILITYMAP_ALL_FROZEN) ||
1036 : : ((prstate->old_vmbits & VISIBILITYMAP_ALL_VISIBLE) &&
1037 : : !prstate->attempt_freeze));
1038 : :
1039 : : /* We'll fill in presult for the caller */
1040 : 197871 : memset(presult, 0, sizeof(PruneFreezeResult));
1041 : :
1042 : : /* Clear any stale prune hint */
1043 [ + + ]: 197871 : if (TransactionIdIsValid(PageGetPruneXid(page)))
1044 : : {
1045 : 98 : PageClearPrunable(page);
1046 : 98 : MarkBufferDirtyHint(prstate->buffer, true);
1047 : : }
1048 : :
1049 [ - + ]: 197871 : if (PageIsEmpty(page))
1050 : 0 : return;
1051 : :
1052 : : /*
1053 : : * Since the page is all-visible, a count of the normal ItemIds on the
1054 : : * page should be sufficient for vacuum's live tuple count.
1055 : : */
1056 : 197871 : for (OffsetNumber off = FirstOffsetNumber;
1057 [ + + ]: 11455711 : off <= maxoff;
1058 : 11257840 : off = OffsetNumberNext(off))
1059 : : {
1060 : 11257840 : ItemId lp = PageGetItemId(page, off);
1061 : :
1062 [ + + ]: 11257840 : if (!ItemIdIsUsed(lp))
1063 : 183444 : continue;
1064 : :
1065 : 11074396 : presult->hastup = true;
1066 : :
1067 [ + + ]: 11074396 : if (ItemIdIsNormal(lp))
1068 : 10874518 : prstate->live_tuples++;
1069 : : }
1070 : :
1071 : 197871 : presult->live_tuples = prstate->live_tuples;
1072 : : }
1073 : :
1074 : : /*
1075 : : * Prune and repair fragmentation and potentially freeze tuples on the
1076 : : * specified page. If the page's visibility status has changed, update it in
1077 : : * the VM.
1078 : : *
1079 : : * Caller must have pin and buffer cleanup lock on the page. Note that we
1080 : : * don't update the FSM information for page on caller's behalf. Caller might
1081 : : * also need to account for a reduction in the length of the line pointer
1082 : : * array following array truncation by us.
1083 : : *
1084 : : * params contains the input parameters used to control freezing and pruning
1085 : : * behavior. See the definition of PruneFreezeParams for more on what each
1086 : : * parameter does.
1087 : : *
1088 : : * If the HEAP_PAGE_PRUNE_FREEZE option is set in params, we will freeze
1089 : : * tuples if it's required in order to advance relfrozenxid / relminmxid, or
1090 : : * if it's considered advantageous for overall system performance to do so
1091 : : * now. The 'params.cutoffs', 'presult', 'new_relfrozen_xid' and
1092 : : * 'new_relmin_mxid' arguments are required when freezing.
1093 : : *
1094 : : * A vmbuffer corresponding to the heap page is also passed and if the page is
1095 : : * found to be all-visible/all-frozen, we will set it in the VM.
1096 : : *
1097 : : * presult contains output parameters needed by callers, such as the number of
1098 : : * tuples removed and the offsets of dead items on the page after pruning.
1099 : : * heap_page_prune_and_freeze() is responsible for initializing it. Required
1100 : : * by all callers.
1101 : : *
1102 : : * off_loc is the offset location required by the caller to use in error
1103 : : * callback.
1104 : : *
1105 : : * new_relfrozen_xid and new_relmin_mxid must be provided by the caller if the
1106 : : * HEAP_PAGE_PRUNE_FREEZE option is set in params. On entry, they contain the
1107 : : * oldest XID and multi-XID seen on the relation so far. They will be updated
1108 : : * with the oldest values present on the page after pruning. After processing
1109 : : * the whole relation, VACUUM can use these values as the new
1110 : : * relfrozenxid/relminmxid for the relation.
1111 : : */
1112 : : void
1113 : 625602 : heap_page_prune_and_freeze(PruneFreezeParams *params,
1114 : : PruneFreezeResult *presult,
1115 : : OffsetNumber *off_loc,
1116 : : TransactionId *new_relfrozen_xid,
1117 : : MultiXactId *new_relmin_mxid)
1118 : : {
1119 : : PruneState prstate;
1120 : : bool do_freeze;
1121 : : bool do_prune;
1122 : : bool do_hint_prune;
1123 : : bool do_set_vm;
1124 : : bool did_tuple_hint_fpi;
1125 : 625602 : int64 fpi_before = pgWalUsage.wal_fpi;
1126 : : TransactionId conflict_xid;
1127 : :
1128 : : /* Initialize prstate */
1129 : 625602 : prune_freeze_setup(params,
1130 : : new_relfrozen_xid, new_relmin_mxid,
1131 : : presult, &prstate);
1132 : :
1133 : : /*
1134 : : * If the VM is set but PD_ALL_VISIBLE is clear, fix that corruption
1135 : : * before pruning and freezing so that the page and VM start out in a
1136 : : * consistent state.
1137 : : */
1138 [ + + ]: 625602 : if ((prstate.old_vmbits & VISIBILITYMAP_VALID_BITS) &&
1139 [ - + ]: 203157 : !PageIsAllVisible(prstate.page))
1140 : 0 : heap_page_fix_vm_corruption(&prstate, InvalidOffsetNumber,
1141 : : VM_CORRUPT_MISSING_PAGE_HINT);
1142 : :
1143 : : /*
1144 : : * If the page is already all-frozen, or already all-visible when freezing
1145 : : * is not being attempted, take the fast path, skipping pruning and
1146 : : * freezing code entirely. This must be done after fixing any discrepancy
1147 : : * between the page-level visibility hint and the VM, since that may have
1148 : : * cleared old_vmbits.
1149 : : */
1150 [ + + ]: 625602 : if ((params->options & HEAP_PAGE_PRUNE_ALLOW_FAST_PATH) != 0 &&
1151 [ + + ]: 624290 : ((prstate.old_vmbits & VISIBILITYMAP_ALL_FROZEN) ||
1152 [ + + ]: 426419 : ((prstate.old_vmbits & VISIBILITYMAP_ALL_VISIBLE) &&
1153 [ - + ]: 4827 : !prstate.attempt_freeze)))
1154 : : {
1155 : 197871 : prune_freeze_fast_path(&prstate, presult);
1156 : 197871 : return;
1157 : : }
1158 : :
1159 : : /*
1160 : : * Examine all line pointers and tuple visibility information to determine
1161 : : * which line pointers should change state and which tuples may be frozen.
1162 : : * Prepare queue of state changes to later be executed in a critical
1163 : : * section.
1164 : : */
1165 : 427731 : prune_freeze_plan(&prstate, off_loc);
1166 : :
1167 : : /*
1168 : : * After processing all the live tuples on the page, if the newest xmin
1169 : : * amongst them may be considered running by any snapshot, the page cannot
1170 : : * be all-visible. This should be done before determining whether or not
1171 : : * to opportunistically freeze.
1172 : : */
1173 [ + + ]: 427731 : if (prstate.set_all_visible &&
1174 [ + + + + ]: 192748 : TransactionIdIsNormal(prstate.newest_live_xid) &&
1175 : 81903 : GlobalVisTestXidConsideredRunning(prstate.vistest,
1176 : : prstate.newest_live_xid,
1177 : : true))
1178 : 2833 : prstate.set_all_visible = prstate.set_all_frozen = false;
1179 : :
1180 : : /*
1181 : : * If checksums are enabled, calling heap_prune_satisfies_vacuum() while
1182 : : * checking tuple visibility information in prune_freeze_plan() may have
1183 : : * caused an FPI to be emitted.
1184 : : */
1185 : 427731 : did_tuple_hint_fpi = fpi_before != pgWalUsage.wal_fpi;
1186 : :
1187 : 1264235 : do_prune = prstate.nredirected > 0 ||
1188 [ + + + + ]: 781688 : prstate.ndead > 0 ||
1189 [ + + ]: 353957 : prstate.nunused > 0;
1190 : :
1191 : : /*
1192 : : * Even if we don't prune anything, if we found a new value for the
1193 : : * pd_prune_xid field or the page was marked full, we will update the hint
1194 : : * bit.
1195 : : */
1196 [ + + + + ]: 675517 : do_hint_prune = PageGetPruneXid(prstate.page) != prstate.new_prune_xid ||
1197 : 247786 : PageIsFull(prstate.page);
1198 : :
1199 : : /*
1200 : : * Decide if we want to go ahead with freezing according to the freeze
1201 : : * plans we prepared, or not.
1202 : : */
1203 : 427731 : do_freeze = heap_page_will_freeze(did_tuple_hint_fpi,
1204 : : do_prune,
1205 : : do_hint_prune,
1206 : : &prstate);
1207 : :
1208 : : /*
1209 : : * While scanning the line pointers, we did not clear
1210 : : * set_all_visible/set_all_frozen when encountering LP_DEAD items because
1211 : : * we wanted the decision whether or not to freeze the page to be
1212 : : * unaffected by the short-term presence of LP_DEAD items. These LP_DEAD
1213 : : * items are effectively assumed to be LP_UNUSED items in the making. It
1214 : : * doesn't matter which vacuum heap pass (initial pass or final pass) ends
1215 : : * up setting the page all-frozen, as long as the ongoing VACUUM does it.
1216 : : *
1217 : : * Now that we finished determining whether or not to freeze the page,
1218 : : * update set_all_visible and set_all_frozen so that they reflect the true
1219 : : * state of the page for setting PD_ALL_VISIBLE and VM bits.
1220 : : */
1221 [ + + ]: 427731 : if (prstate.lpdead_items > 0)
1222 : 76601 : prstate.set_all_visible = prstate.set_all_frozen = false;
1223 : :
1224 : : Assert(!prstate.set_all_frozen || prstate.set_all_visible);
1225 : : Assert(!prstate.set_all_visible || prstate.attempt_set_vm);
1226 : : Assert(!prstate.set_all_visible || (prstate.lpdead_items == 0));
1227 : :
1228 : 427731 : do_set_vm = heap_page_will_set_vm(&prstate, params->reason, do_prune, do_freeze);
1229 : :
1230 : : /*
1231 : : * new_vmbits should be 0 regardless of whether or not the page is
1232 : : * all-visible if we do not intend to set the VM.
1233 : : */
1234 : : Assert(do_set_vm || prstate.new_vmbits == 0);
1235 : :
1236 : : /*
1237 : : * The snapshot conflict horizon for the whole record is the most
1238 : : * conservative (newest) horizon required by any change in the record.
1239 : : */
1240 : 427731 : conflict_xid = InvalidTransactionId;
1241 [ + + ]: 427731 : if (do_set_vm)
1242 : 62017 : conflict_xid = prstate.newest_live_xid;
1243 [ + + + + ]: 427731 : if (do_freeze && TransactionIdFollows(prstate.pagefrz.FreezePageConflictXid, conflict_xid))
1244 : 4650 : conflict_xid = prstate.pagefrz.FreezePageConflictXid;
1245 [ + + + + ]: 427731 : if (do_prune && TransactionIdFollows(prstate.latest_xid_removed, conflict_xid))
1246 : 66070 : conflict_xid = prstate.latest_xid_removed;
1247 : :
1248 : : /* Lock vmbuffer before entering a critical section */
1249 [ + + ]: 427731 : if (do_set_vm)
1250 : 62017 : LockBuffer(prstate.vmbuffer, BUFFER_LOCK_EXCLUSIVE);
1251 : :
1252 : : /* Any error while applying the changes is critical */
1253 : 427731 : START_CRIT_SECTION();
1254 : :
1255 [ + + ]: 427731 : if (do_hint_prune)
1256 : : {
1257 : : /*
1258 : : * Update the page's pd_prune_xid field to either zero, or the lowest
1259 : : * XID of any soon-prunable tuple.
1260 : : */
1261 : 180076 : ((PageHeader) prstate.page)->pd_prune_xid = prstate.new_prune_xid;
1262 : :
1263 : : /*
1264 : : * Also clear the "page is full" flag, since there's no point in
1265 : : * repeating the prune/defrag process until something else happens to
1266 : : * the page.
1267 : : */
1268 : 180076 : PageClearFull(prstate.page);
1269 : :
1270 : : /*
1271 : : * If that's all we had to do to the page, this is a non-WAL-logged
1272 : : * hint. If we are going to freeze or prune the page or set
1273 : : * PD_ALL_VISIBLE, we will mark the buffer dirty below.
1274 : : *
1275 : : * Setting PD_ALL_VISIBLE is fully WAL-logged because it is forbidden
1276 : : * for the VM to be set and PD_ALL_VISIBLE to be clear.
1277 : : */
1278 [ + + + + : 180076 : if (!do_freeze && !do_prune && !do_set_vm)
+ + ]
1279 : 67381 : MarkBufferDirtyHint(prstate.buffer, true);
1280 : : }
1281 : :
1282 [ + + + + : 427731 : if (do_prune || do_freeze || do_set_vm)
+ + ]
1283 : : {
1284 : : /* Apply the planned item changes and repair page fragmentation. */
1285 [ + + ]: 137926 : if (do_prune)
1286 : : {
1287 : 74215 : heap_page_prune_execute(prstate.buffer, false,
1288 : : prstate.redirected, prstate.nredirected,
1289 : : prstate.nowdead, prstate.ndead,
1290 : : prstate.nowunused, prstate.nunused);
1291 : : }
1292 : :
1293 [ + + ]: 137926 : if (do_freeze)
1294 : 27888 : heap_freeze_prepared_tuples(prstate.buffer, prstate.frozen, prstate.nfrozen);
1295 : :
1296 : : /* Set the visibility map and page visibility hint */
1297 [ + + ]: 137926 : if (do_set_vm)
1298 : : {
1299 : : /*
1300 : : * While it is valid for PD_ALL_VISIBLE to be set when the
1301 : : * corresponding VM bit is clear, we strongly prefer to keep them
1302 : : * in sync.
1303 : : *
1304 : : * The heap buffer must be marked dirty before adding it to the
1305 : : * WAL chain when setting the VM. We don't worry about
1306 : : * unnecessarily dirtying the heap buffer if PD_ALL_VISIBLE is
1307 : : * already set, though. It is extremely rare to have a clean heap
1308 : : * buffer with PD_ALL_VISIBLE already set and the VM bits clear,
1309 : : * so there is no point in optimizing it.
1310 : : */
1311 : 62017 : PageSetAllVisible(prstate.page);
1312 : 62017 : PageClearPrunable(prstate.page);
1313 : 62017 : visibilitymap_set(prstate.block, prstate.vmbuffer, prstate.new_vmbits,
1314 : 62017 : prstate.relation->rd_locator);
1315 : : }
1316 : :
1317 : 137926 : MarkBufferDirty(prstate.buffer);
1318 : :
1319 : : /*
1320 : : * Emit a WAL XLOG_HEAP2_PRUNE* record showing what we did
1321 : : */
1322 [ + + + + : 137926 : if (RelationNeedsWAL(prstate.relation))
+ - + - ]
1323 : : {
1324 [ + + + + ]: 195587 : log_heap_prune_and_freeze(prstate.relation, prstate.buffer,
1325 : : do_set_vm ? prstate.vmbuffer : InvalidBuffer,
1326 : 60393 : do_set_vm ? prstate.new_vmbits : 0,
1327 : : conflict_xid,
1328 : : true, /* cleanup lock */
1329 : : params->reason,
1330 : : prstate.frozen, prstate.nfrozen,
1331 : : prstate.redirected, prstate.nredirected,
1332 : : prstate.nowdead, prstate.ndead,
1333 : : prstate.nowunused, prstate.nunused);
1334 : : }
1335 : : }
1336 : :
1337 : 427731 : END_CRIT_SECTION();
1338 : :
1339 [ + + ]: 427731 : if (do_set_vm)
1340 : 62017 : LockBuffer(prstate.vmbuffer, BUFFER_LOCK_UNLOCK);
1341 : :
1342 : : /*
1343 : : * During its second pass over the heap, VACUUM calls
1344 : : * heap_page_would_be_all_visible() to determine whether a page is
1345 : : * all-visible and all-frozen. The logic here is similar. After completing
1346 : : * pruning and freezing, use an assertion to verify that our results
1347 : : * remain consistent with heap_page_would_be_all_visible(). It's also a
1348 : : * valuable cross-check of the page state after pruning and freezing.
1349 : : */
1350 : : #ifdef USE_ASSERT_CHECKING
1351 : : if (prstate.set_all_visible)
1352 : : {
1353 : : TransactionId debug_cutoff;
1354 : : bool debug_all_frozen;
1355 : :
1356 : : Assert(prstate.lpdead_items == 0);
1357 : :
1358 : : Assert(heap_page_is_all_visible(prstate.relation, prstate.buffer,
1359 : : prstate.vistest,
1360 : : &debug_all_frozen,
1361 : : &debug_cutoff, off_loc));
1362 : :
1363 : : Assert(!TransactionIdIsValid(debug_cutoff) ||
1364 : : debug_cutoff == prstate.newest_live_xid);
1365 : :
1366 : : /*
1367 : : * It's possible the page is composed entirely of frozen tuples but is
1368 : : * not set all-frozen in the VM and did not pass
1369 : : * HEAP_PAGE_PRUNE_FREEZE. In this case, it's possible
1370 : : * heap_page_is_all_visible() finds the page completely frozen, even
1371 : : * though prstate.set_all_frozen is false.
1372 : : */
1373 : : Assert(!prstate.set_all_frozen || debug_all_frozen);
1374 : : }
1375 : : #endif
1376 : :
1377 : : /* Copy information back for caller */
1378 : 427731 : presult->ndeleted = prstate.ndeleted;
1379 : 427731 : presult->nnewlpdead = prstate.ndead;
1380 : 427731 : presult->nfrozen = prstate.nfrozen;
1381 : 427731 : presult->live_tuples = prstate.live_tuples;
1382 : 427731 : presult->recently_dead_tuples = prstate.recently_dead_tuples;
1383 : 427731 : presult->hastup = prstate.hastup;
1384 : :
1385 : 427731 : presult->lpdead_items = prstate.lpdead_items;
1386 : : /* the presult->deadoffsets array was already filled in */
1387 : :
1388 : 427731 : presult->newly_all_visible = false;
1389 : 427731 : presult->newly_all_frozen = false;
1390 : 427731 : presult->newly_all_visible_frozen = false;
1391 [ + + ]: 427731 : if (do_set_vm)
1392 : : {
1393 [ + + ]: 62017 : if ((prstate.old_vmbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
1394 : : {
1395 : 58471 : presult->newly_all_visible = true;
1396 [ + + ]: 58471 : if (prstate.set_all_frozen)
1397 : 30868 : presult->newly_all_visible_frozen = true;
1398 : : }
1399 [ + - ]: 3546 : else if ((prstate.old_vmbits & VISIBILITYMAP_ALL_FROZEN) == 0 &&
1400 [ + - ]: 3546 : prstate.set_all_frozen)
1401 : 3546 : presult->newly_all_frozen = true;
1402 : : }
1403 : :
1404 [ + + ]: 427731 : if (prstate.attempt_freeze)
1405 : : {
1406 [ + + ]: 292210 : if (presult->nfrozen > 0)
1407 : : {
1408 : 27888 : *new_relfrozen_xid = prstate.pagefrz.FreezePageRelfrozenXid;
1409 : 27888 : *new_relmin_mxid = prstate.pagefrz.FreezePageRelminMxid;
1410 : : }
1411 : : else
1412 : : {
1413 : 264322 : *new_relfrozen_xid = prstate.pagefrz.NoFreezePageRelfrozenXid;
1414 : 264322 : *new_relmin_mxid = prstate.pagefrz.NoFreezePageRelminMxid;
1415 : : }
1416 : : }
1417 : : }
1418 : :
1419 : :
1420 : : /*
1421 : : * Perform visibility checks for heap pruning.
1422 : : */
1423 : : static HTSV_Result
1424 : 26596861 : heap_prune_satisfies_vacuum(PruneState *prstate, HeapTuple tup)
1425 : : {
1426 : : HTSV_Result res;
1427 : : TransactionId dead_after;
1428 : :
1429 : 26596861 : res = HeapTupleSatisfiesVacuumHorizon(tup, prstate->buffer, &dead_after);
1430 : :
1431 [ + + ]: 26596861 : if (res != HEAPTUPLE_RECENTLY_DEAD)
1432 : 22306242 : return res;
1433 : :
1434 : : /*
1435 : : * For VACUUM, we must be sure to prune tuples with xmax older than
1436 : : * OldestXmin -- a visibility cutoff determined at the beginning of
1437 : : * vacuuming the relation. OldestXmin is used for freezing determination
1438 : : * and we cannot freeze dead tuples' xmaxes.
1439 : : */
1440 [ + + ]: 4290619 : if (prstate->cutoffs &&
1441 [ + - ]: 1265487 : TransactionIdIsValid(prstate->cutoffs->OldestXmin) &&
1442 [ + + ]: 1265487 : NormalTransactionIdPrecedes(dead_after, prstate->cutoffs->OldestXmin))
1443 : 932839 : return HEAPTUPLE_DEAD;
1444 : :
1445 : : /*
1446 : : * Determine whether or not the tuple is considered dead when compared
1447 : : * with the provided GlobalVisState. On-access pruning does not provide
1448 : : * VacuumCutoffs. And for vacuum, even if the tuple's xmax is not older
1449 : : * than OldestXmin, GlobalVisTestIsRemovableXid() could find the row dead
1450 : : * if the GlobalVisState has been updated since the beginning of vacuuming
1451 : : * the relation.
1452 : : */
1453 [ + + ]: 3357780 : if (GlobalVisTestIsRemovableXid(prstate->vistest, dead_after, true))
1454 : 2967537 : return HEAPTUPLE_DEAD;
1455 : :
1456 : 390243 : return res;
1457 : : }
1458 : :
1459 : :
1460 : : /*
1461 : : * Pruning calculates tuple visibility once and saves the results in an array
1462 : : * of int8. See PruneState.htsv for details. This helper function is meant
1463 : : * to guard against examining visibility status array members which have not
1464 : : * yet been computed.
1465 : : */
1466 : : static inline HTSV_Result
1467 : 26579392 : htsv_get_valid_status(int status)
1468 : : {
1469 : : Assert(status >= HEAPTUPLE_DEAD &&
1470 : : status <= HEAPTUPLE_DELETE_IN_PROGRESS);
1471 : 26579392 : return (HTSV_Result) status;
1472 : : }
1473 : :
1474 : : /*
1475 : : * Prune specified line pointer or a HOT chain originating at line pointer.
1476 : : *
1477 : : * Tuple visibility information is provided in prstate->htsv.
1478 : : *
1479 : : * If the item is an index-referenced tuple (i.e. not a heap-only tuple),
1480 : : * the HOT chain is pruned by removing all DEAD tuples at the start of the HOT
1481 : : * chain. We also prune any RECENTLY_DEAD tuples preceding a DEAD tuple.
1482 : : * This is OK because a RECENTLY_DEAD tuple preceding a DEAD tuple is really
1483 : : * DEAD, our visibility test is just too coarse to detect it.
1484 : : *
1485 : : * Pruning must never leave behind a DEAD tuple that still has tuple storage.
1486 : : * VACUUM isn't prepared to deal with that case.
1487 : : *
1488 : : * The root line pointer is redirected to the tuple immediately after the
1489 : : * latest DEAD tuple. If all tuples in the chain are DEAD, the root line
1490 : : * pointer is marked LP_DEAD. (This includes the case of a DEAD simple
1491 : : * tuple, which we treat as a chain of length 1.)
1492 : : *
1493 : : * We don't actually change the page here. We just add entries to the arrays in
1494 : : * prstate showing the changes to be made. Items to be redirected are added
1495 : : * to the redirected[] array (two entries per redirection); items to be set to
1496 : : * LP_DEAD state are added to nowdead[]; and items to be set to LP_UNUSED
1497 : : * state are added to nowunused[]. We perform bookkeeping of live tuples,
1498 : : * visibility etc. based on what the page will look like after the changes
1499 : : * applied. All that bookkeeping is performed in the heap_prune_record_*()
1500 : : * subroutines. The division of labor is that heap_prune_chain() decides the
1501 : : * fate of each tuple, ie. whether it's going to be removed, redirected or
1502 : : * left unchanged, and the heap_prune_record_*() subroutines update PruneState
1503 : : * based on that outcome.
1504 : : */
1505 : : static void
1506 : 26448574 : heap_prune_chain(OffsetNumber maxoff, OffsetNumber rootoffnum,
1507 : : PruneState *prstate)
1508 : : {
1509 : 26448574 : TransactionId priorXmax = InvalidTransactionId;
1510 : : ItemId rootlp;
1511 : : OffsetNumber offnum;
1512 : : OffsetNumber chainitems[MaxHeapTuplesPerPage];
1513 : 26448574 : Page page = prstate->page;
1514 : :
1515 : : /*
1516 : : * After traversing the HOT chain, ndeadchain is the index in chainitems
1517 : : * of the first live successor after the last dead item.
1518 : : */
1519 : 26448574 : int ndeadchain = 0,
1520 : 26448574 : nchain = 0;
1521 : :
1522 : 26448574 : rootlp = PageGetItemId(page, rootoffnum);
1523 : :
1524 : : /* Start from the root tuple */
1525 : 26448574 : offnum = rootoffnum;
1526 : :
1527 : : /* while not end of the chain */
1528 : : for (;;)
1529 : 348663 : {
1530 : : HeapTupleHeader htup;
1531 : : ItemId lp;
1532 : :
1533 : : /* Sanity check (pure paranoia) */
1534 [ - + ]: 26797237 : if (offnum < FirstOffsetNumber)
1535 : 0 : break;
1536 : :
1537 : : /*
1538 : : * An offset past the end of page's line pointer array is possible
1539 : : * when the array was truncated (original item must have been unused)
1540 : : */
1541 [ - + ]: 26797237 : if (offnum > maxoff)
1542 : 0 : break;
1543 : :
1544 : : /* If item is already processed, stop --- it must not be same chain */
1545 [ - + ]: 26797237 : if (prstate->processed[offnum])
1546 : 0 : break;
1547 : :
1548 : 26797237 : lp = PageGetItemId(page, offnum);
1549 : :
1550 : : /*
1551 : : * Unused item obviously isn't part of the chain. Likewise, a dead
1552 : : * line pointer can't be part of the chain. Both of those cases were
1553 : : * already marked as processed.
1554 : : */
1555 : : Assert(ItemIdIsUsed(lp));
1556 : : Assert(!ItemIdIsDead(lp));
1557 : :
1558 : : /*
1559 : : * If we are looking at the redirected root line pointer, jump to the
1560 : : * first normal tuple in the chain. If we find a redirect somewhere
1561 : : * else, stop --- it must not be same chain.
1562 : : */
1563 [ + + ]: 26797237 : if (ItemIdIsRedirected(lp))
1564 : : {
1565 [ - + ]: 217845 : if (nchain > 0)
1566 : 0 : break; /* not at start of chain */
1567 : 217845 : chainitems[nchain++] = offnum;
1568 : 217845 : offnum = ItemIdGetRedirect(rootlp);
1569 : 217845 : continue;
1570 : : }
1571 : :
1572 : : Assert(ItemIdIsNormal(lp));
1573 : :
1574 : 26579392 : htup = (HeapTupleHeader) PageGetItem(page, lp);
1575 : :
1576 : : /*
1577 : : * Check the tuple XMIN against prior XMAX, if any
1578 : : */
1579 [ + + - + ]: 26710210 : if (TransactionIdIsValid(priorXmax) &&
1580 : 130818 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
1581 : 0 : break;
1582 : :
1583 : : /*
1584 : : * OK, this tuple is indeed a member of the chain.
1585 : : */
1586 : 26579392 : chainitems[nchain++] = offnum;
1587 : :
1588 [ + + + - ]: 26579392 : switch (htsv_get_valid_status(prstate->htsv[offnum]))
1589 : : {
1590 : 3978037 : case HEAPTUPLE_DEAD:
1591 : :
1592 : : /* Remember the last DEAD tuple seen */
1593 : 3978037 : ndeadchain = nchain;
1594 : 3978037 : HeapTupleHeaderAdvanceConflictHorizon(htup,
1595 : : &prstate->latest_xid_removed);
1596 : : /* Advance to next chain member */
1597 : 3978037 : break;
1598 : :
1599 : 390243 : case HEAPTUPLE_RECENTLY_DEAD:
1600 : :
1601 : : /*
1602 : : * We don't need to advance the conflict horizon for
1603 : : * RECENTLY_DEAD tuples, even if we are removing them. This
1604 : : * is because we only remove RECENTLY_DEAD tuples if they
1605 : : * precede a DEAD tuple, and the DEAD tuple must have been
1606 : : * inserted by a newer transaction than the RECENTLY_DEAD
1607 : : * tuple by virtue of being later in the chain. We will have
1608 : : * advanced the conflict horizon for the DEAD tuple.
1609 : : */
1610 : :
1611 : : /*
1612 : : * Advance past RECENTLY_DEAD tuples just in case there's a
1613 : : * DEAD one after them. We have to make sure that we don't
1614 : : * miss any DEAD tuples, since DEAD tuples that still have
1615 : : * tuple storage after pruning will confuse VACUUM.
1616 : : */
1617 : 390243 : break;
1618 : :
1619 : 22211112 : case HEAPTUPLE_DELETE_IN_PROGRESS:
1620 : : case HEAPTUPLE_LIVE:
1621 : : case HEAPTUPLE_INSERT_IN_PROGRESS:
1622 : 22211112 : goto process_chain;
1623 : :
1624 : 0 : default:
1625 [ # # ]: 0 : elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1626 : : goto process_chain;
1627 : : }
1628 : :
1629 : : /*
1630 : : * If the tuple is not HOT-updated, then we are at the end of this
1631 : : * HOT-update chain.
1632 : : */
1633 [ + + ]: 4368280 : if (!HeapTupleHeaderIsHotUpdated(htup))
1634 : 4237462 : goto process_chain;
1635 : :
1636 : : /* HOT implies it can't have moved to different partition */
1637 : : Assert(!HeapTupleHeaderIndicatesMovedPartitions(htup));
1638 : :
1639 : : /*
1640 : : * Advance to next chain member.
1641 : : */
1642 : : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == prstate->block);
1643 : 130818 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
1644 : 130818 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
1645 : : }
1646 : :
1647 [ # # # # ]: 0 : if (ItemIdIsRedirected(rootlp) && nchain < 2)
1648 : : {
1649 : : /*
1650 : : * We found a redirect item that doesn't point to a valid follow-on
1651 : : * item. This can happen if the loop in heap_page_prune_and_freeze()
1652 : : * caused us to visit the dead successor of a redirect item before
1653 : : * visiting the redirect item. We can clean up by setting the
1654 : : * redirect item to LP_DEAD state or LP_UNUSED if the caller
1655 : : * indicated.
1656 : : */
1657 : 0 : heap_prune_record_dead_or_unused(prstate, rootoffnum, false);
1658 : 0 : return;
1659 : : }
1660 : :
1661 : 0 : process_chain:
1662 : :
1663 [ + + ]: 26448574 : if (ndeadchain == 0)
1664 : : {
1665 : : /*
1666 : : * No DEAD tuple was found, so the chain is entirely composed of
1667 : : * normal, unchanged tuples. Leave it alone.
1668 : : */
1669 : 22519211 : int i = 0;
1670 : :
1671 [ + + ]: 22519211 : if (ItemIdIsRedirected(rootlp))
1672 : : {
1673 : 194978 : heap_prune_record_unchanged_lp_redirect(prstate, rootoffnum);
1674 : 194978 : i++;
1675 : : }
1676 [ + + ]: 45044322 : for (; i < nchain; i++)
1677 : 22525111 : heap_prune_record_unchanged_lp_normal(prstate, chainitems[i]);
1678 : : }
1679 [ + + ]: 3929363 : else if (ndeadchain == nchain)
1680 : : {
1681 : : /*
1682 : : * The entire chain is dead. Mark the root line pointer LP_DEAD, and
1683 : : * fully remove the other tuples in the chain.
1684 : : */
1685 : 3854768 : heap_prune_record_dead_or_unused(prstate, rootoffnum, ItemIdIsNormal(rootlp));
1686 [ + + ]: 3902585 : for (int i = 1; i < nchain; i++)
1687 : 47817 : heap_prune_record_unused(prstate, chainitems[i], true);
1688 : : }
1689 : : else
1690 : : {
1691 : : /*
1692 : : * We found a DEAD tuple in the chain. Redirect the root line pointer
1693 : : * to the first non-DEAD tuple, and mark as unused each intermediate
1694 : : * item that we are able to remove from the chain.
1695 : : */
1696 : 74595 : heap_prune_record_redirect(prstate, rootoffnum, chainitems[ndeadchain],
1697 : 74595 : ItemIdIsNormal(rootlp));
1698 [ + + ]: 98319 : for (int i = 1; i < ndeadchain; i++)
1699 : 23724 : heap_prune_record_unused(prstate, chainitems[i], true);
1700 : :
1701 : : /* the rest of tuples in the chain are normal, unchanged tuples */
1702 [ + + ]: 150839 : for (int i = ndeadchain; i < nchain; i++)
1703 : 76244 : heap_prune_record_unchanged_lp_normal(prstate, chainitems[i]);
1704 : : }
1705 : : }
1706 : :
1707 : : /* Record lowest soon-prunable XID */
1708 : : static void
1709 : 5923280 : heap_prune_record_prunable(PruneState *prstate, TransactionId xid,
1710 : : OffsetNumber offnum)
1711 : : {
1712 : : /*
1713 : : * This should exactly match the PageSetPrunable macro. We can't store
1714 : : * directly into the page header yet, so we update working state.
1715 : : */
1716 : : Assert(TransactionIdIsNormal(xid));
1717 [ + + + + ]: 11596826 : if (!TransactionIdIsValid(prstate->new_prune_xid) ||
1718 : 5673546 : TransactionIdPrecedes(xid, prstate->new_prune_xid))
1719 : 251309 : prstate->new_prune_xid = xid;
1720 : :
1721 : : /*
1722 : : * It's incorrect for a page to be marked all-visible if it contains
1723 : : * prunable items.
1724 : : */
1725 [ - + ]: 5923280 : if (PageIsAllVisible(prstate->page))
1726 : 0 : heap_page_fix_vm_corruption(prstate, offnum,
1727 : : VM_CORRUPT_TUPLE_VISIBILITY);
1728 : 5923280 : }
1729 : :
1730 : : /* Record line pointer to be redirected */
1731 : : static void
1732 : 74595 : heap_prune_record_redirect(PruneState *prstate,
1733 : : OffsetNumber offnum, OffsetNumber rdoffnum,
1734 : : bool was_normal)
1735 : : {
1736 : : Assert(!prstate->processed[offnum]);
1737 : 74595 : prstate->processed[offnum] = true;
1738 : :
1739 : : /*
1740 : : * Do not mark the redirect target here. It needs to be counted
1741 : : * separately as an unchanged tuple.
1742 : : */
1743 : :
1744 : : Assert(prstate->nredirected < MaxHeapTuplesPerPage);
1745 : 74595 : prstate->redirected[prstate->nredirected * 2] = offnum;
1746 : 74595 : prstate->redirected[prstate->nredirected * 2 + 1] = rdoffnum;
1747 : :
1748 : 74595 : prstate->nredirected++;
1749 : :
1750 : : /*
1751 : : * If the root entry had been a normal tuple, we are deleting it, so count
1752 : : * it in the result. But changing a redirect (even to DEAD state) doesn't
1753 : : * count.
1754 : : */
1755 [ + + ]: 74595 : if (was_normal)
1756 : 64491 : prstate->ndeleted++;
1757 : :
1758 : 74595 : prstate->hastup = true;
1759 : 74595 : }
1760 : :
1761 : : /* Record line pointer to be marked dead */
1762 : : static void
1763 : 3820651 : heap_prune_record_dead(PruneState *prstate, OffsetNumber offnum,
1764 : : bool was_normal)
1765 : : {
1766 : : Assert(!prstate->processed[offnum]);
1767 : 3820651 : prstate->processed[offnum] = true;
1768 : :
1769 : : Assert(prstate->ndead < MaxHeapTuplesPerPage);
1770 : 3820651 : prstate->nowdead[prstate->ndead] = offnum;
1771 : 3820651 : prstate->ndead++;
1772 : :
1773 : : /*
1774 : : * Deliberately delay unsetting set_all_visible and set_all_frozen until
1775 : : * later during pruning. Removable dead tuples shouldn't preclude freezing
1776 : : * the page.
1777 : : */
1778 : :
1779 : : /* Record the dead offset for vacuum */
1780 : 3820651 : prstate->deadoffsets[prstate->lpdead_items++] = offnum;
1781 : :
1782 : : /*
1783 : : * If the root entry had been a normal tuple, we are deleting it, so count
1784 : : * it in the result. But changing a redirect (even to DEAD state) doesn't
1785 : : * count.
1786 : : */
1787 [ + + ]: 3820651 : if (was_normal)
1788 : 3807888 : prstate->ndeleted++;
1789 : 3820651 : }
1790 : :
1791 : : /*
1792 : : * Depending on whether or not the caller set mark_unused_now to true, record that a
1793 : : * line pointer should be marked LP_DEAD or LP_UNUSED. There are other cases in
1794 : : * which we will mark line pointers LP_UNUSED, but we will not mark line
1795 : : * pointers LP_DEAD if mark_unused_now is true.
1796 : : */
1797 : : static void
1798 : 3854768 : heap_prune_record_dead_or_unused(PruneState *prstate, OffsetNumber offnum,
1799 : : bool was_normal)
1800 : : {
1801 : : /*
1802 : : * If the caller set mark_unused_now to true, we can remove dead tuples
1803 : : * during pruning instead of marking their line pointers dead. Set this
1804 : : * tuple's line pointer LP_UNUSED. We hint that this option is less
1805 : : * likely.
1806 : : */
1807 [ + + ]: 3854768 : if (unlikely(prstate->mark_unused_now))
1808 : 34117 : heap_prune_record_unused(prstate, offnum, was_normal);
1809 : : else
1810 : 3820651 : heap_prune_record_dead(prstate, offnum, was_normal);
1811 : :
1812 : : /*
1813 : : * It's incorrect for the page to be set all-visible if it contains dead
1814 : : * items. Fix that on the heap page and check the VM for corruption as
1815 : : * well. Do that here rather than in heap_prune_record_dead() so we also
1816 : : * cover tuples that are directly marked LP_UNUSED via mark_unused_now.
1817 : : */
1818 [ - + ]: 3854768 : if (PageIsAllVisible(prstate->page))
1819 : 0 : heap_page_fix_vm_corruption(prstate, offnum, VM_CORRUPT_LPDEAD);
1820 : 3854768 : }
1821 : :
1822 : : /* Record line pointer to be marked unused */
1823 : : static void
1824 : 110880 : heap_prune_record_unused(PruneState *prstate, OffsetNumber offnum, bool was_normal)
1825 : : {
1826 : : Assert(!prstate->processed[offnum]);
1827 : 110880 : prstate->processed[offnum] = true;
1828 : :
1829 : : Assert(prstate->nunused < MaxHeapTuplesPerPage);
1830 : 110880 : prstate->nowunused[prstate->nunused] = offnum;
1831 : 110880 : prstate->nunused++;
1832 : :
1833 : : /*
1834 : : * If the root entry had been a normal tuple, we are deleting it, so count
1835 : : * it in the result. But changing a redirect (even to DEAD state) doesn't
1836 : : * count.
1837 : : */
1838 [ + + ]: 110880 : if (was_normal)
1839 : 109114 : prstate->ndeleted++;
1840 : 110880 : }
1841 : :
1842 : : /*
1843 : : * Record an unused line pointer that is left unchanged.
1844 : : */
1845 : : static void
1846 : 208727 : heap_prune_record_unchanged_lp_unused(PruneState *prstate, OffsetNumber offnum)
1847 : : {
1848 : : Assert(!prstate->processed[offnum]);
1849 : 208727 : prstate->processed[offnum] = true;
1850 : 208727 : }
1851 : :
1852 : : /*
1853 : : * Record line pointer that is left unchanged. We consider freezing it, and
1854 : : * update bookkeeping of tuple counts and page visibility.
1855 : : */
1856 : : static void
1857 : 22615368 : heap_prune_record_unchanged_lp_normal(PruneState *prstate, OffsetNumber offnum)
1858 : : {
1859 : : HeapTupleHeader htup;
1860 : : TransactionId xmin;
1861 : 22615368 : Page page = prstate->page;
1862 : :
1863 : : Assert(!prstate->processed[offnum]);
1864 : 22615368 : prstate->processed[offnum] = true;
1865 : :
1866 : 22615368 : prstate->hastup = true; /* the page is not empty */
1867 : :
1868 : : /*
1869 : : * The criteria for counting a tuple as live in this block need to match
1870 : : * what analyze.c's acquire_sample_rows() does, otherwise VACUUM and
1871 : : * ANALYZE may produce wildly different reltuples values, e.g. when there
1872 : : * are many recently-dead tuples.
1873 : : *
1874 : : * The logic here is a bit simpler than acquire_sample_rows(), as VACUUM
1875 : : * can't run inside a transaction block, which makes some cases impossible
1876 : : * (e.g. in-progress insert from the same transaction).
1877 : : *
1878 : : * HEAPTUPLE_DEAD are handled by the other heap_prune_record_*()
1879 : : * subroutines. They don't count dead items like acquire_sample_rows()
1880 : : * does, because we assume that all dead items will become LP_UNUSED
1881 : : * before VACUUM finishes. This difference is only superficial. VACUUM
1882 : : * effectively agrees with ANALYZE about DEAD items, in the end. VACUUM
1883 : : * won't remember LP_DEAD items, but only because they're not supposed to
1884 : : * be left behind when it is done. (Cases where we bypass index vacuuming
1885 : : * will violate this optimistic assumption, but the overall impact of that
1886 : : * should be negligible.)
1887 : : */
1888 : 22615368 : htup = (HeapTupleHeader) PageGetItem(page, PageGetItemId(page, offnum));
1889 : :
1890 [ + + + + : 22615368 : switch (prstate->htsv[offnum])
- ]
1891 : : {
1892 : 16692088 : case HEAPTUPLE_LIVE:
1893 : :
1894 : : /*
1895 : : * Count it as live. Not only is this natural, but it's also what
1896 : : * acquire_sample_rows() does.
1897 : : */
1898 : 16692088 : prstate->live_tuples++;
1899 : :
1900 : : /*
1901 : : * Is the tuple definitely visible to all transactions?
1902 : : *
1903 : : * NB: Like with per-tuple hint bits, we can't set the
1904 : : * PD_ALL_VISIBLE flag if the inserter committed asynchronously.
1905 : : * See SetHintBits for more info. Check that the tuple is hinted
1906 : : * xmin-committed because of that.
1907 : : */
1908 [ + + ]: 16692088 : if (!HeapTupleHeaderXminCommitted(htup))
1909 : : {
1910 : 42992 : prstate->set_all_visible = false;
1911 : 42992 : prstate->set_all_frozen = false;
1912 : 42992 : break;
1913 : : }
1914 : :
1915 : : /*
1916 : : * The inserter definitely committed. But we don't know if it is
1917 : : * old enough that everyone sees it as committed. Later, after
1918 : : * processing all the tuples on the page, we'll check if there is
1919 : : * any snapshot that still considers the newest xid on the page to
1920 : : * be running. If so, we don't consider the page all-visible.
1921 : : */
1922 : 16649096 : xmin = HeapTupleHeaderGetXmin(htup);
1923 : :
1924 : : /* Track newest xmin on page. */
1925 [ + + + + ]: 16649096 : if (TransactionIdFollows(xmin, prstate->newest_live_xid) &&
1926 : : TransactionIdIsNormal(xmin))
1927 : 641621 : prstate->newest_live_xid = xmin;
1928 : :
1929 : 16649096 : break;
1930 : :
1931 : 390243 : case HEAPTUPLE_RECENTLY_DEAD:
1932 : 390243 : prstate->recently_dead_tuples++;
1933 : 390243 : prstate->set_all_visible = false;
1934 : 390243 : prstate->set_all_frozen = false;
1935 : :
1936 : : /*
1937 : : * This tuple will soon become DEAD. Update the hint field so
1938 : : * that the page is reconsidered for pruning in future.
1939 : : */
1940 : 390243 : heap_prune_record_prunable(prstate,
1941 : : HeapTupleHeaderGetUpdateXid(htup),
1942 : : offnum);
1943 : 390243 : break;
1944 : :
1945 : 145712 : case HEAPTUPLE_INSERT_IN_PROGRESS:
1946 : :
1947 : : /*
1948 : : * We do not count these rows as live, because we expect the
1949 : : * inserting transaction to update the counters at commit, and we
1950 : : * assume that will happen only after we report our results. This
1951 : : * assumption is a bit shaky, but it is what acquire_sample_rows()
1952 : : * does, so be consistent.
1953 : : */
1954 : 145712 : prstate->set_all_visible = false;
1955 : 145712 : prstate->set_all_frozen = false;
1956 : :
1957 : : /*
1958 : : * Though there is nothing "prunable" on the page, we maintain
1959 : : * pd_prune_xid for inserts so that we have the opportunity to
1960 : : * mark them all-visible during the next round of pruning.
1961 : : */
1962 : 145712 : heap_prune_record_prunable(prstate,
1963 : : HeapTupleHeaderGetXmin(htup),
1964 : : offnum);
1965 : 145712 : break;
1966 : :
1967 : 5387325 : case HEAPTUPLE_DELETE_IN_PROGRESS:
1968 : :
1969 : : /*
1970 : : * This an expected case during concurrent vacuum. Count such
1971 : : * rows as live. As above, we assume the deleting transaction
1972 : : * will commit and update the counters after we report.
1973 : : */
1974 : 5387325 : prstate->live_tuples++;
1975 : 5387325 : prstate->set_all_visible = false;
1976 : 5387325 : prstate->set_all_frozen = false;
1977 : :
1978 : : /*
1979 : : * This tuple may soon become DEAD. Update the hint field so that
1980 : : * the page is reconsidered for pruning in future.
1981 : : */
1982 : 5387325 : heap_prune_record_prunable(prstate,
1983 : : HeapTupleHeaderGetUpdateXid(htup),
1984 : : offnum);
1985 : 5387325 : break;
1986 : :
1987 : 0 : default:
1988 : :
1989 : : /*
1990 : : * DEAD tuples should've been passed to heap_prune_record_dead()
1991 : : * or heap_prune_record_unused() instead.
1992 : : */
1993 [ # # ]: 0 : elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result %d",
1994 : : prstate->htsv[offnum]);
1995 : : break;
1996 : : }
1997 : :
1998 : : /* Consider freezing any normal tuples which will not be removed */
1999 [ + + ]: 22615368 : if (prstate->attempt_freeze)
2000 : : {
2001 : : bool totally_frozen;
2002 : :
2003 [ + + ]: 12407363 : if ((heap_prepare_freeze_tuple(htup,
2004 : 12407363 : prstate->cutoffs,
2005 : : &prstate->pagefrz,
2006 : 12407363 : &prstate->frozen[prstate->nfrozen],
2007 : : &totally_frozen)))
2008 : : {
2009 : : /* Save prepared freeze plan for later */
2010 : 3423388 : prstate->frozen[prstate->nfrozen++].offset = offnum;
2011 : : }
2012 : :
2013 : : /*
2014 : : * If any tuple isn't either totally frozen already or eligible to
2015 : : * become totally frozen (according to its freeze plan), then the page
2016 : : * definitely cannot be set all-frozen in the visibility map later on.
2017 : : */
2018 [ + + ]: 12407363 : if (!totally_frozen)
2019 : 6121231 : prstate->set_all_frozen = false;
2020 : : }
2021 : 22615368 : }
2022 : :
2023 : :
2024 : : /*
2025 : : * Record line pointer that was already LP_DEAD and is left unchanged.
2026 : : */
2027 : : static void
2028 : 1768175 : heap_prune_record_unchanged_lp_dead(PruneState *prstate, OffsetNumber offnum)
2029 : : {
2030 : : Assert(!prstate->processed[offnum]);
2031 : 1768175 : prstate->processed[offnum] = true;
2032 : :
2033 : : /*
2034 : : * Deliberately don't set hastup for LP_DEAD items. We make the soft
2035 : : * assumption that any LP_DEAD items encountered here will become
2036 : : * LP_UNUSED later on, before count_nondeletable_pages is reached. If we
2037 : : * don't make this assumption then rel truncation will only happen every
2038 : : * other VACUUM, at most. Besides, VACUUM must treat
2039 : : * hastup/nonempty_pages as provisional no matter how LP_DEAD items are
2040 : : * handled (handled here, or handled later on).
2041 : : *
2042 : : * Similarly, don't unset set_all_visible and set_all_frozen until later,
2043 : : * at the end of heap_page_prune_and_freeze(). This will allow us to
2044 : : * attempt to freeze the page after pruning. As long as we unset it
2045 : : * before updating the visibility map, this will be correct.
2046 : : */
2047 : :
2048 : : /* Record the dead offset for vacuum */
2049 : 1768175 : prstate->deadoffsets[prstate->lpdead_items++] = offnum;
2050 : :
2051 : : /*
2052 : : * It's incorrect for a page to be marked all-visible if it contains dead
2053 : : * items.
2054 : : */
2055 [ - + ]: 1768175 : if (PageIsAllVisible(prstate->page))
2056 : 0 : heap_page_fix_vm_corruption(prstate, offnum, VM_CORRUPT_LPDEAD);
2057 : 1768175 : }
2058 : :
2059 : : /*
2060 : : * Record LP_REDIRECT that is left unchanged.
2061 : : */
2062 : : static void
2063 : 194978 : heap_prune_record_unchanged_lp_redirect(PruneState *prstate, OffsetNumber offnum)
2064 : : {
2065 : : /*
2066 : : * A redirect line pointer doesn't count as a live tuple.
2067 : : *
2068 : : * If we leave a redirect line pointer in place, there will be another
2069 : : * tuple on the page that it points to. We will do the bookkeeping for
2070 : : * that separately. So we have nothing to do here, except remember that
2071 : : * we processed this item.
2072 : : */
2073 : : Assert(!prstate->processed[offnum]);
2074 : 194978 : prstate->processed[offnum] = true;
2075 : 194978 : }
2076 : :
2077 : : /*
2078 : : * Perform the actual page changes needed by heap_page_prune_and_freeze().
2079 : : *
2080 : : * If 'lp_truncate_only' is set, we are merely marking LP_DEAD line pointers
2081 : : * as unused, not redirecting or removing anything else. The
2082 : : * PageRepairFragmentation() call is skipped in that case.
2083 : : *
2084 : : * If 'lp_truncate_only' is not set, the caller must hold a cleanup lock on
2085 : : * the buffer. If it is set, an ordinary exclusive lock suffices.
2086 : : */
2087 : : void
2088 : 85149 : heap_page_prune_execute(Buffer buffer, bool lp_truncate_only,
2089 : : OffsetNumber *redirected, int nredirected,
2090 : : OffsetNumber *nowdead, int ndead,
2091 : : OffsetNumber *nowunused, int nunused)
2092 : : {
2093 : 85149 : Page page = BufferGetPage(buffer);
2094 : : OffsetNumber *offnum;
2095 : : HeapTupleHeader htup PG_USED_FOR_ASSERTS_ONLY;
2096 : :
2097 : : /* Shouldn't be called unless there's something to do */
2098 : : Assert(nredirected > 0 || ndead > 0 || nunused > 0);
2099 : :
2100 : : /* If 'lp_truncate_only', we can only remove already-dead line pointers */
2101 : : Assert(!lp_truncate_only || (nredirected == 0 && ndead == 0));
2102 : :
2103 : : /* Update all redirected line pointers */
2104 : 85149 : offnum = redirected;
2105 [ + + ]: 179256 : for (int i = 0; i < nredirected; i++)
2106 : : {
2107 : 94107 : OffsetNumber fromoff = *offnum++;
2108 : 94107 : OffsetNumber tooff = *offnum++;
2109 : 94107 : ItemId fromlp = PageGetItemId(page, fromoff);
2110 : : ItemId tolp PG_USED_FOR_ASSERTS_ONLY;
2111 : :
2112 : : #ifdef USE_ASSERT_CHECKING
2113 : :
2114 : : /*
2115 : : * Any existing item that we set as an LP_REDIRECT (any 'from' item)
2116 : : * must be the first item from a HOT chain. If the item has tuple
2117 : : * storage then it can't be a heap-only tuple. Otherwise we are just
2118 : : * maintaining an existing LP_REDIRECT from an existing HOT chain that
2119 : : * has been pruned at least once before now.
2120 : : */
2121 : : if (!ItemIdIsRedirected(fromlp))
2122 : : {
2123 : : Assert(ItemIdHasStorage(fromlp) && ItemIdIsNormal(fromlp));
2124 : :
2125 : : htup = (HeapTupleHeader) PageGetItem(page, fromlp);
2126 : : Assert(!HeapTupleHeaderIsHeapOnly(htup));
2127 : : }
2128 : : else
2129 : : {
2130 : : /* We shouldn't need to redundantly set the redirect */
2131 : : Assert(ItemIdGetRedirect(fromlp) != tooff);
2132 : : }
2133 : :
2134 : : /*
2135 : : * The item that we're about to set as an LP_REDIRECT (the 'from'
2136 : : * item) will point to an existing item (the 'to' item) that is
2137 : : * already a heap-only tuple. There can be at most one LP_REDIRECT
2138 : : * item per HOT chain.
2139 : : *
2140 : : * We need to keep around an LP_REDIRECT item (after original
2141 : : * non-heap-only root tuple gets pruned away) so that it's always
2142 : : * possible for VACUUM to easily figure out what TID to delete from
2143 : : * indexes when an entire HOT chain becomes dead. A heap-only tuple
2144 : : * can never become LP_DEAD; an LP_REDIRECT item or a regular heap
2145 : : * tuple can.
2146 : : *
2147 : : * This check may miss problems, e.g. the target of a redirect could
2148 : : * be marked as unused subsequently. The page_verify_redirects() check
2149 : : * below will catch such problems.
2150 : : */
2151 : : tolp = PageGetItemId(page, tooff);
2152 : : Assert(ItemIdHasStorage(tolp) && ItemIdIsNormal(tolp));
2153 : : htup = (HeapTupleHeader) PageGetItem(page, tolp);
2154 : : Assert(HeapTupleHeaderIsHeapOnly(htup));
2155 : : #endif
2156 : :
2157 : 94107 : ItemIdSetRedirect(fromlp, tooff);
2158 : : }
2159 : :
2160 : : /* Update all now-dead line pointers */
2161 : 85149 : offnum = nowdead;
2162 [ + + ]: 4197114 : for (int i = 0; i < ndead; i++)
2163 : : {
2164 : 4111965 : OffsetNumber off = *offnum++;
2165 : 4111965 : ItemId lp = PageGetItemId(page, off);
2166 : :
2167 : : #ifdef USE_ASSERT_CHECKING
2168 : :
2169 : : /*
2170 : : * An LP_DEAD line pointer must be left behind when the original item
2171 : : * (which is dead to everybody) could still be referenced by a TID in
2172 : : * an index. This should never be necessary with any individual
2173 : : * heap-only tuple item, though. (It's not clear how much of a problem
2174 : : * that would be, but there is no reason to allow it.)
2175 : : */
2176 : : if (ItemIdHasStorage(lp))
2177 : : {
2178 : : Assert(ItemIdIsNormal(lp));
2179 : : htup = (HeapTupleHeader) PageGetItem(page, lp);
2180 : : Assert(!HeapTupleHeaderIsHeapOnly(htup));
2181 : : }
2182 : : else
2183 : : {
2184 : : /* Whole HOT chain becomes dead */
2185 : : Assert(ItemIdIsRedirected(lp));
2186 : : }
2187 : : #endif
2188 : :
2189 : 4111965 : ItemIdSetDead(lp);
2190 : : }
2191 : :
2192 : : /* Update all now-unused line pointers */
2193 : 85149 : offnum = nowunused;
2194 [ + + ]: 402596 : for (int i = 0; i < nunused; i++)
2195 : : {
2196 : 317447 : OffsetNumber off = *offnum++;
2197 : 317447 : ItemId lp = PageGetItemId(page, off);
2198 : :
2199 : : #ifdef USE_ASSERT_CHECKING
2200 : :
2201 : : if (lp_truncate_only)
2202 : : {
2203 : : /* Setting LP_DEAD to LP_UNUSED in vacuum's second pass */
2204 : : Assert(ItemIdIsDead(lp) && !ItemIdHasStorage(lp));
2205 : : }
2206 : : else
2207 : : {
2208 : : /*
2209 : : * When heap_page_prune_and_freeze() was called, mark_unused_now
2210 : : * may have been passed as true, which allows would-be LP_DEAD
2211 : : * items to be made LP_UNUSED instead. This is only possible if
2212 : : * the relation has no indexes. If there are any dead items, then
2213 : : * mark_unused_now was not true and every item being marked
2214 : : * LP_UNUSED must refer to a heap-only tuple.
2215 : : */
2216 : : if (ndead > 0)
2217 : : {
2218 : : Assert(ItemIdHasStorage(lp) && ItemIdIsNormal(lp));
2219 : : htup = (HeapTupleHeader) PageGetItem(page, lp);
2220 : : Assert(HeapTupleHeaderIsHeapOnly(htup));
2221 : : }
2222 : : else
2223 : : Assert(ItemIdIsUsed(lp));
2224 : : }
2225 : :
2226 : : #endif
2227 : :
2228 : 317447 : ItemIdSetUnused(lp);
2229 : : }
2230 : :
2231 [ + + ]: 85149 : if (lp_truncate_only)
2232 : 2121 : PageTruncateLinePointerArray(page);
2233 : : else
2234 : : {
2235 : : /*
2236 : : * Finally, repair any fragmentation, and update the page's hint bit
2237 : : * about whether it has free pointers.
2238 : : */
2239 : 83028 : PageRepairFragmentation(page);
2240 : :
2241 : : /*
2242 : : * Now that the page has been modified, assert that redirect items
2243 : : * still point to valid targets.
2244 : : */
2245 : 83028 : page_verify_redirects(page);
2246 : : }
2247 : 85149 : }
2248 : :
2249 : :
2250 : : /*
2251 : : * If built with assertions, verify that all LP_REDIRECT items point to a
2252 : : * valid item.
2253 : : *
2254 : : * One way that bugs related to HOT pruning show is redirect items pointing to
2255 : : * removed tuples. It's not trivial to reliably check that marking an item
2256 : : * unused will not orphan a redirect item during heap_prune_chain() /
2257 : : * heap_page_prune_execute(), so we additionally check the whole page after
2258 : : * pruning. Without this check such bugs would typically only cause asserts
2259 : : * later, potentially well after the corruption has been introduced.
2260 : : *
2261 : : * Also check comments in heap_page_prune_execute()'s redirection loop.
2262 : : */
2263 : : static void
2264 : 83028 : page_verify_redirects(Page page)
2265 : : {
2266 : : #ifdef USE_ASSERT_CHECKING
2267 : : OffsetNumber offnum;
2268 : : OffsetNumber maxoff;
2269 : :
2270 : : maxoff = PageGetMaxOffsetNumber(page);
2271 : : for (offnum = FirstOffsetNumber;
2272 : : offnum <= maxoff;
2273 : : offnum = OffsetNumberNext(offnum))
2274 : : {
2275 : : ItemId itemid = PageGetItemId(page, offnum);
2276 : : OffsetNumber targoff;
2277 : : ItemId targitem;
2278 : : HeapTupleHeader htup;
2279 : :
2280 : : if (!ItemIdIsRedirected(itemid))
2281 : : continue;
2282 : :
2283 : : targoff = ItemIdGetRedirect(itemid);
2284 : : targitem = PageGetItemId(page, targoff);
2285 : :
2286 : : Assert(ItemIdIsUsed(targitem));
2287 : : Assert(ItemIdIsNormal(targitem));
2288 : : Assert(ItemIdHasStorage(targitem));
2289 : : htup = (HeapTupleHeader) PageGetItem(page, targitem);
2290 : : Assert(HeapTupleHeaderIsHeapOnly(htup));
2291 : : }
2292 : : #endif
2293 : 83028 : }
2294 : :
2295 : :
2296 : : /*
2297 : : * For all items in this page, find their respective root line pointers.
2298 : : * If item k is part of a HOT-chain with root at item j, then we set
2299 : : * root_offsets[k - 1] = j.
2300 : : *
2301 : : * The passed-in root_offsets array must have MaxHeapTuplesPerPage entries.
2302 : : * Unused entries are filled with InvalidOffsetNumber (zero).
2303 : : *
2304 : : * The function must be called with at least share lock on the buffer, to
2305 : : * prevent concurrent prune operations.
2306 : : *
2307 : : * Note: The information collected here is valid only as long as the caller
2308 : : * holds a pin on the buffer. Once pin is released, a tuple might be pruned
2309 : : * and reused by a completely unrelated tuple.
2310 : : */
2311 : : void
2312 : 139506 : heap_get_root_tuples(Page page, OffsetNumber *root_offsets)
2313 : : {
2314 : : OffsetNumber offnum,
2315 : : maxoff;
2316 : :
2317 [ + - - + : 139506 : MemSet(root_offsets, InvalidOffsetNumber,
- - - - -
- ]
2318 : : MaxHeapTuplesPerPage * sizeof(OffsetNumber));
2319 : :
2320 : 139506 : maxoff = PageGetMaxOffsetNumber(page);
2321 [ + + ]: 11665548 : for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
2322 : : {
2323 : 11526042 : ItemId lp = PageGetItemId(page, offnum);
2324 : : HeapTupleHeader htup;
2325 : : OffsetNumber nextoffnum;
2326 : : TransactionId priorXmax;
2327 : :
2328 : : /* skip unused and dead items */
2329 [ + + + + ]: 11526042 : if (!ItemIdIsUsed(lp) || ItemIdIsDead(lp))
2330 : 9876 : continue;
2331 : :
2332 [ + + ]: 11516166 : if (ItemIdIsNormal(lp))
2333 : : {
2334 : 11512284 : htup = (HeapTupleHeader) PageGetItem(page, lp);
2335 : :
2336 : : /*
2337 : : * Check if this tuple is part of a HOT-chain rooted at some other
2338 : : * tuple. If so, skip it for now; we'll process it when we find
2339 : : * its root.
2340 : : */
2341 [ + + ]: 11512284 : if (HeapTupleHeaderIsHeapOnly(htup))
2342 : 4354 : continue;
2343 : :
2344 : : /*
2345 : : * This is either a plain tuple or the root of a HOT-chain.
2346 : : * Remember it in the mapping.
2347 : : */
2348 : 11507930 : root_offsets[offnum - 1] = offnum;
2349 : :
2350 : : /* If it's not the start of a HOT-chain, we're done with it */
2351 [ + + ]: 11507930 : if (!HeapTupleHeaderIsHotUpdated(htup))
2352 : 11507606 : continue;
2353 : :
2354 : : /* Set up to scan the HOT-chain */
2355 : 324 : nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
2356 : 324 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
2357 : : }
2358 : : else
2359 : : {
2360 : : /* Must be a redirect item. We do not set its root_offsets entry */
2361 : : Assert(ItemIdIsRedirected(lp));
2362 : : /* Set up to scan the HOT-chain */
2363 : 3882 : nextoffnum = ItemIdGetRedirect(lp);
2364 : 3882 : priorXmax = InvalidTransactionId;
2365 : : }
2366 : :
2367 : : /*
2368 : : * Now follow the HOT-chain and collect other tuples in the chain.
2369 : : *
2370 : : * Note: Even though this is a nested loop, the complexity of the
2371 : : * function is O(N) because a tuple in the page should be visited not
2372 : : * more than twice, once in the outer loop and once in HOT-chain
2373 : : * chases.
2374 : : */
2375 : : for (;;)
2376 : : {
2377 : : /* Sanity check (pure paranoia) */
2378 [ - + ]: 4350 : if (nextoffnum < FirstOffsetNumber)
2379 : 0 : break;
2380 : :
2381 : : /*
2382 : : * An offset past the end of page's line pointer array is possible
2383 : : * when the array was truncated
2384 : : */
2385 [ - + ]: 4350 : if (nextoffnum > maxoff)
2386 : 0 : break;
2387 : :
2388 : 4350 : lp = PageGetItemId(page, nextoffnum);
2389 : :
2390 : : /* Check for broken chains */
2391 [ - + ]: 4350 : if (!ItemIdIsNormal(lp))
2392 : 0 : break;
2393 : :
2394 : 4350 : htup = (HeapTupleHeader) PageGetItem(page, lp);
2395 : :
2396 [ + + - + ]: 4818 : if (TransactionIdIsValid(priorXmax) &&
2397 : 468 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(htup)))
2398 : 0 : break;
2399 : :
2400 : : /* Remember the root line pointer for this item */
2401 : 4350 : root_offsets[nextoffnum - 1] = offnum;
2402 : :
2403 : : /* Advance to next chain member, if any */
2404 [ + + ]: 4350 : if (!HeapTupleHeaderIsHotUpdated(htup))
2405 : 4206 : break;
2406 : :
2407 : : /* HOT implies it can't have moved to different partition */
2408 : : Assert(!HeapTupleHeaderIndicatesMovedPartitions(htup));
2409 : :
2410 : 144 : nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
2411 : 144 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
2412 : : }
2413 : : }
2414 : 139506 : }
2415 : :
2416 : :
2417 : : /*
2418 : : * Compare fields that describe actions required to freeze tuple with caller's
2419 : : * open plan. If everything matches then the frz tuple plan is equivalent to
2420 : : * caller's plan.
2421 : : */
2422 : : static inline bool
2423 : 1373901 : heap_log_freeze_eq(xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
2424 : : {
2425 [ + + ]: 1373901 : if (plan->xmax == frz->xmax &&
2426 [ + + ]: 1372605 : plan->t_infomask2 == frz->t_infomask2 &&
2427 [ + + ]: 1371777 : plan->t_infomask == frz->t_infomask &&
2428 [ + - ]: 1368556 : plan->frzflags == frz->frzflags)
2429 : 1368556 : return true;
2430 : :
2431 : : /* Caller must call heap_log_freeze_new_plan again for frz */
2432 : 5345 : return false;
2433 : : }
2434 : :
2435 : : /*
2436 : : * Comparator used to deduplicate the freeze plans used in WAL records.
2437 : : */
2438 : : static int
2439 : 1862420 : heap_log_freeze_cmp(const void *arg1, const void *arg2)
2440 : : {
2441 : 1862420 : const HeapTupleFreeze *frz1 = arg1;
2442 : 1862420 : const HeapTupleFreeze *frz2 = arg2;
2443 : :
2444 [ + + ]: 1862420 : if (frz1->xmax < frz2->xmax)
2445 : 13140 : return -1;
2446 [ + + ]: 1849280 : else if (frz1->xmax > frz2->xmax)
2447 : 14310 : return 1;
2448 : :
2449 [ + + ]: 1834970 : if (frz1->t_infomask2 < frz2->t_infomask2)
2450 : 3698 : return -1;
2451 [ + + ]: 1831272 : else if (frz1->t_infomask2 > frz2->t_infomask2)
2452 : 5774 : return 1;
2453 : :
2454 [ + + ]: 1825498 : if (frz1->t_infomask < frz2->t_infomask)
2455 : 13812 : return -1;
2456 [ + + ]: 1811686 : else if (frz1->t_infomask > frz2->t_infomask)
2457 : 18744 : return 1;
2458 : :
2459 [ - + ]: 1792942 : if (frz1->frzflags < frz2->frzflags)
2460 : 0 : return -1;
2461 [ - + ]: 1792942 : else if (frz1->frzflags > frz2->frzflags)
2462 : 0 : return 1;
2463 : :
2464 : : /*
2465 : : * heap_log_freeze_eq would consider these tuple-wise plans to be equal.
2466 : : * (So the tuples will share a single canonical freeze plan.)
2467 : : *
2468 : : * We tiebreak on page offset number to keep each freeze plan's page
2469 : : * offset number array individually sorted. (Unnecessary, but be tidy.)
2470 : : */
2471 [ + + ]: 1792942 : if (frz1->offset < frz2->offset)
2472 : 1546607 : return -1;
2473 [ + - ]: 246335 : else if (frz1->offset > frz2->offset)
2474 : 246335 : return 1;
2475 : :
2476 : : Assert(false);
2477 : 0 : return 0;
2478 : : }
2479 : :
2480 : : /*
2481 : : * Start new plan initialized using tuple-level actions. At least one tuple
2482 : : * will have steps required to freeze described by caller's plan during REDO.
2483 : : */
2484 : : static inline void
2485 : 33230 : heap_log_freeze_new_plan(xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
2486 : : {
2487 : 33230 : plan->xmax = frz->xmax;
2488 : 33230 : plan->t_infomask2 = frz->t_infomask2;
2489 : 33230 : plan->t_infomask = frz->t_infomask;
2490 : 33230 : plan->frzflags = frz->frzflags;
2491 : 33230 : plan->ntuples = 1; /* for now */
2492 : 33230 : }
2493 : :
2494 : : /*
2495 : : * Deduplicate tuple-based freeze plans so that each distinct set of
2496 : : * processing steps is only stored once in the WAL record.
2497 : : * Called during original execution of freezing (for logged relations).
2498 : : *
2499 : : * Return value is number of plans set in *plans_out for caller. Also writes
2500 : : * an array of offset numbers into *offsets_out output argument for caller
2501 : : * (actually there is one array per freeze plan, but that's not of immediate
2502 : : * concern to our caller).
2503 : : */
2504 : : static int
2505 : 27885 : heap_log_freeze_plan(HeapTupleFreeze *tuples, int ntuples,
2506 : : xlhp_freeze_plan *plans_out,
2507 : : OffsetNumber *offsets_out)
2508 : : {
2509 : 27885 : int nplans = 0;
2510 : :
2511 : : /* Sort tuple-based freeze plans in the order required to deduplicate */
2512 : 27885 : qsort(tuples, ntuples, sizeof(HeapTupleFreeze), heap_log_freeze_cmp);
2513 : :
2514 [ + + ]: 1429671 : for (int i = 0; i < ntuples; i++)
2515 : : {
2516 : 1401786 : HeapTupleFreeze *frz = tuples + i;
2517 : :
2518 [ + + ]: 1401786 : if (i == 0)
2519 : : {
2520 : : /* New canonical freeze plan starting with first tup */
2521 : 27885 : heap_log_freeze_new_plan(plans_out, frz);
2522 : 27885 : nplans++;
2523 : : }
2524 [ + + ]: 1373901 : else if (heap_log_freeze_eq(plans_out, frz))
2525 : : {
2526 : : /* tup matches open canonical plan -- include tup in it */
2527 : : Assert(offsets_out[i - 1] < frz->offset);
2528 : 1368556 : plans_out->ntuples++;
2529 : : }
2530 : : else
2531 : : {
2532 : : /* Tup doesn't match current plan -- done with it now */
2533 : 5345 : plans_out++;
2534 : :
2535 : : /* New canonical freeze plan starting with this tup */
2536 : 5345 : heap_log_freeze_new_plan(plans_out, frz);
2537 : 5345 : nplans++;
2538 : : }
2539 : :
2540 : : /*
2541 : : * Save page offset number in dedicated buffer in passing.
2542 : : *
2543 : : * REDO routine relies on the record's offset numbers array grouping
2544 : : * offset numbers by freeze plan. The sort order within each grouping
2545 : : * is ascending offset number order, just to keep things tidy.
2546 : : */
2547 : 1401786 : offsets_out[i] = frz->offset;
2548 : : }
2549 : :
2550 : : Assert(nplans > 0 && nplans <= ntuples);
2551 : :
2552 : 27885 : return nplans;
2553 : : }
2554 : :
2555 : : /*
2556 : : * Write an XLOG_HEAP2_PRUNE* WAL record
2557 : : *
2558 : : * This is used for several different page maintenance operations:
2559 : : *
2560 : : * - Page pruning, in VACUUM's 1st pass or on access: Some items are
2561 : : * redirected, some marked dead, and some removed altogether.
2562 : : *
2563 : : * - Freezing: Items are marked as 'frozen'.
2564 : : *
2565 : : * - Vacuum, 2nd pass: Items that are already LP_DEAD are marked as unused.
2566 : : *
2567 : : * They have enough commonalities that we use a single WAL record for them
2568 : : * all.
2569 : : *
2570 : : * If replaying the record requires a cleanup lock, pass cleanup_lock = true.
2571 : : * Replaying 'redirected' or 'dead' items always requires a cleanup lock, but
2572 : : * replaying 'unused' items depends on whether they were all previously marked
2573 : : * as dead.
2574 : : *
2575 : : * If the VM is being updated, vmflags will contain the bits to set. In this
2576 : : * case, vmbuffer should already have been updated and marked dirty and should
2577 : : * still be pinned and locked.
2578 : : *
2579 : : * Note: This function scribbles on the 'frozen' array.
2580 : : *
2581 : : * Note: This is called in a critical section, so careful what you do here.
2582 : : */
2583 : : void
2584 : 152725 : log_heap_prune_and_freeze(Relation relation, Buffer buffer,
2585 : : Buffer vmbuffer, uint8 vmflags,
2586 : : TransactionId conflict_xid,
2587 : : bool cleanup_lock,
2588 : : PruneReason reason,
2589 : : HeapTupleFreeze *frozen, int nfrozen,
2590 : : OffsetNumber *redirected, int nredirected,
2591 : : OffsetNumber *dead, int ndead,
2592 : : OffsetNumber *unused, int nunused)
2593 : : {
2594 : : xl_heap_prune xlrec;
2595 : : XLogRecPtr recptr;
2596 : : uint8 info;
2597 : : uint8 regbuf_flags_heap;
2598 : :
2599 : 152725 : Page heap_page = BufferGetPage(buffer);
2600 : :
2601 : : /* The following local variables hold data registered in the WAL record: */
2602 : : xlhp_freeze_plan plans[MaxHeapTuplesPerPage];
2603 : : xlhp_freeze_plans freeze_plans;
2604 : : xlhp_prune_items redirect_items;
2605 : : xlhp_prune_items dead_items;
2606 : : xlhp_prune_items unused_items;
2607 : : OffsetNumber frz_offsets[MaxHeapTuplesPerPage];
2608 [ + + + + : 152725 : bool do_prune = nredirected > 0 || ndead > 0 || nunused > 0;
+ + ]
2609 : 152725 : bool do_set_vm = vmflags & VISIBILITYMAP_VALID_BITS;
2610 : 152725 : bool heap_fpi_allowed = true;
2611 : :
2612 : : Assert((vmflags & VISIBILITYMAP_VALID_BITS) == vmflags);
2613 : :
2614 : 152725 : xlrec.flags = 0;
2615 : 152725 : regbuf_flags_heap = REGBUF_STANDARD;
2616 : :
2617 : : /*
2618 : : * We can avoid an FPI of the heap page if the only modification we are
2619 : : * making to it is to set PD_ALL_VISIBLE and checksums/wal_log_hints are
2620 : : * disabled.
2621 : : *
2622 : : * However, if the page has never been WAL-logged (LSN is invalid), we
2623 : : * must force an FPI regardless. This can happen when another backend
2624 : : * extends the heap, initializes the page, and then fails before WAL-
2625 : : * logging it. Since heap extension is not WAL-logged, recovery might try
2626 : : * to replay our record and find that the page isn't initialized, which
2627 : : * would cause a PANIC.
2628 : : */
2629 [ - + ]: 152725 : if (!XLogRecPtrIsValid(PageGetLSN(heap_page)))
2630 : 0 : regbuf_flags_heap |= REGBUF_FORCE_IMAGE;
2631 [ + + + + : 152725 : else if (!do_prune && nfrozen == 0 && (!do_set_vm || !XLogHintBitIsNeeded()))
+ - + + +
+ ]
2632 : : {
2633 : 2664 : regbuf_flags_heap |= REGBUF_NO_IMAGE;
2634 : 2664 : heap_fpi_allowed = false;
2635 : : }
2636 : :
2637 : : /*
2638 : : * Prepare data for the buffer. The arrays are not actually in the
2639 : : * buffer, but we pretend that they are. When XLogInsert stores a full
2640 : : * page image, the arrays can be omitted.
2641 : : */
2642 : 152725 : XLogBeginInsert();
2643 : 152725 : XLogRegisterBuffer(0, buffer, regbuf_flags_heap);
2644 : :
2645 [ + + ]: 152725 : if (do_set_vm)
2646 : 77811 : XLogRegisterBuffer(1, vmbuffer, 0);
2647 : :
2648 [ + + ]: 152725 : if (nfrozen > 0)
2649 : : {
2650 : : int nplans;
2651 : :
2652 : 27885 : xlrec.flags |= XLHP_HAS_FREEZE_PLANS;
2653 : :
2654 : : /*
2655 : : * Prepare deduplicated representation for use in the WAL record. This
2656 : : * destructively sorts frozen tuples array in-place.
2657 : : */
2658 : 27885 : nplans = heap_log_freeze_plan(frozen, nfrozen, plans, frz_offsets);
2659 : :
2660 : 27885 : freeze_plans.nplans = nplans;
2661 : 27885 : XLogRegisterBufData(0, &freeze_plans,
2662 : : offsetof(xlhp_freeze_plans, plans));
2663 : 27885 : XLogRegisterBufData(0, plans,
2664 : : sizeof(xlhp_freeze_plan) * nplans);
2665 : : }
2666 [ + + ]: 152725 : if (nredirected > 0)
2667 : : {
2668 : 18951 : xlrec.flags |= XLHP_HAS_REDIRECTIONS;
2669 : :
2670 : 18951 : redirect_items.ntargets = nredirected;
2671 : 18951 : XLogRegisterBufData(0, &redirect_items,
2672 : : offsetof(xlhp_prune_items, data));
2673 : 18951 : XLogRegisterBufData(0, redirected,
2674 : : sizeof(OffsetNumber[2]) * nredirected);
2675 : : }
2676 [ + + ]: 152725 : if (ndead > 0)
2677 : : {
2678 : 59284 : xlrec.flags |= XLHP_HAS_DEAD_ITEMS;
2679 : :
2680 : 59284 : dead_items.ntargets = ndead;
2681 : 59284 : XLogRegisterBufData(0, &dead_items,
2682 : : offsetof(xlhp_prune_items, data));
2683 : 59284 : XLogRegisterBufData(0, dead,
2684 : : sizeof(OffsetNumber) * ndead);
2685 : : }
2686 [ + + ]: 152725 : if (nunused > 0)
2687 : : {
2688 : 32909 : xlrec.flags |= XLHP_HAS_NOW_UNUSED_ITEMS;
2689 : :
2690 : 32909 : unused_items.ntargets = nunused;
2691 : 32909 : XLogRegisterBufData(0, &unused_items,
2692 : : offsetof(xlhp_prune_items, data));
2693 : 32909 : XLogRegisterBufData(0, unused,
2694 : : sizeof(OffsetNumber) * nunused);
2695 : : }
2696 [ + + ]: 152725 : if (nfrozen > 0)
2697 : 27885 : XLogRegisterBufData(0, frz_offsets,
2698 : : sizeof(OffsetNumber) * nfrozen);
2699 : :
2700 : : /*
2701 : : * Prepare the main xl_heap_prune record. We already set the XLHP_HAS_*
2702 : : * flag above.
2703 : : */
2704 [ + + ]: 152725 : if (vmflags & VISIBILITYMAP_ALL_VISIBLE)
2705 : : {
2706 : 77811 : xlrec.flags |= XLHP_VM_ALL_VISIBLE;
2707 [ + + ]: 77811 : if (vmflags & VISIBILITYMAP_ALL_FROZEN)
2708 : 47394 : xlrec.flags |= XLHP_VM_ALL_FROZEN;
2709 : : }
2710 [ + + + + : 152725 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + - ]
2711 : 625 : xlrec.flags |= XLHP_IS_CATALOG_REL;
2712 [ + + ]: 152725 : if (TransactionIdIsValid(conflict_xid))
2713 : 122077 : xlrec.flags |= XLHP_HAS_CONFLICT_HORIZON;
2714 [ + + ]: 152725 : if (cleanup_lock)
2715 : 135194 : xlrec.flags |= XLHP_CLEANUP_LOCK;
2716 : : else
2717 : : {
2718 : : Assert(nredirected == 0 && ndead == 0);
2719 : : /* also, any items in 'unused' must've been LP_DEAD previously */
2720 : : }
2721 : 152725 : XLogRegisterData(&xlrec, SizeOfHeapPrune);
2722 [ + + ]: 152725 : if (TransactionIdIsValid(conflict_xid))
2723 : 122077 : XLogRegisterData(&conflict_xid, sizeof(TransactionId));
2724 : :
2725 [ + + + - ]: 152725 : switch (reason)
2726 : : {
2727 : 72137 : case PRUNE_ON_ACCESS:
2728 : 72137 : info = XLOG_HEAP2_PRUNE_ON_ACCESS;
2729 : 72137 : break;
2730 : 63057 : case PRUNE_VACUUM_SCAN:
2731 : 63057 : info = XLOG_HEAP2_PRUNE_VACUUM_SCAN;
2732 : 63057 : break;
2733 : 17531 : case PRUNE_VACUUM_CLEANUP:
2734 : 17531 : info = XLOG_HEAP2_PRUNE_VACUUM_CLEANUP;
2735 : 17531 : break;
2736 : 0 : default:
2737 [ # # ]: 0 : elog(ERROR, "unrecognized prune reason: %d", (int) reason);
2738 : : break;
2739 : : }
2740 : 152725 : recptr = XLogInsert(RM_HEAP2_ID, info);
2741 : :
2742 [ + + ]: 152725 : if (do_set_vm)
2743 : : {
2744 : : Assert(BufferIsDirty(vmbuffer));
2745 : 77811 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2746 : : }
2747 : :
2748 : : /*
2749 : : * If we explicitly skip an FPI, we must not stamp the heap page with this
2750 : : * record's LSN. Recovery skips records <= the stamped LSN, so this could
2751 : : * lead to skipping an earlier FPI needed to repair a torn page.
2752 : : */
2753 [ + + ]: 152725 : if (heap_fpi_allowed)
2754 : : {
2755 : : Assert(BufferIsDirty(buffer));
2756 : 150061 : PageSetLSN(heap_page, recptr);
2757 : : }
2758 : 152725 : }
|