PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pruneheap.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "commands/vacuum.h"
#include "executor/instrument.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
Include dependency graph for pruneheap.c:

Go to the source code of this file.

Data Structures

struct  PruneState
 

Typedefs

typedef enum VMCorruptionType VMCorruptionType
 

Enumerations

enum  VMCorruptionType { VM_CORRUPT_MISSING_PAGE_HINT , VM_CORRUPT_LPDEAD , VM_CORRUPT_TUPLE_VISIBILITY }
 

Functions

static void prune_freeze_setup (PruneFreezeParams *params, TransactionId *new_relfrozen_xid, MultiXactId *new_relmin_mxid, PruneFreezeResult *presult, PruneState *prstate)
 
static void heap_page_fix_vm_corruption (PruneState *prstate, OffsetNumber offnum, VMCorruptionType corruption_type)
 
static void prune_freeze_fast_path (PruneState *prstate, PruneFreezeResult *presult)
 
static void prune_freeze_plan (PruneState *prstate, OffsetNumber *off_loc)
 
static HTSV_Result heap_prune_satisfies_vacuum (PruneState *prstate, HeapTuple tup)
 
static HTSV_Result htsv_get_valid_status (int status)
 
static void heap_prune_chain (OffsetNumber maxoff, OffsetNumber rootoffnum, PruneState *prstate)
 
static void heap_prune_record_prunable (PruneState *prstate, TransactionId xid, OffsetNumber offnum)
 
static void heap_prune_record_redirect (PruneState *prstate, OffsetNumber offnum, OffsetNumber rdoffnum, bool was_normal)
 
static void heap_prune_record_dead (PruneState *prstate, OffsetNumber offnum, bool was_normal)
 
static void heap_prune_record_dead_or_unused (PruneState *prstate, OffsetNumber offnum, bool was_normal)
 
static void heap_prune_record_unused (PruneState *prstate, OffsetNumber offnum, bool was_normal)
 
static void heap_prune_record_unchanged_lp_unused (PruneState *prstate, OffsetNumber offnum)
 
static void heap_prune_record_unchanged_lp_normal (PruneState *prstate, OffsetNumber offnum)
 
static void heap_prune_record_unchanged_lp_dead (PruneState *prstate, OffsetNumber offnum)
 
static void heap_prune_record_unchanged_lp_redirect (PruneState *prstate, OffsetNumber offnum)
 
static void page_verify_redirects (Page page)
 
static bool heap_page_will_freeze (bool did_tuple_hint_fpi, bool do_prune, bool do_hint_prune, PruneState *prstate)
 
static bool heap_page_will_set_vm (PruneState *prstate, PruneReason reason, bool do_prune, bool do_freeze)
 
void heap_page_prune_opt (Relation relation, Buffer buffer, Buffer *vmbuffer, bool rel_read_only)
 
void heap_page_prune_and_freeze (PruneFreezeParams *params, PruneFreezeResult *presult, OffsetNumber *off_loc, TransactionId *new_relfrozen_xid, MultiXactId *new_relmin_mxid)
 
void heap_page_prune_execute (Buffer buffer, bool lp_truncate_only, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
 
void heap_get_root_tuples (Page page, OffsetNumber *root_offsets)
 
static bool heap_log_freeze_eq (xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
 
static int heap_log_freeze_cmp (const void *arg1, const void *arg2)
 
static void heap_log_freeze_new_plan (xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
 
static int heap_log_freeze_plan (HeapTupleFreeze *tuples, int ntuples, xlhp_freeze_plan *plans_out, OffsetNumber *offsets_out)
 
void log_heap_prune_and_freeze (Relation relation, Buffer buffer, Buffer vmbuffer, uint8 vmflags, TransactionId conflict_xid, bool cleanup_lock, PruneReason reason, HeapTupleFreeze *frozen, int nfrozen, OffsetNumber *redirected, int nredirected, OffsetNumber *dead, int ndead, OffsetNumber *unused, int nunused)
 

Typedef Documentation

◆ VMCorruptionType

Enumeration Type Documentation

◆ VMCorruptionType

Enumerator
VM_CORRUPT_MISSING_PAGE_HINT 
VM_CORRUPT_LPDEAD 
VM_CORRUPT_TUPLE_VISIBILITY 

Definition at line 191 of file pruneheap.c.

192{
193 /* VM bits are set but the heap page-level PD_ALL_VISIBLE flag is not */
195 /* LP_DEAD line pointers found on a page marked all-visible */
197 /* Tuple not visible to all transactions on a page marked all-visible */
VMCorruptionType
Definition pruneheap.c:192
@ VM_CORRUPT_MISSING_PAGE_HINT
Definition pruneheap.c:194
@ VM_CORRUPT_LPDEAD
Definition pruneheap.c:196
@ VM_CORRUPT_TUPLE_VISIBILITY
Definition pruneheap.c:198

Function Documentation

◆ heap_get_root_tuples()

void heap_get_root_tuples ( Page  page,
OffsetNumber root_offsets 
)

Definition at line 2311 of file pruneheap.c.

2312{
2313 OffsetNumber offnum,
2314 maxoff;
2315
2318
2319 maxoff = PageGetMaxOffsetNumber(page);
2320 for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
2321 {
2322 ItemId lp = PageGetItemId(page, offnum);
2323 HeapTupleHeader htup;
2326
2327 /* skip unused and dead items */
2328 if (!ItemIdIsUsed(lp) || ItemIdIsDead(lp))
2329 continue;
2330
2331 if (ItemIdIsNormal(lp))
2332 {
2333 htup = (HeapTupleHeader) PageGetItem(page, lp);
2334
2335 /*
2336 * Check if this tuple is part of a HOT-chain rooted at some other
2337 * tuple. If so, skip it for now; we'll process it when we find
2338 * its root.
2339 */
2340 if (HeapTupleHeaderIsHeapOnly(htup))
2341 continue;
2342
2343 /*
2344 * This is either a plain tuple or the root of a HOT-chain.
2345 * Remember it in the mapping.
2346 */
2347 root_offsets[offnum - 1] = offnum;
2348
2349 /* If it's not the start of a HOT-chain, we're done with it */
2350 if (!HeapTupleHeaderIsHotUpdated(htup))
2351 continue;
2352
2353 /* Set up to scan the HOT-chain */
2356 }
2357 else
2358 {
2359 /* Must be a redirect item. We do not set its root_offsets entry */
2361 /* Set up to scan the HOT-chain */
2364 }
2365
2366 /*
2367 * Now follow the HOT-chain and collect other tuples in the chain.
2368 *
2369 * Note: Even though this is a nested loop, the complexity of the
2370 * function is O(N) because a tuple in the page should be visited not
2371 * more than twice, once in the outer loop and once in HOT-chain
2372 * chases.
2373 */
2374 for (;;)
2375 {
2376 /* Sanity check (pure paranoia) */
2378 break;
2379
2380 /*
2381 * An offset past the end of page's line pointer array is possible
2382 * when the array was truncated
2383 */
2384 if (nextoffnum > maxoff)
2385 break;
2386
2387 lp = PageGetItemId(page, nextoffnum);
2388
2389 /* Check for broken chains */
2390 if (!ItemIdIsNormal(lp))
2391 break;
2392
2393 htup = (HeapTupleHeader) PageGetItem(page, lp);
2394
2397 break;
2398
2399 /* Remember the root line pointer for this item */
2400 root_offsets[nextoffnum - 1] = offnum;
2401
2402 /* Advance to next chain member, if any */
2403 if (!HeapTupleHeaderIsHotUpdated(htup))
2404 break;
2405
2406 /* HOT implies it can't have moved to different partition */
2408
2411 }
2412 }
2413}
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition bufpage.h:268
static void * PageGetItem(PageData *page, const ItemIdData *itemId)
Definition bufpage.h:378
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition bufpage.h:396
#define Assert(condition)
Definition c.h:1002
#define MemSet(start, val, len)
Definition c.h:1147
uint32 TransactionId
Definition c.h:795
HeapTupleHeaderData * HeapTupleHeader
Definition htup.h:23
static bool HeapTupleHeaderIsHeapOnly(const HeapTupleHeaderData *tup)
static TransactionId HeapTupleHeaderGetXmin(const HeapTupleHeaderData *tup)
static bool HeapTupleHeaderIndicatesMovedPartitions(const HeapTupleHeaderData *tup)
static bool HeapTupleHeaderIsHotUpdated(const HeapTupleHeaderData *tup)
static TransactionId HeapTupleHeaderGetUpdateXid(const HeapTupleHeaderData *tup)
#define MaxHeapTuplesPerPage
#define ItemIdIsNormal(itemId)
Definition itemid.h:99
#define ItemIdGetRedirect(itemId)
Definition itemid.h:78
#define ItemIdIsDead(itemId)
Definition itemid.h:113
#define ItemIdIsUsed(itemId)
Definition itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition itemid.h:106
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition itemptr.h:124
#define InvalidOffsetNumber
Definition off.h:26
#define OffsetNumberNext(offsetNumber)
Definition off.h:52
uint16 OffsetNumber
Definition off.h:24
#define FirstOffsetNumber
Definition off.h:27
static int fb(int x)
ItemPointerData t_ctid
#define InvalidTransactionId
Definition transam.h:31
#define TransactionIdEquals(id1, id2)
Definition transam.h:43
#define TransactionIdIsValid(xid)
Definition transam.h:41

References Assert, fb(), FirstOffsetNumber, HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderGetXmin(), HeapTupleHeaderIndicatesMovedPartitions(), HeapTupleHeaderIsHeapOnly(), HeapTupleHeaderIsHotUpdated(), InvalidOffsetNumber, InvalidTransactionId, ItemIdGetRedirect, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerGetOffsetNumber(), MaxHeapTuplesPerPage, MemSet, OffsetNumberNext, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), HeapTupleHeaderData::t_ctid, TransactionIdEquals, and TransactionIdIsValid.

Referenced by heapam_index_build_range_scan(), and heapam_index_validate_scan().

◆ heap_log_freeze_cmp()

static int heap_log_freeze_cmp ( const void arg1,
const void arg2 
)
static

Definition at line 2438 of file pruneheap.c.

2439{
2440 const HeapTupleFreeze *frz1 = arg1;
2441 const HeapTupleFreeze *frz2 = arg2;
2442
2443 if (frz1->xmax < frz2->xmax)
2444 return -1;
2445 else if (frz1->xmax > frz2->xmax)
2446 return 1;
2447
2448 if (frz1->t_infomask2 < frz2->t_infomask2)
2449 return -1;
2450 else if (frz1->t_infomask2 > frz2->t_infomask2)
2451 return 1;
2452
2453 if (frz1->t_infomask < frz2->t_infomask)
2454 return -1;
2455 else if (frz1->t_infomask > frz2->t_infomask)
2456 return 1;
2457
2458 if (frz1->frzflags < frz2->frzflags)
2459 return -1;
2460 else if (frz1->frzflags > frz2->frzflags)
2461 return 1;
2462
2463 /*
2464 * heap_log_freeze_eq would consider these tuple-wise plans to be equal.
2465 * (So the tuples will share a single canonical freeze plan.)
2466 *
2467 * We tiebreak on page offset number to keep each freeze plan's page
2468 * offset number array individually sorted. (Unnecessary, but be tidy.)
2469 */
2470 if (frz1->offset < frz2->offset)
2471 return -1;
2472 else if (frz1->offset > frz2->offset)
2473 return 1;
2474
2475 Assert(false);
2476 return 0;
2477}

References Assert, and fb().

Referenced by heap_log_freeze_plan().

◆ heap_log_freeze_eq()

static bool heap_log_freeze_eq ( xlhp_freeze_plan plan,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 2422 of file pruneheap.c.

2423{
2424 if (plan->xmax == frz->xmax &&
2425 plan->t_infomask2 == frz->t_infomask2 &&
2426 plan->t_infomask == frz->t_infomask &&
2427 plan->frzflags == frz->frzflags)
2428 return true;
2429
2430 /* Caller must call heap_log_freeze_new_plan again for frz */
2431 return false;
2432}
#define plan(x)
Definition pg_regress.c:164

References fb(), and plan.

Referenced by heap_log_freeze_plan().

◆ heap_log_freeze_new_plan()

static void heap_log_freeze_new_plan ( xlhp_freeze_plan plan,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 2484 of file pruneheap.c.

2485{
2486 plan->xmax = frz->xmax;
2487 plan->t_infomask2 = frz->t_infomask2;
2488 plan->t_infomask = frz->t_infomask;
2489 plan->frzflags = frz->frzflags;
2490 plan->ntuples = 1; /* for now */
2491}

References fb(), and plan.

Referenced by heap_log_freeze_plan().

◆ heap_log_freeze_plan()

static int heap_log_freeze_plan ( HeapTupleFreeze tuples,
int  ntuples,
xlhp_freeze_plan plans_out,
OffsetNumber offsets_out 
)
static

Definition at line 2504 of file pruneheap.c.

2507{
2508 int nplans = 0;
2509
2510 /* Sort tuple-based freeze plans in the order required to deduplicate */
2511 qsort(tuples, ntuples, sizeof(HeapTupleFreeze), heap_log_freeze_cmp);
2512
2513 for (int i = 0; i < ntuples; i++)
2514 {
2515 HeapTupleFreeze *frz = tuples + i;
2516
2517 if (i == 0)
2518 {
2519 /* New canonical freeze plan starting with first tup */
2521 nplans++;
2522 }
2523 else if (heap_log_freeze_eq(plans_out, frz))
2524 {
2525 /* tup matches open canonical plan -- include tup in it */
2526 Assert(offsets_out[i - 1] < frz->offset);
2527 plans_out->ntuples++;
2528 }
2529 else
2530 {
2531 /* Tup doesn't match current plan -- done with it now */
2532 plans_out++;
2533
2534 /* New canonical freeze plan starting with this tup */
2536 nplans++;
2537 }
2538
2539 /*
2540 * Save page offset number in dedicated buffer in passing.
2541 *
2542 * REDO routine relies on the record's offset numbers array grouping
2543 * offset numbers by freeze plan. The sort order within each grouping
2544 * is ascending offset number order, just to keep things tidy.
2545 */
2546 offsets_out[i] = frz->offset;
2547 }
2548
2549 Assert(nplans > 0 && nplans <= ntuples);
2550
2551 return nplans;
2552}
int i
Definition isn.c:77
#define qsort(a, b, c, d)
Definition port.h:496
static int heap_log_freeze_cmp(const void *arg1, const void *arg2)
Definition pruneheap.c:2438
static bool heap_log_freeze_eq(xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
Definition pruneheap.c:2422
static void heap_log_freeze_new_plan(xlhp_freeze_plan *plan, HeapTupleFreeze *frz)
Definition pruneheap.c:2484

References Assert, fb(), heap_log_freeze_cmp(), heap_log_freeze_eq(), heap_log_freeze_new_plan(), i, and qsort.

Referenced by log_heap_prune_and_freeze().

◆ heap_page_fix_vm_corruption()

static void heap_page_fix_vm_corruption ( PruneState prstate,
OffsetNumber  offnum,
VMCorruptionType  corruption_type 
)
static

Definition at line 872 of file pruneheap.c.

874{
875 const char *relname = RelationGetRelationName(prstate->relation);
876 bool do_clear_vm = false;
877 bool do_clear_heap = false;
878
880
881 switch (corruption_type)
882 {
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 do_clear_vm = true;
890 do_clear_heap = true;
891 break;
892
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 */
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 do_clear_vm = true;
914 do_clear_heap = true;
915 break;
916
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 */
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 do_clear_vm = true;
935 break;
936 }
937
939
940 /* Avoid marking the buffer dirty if PD_ALL_VISIBLE is already clear */
941 if (do_clear_heap)
942 {
945 MarkBufferDirtyHint(prstate->buffer, true);
946 }
947
948 if (do_clear_vm)
949 {
951 visibilitymap_clear(prstate->relation->rd_locator, prstate->block,
952 prstate->vmbuffer,
955 prstate->old_vmbits = 0;
956 }
957}
bool BufferIsLockedByMeInMode(Buffer buffer, BufferLockMode mode)
Definition bufmgr.c:3110
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition bufmgr.c:5844
@ BUFFER_LOCK_EXCLUSIVE
Definition bufmgr.h:222
@ BUFFER_LOCK_UNLOCK
Definition bufmgr.h:207
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:334
static bool PageIsAllVisible(const PageData *page)
Definition bufpage.h:454
static void PageClearAllVisible(Page page)
Definition bufpage.h:464
int errcode(int sqlerrcode)
Definition elog.c:875
#define errcontext
Definition elog.h:200
#define WARNING
Definition elog.h:37
#define ereport(elevel,...)
Definition elog.h:152
static char * errmsg
#define ERRCODE_DATA_CORRUPTED
NameData relname
Definition pg_class.h:40
#define RelationGetRelationName(relation)
Definition rel.h:550
bool visibilitymap_clear(RelFileLocator rlocator, BlockNumber heapBlk, Buffer vmbuf, uint8 flags)
#define VISIBILITYMAP_VALID_BITS

References Assert, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferIsLockedByMeInMode(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcontext, errmsg, fb(), LockBuffer(), MarkBufferDirtyHint(), PageClearAllVisible(), PageIsAllVisible(), RelationGetRelationName, relname, visibilitymap_clear(), VISIBILITYMAP_VALID_BITS, VM_CORRUPT_LPDEAD, VM_CORRUPT_MISSING_PAGE_HINT, VM_CORRUPT_TUPLE_VISIBILITY, and WARNING.

Referenced by heap_page_prune_and_freeze(), heap_prune_record_dead_or_unused(), heap_prune_record_prunable(), and heap_prune_record_unchanged_lp_dead().

◆ heap_page_prune_and_freeze()

void heap_page_prune_and_freeze ( PruneFreezeParams params,
PruneFreezeResult presult,
OffsetNumber off_loc,
TransactionId new_relfrozen_xid,
MultiXactId new_relmin_mxid 
)

Definition at line 1112 of file pruneheap.c.

1117{
1119 bool do_freeze;
1120 bool do_prune;
1121 bool do_hint_prune;
1122 bool do_set_vm;
1123 bool did_tuple_hint_fpi;
1126
1127 /* Initialize prstate */
1128 prune_freeze_setup(params,
1130 presult, &prstate);
1131
1132 /*
1133 * If the VM is set but PD_ALL_VISIBLE is clear, fix that corruption
1134 * before pruning and freezing so that the page and VM start out in a
1135 * consistent state.
1136 */
1137 if ((prstate.old_vmbits & VISIBILITYMAP_VALID_BITS) &&
1141
1142 /*
1143 * If the page is already all-frozen, or already all-visible when freezing
1144 * is not being attempted, take the fast path, skipping pruning and
1145 * freezing code entirely. This must be done after fixing any discrepancy
1146 * between the page-level visibility hint and the VM, since that may have
1147 * cleared old_vmbits.
1148 */
1149 if ((params->options & HEAP_PAGE_PRUNE_ALLOW_FAST_PATH) != 0 &&
1150 ((prstate.old_vmbits & VISIBILITYMAP_ALL_FROZEN) ||
1151 ((prstate.old_vmbits & VISIBILITYMAP_ALL_VISIBLE) &&
1152 !prstate.attempt_freeze)))
1153 {
1155 return;
1156 }
1157
1158 /*
1159 * Examine all line pointers and tuple visibility information to determine
1160 * which line pointers should change state and which tuples may be frozen.
1161 * Prepare queue of state changes to later be executed in a critical
1162 * section.
1163 */
1165
1166 /*
1167 * After processing all the live tuples on the page, if the newest xmin
1168 * amongst them may be considered running by any snapshot, the page cannot
1169 * be all-visible. This should be done before determining whether or not
1170 * to opportunistically freeze.
1171 */
1172 if (prstate.set_all_visible &&
1173 TransactionIdIsNormal(prstate.newest_live_xid) &&
1175 prstate.newest_live_xid,
1176 true))
1177 prstate.set_all_visible = prstate.set_all_frozen = false;
1178
1179 /*
1180 * If checksums are enabled, calling heap_prune_satisfies_vacuum() while
1181 * checking tuple visibility information in prune_freeze_plan() may have
1182 * caused an FPI to be emitted.
1183 */
1185
1186 do_prune = prstate.nredirected > 0 ||
1187 prstate.ndead > 0 ||
1188 prstate.nunused > 0;
1189
1190 /*
1191 * Even if we don't prune anything, if we found a new value for the
1192 * pd_prune_xid field or the page was marked full, we will update the hint
1193 * bit.
1194 */
1195 do_hint_prune = PageGetPruneXid(prstate.page) != prstate.new_prune_xid ||
1196 PageIsFull(prstate.page);
1197
1198 /*
1199 * Decide if we want to go ahead with freezing according to the freeze
1200 * plans we prepared, or not.
1201 */
1203 do_prune,
1205 &prstate);
1206
1207 /*
1208 * While scanning the line pointers, we did not clear
1209 * set_all_visible/set_all_frozen when encountering LP_DEAD items because
1210 * we wanted the decision whether or not to freeze the page to be
1211 * unaffected by the short-term presence of LP_DEAD items. These LP_DEAD
1212 * items are effectively assumed to be LP_UNUSED items in the making. It
1213 * doesn't matter which vacuum heap pass (initial pass or final pass) ends
1214 * up setting the page all-frozen, as long as the ongoing VACUUM does it.
1215 *
1216 * Now that we finished determining whether or not to freeze the page,
1217 * update set_all_visible and set_all_frozen so that they reflect the true
1218 * state of the page for setting PD_ALL_VISIBLE and VM bits.
1219 */
1220 if (prstate.lpdead_items > 0)
1221 prstate.set_all_visible = prstate.set_all_frozen = false;
1222
1223 Assert(!prstate.set_all_frozen || prstate.set_all_visible);
1224 Assert(!prstate.set_all_visible || prstate.attempt_set_vm);
1225 Assert(!prstate.set_all_visible || (prstate.lpdead_items == 0));
1226
1228
1229 /*
1230 * new_vmbits should be 0 regardless of whether or not the page is
1231 * all-visible if we do not intend to set the VM.
1232 */
1233 Assert(do_set_vm || prstate.new_vmbits == 0);
1234
1235 /*
1236 * The snapshot conflict horizon for the whole record is the most
1237 * conservative (newest) horizon required by any change in the record.
1238 */
1240 if (do_set_vm)
1241 conflict_xid = prstate.newest_live_xid;
1242 if (do_freeze && TransactionIdFollows(prstate.pagefrz.FreezePageConflictXid, conflict_xid))
1243 conflict_xid = prstate.pagefrz.FreezePageConflictXid;
1244 if (do_prune && TransactionIdFollows(prstate.latest_xid_removed, conflict_xid))
1245 conflict_xid = prstate.latest_xid_removed;
1246
1247 /* Lock vmbuffer before entering a critical section */
1248 if (do_set_vm)
1250
1251 /* Any error while applying the changes is critical */
1253
1254 if (do_hint_prune)
1255 {
1256 /*
1257 * Update the page's pd_prune_xid field to either zero, or the lowest
1258 * XID of any soon-prunable tuple.
1259 */
1260 ((PageHeader) prstate.page)->pd_prune_xid = prstate.new_prune_xid;
1261
1262 /*
1263 * Also clear the "page is full" flag, since there's no point in
1264 * repeating the prune/defrag process until something else happens to
1265 * the page.
1266 */
1267 PageClearFull(prstate.page);
1268
1269 /*
1270 * If that's all we had to do to the page, this is a non-WAL-logged
1271 * hint. If we are going to freeze or prune the page or set
1272 * PD_ALL_VISIBLE, we will mark the buffer dirty below.
1273 *
1274 * Setting PD_ALL_VISIBLE is fully WAL-logged because it is forbidden
1275 * for the VM to be set and PD_ALL_VISIBLE to be clear.
1276 */
1277 if (!do_freeze && !do_prune && !do_set_vm)
1278 MarkBufferDirtyHint(prstate.buffer, true);
1279 }
1280
1281 if (do_prune || do_freeze || do_set_vm)
1282 {
1283 /* Apply the planned item changes and repair page fragmentation. */
1284 if (do_prune)
1285 {
1286 heap_page_prune_execute(prstate.buffer, false,
1287 prstate.redirected, prstate.nredirected,
1288 prstate.nowdead, prstate.ndead,
1289 prstate.nowunused, prstate.nunused);
1290 }
1291
1292 if (do_freeze)
1293 heap_freeze_prepared_tuples(prstate.buffer, prstate.frozen, prstate.nfrozen);
1294
1295 /* Set the visibility map and page visibility hint */
1296 if (do_set_vm)
1297 {
1298 /*
1299 * While it is valid for PD_ALL_VISIBLE to be set when the
1300 * corresponding VM bit is clear, we strongly prefer to keep them
1301 * in sync.
1302 *
1303 * The heap buffer must be marked dirty before adding it to the
1304 * WAL chain when setting the VM. We don't worry about
1305 * unnecessarily dirtying the heap buffer if PD_ALL_VISIBLE is
1306 * already set, though. It is extremely rare to have a clean heap
1307 * buffer with PD_ALL_VISIBLE already set and the VM bits clear,
1308 * so there is no point in optimizing it.
1309 */
1312 visibilitymap_set(prstate.block, prstate.vmbuffer, prstate.new_vmbits,
1313 prstate.relation->rd_locator);
1314 }
1315
1316 MarkBufferDirty(prstate.buffer);
1317
1318 /*
1319 * Emit a WAL XLOG_HEAP2_PRUNE* record showing what we did
1320 */
1321 if (RelationNeedsWAL(prstate.relation))
1322 {
1323 log_heap_prune_and_freeze(prstate.relation, prstate.buffer,
1324 do_set_vm ? prstate.vmbuffer : InvalidBuffer,
1325 do_set_vm ? prstate.new_vmbits : 0,
1327 true, /* cleanup lock */
1328 params->reason,
1329 prstate.frozen, prstate.nfrozen,
1330 prstate.redirected, prstate.nredirected,
1331 prstate.nowdead, prstate.ndead,
1332 prstate.nowunused, prstate.nunused);
1333 }
1334 }
1335
1337
1338 if (do_set_vm)
1340
1341 /*
1342 * During its second pass over the heap, VACUUM calls
1343 * heap_page_would_be_all_visible() to determine whether a page is
1344 * all-visible and all-frozen. The logic here is similar. After completing
1345 * pruning and freezing, use an assertion to verify that our results
1346 * remain consistent with heap_page_would_be_all_visible(). It's also a
1347 * valuable cross-check of the page state after pruning and freezing.
1348 */
1349#ifdef USE_ASSERT_CHECKING
1350 if (prstate.set_all_visible)
1351 {
1353 bool debug_all_frozen;
1354
1355 Assert(prstate.lpdead_items == 0);
1356
1358 prstate.vistest,
1361
1363 debug_cutoff == prstate.newest_live_xid);
1364
1365 /*
1366 * It's possible the page is composed entirely of frozen tuples but is
1367 * not set all-frozen in the VM and did not pass
1368 * HEAP_PAGE_PRUNE_FREEZE. In this case, it's possible
1369 * heap_page_is_all_visible() finds the page completely frozen, even
1370 * though prstate.set_all_frozen is false.
1371 */
1372 Assert(!prstate.set_all_frozen || debug_all_frozen);
1373 }
1374#endif
1375
1376 /* Copy information back for caller */
1377 presult->ndeleted = prstate.ndeleted;
1378 presult->nnewlpdead = prstate.ndead;
1379 presult->nfrozen = prstate.nfrozen;
1380 presult->live_tuples = prstate.live_tuples;
1381 presult->recently_dead_tuples = prstate.recently_dead_tuples;
1382 presult->hastup = prstate.hastup;
1383
1384 presult->lpdead_items = prstate.lpdead_items;
1385 /* the presult->deadoffsets array was already filled in */
1386
1387 presult->newly_all_visible = false;
1388 presult->newly_all_frozen = false;
1389 presult->newly_all_visible_frozen = false;
1390 if (do_set_vm)
1391 {
1392 if ((prstate.old_vmbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
1393 {
1394 presult->newly_all_visible = true;
1395 if (prstate.set_all_frozen)
1396 presult->newly_all_visible_frozen = true;
1397 }
1398 else if ((prstate.old_vmbits & VISIBILITYMAP_ALL_FROZEN) == 0 &&
1399 prstate.set_all_frozen)
1400 presult->newly_all_frozen = true;
1401 }
1402
1403 if (prstate.attempt_freeze)
1404 {
1405 if (presult->nfrozen > 0)
1406 {
1407 *new_relfrozen_xid = prstate.pagefrz.FreezePageRelfrozenXid;
1408 *new_relmin_mxid = prstate.pagefrz.FreezePageRelminMxid;
1409 }
1410 else
1411 {
1412 *new_relfrozen_xid = prstate.pagefrz.NoFreezePageRelfrozenXid;
1413 *new_relmin_mxid = prstate.pagefrz.NoFreezePageRelminMxid;
1414 }
1415 }
1416}
#define InvalidBuffer
Definition buf.h:25
void MarkBufferDirty(Buffer buffer)
Definition bufmgr.c:3170
PageHeaderData * PageHeader
Definition bufpage.h:199
static TransactionId PageGetPruneXid(const PageData *page)
Definition bufpage.h:470
static void PageClearFull(Page page)
Definition bufpage.h:448
static void PageSetAllVisible(Page page)
Definition bufpage.h:459
#define PageClearPrunable(page)
Definition bufpage.h:485
static bool PageIsFull(const PageData *page)
Definition bufpage.h:438
int64_t int64
Definition c.h:680
void heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
Definition heapam.c:7600
#define HEAP_PAGE_PRUNE_ALLOW_FAST_PATH
Definition heapam.h:44
WalUsage pgWalUsage
Definition instrument.c:27
return true
Definition isn.c:130
#define START_CRIT_SECTION()
Definition miscadmin.h:152
#define END_CRIT_SECTION()
Definition miscadmin.h:154
bool GlobalVisTestXidConsideredRunning(GlobalVisState *state, TransactionId xid, bool allow_update)
Definition procarray.c:4315
static void prune_freeze_fast_path(PruneState *prstate, PruneFreezeResult *presult)
Definition pruneheap.c:1029
static void prune_freeze_plan(PruneState *prstate, OffsetNumber *off_loc)
Definition pruneheap.c:551
static bool heap_page_will_freeze(bool did_tuple_hint_fpi, bool do_prune, bool do_hint_prune, PruneState *prstate)
Definition pruneheap.c:754
static bool heap_page_will_set_vm(PruneState *prstate, PruneReason reason, bool do_prune, bool do_freeze)
Definition pruneheap.c:972
static void heap_page_fix_vm_corruption(PruneState *prstate, OffsetNumber offnum, VMCorruptionType corruption_type)
Definition pruneheap.c:872
void log_heap_prune_and_freeze(Relation relation, Buffer buffer, Buffer vmbuffer, uint8 vmflags, TransactionId conflict_xid, bool cleanup_lock, PruneReason reason, HeapTupleFreeze *frozen, int nfrozen, OffsetNumber *redirected, int nredirected, OffsetNumber *dead, int ndead, OffsetNumber *unused, int nunused)
Definition pruneheap.c:2583
static void prune_freeze_setup(PruneFreezeParams *params, TransactionId *new_relfrozen_xid, MultiXactId *new_relmin_mxid, PruneFreezeResult *presult, PruneState *prstate)
Definition pruneheap.c:420
void heap_page_prune_execute(Buffer buffer, bool lp_truncate_only, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
Definition pruneheap.c:2087
#define RelationNeedsWAL(relation)
Definition rel.h:639
PruneReason reason
Definition heapam.h:276
int64 wal_fpi
Definition instrument.h:54
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
#define TransactionIdIsNormal(xid)
Definition transam.h:42
void visibilitymap_set(BlockNumber heapBlk, Buffer vmBuf, uint8 flags, RelFileLocator rlocator)
#define VISIBILITYMAP_ALL_FROZEN
#define VISIBILITYMAP_ALL_VISIBLE

References Assert, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, END_CRIT_SECTION, fb(), GlobalVisTestXidConsideredRunning(), heap_freeze_prepared_tuples(), heap_page_fix_vm_corruption(), HEAP_PAGE_PRUNE_ALLOW_FAST_PATH, heap_page_prune_execute(), heap_page_will_freeze(), heap_page_will_set_vm(), InvalidBuffer, InvalidOffsetNumber, InvalidTransactionId, LockBuffer(), log_heap_prune_and_freeze(), MarkBufferDirty(), MarkBufferDirtyHint(), PruneFreezeParams::options, PageClearFull(), PageClearPrunable, PageGetPruneXid(), PageIsAllVisible(), PageIsFull(), PageSetAllVisible(), pgWalUsage, prune_freeze_fast_path(), prune_freeze_plan(), prune_freeze_setup(), PruneFreezeParams::reason, RelationNeedsWAL, START_CRIT_SECTION, TransactionIdFollows(), TransactionIdIsNormal, TransactionIdIsValid, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_set(), VISIBILITYMAP_VALID_BITS, VM_CORRUPT_MISSING_PAGE_HINT, and WalUsage::wal_fpi.

Referenced by heap_page_prune_opt(), and lazy_scan_prune().

◆ heap_page_prune_execute()

void heap_page_prune_execute ( Buffer  buffer,
bool  lp_truncate_only,
OffsetNumber redirected,
int  nredirected,
OffsetNumber nowdead,
int  ndead,
OffsetNumber nowunused,
int  nunused 
)

Definition at line 2087 of file pruneheap.c.

2091{
2092 Page page = BufferGetPage(buffer);
2093 OffsetNumber *offnum;
2095
2096 /* Shouldn't be called unless there's something to do */
2097 Assert(nredirected > 0 || ndead > 0 || nunused > 0);
2098
2099 /* If 'lp_truncate_only', we can only remove already-dead line pointers */
2100 Assert(!lp_truncate_only || (nredirected == 0 && ndead == 0));
2101
2102 /* Update all redirected line pointers */
2103 offnum = redirected;
2104 for (int i = 0; i < nredirected; i++)
2105 {
2106 OffsetNumber fromoff = *offnum++;
2107 OffsetNumber tooff = *offnum++;
2110
2111#ifdef USE_ASSERT_CHECKING
2112
2113 /*
2114 * Any existing item that we set as an LP_REDIRECT (any 'from' item)
2115 * must be the first item from a HOT chain. If the item has tuple
2116 * storage then it can't be a heap-only tuple. Otherwise we are just
2117 * maintaining an existing LP_REDIRECT from an existing HOT chain that
2118 * has been pruned at least once before now.
2119 */
2121 {
2123
2124 htup = (HeapTupleHeader) PageGetItem(page, fromlp);
2126 }
2127 else
2128 {
2129 /* We shouldn't need to redundantly set the redirect */
2131 }
2132
2133 /*
2134 * The item that we're about to set as an LP_REDIRECT (the 'from'
2135 * item) will point to an existing item (the 'to' item) that is
2136 * already a heap-only tuple. There can be at most one LP_REDIRECT
2137 * item per HOT chain.
2138 *
2139 * We need to keep around an LP_REDIRECT item (after original
2140 * non-heap-only root tuple gets pruned away) so that it's always
2141 * possible for VACUUM to easily figure out what TID to delete from
2142 * indexes when an entire HOT chain becomes dead. A heap-only tuple
2143 * can never become LP_DEAD; an LP_REDIRECT item or a regular heap
2144 * tuple can.
2145 *
2146 * This check may miss problems, e.g. the target of a redirect could
2147 * be marked as unused subsequently. The page_verify_redirects() check
2148 * below will catch such problems.
2149 */
2150 tolp = PageGetItemId(page, tooff);
2152 htup = (HeapTupleHeader) PageGetItem(page, tolp);
2154#endif
2155
2157 }
2158
2159 /* Update all now-dead line pointers */
2160 offnum = nowdead;
2161 for (int i = 0; i < ndead; i++)
2162 {
2163 OffsetNumber off = *offnum++;
2164 ItemId lp = PageGetItemId(page, off);
2165
2166#ifdef USE_ASSERT_CHECKING
2167
2168 /*
2169 * An LP_DEAD line pointer must be left behind when the original item
2170 * (which is dead to everybody) could still be referenced by a TID in
2171 * an index. This should never be necessary with any individual
2172 * heap-only tuple item, though. (It's not clear how much of a problem
2173 * that would be, but there is no reason to allow it.)
2174 */
2175 if (ItemIdHasStorage(lp))
2176 {
2178 htup = (HeapTupleHeader) PageGetItem(page, lp);
2180 }
2181 else
2182 {
2183 /* Whole HOT chain becomes dead */
2185 }
2186#endif
2187
2189 }
2190
2191 /* Update all now-unused line pointers */
2192 offnum = nowunused;
2193 for (int i = 0; i < nunused; i++)
2194 {
2195 OffsetNumber off = *offnum++;
2196 ItemId lp = PageGetItemId(page, off);
2197
2198#ifdef USE_ASSERT_CHECKING
2199
2200 if (lp_truncate_only)
2201 {
2202 /* Setting LP_DEAD to LP_UNUSED in vacuum's second pass */
2204 }
2205 else
2206 {
2207 /*
2208 * When heap_page_prune_and_freeze() was called, mark_unused_now
2209 * may have been passed as true, which allows would-be LP_DEAD
2210 * items to be made LP_UNUSED instead. This is only possible if
2211 * the relation has no indexes. If there are any dead items, then
2212 * mark_unused_now was not true and every item being marked
2213 * LP_UNUSED must refer to a heap-only tuple.
2214 */
2215 if (ndead > 0)
2216 {
2218 htup = (HeapTupleHeader) PageGetItem(page, lp);
2220 }
2221 else
2223 }
2224
2225#endif
2226
2228 }
2229
2230 if (lp_truncate_only)
2232 else
2233 {
2234 /*
2235 * Finally, repair any fragmentation, and update the page's hint bit
2236 * about whether it has free pointers.
2237 */
2239
2240 /*
2241 * Now that the page has been modified, assert that redirect items
2242 * still point to valid targets.
2243 */
2245 }
2246}
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:468
void PageRepairFragmentation(Page page)
Definition bufpage.c:708
void PageTruncateLinePointerArray(Page page)
Definition bufpage.c:844
PageData * Page
Definition bufpage.h:81
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:308
#define ItemIdSetRedirect(itemId, link)
Definition itemid.h:152
#define ItemIdSetDead(itemId)
Definition itemid.h:164
#define ItemIdSetUnused(itemId)
Definition itemid.h:128
#define ItemIdHasStorage(itemId)
Definition itemid.h:120
static void page_verify_redirects(Page page)
Definition pruneheap.c:2263

References Assert, BufferGetPage(), fb(), HeapTupleHeaderIsHeapOnly(), i, ItemIdGetRedirect, ItemIdHasStorage, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemIdSetDead, ItemIdSetRedirect, ItemIdSetUnused, page_verify_redirects(), PageGetItem(), PageGetItemId(), PageRepairFragmentation(), PageTruncateLinePointerArray(), and PG_USED_FOR_ASSERTS_ONLY.

Referenced by heap_page_prune_and_freeze(), and heap_xlog_prune_freeze().

◆ heap_page_prune_opt()

void heap_page_prune_opt ( Relation  relation,
Buffer  buffer,
Buffer vmbuffer,
bool  rel_read_only 
)

Definition at line 272 of file pruneheap.c.

274{
275 Page page = BufferGetPage(buffer);
277 GlobalVisState *vistest;
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 if (RecoveryInProgress())
286 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 */
296 return;
297
298 /*
299 * Check whether prune_xid indicates that there may be dead rows that can
300 * be cleaned up.
301 */
302 vistest = GlobalVisTestFor(relation);
303
304 if (!GlobalVisTestIsRemovableXid(vistest, prune_xid, true))
305 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 */
321 minfree = Max(minfree, BLCKSZ / 10);
322
323 if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
324 {
325 bool record_free_space = false;
326 Size freespace = 0;
327
328 /* OK, try to get exclusive buffer lock */
330 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 if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
338 {
341 PruneFreezeParams params;
342
343 visibilitymap_pin(relation, BufferGetBlockNumber(buffer),
344 vmbuffer);
345
346 params.relation = relation;
347 params.buffer = buffer;
348 params.vmbuffer = *vmbuffer;
349 params.reason = PRUNE_ON_ACCESS;
350 params.vistest = vistest;
351 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 */
360 if (rel_read_only)
362
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 if (presult.ndeleted > presult.nnewlpdead)
382 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 if (presult.newly_all_visible)
392 {
393 record_free_space = true;
394 freespace = PageGetHeapFreeSpace(page);
395 }
396 }
397
398 /* And release buffer lock */
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 */
408 RecordPageWithFreeSpace(relation, BufferGetBlockNumber(buffer), freespace);
409 }
410}
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition bufmgr.c:4469
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition bufmgr.c:6892
Size PageGetHeapFreeSpace(const PageData *page)
Definition bufpage.c:1000
#define Max(x, y)
Definition c.h:1125
size_t Size
Definition c.h:748
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition freespace.c:194
#define HEAP_PAGE_PRUNE_SET_VM
Definition heapam.h:45
@ PRUNE_ON_ACCESS
Definition heapam.h:252
void pgstat_update_heap_dead_tuples(Relation rel, int delta)
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition procarray.c:4114
bool GlobalVisTestIsRemovableXid(GlobalVisState *state, TransactionId xid, bool allow_update)
Definition procarray.c:4277
void heap_page_prune_and_freeze(PruneFreezeParams *params, PruneFreezeResult *presult, OffsetNumber *off_loc, TransactionId *new_relfrozen_xid, MultiXactId *new_relmin_mxid)
Definition pruneheap.c:1112
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition rel.h:391
#define HEAP_DEFAULT_FILLFACTOR
Definition rel.h:362
VacuumCutoffs * cutoffs
Definition heapam.h:301
GlobalVisState * vistest
Definition heapam.h:292
Relation relation
Definition heapam.h:262
Buffer vmbuffer
Definition heapam.h:270
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
bool RecoveryInProgress(void)
Definition xlog.c:6835

References PruneFreezeParams::buffer, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage(), ConditionalLockBufferForCleanup(), PruneFreezeParams::cutoffs, fb(), GlobalVisTestFor(), GlobalVisTestIsRemovableXid(), HEAP_DEFAULT_FILLFACTOR, HEAP_PAGE_PRUNE_ALLOW_FAST_PATH, heap_page_prune_and_freeze(), HEAP_PAGE_PRUNE_SET_VM, LockBuffer(), Max, PruneFreezeParams::options, PageGetHeapFreeSpace(), PageGetPruneXid(), PageIsFull(), pgstat_update_heap_dead_tuples(), PRUNE_ON_ACCESS, PruneFreezeParams::reason, RecordPageWithFreeSpace(), RecoveryInProgress(), PruneFreezeParams::relation, RelationGetTargetPageFreeSpace, TransactionIdIsValid, visibilitymap_pin(), PruneFreezeParams::vistest, and PruneFreezeParams::vmbuffer.

Referenced by BitmapHeapScanNextBlock(), heap_prepare_pagescan(), and heapam_index_fetch_tuple().

◆ heap_page_will_freeze()

static bool heap_page_will_freeze ( bool  did_tuple_hint_fpi,
bool  do_prune,
bool  do_hint_prune,
PruneState prstate 
)
static

Definition at line 754 of file pruneheap.c.

758{
759 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 if (!prstate->attempt_freeze)
766 {
767 Assert(!prstate->set_all_frozen && prstate->nfrozen == 0);
768 return false;
769 }
770
771 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 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 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 if (RelationNeedsWAL(prstate->relation))
802 {
804 do_freeze = true;
805 else if (do_prune)
806 {
808 do_freeze = true;
809 }
810 else if (do_hint_prune)
811 {
812 if (XLogHintBitIsNeeded() &&
814 do_freeze = true;
815 }
816 }
817 }
818 }
819
820 if (do_freeze)
821 {
822 /*
823 * Validate the tuples we will be freezing before entering the
824 * critical section.
825 */
826 heap_pre_freeze_checks(prstate->buffer, prstate->frozen, prstate->nfrozen);
827 Assert(TransactionIdPrecedes(prstate->pagefrz.FreezePageConflictXid,
828 prstate->cutoffs->OldestXmin));
829 }
830 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 prstate->set_all_frozen = false;
839 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 return do_freeze;
852}
void heap_pre_freeze_checks(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
Definition heapam.c:7547
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
#define XLogHintBitIsNeeded()
Definition xlog.h:123
bool XLogCheckBufferNeedsBackup(Buffer buffer)

References Assert, fb(), heap_pre_freeze_checks(), RelationNeedsWAL, TransactionIdPrecedes(), XLogCheckBufferNeedsBackup(), and XLogHintBitIsNeeded.

Referenced by heap_page_prune_and_freeze().

◆ heap_page_will_set_vm()

static bool heap_page_will_set_vm ( PruneState prstate,
PruneReason  reason,
bool  do_prune,
bool  do_freeze 
)
static

Definition at line 972 of file pruneheap.c.

974{
975 if (!prstate->attempt_set_vm)
976 return false;
977
978 if (!prstate->set_all_visible)
979 return false;
980
981 /*
982 * If this is an on-access call and we're not actually pruning, avoid
983 * setting the visibility map if it would newly dirty the heap page or, if
984 * the page is already dirty, if doing so would require including a
985 * full-page image (FPI) of the heap page in the WAL.
986 */
987 if (reason == PRUNE_ON_ACCESS && !do_prune && !do_freeze &&
989 {
990 prstate->set_all_visible = prstate->set_all_frozen = false;
991 return false;
992 }
993
995
996 if (prstate->set_all_frozen)
997 prstate->new_vmbits |= VISIBILITYMAP_ALL_FROZEN;
998
999 if (prstate->new_vmbits == prstate->old_vmbits)
1000 {
1001 prstate->new_vmbits = 0;
1002 return false;
1003 }
1004
1005 return true;
1006}
bool BufferIsDirty(Buffer buffer)
Definition bufmgr.c:3137

References BufferIsDirty(), fb(), PRUNE_ON_ACCESS, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and XLogCheckBufferNeedsBackup().

Referenced by heap_page_prune_and_freeze().

◆ heap_prune_chain()

static void heap_prune_chain ( OffsetNumber  maxoff,
OffsetNumber  rootoffnum,
PruneState prstate 
)
static

Definition at line 1505 of file pruneheap.c.

1507{
1509 ItemId rootlp;
1510 OffsetNumber offnum;
1512 Page page = prstate->page;
1513
1514 /*
1515 * After traversing the HOT chain, ndeadchain is the index in chainitems
1516 * of the first live successor after the last dead item.
1517 */
1518 int ndeadchain = 0,
1519 nchain = 0;
1520
1522
1523 /* Start from the root tuple */
1524 offnum = rootoffnum;
1525
1526 /* while not end of the chain */
1527 for (;;)
1528 {
1529 HeapTupleHeader htup;
1530 ItemId lp;
1531
1532 /* Sanity check (pure paranoia) */
1533 if (offnum < FirstOffsetNumber)
1534 break;
1535
1536 /*
1537 * An offset past the end of page's line pointer array is possible
1538 * when the array was truncated (original item must have been unused)
1539 */
1540 if (offnum > maxoff)
1541 break;
1542
1543 /* If item is already processed, stop --- it must not be same chain */
1544 if (prstate->processed[offnum])
1545 break;
1546
1547 lp = PageGetItemId(page, offnum);
1548
1549 /*
1550 * Unused item obviously isn't part of the chain. Likewise, a dead
1551 * line pointer can't be part of the chain. Both of those cases were
1552 * already marked as processed.
1553 */
1556
1557 /*
1558 * If we are looking at the redirected root line pointer, jump to the
1559 * first normal tuple in the chain. If we find a redirect somewhere
1560 * else, stop --- it must not be same chain.
1561 */
1563 {
1564 if (nchain > 0)
1565 break; /* not at start of chain */
1566 chainitems[nchain++] = offnum;
1567 offnum = ItemIdGetRedirect(rootlp);
1568 continue;
1569 }
1570
1572
1573 htup = (HeapTupleHeader) PageGetItem(page, lp);
1574
1575 /*
1576 * Check the tuple XMIN against prior XMAX, if any
1577 */
1580 break;
1581
1582 /*
1583 * OK, this tuple is indeed a member of the chain.
1584 */
1585 chainitems[nchain++] = offnum;
1586
1587 switch (htsv_get_valid_status(prstate->htsv[offnum]))
1588 {
1589 case HEAPTUPLE_DEAD:
1590
1591 /* Remember the last DEAD tuple seen */
1594 &prstate->latest_xid_removed);
1595 /* Advance to next chain member */
1596 break;
1597
1599
1600 /*
1601 * We don't need to advance the conflict horizon for
1602 * RECENTLY_DEAD tuples, even if we are removing them. This
1603 * is because we only remove RECENTLY_DEAD tuples if they
1604 * precede a DEAD tuple, and the DEAD tuple must have been
1605 * inserted by a newer transaction than the RECENTLY_DEAD
1606 * tuple by virtue of being later in the chain. We will have
1607 * advanced the conflict horizon for the DEAD tuple.
1608 */
1609
1610 /*
1611 * Advance past RECENTLY_DEAD tuples just in case there's a
1612 * DEAD one after them. We have to make sure that we don't
1613 * miss any DEAD tuples, since DEAD tuples that still have
1614 * tuple storage after pruning will confuse VACUUM.
1615 */
1616 break;
1617
1619 case HEAPTUPLE_LIVE:
1621 goto process_chain;
1622
1623 default:
1624 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1625 goto process_chain;
1626 }
1627
1628 /*
1629 * If the tuple is not HOT-updated, then we are at the end of this
1630 * HOT-update chain.
1631 */
1632 if (!HeapTupleHeaderIsHotUpdated(htup))
1633 goto process_chain;
1634
1635 /* HOT implies it can't have moved to different partition */
1637
1638 /*
1639 * Advance to next chain member.
1640 */
1642 offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
1644 }
1645
1646 if (ItemIdIsRedirected(rootlp) && nchain < 2)
1647 {
1648 /*
1649 * We found a redirect item that doesn't point to a valid follow-on
1650 * item. This can happen if the loop in heap_page_prune_and_freeze()
1651 * caused us to visit the dead successor of a redirect item before
1652 * visiting the redirect item. We can clean up by setting the
1653 * redirect item to LP_DEAD state or LP_UNUSED if the caller
1654 * indicated.
1655 */
1657 return;
1658 }
1659
1661
1662 if (ndeadchain == 0)
1663 {
1664 /*
1665 * No DEAD tuple was found, so the chain is entirely composed of
1666 * normal, unchanged tuples. Leave it alone.
1667 */
1668 int i = 0;
1669
1671 {
1673 i++;
1674 }
1675 for (; i < nchain; i++)
1677 }
1678 else if (ndeadchain == nchain)
1679 {
1680 /*
1681 * The entire chain is dead. Mark the root line pointer LP_DEAD, and
1682 * fully remove the other tuples in the chain.
1683 */
1685 for (int i = 1; i < nchain; i++)
1687 }
1688 else
1689 {
1690 /*
1691 * We found a DEAD tuple in the chain. Redirect the root line pointer
1692 * to the first non-DEAD tuple, and mark as unused each intermediate
1693 * item that we are able to remove from the chain.
1694 */
1697 for (int i = 1; i < ndeadchain; i++)
1699
1700 /* the rest of tuples in the chain are normal, unchanged tuples */
1701 for (int i = ndeadchain; i < nchain; i++)
1703 }
1704}
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
void HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
Definition heapam.c:8194
@ HEAPTUPLE_RECENTLY_DEAD
Definition heapam.h:140
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition heapam.h:141
@ HEAPTUPLE_LIVE
Definition heapam.h:139
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition heapam.h:142
@ HEAPTUPLE_DEAD
Definition heapam.h:138
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition itemptr.h:103
static HTSV_Result htsv_get_valid_status(int status)
Definition pruneheap.c:1466
static void heap_prune_record_unused(PruneState *prstate, OffsetNumber offnum, bool was_normal)
Definition pruneheap.c:1823
static void heap_prune_record_redirect(PruneState *prstate, OffsetNumber offnum, OffsetNumber rdoffnum, bool was_normal)
Definition pruneheap.c:1731
static void heap_prune_record_dead_or_unused(PruneState *prstate, OffsetNumber offnum, bool was_normal)
Definition pruneheap.c:1797
static void heap_prune_record_unchanged_lp_redirect(PruneState *prstate, OffsetNumber offnum)
Definition pruneheap.c:2062
static void heap_prune_record_unchanged_lp_normal(PruneState *prstate, OffsetNumber offnum)
Definition pruneheap.c:1856

References Assert, elog, ERROR, fb(), FirstOffsetNumber, heap_prune_record_dead_or_unused(), heap_prune_record_redirect(), heap_prune_record_unchanged_lp_normal(), heap_prune_record_unchanged_lp_redirect(), heap_prune_record_unused(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderAdvanceConflictHorizon(), HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderGetXmin(), HeapTupleHeaderIndicatesMovedPartitions(), HeapTupleHeaderIsHotUpdated(), htsv_get_valid_status(), i, InvalidTransactionId, ItemIdGetRedirect, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), MaxHeapTuplesPerPage, PageGetItem(), PageGetItemId(), HeapTupleHeaderData::t_ctid, TransactionIdEquals, and TransactionIdIsValid.

Referenced by prune_freeze_plan().

◆ heap_prune_record_dead()

static void heap_prune_record_dead ( PruneState prstate,
OffsetNumber  offnum,
bool  was_normal 
)
static

Definition at line 1762 of file pruneheap.c.

1764{
1765 Assert(!prstate->processed[offnum]);
1766 prstate->processed[offnum] = true;
1767
1769 prstate->nowdead[prstate->ndead] = offnum;
1770 prstate->ndead++;
1771
1772 /*
1773 * Deliberately delay unsetting set_all_visible and set_all_frozen until
1774 * later during pruning. Removable dead tuples shouldn't preclude freezing
1775 * the page.
1776 */
1777
1778 /* Record the dead offset for vacuum */
1779 prstate->deadoffsets[prstate->lpdead_items++] = offnum;
1780
1781 /*
1782 * If the root entry had been a normal tuple, we are deleting it, so count
1783 * it in the result. But changing a redirect (even to DEAD state) doesn't
1784 * count.
1785 */
1786 if (was_normal)
1787 prstate->ndeleted++;
1788}

References Assert, fb(), and MaxHeapTuplesPerPage.

Referenced by heap_prune_record_dead_or_unused().

◆ heap_prune_record_dead_or_unused()

static void heap_prune_record_dead_or_unused ( PruneState prstate,
OffsetNumber  offnum,
bool  was_normal 
)
static

Definition at line 1797 of file pruneheap.c.

1799{
1800 /*
1801 * If the caller set mark_unused_now to true, we can remove dead tuples
1802 * during pruning instead of marking their line pointers dead. Set this
1803 * tuple's line pointer LP_UNUSED. We hint that this option is less
1804 * likely.
1805 */
1806 if (unlikely(prstate->mark_unused_now))
1808 else
1810
1811 /*
1812 * It's incorrect for the page to be set all-visible if it contains dead
1813 * items. Fix that on the heap page and check the VM for corruption as
1814 * well. Do that here rather than in heap_prune_record_dead() so we also
1815 * cover tuples that are directly marked LP_UNUSED via mark_unused_now.
1816 */
1817 if (PageIsAllVisible(prstate->page))
1819}
#define unlikely(x)
Definition c.h:497
static void heap_prune_record_dead(PruneState *prstate, OffsetNumber offnum, bool was_normal)
Definition pruneheap.c:1762

References fb(), heap_page_fix_vm_corruption(), heap_prune_record_dead(), heap_prune_record_unused(), PageIsAllVisible(), unlikely, and VM_CORRUPT_LPDEAD.

Referenced by heap_prune_chain().

◆ heap_prune_record_prunable()

static void heap_prune_record_prunable ( PruneState prstate,
TransactionId  xid,
OffsetNumber  offnum 
)
static

Definition at line 1708 of file pruneheap.c.

1710{
1711 /*
1712 * This should exactly match the PageSetPrunable macro. We can't store
1713 * directly into the page header yet, so we update working state.
1714 */
1716 if (!TransactionIdIsValid(prstate->new_prune_xid) ||
1717 TransactionIdPrecedes(xid, prstate->new_prune_xid))
1718 prstate->new_prune_xid = xid;
1719
1720 /*
1721 * It's incorrect for a page to be marked all-visible if it contains
1722 * prunable items.
1723 */
1724 if (PageIsAllVisible(prstate->page))
1727}

References Assert, fb(), heap_page_fix_vm_corruption(), PageIsAllVisible(), TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), and VM_CORRUPT_TUPLE_VISIBILITY.

Referenced by heap_prune_record_unchanged_lp_normal().

◆ heap_prune_record_redirect()

static void heap_prune_record_redirect ( PruneState prstate,
OffsetNumber  offnum,
OffsetNumber  rdoffnum,
bool  was_normal 
)
static

Definition at line 1731 of file pruneheap.c.

1734{
1735 Assert(!prstate->processed[offnum]);
1736 prstate->processed[offnum] = true;
1737
1738 /*
1739 * Do not mark the redirect target here. It needs to be counted
1740 * separately as an unchanged tuple.
1741 */
1742
1743 Assert(prstate->nredirected < MaxHeapTuplesPerPage);
1744 prstate->redirected[prstate->nredirected * 2] = offnum;
1745 prstate->redirected[prstate->nredirected * 2 + 1] = rdoffnum;
1746
1747 prstate->nredirected++;
1748
1749 /*
1750 * If the root entry had been a normal tuple, we are deleting it, so count
1751 * it in the result. But changing a redirect (even to DEAD state) doesn't
1752 * count.
1753 */
1754 if (was_normal)
1755 prstate->ndeleted++;
1756
1757 prstate->hastup = true;
1758}

References Assert, fb(), and MaxHeapTuplesPerPage.

Referenced by heap_prune_chain().

◆ heap_prune_record_unchanged_lp_dead()

static void heap_prune_record_unchanged_lp_dead ( PruneState prstate,
OffsetNumber  offnum 
)
static

Definition at line 2027 of file pruneheap.c.

2028{
2029 Assert(!prstate->processed[offnum]);
2030 prstate->processed[offnum] = true;
2031
2032 /*
2033 * Deliberately don't set hastup for LP_DEAD items. We make the soft
2034 * assumption that any LP_DEAD items encountered here will become
2035 * LP_UNUSED later on, before count_nondeletable_pages is reached. If we
2036 * don't make this assumption then rel truncation will only happen every
2037 * other VACUUM, at most. Besides, VACUUM must treat
2038 * hastup/nonempty_pages as provisional no matter how LP_DEAD items are
2039 * handled (handled here, or handled later on).
2040 *
2041 * Similarly, don't unset set_all_visible and set_all_frozen until later,
2042 * at the end of heap_page_prune_and_freeze(). This will allow us to
2043 * attempt to freeze the page after pruning. As long as we unset it
2044 * before updating the visibility map, this will be correct.
2045 */
2046
2047 /* Record the dead offset for vacuum */
2048 prstate->deadoffsets[prstate->lpdead_items++] = offnum;
2049
2050 /*
2051 * It's incorrect for a page to be marked all-visible if it contains dead
2052 * items.
2053 */
2054 if (PageIsAllVisible(prstate->page))
2056}

References Assert, fb(), heap_page_fix_vm_corruption(), PageIsAllVisible(), and VM_CORRUPT_LPDEAD.

Referenced by prune_freeze_plan().

◆ heap_prune_record_unchanged_lp_normal()

static void heap_prune_record_unchanged_lp_normal ( PruneState prstate,
OffsetNumber  offnum 
)
static

Definition at line 1856 of file pruneheap.c.

1857{
1858 HeapTupleHeader htup;
1859 TransactionId xmin;
1860 Page page = prstate->page;
1861
1862 Assert(!prstate->processed[offnum]);
1863 prstate->processed[offnum] = true;
1864
1865 prstate->hastup = true; /* the page is not empty */
1866
1867 /*
1868 * The criteria for counting a tuple as live in this block need to match
1869 * what analyze.c's acquire_sample_rows() does, otherwise VACUUM and
1870 * ANALYZE may produce wildly different reltuples values, e.g. when there
1871 * are many recently-dead tuples.
1872 *
1873 * The logic here is a bit simpler than acquire_sample_rows(), as VACUUM
1874 * can't run inside a transaction block, which makes some cases impossible
1875 * (e.g. in-progress insert from the same transaction).
1876 *
1877 * HEAPTUPLE_DEAD are handled by the other heap_prune_record_*()
1878 * subroutines. They don't count dead items like acquire_sample_rows()
1879 * does, because we assume that all dead items will become LP_UNUSED
1880 * before VACUUM finishes. This difference is only superficial. VACUUM
1881 * effectively agrees with ANALYZE about DEAD items, in the end. VACUUM
1882 * won't remember LP_DEAD items, but only because they're not supposed to
1883 * be left behind when it is done. (Cases where we bypass index vacuuming
1884 * will violate this optimistic assumption, but the overall impact of that
1885 * should be negligible.)
1886 */
1887 htup = (HeapTupleHeader) PageGetItem(page, PageGetItemId(page, offnum));
1888
1889 switch (prstate->htsv[offnum])
1890 {
1891 case HEAPTUPLE_LIVE:
1892
1893 /*
1894 * Count it as live. Not only is this natural, but it's also what
1895 * acquire_sample_rows() does.
1896 */
1897 prstate->live_tuples++;
1898
1899 /*
1900 * Is the tuple definitely visible to all transactions?
1901 *
1902 * NB: Like with per-tuple hint bits, we can't set the
1903 * PD_ALL_VISIBLE flag if the inserter committed asynchronously.
1904 * See SetHintBits for more info. Check that the tuple is hinted
1905 * xmin-committed because of that.
1906 */
1908 {
1909 prstate->set_all_visible = false;
1910 prstate->set_all_frozen = false;
1911 break;
1912 }
1913
1914 /*
1915 * The inserter definitely committed. But we don't know if it is
1916 * old enough that everyone sees it as committed. Later, after
1917 * processing all the tuples on the page, we'll check if there is
1918 * any snapshot that still considers the newest xid on the page to
1919 * be running. If so, we don't consider the page all-visible.
1920 */
1921 xmin = HeapTupleHeaderGetXmin(htup);
1922
1923 /* Track newest xmin on page. */
1924 if (TransactionIdFollows(xmin, prstate->newest_live_xid) &&
1926 prstate->newest_live_xid = xmin;
1927
1928 break;
1929
1931 prstate->recently_dead_tuples++;
1932 prstate->set_all_visible = false;
1933 prstate->set_all_frozen = false;
1934
1935 /*
1936 * This tuple will soon become DEAD. Update the hint field so
1937 * that the page is reconsidered for pruning in future.
1938 */
1941 offnum);
1942 break;
1943
1945
1946 /*
1947 * We do not count these rows as live, because we expect the
1948 * inserting transaction to update the counters at commit, and we
1949 * assume that will happen only after we report our results. This
1950 * assumption is a bit shaky, but it is what acquire_sample_rows()
1951 * does, so be consistent.
1952 */
1953 prstate->set_all_visible = false;
1954 prstate->set_all_frozen = false;
1955
1956 /*
1957 * Though there is nothing "prunable" on the page, we maintain
1958 * pd_prune_xid for inserts so that we have the opportunity to
1959 * mark them all-visible during the next round of pruning.
1960 */
1963 offnum);
1964 break;
1965
1967
1968 /*
1969 * This an expected case during concurrent vacuum. Count such
1970 * rows as live. As above, we assume the deleting transaction
1971 * will commit and update the counters after we report.
1972 */
1973 prstate->live_tuples++;
1974 prstate->set_all_visible = false;
1975 prstate->set_all_frozen = false;
1976
1977 /*
1978 * This tuple may soon become DEAD. Update the hint field so that
1979 * the page is reconsidered for pruning in future.
1980 */
1983 offnum);
1984 break;
1985
1986 default:
1987
1988 /*
1989 * DEAD tuples should've been passed to heap_prune_record_dead()
1990 * or heap_prune_record_unused() instead.
1991 */
1992 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result %d",
1993 prstate->htsv[offnum]);
1994 break;
1995 }
1996
1997 /* Consider freezing any normal tuples which will not be removed */
1998 if (prstate->attempt_freeze)
1999 {
2000 bool totally_frozen;
2001
2002 if ((heap_prepare_freeze_tuple(htup,
2003 prstate->cutoffs,
2004 &prstate->pagefrz,
2005 &prstate->frozen[prstate->nfrozen],
2006 &totally_frozen)))
2007 {
2008 /* Save prepared freeze plan for later */
2009 prstate->frozen[prstate->nfrozen++].offset = offnum;
2010 }
2011
2012 /*
2013 * If any tuple isn't either totally frozen already or eligible to
2014 * become totally frozen (according to its freeze plan), then the page
2015 * definitely cannot be set all-frozen in the visibility map later on.
2016 */
2017 if (!totally_frozen)
2018 prstate->set_all_frozen = false;
2019 }
2020}
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition heapam.c:7267
static bool HeapTupleHeaderXminCommitted(const HeapTupleHeaderData *tup)
static void heap_prune_record_prunable(PruneState *prstate, TransactionId xid, OffsetNumber offnum)
Definition pruneheap.c:1708

References Assert, elog, ERROR, fb(), heap_prepare_freeze_tuple(), heap_prune_record_prunable(), HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderGetXmin(), HeapTupleHeaderXminCommitted(), PageGetItem(), PageGetItemId(), TransactionIdFollows(), and TransactionIdIsNormal.

Referenced by heap_prune_chain(), and prune_freeze_plan().

◆ heap_prune_record_unchanged_lp_redirect()

static void heap_prune_record_unchanged_lp_redirect ( PruneState prstate,
OffsetNumber  offnum 
)
static

Definition at line 2062 of file pruneheap.c.

2063{
2064 /*
2065 * A redirect line pointer doesn't count as a live tuple.
2066 *
2067 * If we leave a redirect line pointer in place, there will be another
2068 * tuple on the page that it points to. We will do the bookkeeping for
2069 * that separately. So we have nothing to do here, except remember that
2070 * we processed this item.
2071 */
2072 Assert(!prstate->processed[offnum]);
2073 prstate->processed[offnum] = true;
2074}

References Assert, and fb().

Referenced by heap_prune_chain().

◆ heap_prune_record_unchanged_lp_unused()

static void heap_prune_record_unchanged_lp_unused ( PruneState prstate,
OffsetNumber  offnum 
)
static

Definition at line 1845 of file pruneheap.c.

1846{
1847 Assert(!prstate->processed[offnum]);
1848 prstate->processed[offnum] = true;
1849}

References Assert, and fb().

Referenced by prune_freeze_plan().

◆ heap_prune_record_unused()

static void heap_prune_record_unused ( PruneState prstate,
OffsetNumber  offnum,
bool  was_normal 
)
static

Definition at line 1823 of file pruneheap.c.

1824{
1825 Assert(!prstate->processed[offnum]);
1826 prstate->processed[offnum] = true;
1827
1829 prstate->nowunused[prstate->nunused] = offnum;
1830 prstate->nunused++;
1831
1832 /*
1833 * If the root entry had been a normal tuple, we are deleting it, so count
1834 * it in the result. But changing a redirect (even to DEAD state) doesn't
1835 * count.
1836 */
1837 if (was_normal)
1838 prstate->ndeleted++;
1839}

References Assert, fb(), and MaxHeapTuplesPerPage.

Referenced by heap_prune_chain(), heap_prune_record_dead_or_unused(), and prune_freeze_plan().

◆ heap_prune_satisfies_vacuum()

static HTSV_Result heap_prune_satisfies_vacuum ( PruneState prstate,
HeapTuple  tup 
)
static

Definition at line 1423 of file pruneheap.c.

1424{
1425 HTSV_Result res;
1427
1429
1430 if (res != HEAPTUPLE_RECENTLY_DEAD)
1431 return res;
1432
1433 /*
1434 * For VACUUM, we must be sure to prune tuples with xmax older than
1435 * OldestXmin -- a visibility cutoff determined at the beginning of
1436 * vacuuming the relation. OldestXmin is used for freezing determination
1437 * and we cannot freeze dead tuples' xmaxes.
1438 */
1439 if (prstate->cutoffs &&
1440 TransactionIdIsValid(prstate->cutoffs->OldestXmin) &&
1441 NormalTransactionIdPrecedes(dead_after, prstate->cutoffs->OldestXmin))
1442 return HEAPTUPLE_DEAD;
1443
1444 /*
1445 * Determine whether or not the tuple is considered dead when compared
1446 * with the provided GlobalVisState. On-access pruning does not provide
1447 * VacuumCutoffs. And for vacuum, even if the tuple's xmax is not older
1448 * than OldestXmin, GlobalVisTestIsRemovableXid() could find the row dead
1449 * if the GlobalVisState has been updated since the beginning of vacuuming
1450 * the relation.
1451 */
1452 if (GlobalVisTestIsRemovableXid(prstate->vistest, dead_after, true))
1453 return HEAPTUPLE_DEAD;
1454
1455 return res;
1456}
HTSV_Result
Definition heapam.h:137
HTSV_Result HeapTupleSatisfiesVacuumHorizon(HeapTuple htup, Buffer buffer, TransactionId *dead_after)
#define NormalTransactionIdPrecedes(id1, id2)
Definition transam.h:147

References fb(), GlobalVisTestIsRemovableXid(), HEAPTUPLE_DEAD, HEAPTUPLE_RECENTLY_DEAD, HeapTupleSatisfiesVacuumHorizon(), NormalTransactionIdPrecedes, and TransactionIdIsValid.

Referenced by prune_freeze_plan().

◆ htsv_get_valid_status()

static HTSV_Result htsv_get_valid_status ( int  status)
inlinestatic

Definition at line 1466 of file pruneheap.c.

1467{
1468 Assert(status >= HEAPTUPLE_DEAD &&
1470 return (HTSV_Result) status;
1471}

References Assert, HEAPTUPLE_DEAD, and HEAPTUPLE_DELETE_IN_PROGRESS.

Referenced by heap_prune_chain().

◆ log_heap_prune_and_freeze()

void log_heap_prune_and_freeze ( Relation  relation,
Buffer  buffer,
Buffer  vmbuffer,
uint8  vmflags,
TransactionId  conflict_xid,
bool  cleanup_lock,
PruneReason  reason,
HeapTupleFreeze frozen,
int  nfrozen,
OffsetNumber redirected,
int  nredirected,
OffsetNumber dead,
int  ndead,
OffsetNumber unused,
int  nunused 
)

Definition at line 2583 of file pruneheap.c.

2592{
2595 uint8 info;
2597
2598 Page heap_page = BufferGetPage(buffer);
2599
2600 /* The following local variables hold data registered in the WAL record: */
2604 xlhp_prune_items dead_items;
2607 bool do_prune = nredirected > 0 || ndead > 0 || nunused > 0;
2609 bool heap_fpi_allowed = true;
2610
2612
2613 xlrec.flags = 0;
2615
2616 /*
2617 * We can avoid an FPI of the heap page if the only modification we are
2618 * making to it is to set PD_ALL_VISIBLE and checksums/wal_log_hints are
2619 * disabled.
2620 *
2621 * However, if the page has never been WAL-logged (LSN is invalid), we
2622 * must force an FPI regardless. This can happen when another backend
2623 * extends the heap, initializes the page, and then fails before WAL-
2624 * logging it. Since heap extension is not WAL-logged, recovery might try
2625 * to replay our record and find that the page isn't initialized, which
2626 * would cause a PANIC.
2627 */
2630 else if (!do_prune && nfrozen == 0 && (!do_set_vm || !XLogHintBitIsNeeded()))
2631 {
2633 heap_fpi_allowed = false;
2634 }
2635
2636 /*
2637 * Prepare data for the buffer. The arrays are not actually in the
2638 * buffer, but we pretend that they are. When XLogInsert stores a full
2639 * page image, the arrays can be omitted.
2640 */
2643
2644 if (do_set_vm)
2645 XLogRegisterBuffer(1, vmbuffer, 0);
2646
2647 if (nfrozen > 0)
2648 {
2649 int nplans;
2650
2652
2653 /*
2654 * Prepare deduplicated representation for use in the WAL record. This
2655 * destructively sorts frozen tuples array in-place.
2656 */
2657 nplans = heap_log_freeze_plan(frozen, nfrozen, plans, frz_offsets);
2658
2659 freeze_plans.nplans = nplans;
2661 offsetof(xlhp_freeze_plans, plans));
2662 XLogRegisterBufData(0, plans,
2663 sizeof(xlhp_freeze_plan) * nplans);
2664 }
2665 if (nredirected > 0)
2666 {
2668
2669 redirect_items.ntargets = nredirected;
2672 XLogRegisterBufData(0, redirected,
2673 sizeof(OffsetNumber[2]) * nredirected);
2674 }
2675 if (ndead > 0)
2676 {
2677 xlrec.flags |= XLHP_HAS_DEAD_ITEMS;
2678
2679 dead_items.ntargets = ndead;
2680 XLogRegisterBufData(0, &dead_items,
2682 XLogRegisterBufData(0, dead,
2683 sizeof(OffsetNumber) * ndead);
2684 }
2685 if (nunused > 0)
2686 {
2688
2689 unused_items.ntargets = nunused;
2692 XLogRegisterBufData(0, unused,
2693 sizeof(OffsetNumber) * nunused);
2694 }
2695 if (nfrozen > 0)
2697 sizeof(OffsetNumber) * nfrozen);
2698
2699 /*
2700 * Prepare the main xl_heap_prune record. We already set the XLHP_HAS_*
2701 * flag above.
2702 */
2704 {
2705 xlrec.flags |= XLHP_VM_ALL_VISIBLE;
2707 xlrec.flags |= XLHP_VM_ALL_FROZEN;
2708 }
2710 xlrec.flags |= XLHP_IS_CATALOG_REL;
2713 if (cleanup_lock)
2714 xlrec.flags |= XLHP_CLEANUP_LOCK;
2715 else
2716 {
2717 Assert(nredirected == 0 && ndead == 0);
2718 /* also, any items in 'unused' must've been LP_DEAD previously */
2719 }
2723
2724 switch (reason)
2725 {
2726 case PRUNE_ON_ACCESS:
2728 break;
2729 case PRUNE_VACUUM_SCAN:
2731 break;
2734 break;
2735 default:
2736 elog(ERROR, "unrecognized prune reason: %d", (int) reason);
2737 break;
2738 }
2739 recptr = XLogInsert(RM_HEAP2_ID, info);
2740
2741 if (do_set_vm)
2742 {
2743 Assert(BufferIsDirty(vmbuffer));
2744 PageSetLSN(BufferGetPage(vmbuffer), recptr);
2745 }
2746
2747 /*
2748 * If we explicitly skip an FPI, we must not stamp the heap page with this
2749 * record's LSN. Recovery skips records <= the stamped LSN, so this could
2750 * lead to skipping an earlier FPI needed to repair a torn page.
2751 */
2752 if (heap_fpi_allowed)
2753 {
2754 Assert(BufferIsDirty(buffer));
2756 }
2757}
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition bufpage.h:416
static XLogRecPtr PageGetLSN(const PageData *page)
Definition bufpage.h:410
uint8_t uint8
Definition c.h:681
@ PRUNE_VACUUM_CLEANUP
Definition heapam.h:254
@ PRUNE_VACUUM_SCAN
Definition heapam.h:253
#define XLHP_HAS_CONFLICT_HORIZON
#define XLHP_HAS_FREEZE_PLANS
#define XLHP_VM_ALL_VISIBLE
#define SizeOfHeapPrune
#define XLHP_HAS_NOW_UNUSED_ITEMS
#define XLHP_VM_ALL_FROZEN
#define XLHP_HAS_REDIRECTIONS
#define XLOG_HEAP2_PRUNE_VACUUM_SCAN
Definition heapam_xlog.h:61
#define XLOG_HEAP2_PRUNE_ON_ACCESS
Definition heapam_xlog.h:60
#define XLHP_CLEANUP_LOCK
#define XLHP_HAS_DEAD_ITEMS
#define XLOG_HEAP2_PRUNE_VACUUM_CLEANUP
Definition heapam_xlog.h:62
#define XLHP_IS_CATALOG_REL
const void * data
static int heap_log_freeze_plan(HeapTupleFreeze *tuples, int ntuples, xlhp_freeze_plan *plans_out, OffsetNumber *offsets_out)
Definition pruneheap.c:2504
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition rel.h:704
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
uint64 XLogRecPtr
Definition xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:482
void XLogRegisterBufData(uint8 block_id, const void *data, uint32 len)
Definition xloginsert.c:413
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:372
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition xloginsert.c:246
void XLogBeginInsert(void)
Definition xloginsert.c:153
#define REGBUF_STANDARD
Definition xloginsert.h:35
#define REGBUF_FORCE_IMAGE
Definition xloginsert.h:32
#define REGBUF_NO_IMAGE
Definition xloginsert.h:33

References Assert, BufferGetPage(), BufferIsDirty(), data, elog, ERROR, fb(), heap_log_freeze_plan(), MaxHeapTuplesPerPage, xlhp_prune_items::ntargets, PageGetLSN(), PageSetLSN(), PRUNE_ON_ACCESS, PRUNE_VACUUM_CLEANUP, PRUNE_VACUUM_SCAN, REGBUF_FORCE_IMAGE, REGBUF_NO_IMAGE, REGBUF_STANDARD, RelationIsAccessibleInLogicalDecoding, SizeOfHeapPrune, TransactionIdIsValid, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, VISIBILITYMAP_VALID_BITS, XLHP_CLEANUP_LOCK, XLHP_HAS_CONFLICT_HORIZON, XLHP_HAS_DEAD_ITEMS, XLHP_HAS_FREEZE_PLANS, XLHP_HAS_NOW_UNUSED_ITEMS, XLHP_HAS_REDIRECTIONS, XLHP_IS_CATALOG_REL, XLHP_VM_ALL_FROZEN, XLHP_VM_ALL_VISIBLE, XLOG_HEAP2_PRUNE_ON_ACCESS, XLOG_HEAP2_PRUNE_VACUUM_CLEANUP, XLOG_HEAP2_PRUNE_VACUUM_SCAN, XLogBeginInsert(), XLogHintBitIsNeeded, XLogInsert(), XLogRecPtrIsValid, XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by heap_page_prune_and_freeze(), lazy_scan_new_or_empty(), and lazy_vacuum_heap_page().

◆ page_verify_redirects()

static void page_verify_redirects ( Page  page)
static

Definition at line 2263 of file pruneheap.c.

2264{
2265#ifdef USE_ASSERT_CHECKING
2266 OffsetNumber offnum;
2267 OffsetNumber maxoff;
2268
2269 maxoff = PageGetMaxOffsetNumber(page);
2270 for (offnum = FirstOffsetNumber;
2271 offnum <= maxoff;
2272 offnum = OffsetNumberNext(offnum))
2273 {
2274 ItemId itemid = PageGetItemId(page, offnum);
2277 HeapTupleHeader htup;
2278
2279 if (!ItemIdIsRedirected(itemid))
2280 continue;
2281
2282 targoff = ItemIdGetRedirect(itemid);
2284
2288 htup = (HeapTupleHeader) PageGetItem(page, targitem);
2290 }
2291#endif
2292}

References Assert, fb(), FirstOffsetNumber, HeapTupleHeaderIsHeapOnly(), ItemIdGetRedirect, ItemIdHasStorage, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, OffsetNumberNext, PageGetItem(), PageGetItemId(), and PageGetMaxOffsetNumber().

Referenced by heap_page_prune_execute().

◆ prune_freeze_fast_path()

static void prune_freeze_fast_path ( PruneState prstate,
PruneFreezeResult presult 
)
static

Definition at line 1029 of file pruneheap.c.

1030{
1032 Page page = prstate->page;
1033
1034 Assert((prstate->old_vmbits & VISIBILITYMAP_ALL_FROZEN) ||
1035 ((prstate->old_vmbits & VISIBILITYMAP_ALL_VISIBLE) &&
1036 !prstate->attempt_freeze));
1037
1038 /* We'll fill in presult for the caller */
1039 memset(presult, 0, sizeof(PruneFreezeResult));
1040
1041 /* Clear any stale prune hint */
1043 {
1044 PageClearPrunable(page);
1045 MarkBufferDirtyHint(prstate->buffer, true);
1046 }
1047
1048 if (PageIsEmpty(page))
1049 return;
1050
1051 /*
1052 * Since the page is all-visible, a count of the normal ItemIds on the
1053 * page should be sufficient for vacuum's live tuple count.
1054 */
1056 off <= maxoff;
1057 off = OffsetNumberNext(off))
1058 {
1059 ItemId lp = PageGetItemId(page, off);
1060
1061 if (!ItemIdIsUsed(lp))
1062 continue;
1063
1064 presult->hastup = true;
1065
1066 if (ItemIdIsNormal(lp))
1067 prstate->live_tuples++;
1068 }
1069
1070 presult->live_tuples = prstate->live_tuples;
1071}
static bool PageIsEmpty(const PageData *page)
Definition bufpage.h:248

References Assert, fb(), FirstOffsetNumber, ItemIdIsNormal, ItemIdIsUsed, MarkBufferDirtyHint(), OffsetNumberNext, PageClearPrunable, PageGetItemId(), PageGetMaxOffsetNumber(), PageGetPruneXid(), PageIsEmpty(), TransactionIdIsValid, VISIBILITYMAP_ALL_FROZEN, and VISIBILITYMAP_ALL_VISIBLE.

Referenced by heap_page_prune_and_freeze().

◆ prune_freeze_plan()

static void prune_freeze_plan ( PruneState prstate,
OffsetNumber off_loc 
)
static

Definition at line 551 of file pruneheap.c.

552{
553 Page page = prstate->page;
554 BlockNumber blockno = prstate->block;
556 OffsetNumber offnum;
558
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 for (offnum = maxoff;
582 offnum >= FirstOffsetNumber;
583 offnum = OffsetNumberPrev(offnum))
584 {
585 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 *off_loc = offnum;
593
594 prstate->processed[offnum] = false;
595 prstate->htsv[offnum] = -1;
596
597 /* Nothing to do if slot doesn't contain a tuple */
598 if (!ItemIdIsUsed(itemid))
599 {
601 continue;
602 }
603
604 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 if (unlikely(prstate->mark_unused_now))
611 heap_prune_record_unused(prstate, offnum, false);
612 else
614 continue;
615 }
616
617 if (ItemIdIsRedirected(itemid))
618 {
619 /* This is the start of a HOT chain */
620 prstate->root_items[prstate->nroot_items++] = offnum;
621 continue;
622 }
623
624 Assert(ItemIdIsNormal(itemid));
625
626 /*
627 * Get the tuple's visibility status and queue it up for processing.
628 */
629 htup = (HeapTupleHeader) PageGetItem(page, itemid);
630 tup.t_data = htup;
631 tup.t_len = ItemIdGetLength(itemid);
632 ItemPointerSet(&tup.t_self, blockno, offnum);
633
635
636 if (!HeapTupleHeaderIsHeapOnly(htup))
637 prstate->root_items[prstate->nroot_items++] = offnum;
638 else
639 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 for (int i = prstate->nroot_items - 1; i >= 0; i--)
654 {
655 offnum = prstate->root_items[i];
656
657 /* Ignore items already processed as part of an earlier chain */
658 if (prstate->processed[offnum])
659 continue;
660
661 /* see preceding loop */
662 *off_loc = offnum;
663
664 /* Process this item or chain of items */
665 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 for (int i = prstate->nheaponly_items - 1; i >= 0; i--)
673 {
674 offnum = prstate->heaponly_items[i];
675
676 if (prstate->processed[offnum])
677 continue;
678
679 /* see preceding loop */
680 *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 if (prstate->htsv[offnum] == HEAPTUPLE_DEAD)
696 {
697 ItemId itemid = PageGetItemId(page, offnum);
698 HeapTupleHeader htup = (HeapTupleHeader) PageGetItem(page, itemid);
699
701 {
703 &prstate->latest_xid_removed);
704 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 elog(ERROR, "dead heap-only tuple (%u, %d) is not linked to from any HOT chain",
717 blockno, offnum);
718 }
719 }
720 else
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. */
738}
uint32 BlockNumber
Definition block.h:31
#define likely(x)
Definition c.h:496
#define ItemIdGetLength(itemId)
Definition itemid.h:59
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition itemptr.h:135
#define OffsetNumberPrev(offsetNumber)
Definition off.h:54
static void heap_prune_chain(OffsetNumber maxoff, OffsetNumber rootoffnum, PruneState *prstate)
Definition pruneheap.c:1505
static void heap_prune_record_unchanged_lp_unused(PruneState *prstate, OffsetNumber offnum)
Definition pruneheap.c:1845
static void heap_prune_record_unchanged_lp_dead(PruneState *prstate, OffsetNumber offnum)
Definition pruneheap.c:2027
static HTSV_Result heap_prune_satisfies_vacuum(PruneState *prstate, HeapTuple tup)
Definition pruneheap.c:1423
#define RelationGetRelid(relation)
Definition rel.h:516
Oid t_tableOid
Definition htup.h:66

References Assert, elog, ERROR, fb(), FirstOffsetNumber, heap_prune_chain(), heap_prune_record_unchanged_lp_dead(), heap_prune_record_unchanged_lp_normal(), heap_prune_record_unchanged_lp_unused(), heap_prune_record_unused(), heap_prune_satisfies_vacuum(), HEAPTUPLE_DEAD, HeapTupleHeaderAdvanceConflictHorizon(), HeapTupleHeaderIsHeapOnly(), HeapTupleHeaderIsHotUpdated(), i, InvalidOffsetNumber, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet(), likely, OffsetNumberNext, OffsetNumberPrev, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), RelationGetRelid, HeapTupleData::t_tableOid, and unlikely.

Referenced by heap_page_prune_and_freeze().

◆ prune_freeze_setup()

static void prune_freeze_setup ( PruneFreezeParams params,
TransactionId new_relfrozen_xid,
MultiXactId new_relmin_mxid,
PruneFreezeResult presult,
PruneState prstate 
)
static

Definition at line 420 of file pruneheap.c.

425{
426 /* Copy parameters to prstate */
427 prstate->vistest = params->vistest;
428 prstate->mark_unused_now =
430
431 /* cutoffs must be provided if we will attempt freezing */
432 Assert(!(params->options & HEAP_PAGE_PRUNE_FREEZE) || params->cutoffs);
433 prstate->attempt_freeze = (params->options & HEAP_PAGE_PRUNE_FREEZE) != 0;
434 prstate->attempt_set_vm = (params->options & HEAP_PAGE_PRUNE_SET_VM) != 0;
435 prstate->cutoffs = params->cutoffs;
436 prstate->relation = params->relation;
437 prstate->block = BufferGetBlockNumber(params->buffer);
438 prstate->buffer = params->buffer;
439 prstate->page = BufferGetPage(params->buffer);
440
441 Assert(BufferIsValid(params->vmbuffer));
442 prstate->vmbuffer = params->vmbuffer;
443 prstate->new_vmbits = 0;
444 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 prstate->new_prune_xid = InvalidTransactionId;
460 prstate->latest_xid_removed = InvalidTransactionId;
461 prstate->nredirected = prstate->ndead = prstate->nunused = 0;
462 prstate->nfrozen = 0;
463 prstate->nroot_items = 0;
464 prstate->nheaponly_items = 0;
465
466 /* initialize page freezing working state */
467 prstate->pagefrz.freeze_required = false;
468 prstate->pagefrz.FreezePageConflictXid = InvalidTransactionId;
469 if (prstate->attempt_freeze)
470 {
472 prstate->pagefrz.FreezePageRelfrozenXid = *new_relfrozen_xid;
473 prstate->pagefrz.NoFreezePageRelfrozenXid = *new_relfrozen_xid;
474 prstate->pagefrz.FreezePageRelminMxid = *new_relmin_mxid;
475 prstate->pagefrz.NoFreezePageRelminMxid = *new_relmin_mxid;
476 }
477 else
478 {
480 prstate->pagefrz.FreezePageRelminMxid = InvalidMultiXactId;
481 prstate->pagefrz.NoFreezePageRelminMxid = InvalidMultiXactId;
482 prstate->pagefrz.FreezePageRelfrozenXid = InvalidTransactionId;
483 prstate->pagefrz.NoFreezePageRelfrozenXid = InvalidTransactionId;
484 }
485
486 prstate->ndeleted = 0;
487 prstate->live_tuples = 0;
488 prstate->recently_dead_tuples = 0;
489 prstate->hastup = false;
490 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 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 prstate->set_all_visible = prstate->attempt_set_vm;
511 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 prstate->set_all_frozen = prstate->attempt_freeze && prstate->attempt_set_vm;
539}
static bool BufferIsValid(Buffer bufnum)
Definition bufmgr.h:419
#define HEAP_PAGE_PRUNE_FREEZE
Definition heapam.h:43
#define HEAP_PAGE_PRUNE_MARK_UNUSED_NOW
Definition heapam.h:42
#define InvalidMultiXactId
Definition multixact.h:25
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)

References Assert, PruneFreezeParams::buffer, BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), PruneFreezeParams::cutoffs, fb(), HEAP_PAGE_PRUNE_FREEZE, HEAP_PAGE_PRUNE_MARK_UNUSED_NOW, HEAP_PAGE_PRUNE_SET_VM, InvalidMultiXactId, InvalidTransactionId, PruneFreezeParams::options, PruneFreezeParams::relation, visibilitymap_get_status(), PruneFreezeParams::vistest, and PruneFreezeParams::vmbuffer.

Referenced by heap_page_prune_and_freeze().