Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * heapam.c
4 : * heap access method code
5 : *
6 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/access/heap/heapam.c
12 : *
13 : *
14 : * INTERFACE ROUTINES
15 : * heap_beginscan - begin relation scan
16 : * heap_rescan - restart a relation scan
17 : * heap_endscan - end relation scan
18 : * heap_getnext - retrieve next tuple in scan
19 : * heap_fetch - retrieve tuple with given tid
20 : * heap_insert - insert tuple into a relation
21 : * heap_multi_insert - insert multiple tuples into a relation
22 : * heap_delete - delete a tuple from a relation
23 : * heap_update - replace a tuple in a relation with another tuple
24 : *
25 : * NOTES
26 : * This file contains the heap_ routines which implement
27 : * the POSTGRES heap access method used for all POSTGRES
28 : * relations.
29 : *
30 : *-------------------------------------------------------------------------
31 : */
32 : #include "postgres.h"
33 :
34 : #include "access/bufmask.h"
35 : #include "access/heapam.h"
36 : #include "access/heapam_xlog.h"
37 : #include "access/heaptoast.h"
38 : #include "access/hio.h"
39 : #include "access/multixact.h"
40 : #include "access/parallel.h"
41 : #include "access/relscan.h"
42 : #include "access/subtrans.h"
43 : #include "access/syncscan.h"
44 : #include "access/sysattr.h"
45 : #include "access/tableam.h"
46 : #include "access/transam.h"
47 : #include "access/valid.h"
48 : #include "access/visibilitymap.h"
49 : #include "access/xact.h"
50 : #include "access/xlog.h"
51 : #include "access/xloginsert.h"
52 : #include "access/xlogutils.h"
53 : #include "catalog/catalog.h"
54 : #include "commands/vacuum.h"
55 : #include "miscadmin.h"
56 : #include "pgstat.h"
57 : #include "port/atomics.h"
58 : #include "port/pg_bitutils.h"
59 : #include "storage/bufmgr.h"
60 : #include "storage/freespace.h"
61 : #include "storage/lmgr.h"
62 : #include "storage/predicate.h"
63 : #include "storage/procarray.h"
64 : #include "storage/standby.h"
65 : #include "utils/datum.h"
66 : #include "utils/inval.h"
67 : #include "utils/relcache.h"
68 : #include "utils/snapmgr.h"
69 : #include "utils/spccache.h"
70 :
71 :
72 : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
73 : TransactionId xid, CommandId cid, int options);
74 : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
75 : Buffer newbuf, HeapTuple oldtup,
76 : HeapTuple newtup, HeapTuple old_key_tuple,
77 : bool all_visible_cleared, bool new_all_visible_cleared);
78 : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
79 : Bitmapset *interesting_cols,
80 : Bitmapset *external_cols,
81 : HeapTuple oldtup, HeapTuple newtup,
82 : bool *has_external);
83 : static bool heap_acquire_tuplock(Relation relation, ItemPointer tid,
84 : LockTupleMode mode, LockWaitPolicy wait_policy,
85 : bool *have_tuple_lock);
86 : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
87 : BlockNumber block,
88 : ScanDirection dir);
89 : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
90 : ScanDirection dir);
91 : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
92 : uint16 old_infomask2, TransactionId add_to_xmax,
93 : LockTupleMode mode, bool is_update,
94 : TransactionId *result_xmax, uint16 *result_infomask,
95 : uint16 *result_infomask2);
96 : static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple,
97 : ItemPointer ctid, TransactionId xid,
98 : LockTupleMode mode);
99 : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
100 : uint16 *new_infomask2);
101 : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
102 : uint16 t_infomask);
103 : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
104 : LockTupleMode lockmode, bool *current_is_member);
105 : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
106 : Relation rel, ItemPointer ctid, XLTW_Oper oper,
107 : int *remaining);
108 : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
109 : uint16 infomask, Relation rel, int *remaining);
110 : static void index_delete_sort(TM_IndexDeleteOp *delstate);
111 : static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
112 : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
113 : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
114 : bool *copy);
115 :
116 :
117 : /*
118 : * Each tuple lock mode has a corresponding heavyweight lock, and one or two
119 : * corresponding MultiXactStatuses (one to merely lock tuples, another one to
120 : * update them). This table (and the macros below) helps us determine the
121 : * heavyweight lock mode and MultiXactStatus values to use for any particular
122 : * tuple lock strength.
123 : *
124 : * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
125 : * instead.
126 : */
127 : static const struct
128 : {
129 : LOCKMODE hwlock;
130 : int lockstatus;
131 : int updstatus;
132 : }
133 :
134 : tupleLockExtraInfo[MaxLockTupleMode + 1] =
135 : {
136 : { /* LockTupleKeyShare */
137 : AccessShareLock,
138 : MultiXactStatusForKeyShare,
139 : -1 /* KeyShare does not allow updating tuples */
140 : },
141 : { /* LockTupleShare */
142 : RowShareLock,
143 : MultiXactStatusForShare,
144 : -1 /* Share does not allow updating tuples */
145 : },
146 : { /* LockTupleNoKeyExclusive */
147 : ExclusiveLock,
148 : MultiXactStatusForNoKeyUpdate,
149 : MultiXactStatusNoKeyUpdate
150 : },
151 : { /* LockTupleExclusive */
152 : AccessExclusiveLock,
153 : MultiXactStatusForUpdate,
154 : MultiXactStatusUpdate
155 : }
156 : };
157 :
158 : /* Get the LOCKMODE for a given MultiXactStatus */
159 : #define LOCKMODE_from_mxstatus(status) \
160 : (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
161 :
162 : /*
163 : * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
164 : * This is more readable than having every caller translate it to lock.h's
165 : * LOCKMODE.
166 : */
167 : #define LockTupleTuplock(rel, tup, mode) \
168 : LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
169 : #define UnlockTupleTuplock(rel, tup, mode) \
170 : UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
171 : #define ConditionalLockTupleTuplock(rel, tup, mode) \
172 : ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
173 :
174 : #ifdef USE_PREFETCH
175 : /*
176 : * heap_index_delete_tuples and index_delete_prefetch_buffer use this
177 : * structure to coordinate prefetching activity
178 : */
179 : typedef struct
180 : {
181 : BlockNumber cur_hblkno;
182 : int next_item;
183 : int ndeltids;
184 : TM_IndexDelete *deltids;
185 : } IndexDeletePrefetchState;
186 : #endif
187 :
188 : /* heap_index_delete_tuples bottom-up index deletion costing constants */
189 : #define BOTTOMUP_MAX_NBLOCKS 6
190 : #define BOTTOMUP_TOLERANCE_NBLOCKS 3
191 :
192 : /*
193 : * heap_index_delete_tuples uses this when determining which heap blocks it
194 : * must visit to help its bottom-up index deletion caller
195 : */
196 : typedef struct IndexDeleteCounts
197 : {
198 : int16 npromisingtids; /* Number of "promising" TIDs in group */
199 : int16 ntids; /* Number of TIDs in group */
200 : int16 ifirsttid; /* Offset to group's first deltid */
201 : } IndexDeleteCounts;
202 :
203 : /*
204 : * This table maps tuple lock strength values for each particular
205 : * MultiXactStatus value.
206 : */
207 : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
208 : {
209 : LockTupleKeyShare, /* ForKeyShare */
210 : LockTupleShare, /* ForShare */
211 : LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
212 : LockTupleExclusive, /* ForUpdate */
213 : LockTupleNoKeyExclusive, /* NoKeyUpdate */
214 : LockTupleExclusive /* Update */
215 : };
216 :
217 : /* Get the LockTupleMode for a given MultiXactStatus */
218 : #define TUPLOCK_from_mxstatus(status) \
219 : (MultiXactStatusLock[(status)])
220 :
221 : /* ----------------------------------------------------------------
222 : * heap support routines
223 : * ----------------------------------------------------------------
224 : */
225 :
226 : /*
227 : * Streaming read API callback for parallel sequential scans. Returns the next
228 : * block the caller wants from the read stream or InvalidBlockNumber when done.
229 : */
230 : static BlockNumber
231 200904 : heap_scan_stream_read_next_parallel(ReadStream *stream,
232 : void *callback_private_data,
233 : void *per_buffer_data)
234 : {
235 200904 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
236 :
237 : Assert(ScanDirectionIsForward(scan->rs_dir));
238 : Assert(scan->rs_base.rs_parallel);
239 :
240 200904 : if (unlikely(!scan->rs_inited))
241 : {
242 : /* parallel scan */
243 2774 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
244 2774 : scan->rs_parallelworkerdata,
245 2774 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
246 :
247 : /* may return InvalidBlockNumber if there are no more blocks */
248 5548 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
249 2774 : scan->rs_parallelworkerdata,
250 2774 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
251 2774 : scan->rs_inited = true;
252 : }
253 : else
254 : {
255 198130 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
256 198130 : scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
257 198130 : scan->rs_base.rs_parallel);
258 : }
259 :
260 200904 : return scan->rs_prefetch_block;
261 : }
262 :
263 : /*
264 : * Streaming read API callback for serial sequential and TID range scans.
265 : * Returns the next block the caller wants from the read stream or
266 : * InvalidBlockNumber when done.
267 : */
268 : static BlockNumber
269 6048008 : heap_scan_stream_read_next_serial(ReadStream *stream,
270 : void *callback_private_data,
271 : void *per_buffer_data)
272 : {
273 6048008 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
274 :
275 6048008 : if (unlikely(!scan->rs_inited))
276 : {
277 1545378 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
278 1545378 : scan->rs_inited = true;
279 : }
280 : else
281 4502630 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
282 : scan->rs_prefetch_block,
283 : scan->rs_dir);
284 :
285 6048008 : return scan->rs_prefetch_block;
286 : }
287 :
288 : /* ----------------
289 : * initscan - scan code common to heap_beginscan and heap_rescan
290 : * ----------------
291 : */
292 : static void
293 1584734 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
294 : {
295 1584734 : ParallelBlockTableScanDesc bpscan = NULL;
296 : bool allow_strat;
297 : bool allow_sync;
298 :
299 : /*
300 : * Determine the number of blocks we have to scan.
301 : *
302 : * It is sufficient to do this once at scan start, since any tuples added
303 : * while the scan is in progress will be invisible to my snapshot anyway.
304 : * (That is not true when using a non-MVCC snapshot. However, we couldn't
305 : * guarantee to return tuples added after scan start anyway, since they
306 : * might go into pages we already scanned. To guarantee consistent
307 : * results for a non-MVCC snapshot, the caller must hold some higher-level
308 : * lock that ensures the interesting tuple(s) won't change.)
309 : */
310 1584734 : if (scan->rs_base.rs_parallel != NULL)
311 : {
312 3964 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
313 3964 : scan->rs_nblocks = bpscan->phs_nblocks;
314 : }
315 : else
316 1580770 : scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
317 :
318 : /*
319 : * If the table is large relative to NBuffers, use a bulk-read access
320 : * strategy and enable synchronized scanning (see syncscan.c). Although
321 : * the thresholds for these features could be different, we make them the
322 : * same so that there are only two behaviors to tune rather than four.
323 : * (However, some callers need to be able to disable one or both of these
324 : * behaviors, independently of the size of the table; also there is a GUC
325 : * variable that can disable synchronized scanning.)
326 : *
327 : * Note that table_block_parallelscan_initialize has a very similar test;
328 : * if you change this, consider changing that one, too.
329 : */
330 1584730 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
331 1572954 : scan->rs_nblocks > NBuffers / 4)
332 : {
333 21320 : allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
334 21320 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
335 : }
336 : else
337 1563410 : allow_strat = allow_sync = false;
338 :
339 1584730 : if (allow_strat)
340 : {
341 : /* During a rescan, keep the previous strategy object. */
342 18846 : if (scan->rs_strategy == NULL)
343 18644 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
344 : }
345 : else
346 : {
347 1565884 : if (scan->rs_strategy != NULL)
348 0 : FreeAccessStrategy(scan->rs_strategy);
349 1565884 : scan->rs_strategy = NULL;
350 : }
351 :
352 1584730 : if (scan->rs_base.rs_parallel != NULL)
353 : {
354 : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
355 3964 : if (scan->rs_base.rs_parallel->phs_syncscan)
356 4 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
357 : else
358 3960 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
359 : }
360 1580766 : else if (keep_startblock)
361 : {
362 : /*
363 : * When rescanning, we want to keep the previous startblock setting,
364 : * so that rewinding a cursor doesn't generate surprising results.
365 : * Reset the active syncscan setting, though.
366 : */
367 980140 : if (allow_sync && synchronize_seqscans)
368 40 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
369 : else
370 980100 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
371 : }
372 600626 : else if (allow_sync && synchronize_seqscans)
373 : {
374 118 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
375 118 : scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
376 : }
377 : else
378 : {
379 600508 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
380 600508 : scan->rs_startblock = 0;
381 : }
382 :
383 1584730 : scan->rs_numblocks = InvalidBlockNumber;
384 1584730 : scan->rs_inited = false;
385 1584730 : scan->rs_ctup.t_data = NULL;
386 1584730 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
387 1584730 : scan->rs_cbuf = InvalidBuffer;
388 1584730 : scan->rs_cblock = InvalidBlockNumber;
389 :
390 : /*
391 : * Initialize to ForwardScanDirection because it is most common and
392 : * because heap scans go forward before going backward (e.g. CURSORs).
393 : */
394 1584730 : scan->rs_dir = ForwardScanDirection;
395 1584730 : scan->rs_prefetch_block = InvalidBlockNumber;
396 :
397 : /* page-at-a-time fields are always invalid when not rs_inited */
398 :
399 : /*
400 : * copy the scan key, if appropriate
401 : */
402 1584730 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
403 337268 : memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
404 :
405 : /*
406 : * Currently, we only have a stats counter for sequential heap scans (but
407 : * e.g for bitmap scans the underlying bitmap index scans will be counted,
408 : * and for sample scans we update stats for tuple fetches).
409 : */
410 1584730 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
411 1549656 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
412 1584730 : }
413 :
414 : /*
415 : * heap_setscanlimits - restrict range of a heapscan
416 : *
417 : * startBlk is the page to start at
418 : * numBlks is number of pages to scan (InvalidBlockNumber means "all")
419 : */
420 : void
421 3748 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
422 : {
423 3748 : HeapScanDesc scan = (HeapScanDesc) sscan;
424 :
425 : Assert(!scan->rs_inited); /* else too late to change */
426 : /* else rs_startblock is significant */
427 : Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
428 :
429 : /* Check startBlk is valid (but allow case of zero blocks...) */
430 : Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
431 :
432 3748 : scan->rs_startblock = startBlk;
433 3748 : scan->rs_numblocks = numBlks;
434 3748 : }
435 :
436 : /*
437 : * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
438 : * multiple times, with constant arguments for all_visible,
439 : * check_serializable.
440 : */
441 : pg_attribute_always_inline
442 : static int
443 3823514 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
444 : Page page, Buffer buffer,
445 : BlockNumber block, int lines,
446 : bool all_visible, bool check_serializable)
447 : {
448 3823514 : int ntup = 0;
449 : OffsetNumber lineoff;
450 :
451 199581462 : for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
452 : {
453 195757964 : ItemId lpp = PageGetItemId(page, lineoff);
454 : HeapTupleData loctup;
455 : bool valid;
456 :
457 195757964 : if (!ItemIdIsNormal(lpp))
458 37040410 : continue;
459 :
460 158717554 : loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
461 158717554 : loctup.t_len = ItemIdGetLength(lpp);
462 158717554 : loctup.t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
463 158717554 : ItemPointerSet(&(loctup.t_self), block, lineoff);
464 :
465 158717554 : if (all_visible)
466 51789464 : valid = true;
467 : else
468 106928090 : valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
469 :
470 158717554 : if (check_serializable)
471 2834 : HeapCheckForSerializableConflictOut(valid, scan->rs_base.rs_rd,
472 : &loctup, buffer, snapshot);
473 :
474 158717538 : if (valid)
475 : {
476 146120078 : scan->rs_vistuples[ntup] = lineoff;
477 146120078 : ntup++;
478 : }
479 : }
480 :
481 : Assert(ntup <= MaxHeapTuplesPerPage);
482 :
483 3823498 : return ntup;
484 : }
485 :
486 : /*
487 : * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
488 : *
489 : * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
490 : * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
491 : */
492 : void
493 3823514 : heap_prepare_pagescan(TableScanDesc sscan)
494 : {
495 3823514 : HeapScanDesc scan = (HeapScanDesc) sscan;
496 3823514 : Buffer buffer = scan->rs_cbuf;
497 3823514 : BlockNumber block = scan->rs_cblock;
498 : Snapshot snapshot;
499 : Page page;
500 : int lines;
501 : bool all_visible;
502 : bool check_serializable;
503 :
504 : Assert(BufferGetBlockNumber(buffer) == block);
505 :
506 : /* ensure we're not accidentally being used when not in pagemode */
507 : Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
508 3823514 : snapshot = scan->rs_base.rs_snapshot;
509 :
510 : /*
511 : * Prune and repair fragmentation for the whole page, if possible.
512 : */
513 3823514 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
514 :
515 : /*
516 : * We must hold share lock on the buffer content while examining tuple
517 : * visibility. Afterwards, however, the tuples we have found to be
518 : * visible are guaranteed good as long as we hold the buffer pin.
519 : */
520 3823514 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
521 :
522 3823514 : page = BufferGetPage(buffer);
523 3823514 : lines = PageGetMaxOffsetNumber(page);
524 :
525 : /*
526 : * If the all-visible flag indicates that all tuples on the page are
527 : * visible to everyone, we can skip the per-tuple visibility tests.
528 : *
529 : * Note: In hot standby, a tuple that's already visible to all
530 : * transactions on the primary might still be invisible to a read-only
531 : * transaction in the standby. We partly handle this problem by tracking
532 : * the minimum xmin of visible tuples as the cut-off XID while marking a
533 : * page all-visible on the primary and WAL log that along with the
534 : * visibility map SET operation. In hot standby, we wait for (or abort)
535 : * all transactions that can potentially may not see one or more tuples on
536 : * the page. That's how index-only scans work fine in hot standby. A
537 : * crucial difference between index-only scans and heap scans is that the
538 : * index-only scan completely relies on the visibility map where as heap
539 : * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
540 : * the page-level flag can be trusted in the same way, because it might
541 : * get propagated somehow without being explicitly WAL-logged, e.g. via a
542 : * full page write. Until we can prove that beyond doubt, let's check each
543 : * tuple for visibility the hard way.
544 : */
545 3823514 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
546 : check_serializable =
547 3823514 : CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
548 :
549 : /*
550 : * We call page_collect_tuples() with constant arguments, to get the
551 : * compiler to constant fold the constant arguments. Separate calls with
552 : * constant arguments, rather than variables, are needed on several
553 : * compilers to actually perform constant folding.
554 : */
555 3823514 : if (likely(all_visible))
556 : {
557 1164508 : if (likely(!check_serializable))
558 1164508 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
559 : block, lines, true, false);
560 : else
561 0 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
562 : block, lines, true, true);
563 : }
564 : else
565 : {
566 2659006 : if (likely(!check_serializable))
567 2657750 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
568 : block, lines, false, false);
569 : else
570 1256 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
571 : block, lines, false, true);
572 : }
573 :
574 3823498 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
575 3823498 : }
576 :
577 : /*
578 : * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
579 : *
580 : * Read the next block of the scan relation from the read stream and save it
581 : * in the scan descriptor. It is already pinned.
582 : */
583 : static inline void
584 5305896 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
585 : {
586 : Assert(scan->rs_read_stream);
587 :
588 : /* release previous scan buffer, if any */
589 5305896 : if (BufferIsValid(scan->rs_cbuf))
590 : {
591 3757738 : ReleaseBuffer(scan->rs_cbuf);
592 3757738 : scan->rs_cbuf = InvalidBuffer;
593 : }
594 :
595 : /*
596 : * Be sure to check for interrupts at least once per page. Checks at
597 : * higher code levels won't be able to stop a seqscan that encounters many
598 : * pages' worth of consecutive dead tuples.
599 : */
600 5305896 : CHECK_FOR_INTERRUPTS();
601 :
602 : /*
603 : * If the scan direction is changing, reset the prefetch block to the
604 : * current block. Otherwise, we will incorrectly prefetch the blocks
605 : * between the prefetch block and the current block again before
606 : * prefetching blocks in the new, correct scan direction.
607 : */
608 5305890 : if (unlikely(scan->rs_dir != dir))
609 : {
610 154 : scan->rs_prefetch_block = scan->rs_cblock;
611 154 : read_stream_reset(scan->rs_read_stream);
612 : }
613 :
614 5305890 : scan->rs_dir = dir;
615 :
616 5305890 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
617 5305890 : if (BufferIsValid(scan->rs_cbuf))
618 3998718 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
619 5305890 : }
620 :
621 : /*
622 : * heapgettup_initial_block - return the first BlockNumber to scan
623 : *
624 : * Returns InvalidBlockNumber when there are no blocks to scan. This can
625 : * occur with empty tables and in parallel scans when parallel workers get all
626 : * of the pages before we can get a chance to get our first page.
627 : */
628 : static pg_noinline BlockNumber
629 1545378 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
630 : {
631 : Assert(!scan->rs_inited);
632 : Assert(scan->rs_base.rs_parallel == NULL);
633 :
634 : /* When there are no pages to scan, return InvalidBlockNumber */
635 1545378 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
636 759620 : return InvalidBlockNumber;
637 :
638 785758 : if (ScanDirectionIsForward(dir))
639 : {
640 785694 : return scan->rs_startblock;
641 : }
642 : else
643 : {
644 : /*
645 : * Disable reporting to syncscan logic in a backwards scan; it's not
646 : * very likely anyone else is doing the same thing at the same time,
647 : * and much more likely that we'll just bollix things for forward
648 : * scanners.
649 : */
650 64 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
651 :
652 : /*
653 : * Start from last page of the scan. Ensure we take into account
654 : * rs_numblocks if it's been adjusted by heap_setscanlimits().
655 : */
656 64 : if (scan->rs_numblocks != InvalidBlockNumber)
657 6 : return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
658 :
659 58 : if (scan->rs_startblock > 0)
660 0 : return scan->rs_startblock - 1;
661 :
662 58 : return scan->rs_nblocks - 1;
663 : }
664 : }
665 :
666 :
667 : /*
668 : * heapgettup_start_page - helper function for heapgettup()
669 : *
670 : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
671 : * to the number of tuples on this page. Also set *lineoff to the first
672 : * offset to scan with forward scans getting the first offset and backward
673 : * getting the final offset on the page.
674 : */
675 : static Page
676 183756 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
677 : OffsetNumber *lineoff)
678 : {
679 : Page page;
680 :
681 : Assert(scan->rs_inited);
682 : Assert(BufferIsValid(scan->rs_cbuf));
683 :
684 : /* Caller is responsible for ensuring buffer is locked if needed */
685 183756 : page = BufferGetPage(scan->rs_cbuf);
686 :
687 183756 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
688 :
689 183756 : if (ScanDirectionIsForward(dir))
690 183756 : *lineoff = FirstOffsetNumber;
691 : else
692 0 : *lineoff = (OffsetNumber) (*linesleft);
693 :
694 : /* lineoff now references the physically previous or next tid */
695 183756 : return page;
696 : }
697 :
698 :
699 : /*
700 : * heapgettup_continue_page - helper function for heapgettup()
701 : *
702 : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
703 : * to the number of tuples left to scan on this page. Also set *lineoff to
704 : * the next offset to scan according to the ScanDirection in 'dir'.
705 : */
706 : static inline Page
707 15408632 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
708 : OffsetNumber *lineoff)
709 : {
710 : Page page;
711 :
712 : Assert(scan->rs_inited);
713 : Assert(BufferIsValid(scan->rs_cbuf));
714 :
715 : /* Caller is responsible for ensuring buffer is locked if needed */
716 15408632 : page = BufferGetPage(scan->rs_cbuf);
717 :
718 15408632 : if (ScanDirectionIsForward(dir))
719 : {
720 15408632 : *lineoff = OffsetNumberNext(scan->rs_coffset);
721 15408632 : *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
722 : }
723 : else
724 : {
725 : /*
726 : * The previous returned tuple may have been vacuumed since the
727 : * previous scan when we use a non-MVCC snapshot, so we must
728 : * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
729 : */
730 0 : *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
731 0 : *linesleft = *lineoff;
732 : }
733 :
734 : /* lineoff now references the physically previous or next tid */
735 15408632 : return page;
736 : }
737 :
738 : /*
739 : * heapgettup_advance_block - helper for heap_fetch_next_buffer()
740 : *
741 : * Given the current block number, the scan direction, and various information
742 : * contained in the scan descriptor, calculate the BlockNumber to scan next
743 : * and return it. If there are no further blocks to scan, return
744 : * InvalidBlockNumber to indicate this fact to the caller.
745 : *
746 : * This should not be called to determine the initial block number -- only for
747 : * subsequent blocks.
748 : *
749 : * This also adjusts rs_numblocks when a limit has been imposed by
750 : * heap_setscanlimits().
751 : */
752 : static inline BlockNumber
753 4502630 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
754 : {
755 : Assert(scan->rs_base.rs_parallel == NULL);
756 :
757 4502630 : if (likely(ScanDirectionIsForward(dir)))
758 : {
759 4502512 : block++;
760 :
761 : /* wrap back to the start of the heap */
762 4502512 : if (block >= scan->rs_nblocks)
763 695420 : block = 0;
764 :
765 : /*
766 : * Report our new scan position for synchronization purposes. We don't
767 : * do that when moving backwards, however. That would just mess up any
768 : * other forward-moving scanners.
769 : *
770 : * Note: we do this before checking for end of scan so that the final
771 : * state of the position hint is back at the start of the rel. That's
772 : * not strictly necessary, but otherwise when you run the same query
773 : * multiple times the starting position would shift a little bit
774 : * backwards on every invocation, which is confusing. We don't
775 : * guarantee any specific ordering in general, though.
776 : */
777 4502512 : if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
778 17574 : ss_report_location(scan->rs_base.rs_rd, block);
779 :
780 : /* we're done if we're back at where we started */
781 4502512 : if (block == scan->rs_startblock)
782 695338 : return InvalidBlockNumber;
783 :
784 : /* check if the limit imposed by heap_setscanlimits() is met */
785 3807174 : if (scan->rs_numblocks != InvalidBlockNumber)
786 : {
787 3180 : if (--scan->rs_numblocks == 0)
788 3052 : return InvalidBlockNumber;
789 : }
790 :
791 3804122 : return block;
792 : }
793 : else
794 : {
795 : /* we're done if the last block is the start position */
796 118 : if (block == scan->rs_startblock)
797 118 : return InvalidBlockNumber;
798 :
799 : /* check if the limit imposed by heap_setscanlimits() is met */
800 0 : if (scan->rs_numblocks != InvalidBlockNumber)
801 : {
802 0 : if (--scan->rs_numblocks == 0)
803 0 : return InvalidBlockNumber;
804 : }
805 :
806 : /* wrap to the end of the heap when the last page was page 0 */
807 0 : if (block == 0)
808 0 : block = scan->rs_nblocks;
809 :
810 0 : block--;
811 :
812 0 : return block;
813 : }
814 : }
815 :
816 : /* ----------------
817 : * heapgettup - fetch next heap tuple
818 : *
819 : * Initialize the scan if not already done; then advance to the next
820 : * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
821 : * or set scan->rs_ctup.t_data = NULL if no more tuples.
822 : *
823 : * Note: the reason nkeys/key are passed separately, even though they are
824 : * kept in the scan descriptor, is that the caller may not want us to check
825 : * the scankeys.
826 : *
827 : * Note: when we fall off the end of the scan in either direction, we
828 : * reset rs_inited. This means that a further request with the same
829 : * scan direction will restart the scan, which is a bit odd, but a
830 : * request with the opposite scan direction will start a fresh scan
831 : * in the proper direction. The latter is required behavior for cursors,
832 : * while the former case is generally undefined behavior in Postgres
833 : * so we don't care too much.
834 : * ----------------
835 : */
836 : static void
837 15447148 : heapgettup(HeapScanDesc scan,
838 : ScanDirection dir,
839 : int nkeys,
840 : ScanKey key)
841 : {
842 15447148 : HeapTuple tuple = &(scan->rs_ctup);
843 : Page page;
844 : OffsetNumber lineoff;
845 : int linesleft;
846 :
847 15447148 : if (likely(scan->rs_inited))
848 : {
849 : /* continue from previously returned page/tuple */
850 15408632 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
851 15408632 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
852 15408632 : goto continue_page;
853 : }
854 :
855 : /*
856 : * advance the scan until we find a qualifying tuple or run out of stuff
857 : * to scan
858 : */
859 : while (true)
860 : {
861 221974 : heap_fetch_next_buffer(scan, dir);
862 :
863 : /* did we run out of blocks to scan? */
864 221974 : if (!BufferIsValid(scan->rs_cbuf))
865 38218 : break;
866 :
867 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
868 :
869 183756 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
870 183756 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
871 15592388 : continue_page:
872 :
873 : /*
874 : * Only continue scanning the page while we have lines left.
875 : *
876 : * Note that this protects us from accessing line pointers past
877 : * PageGetMaxOffsetNumber(); both for forward scans when we resume the
878 : * table scan, and for when we start scanning a new page.
879 : */
880 15690198 : for (; linesleft > 0; linesleft--, lineoff += dir)
881 : {
882 : bool visible;
883 15506740 : ItemId lpp = PageGetItemId(page, lineoff);
884 :
885 15506740 : if (!ItemIdIsNormal(lpp))
886 87444 : continue;
887 :
888 15419296 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
889 15419296 : tuple->t_len = ItemIdGetLength(lpp);
890 15419296 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
891 :
892 15419296 : visible = HeapTupleSatisfiesVisibility(tuple,
893 : scan->rs_base.rs_snapshot,
894 : scan->rs_cbuf);
895 :
896 15419296 : HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
897 : tuple, scan->rs_cbuf,
898 : scan->rs_base.rs_snapshot);
899 :
900 : /* skip tuples not visible to this snapshot */
901 15419296 : if (!visible)
902 10366 : continue;
903 :
904 : /* skip any tuples that don't match the scan key */
905 15408930 : if (key != NULL &&
906 0 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
907 : nkeys, key))
908 0 : continue;
909 :
910 15408930 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
911 15408930 : scan->rs_coffset = lineoff;
912 15408930 : return;
913 : }
914 :
915 : /*
916 : * if we get here, it means we've exhausted the items on this page and
917 : * it's time to move to the next.
918 : */
919 183458 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
920 : }
921 :
922 : /* end of scan */
923 38218 : if (BufferIsValid(scan->rs_cbuf))
924 0 : ReleaseBuffer(scan->rs_cbuf);
925 :
926 38218 : scan->rs_cbuf = InvalidBuffer;
927 38218 : scan->rs_cblock = InvalidBlockNumber;
928 38218 : scan->rs_prefetch_block = InvalidBlockNumber;
929 38218 : tuple->t_data = NULL;
930 38218 : scan->rs_inited = false;
931 : }
932 :
933 : /* ----------------
934 : * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
935 : *
936 : * Same API as heapgettup, but used in page-at-a-time mode
937 : *
938 : * The internal logic is much the same as heapgettup's too, but there are some
939 : * differences: we do not take the buffer content lock (that only needs to
940 : * happen inside heap_prepare_pagescan), and we iterate through just the
941 : * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
942 : * that lineindex is 0-based, where the corresponding loop variable lineoff in
943 : * heapgettup is 1-based.
944 : * ----------------
945 : */
946 : static void
947 74680950 : heapgettup_pagemode(HeapScanDesc scan,
948 : ScanDirection dir,
949 : int nkeys,
950 : ScanKey key)
951 : {
952 74680950 : HeapTuple tuple = &(scan->rs_ctup);
953 : Page page;
954 : int lineindex;
955 : int linesleft;
956 :
957 74680950 : if (likely(scan->rs_inited))
958 : {
959 : /* continue from previously returned page/tuple */
960 73171308 : page = BufferGetPage(scan->rs_cbuf);
961 :
962 73171308 : lineindex = scan->rs_cindex + dir;
963 73171308 : if (ScanDirectionIsForward(dir))
964 73170650 : linesleft = scan->rs_ntuples - lineindex;
965 : else
966 658 : linesleft = scan->rs_cindex;
967 : /* lineindex now references the next or previous visible tid */
968 :
969 73171308 : goto continue_page;
970 : }
971 :
972 : /*
973 : * advance the scan until we find a qualifying tuple or run out of stuff
974 : * to scan
975 : */
976 : while (true)
977 : {
978 5083922 : heap_fetch_next_buffer(scan, dir);
979 :
980 : /* did we run out of blocks to scan? */
981 5083916 : if (!BufferIsValid(scan->rs_cbuf))
982 1268954 : break;
983 :
984 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
985 :
986 : /* prune the page and determine visible tuple offsets */
987 3814962 : heap_prepare_pagescan((TableScanDesc) scan);
988 3814946 : page = BufferGetPage(scan->rs_cbuf);
989 3814946 : linesleft = scan->rs_ntuples;
990 3814946 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
991 :
992 : /* lineindex now references the next or previous visible tid */
993 76986254 : continue_page:
994 :
995 144939028 : for (; linesleft > 0; linesleft--, lineindex += dir)
996 : {
997 : ItemId lpp;
998 : OffsetNumber lineoff;
999 :
1000 141364748 : lineoff = scan->rs_vistuples[lineindex];
1001 141364748 : lpp = PageGetItemId(page, lineoff);
1002 : Assert(ItemIdIsNormal(lpp));
1003 :
1004 141364748 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1005 141364748 : tuple->t_len = ItemIdGetLength(lpp);
1006 141364748 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1007 :
1008 : /* skip any tuples that don't match the scan key */
1009 141364748 : if (key != NULL &&
1010 68434686 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1011 : nkeys, key))
1012 67952774 : continue;
1013 :
1014 73411974 : scan->rs_cindex = lineindex;
1015 73411974 : return;
1016 : }
1017 : }
1018 :
1019 : /* end of scan */
1020 1268954 : if (BufferIsValid(scan->rs_cbuf))
1021 0 : ReleaseBuffer(scan->rs_cbuf);
1022 1268954 : scan->rs_cbuf = InvalidBuffer;
1023 1268954 : scan->rs_cblock = InvalidBlockNumber;
1024 1268954 : scan->rs_prefetch_block = InvalidBlockNumber;
1025 1268954 : tuple->t_data = NULL;
1026 1268954 : scan->rs_inited = false;
1027 : }
1028 :
1029 :
1030 : /* ----------------------------------------------------------------
1031 : * heap access method interface
1032 : * ----------------------------------------------------------------
1033 : */
1034 :
1035 :
1036 : TableScanDesc
1037 604486 : heap_beginscan(Relation relation, Snapshot snapshot,
1038 : int nkeys, ScanKey key,
1039 : ParallelTableScanDesc parallel_scan,
1040 : uint32 flags)
1041 : {
1042 : HeapScanDesc scan;
1043 :
1044 : /*
1045 : * increment relation ref count while scanning relation
1046 : *
1047 : * This is just to make really sure the relcache entry won't go away while
1048 : * the scan has a pointer to it. Caller should be holding the rel open
1049 : * anyway, so this is redundant in all normal scenarios...
1050 : */
1051 604486 : RelationIncrementReferenceCount(relation);
1052 :
1053 : /*
1054 : * allocate and initialize scan descriptor
1055 : */
1056 604486 : scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1057 :
1058 604486 : scan->rs_base.rs_rd = relation;
1059 604486 : scan->rs_base.rs_snapshot = snapshot;
1060 604486 : scan->rs_base.rs_nkeys = nkeys;
1061 604486 : scan->rs_base.rs_flags = flags;
1062 604486 : scan->rs_base.rs_parallel = parallel_scan;
1063 604486 : scan->rs_strategy = NULL; /* set in initscan */
1064 604486 : scan->rs_vmbuffer = InvalidBuffer;
1065 604486 : scan->rs_empty_tuples_pending = 0;
1066 :
1067 : /*
1068 : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1069 : */
1070 604486 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
1071 51780 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1072 :
1073 : /*
1074 : * For seqscan and sample scans in a serializable transaction, acquire a
1075 : * predicate lock on the entire relation. This is required not only to
1076 : * lock all the matching tuples, but also to conflict with new insertions
1077 : * into the table. In an indexscan, we take page locks on the index pages
1078 : * covering the range specified in the scan qual, but in a heap scan there
1079 : * is nothing more fine-grained to lock. A bitmap scan is a different
1080 : * story, there we have already scanned the index and locked the index
1081 : * pages covering the predicate. But in that case we still have to lock
1082 : * any matching heap tuples. For sample scan we could optimize the locking
1083 : * to be at least page-level granularity, but we'd need to add per-tuple
1084 : * locking for that.
1085 : */
1086 604486 : if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
1087 : {
1088 : /*
1089 : * Ensure a missing snapshot is noticed reliably, even if the
1090 : * isolation mode means predicate locking isn't performed (and
1091 : * therefore the snapshot isn't used here).
1092 : */
1093 : Assert(snapshot);
1094 573684 : PredicateLockRelation(relation, snapshot);
1095 : }
1096 :
1097 : /* we only need to set this up once */
1098 604486 : scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1099 :
1100 : /*
1101 : * Allocate memory to keep track of page allocation for parallel workers
1102 : * when doing a parallel scan.
1103 : */
1104 604486 : if (parallel_scan != NULL)
1105 3856 : scan->rs_parallelworkerdata = palloc(sizeof(ParallelBlockTableScanWorkerData));
1106 : else
1107 600630 : scan->rs_parallelworkerdata = NULL;
1108 :
1109 : /*
1110 : * we do this here instead of in initscan() because heap_rescan also calls
1111 : * initscan() and we don't want to allocate memory again
1112 : */
1113 604486 : if (nkeys > 0)
1114 337268 : scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1115 : else
1116 267218 : scan->rs_base.rs_key = NULL;
1117 :
1118 604486 : initscan(scan, key, false);
1119 :
1120 604482 : scan->rs_read_stream = NULL;
1121 :
1122 : /*
1123 : * Set up a read stream for sequential scans and TID range scans. This
1124 : * should be done after initscan() because initscan() allocates the
1125 : * BufferAccessStrategy object passed to the read stream API.
1126 : */
1127 604482 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1128 30948 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
1129 : {
1130 : ReadStreamBlockNumberCB cb;
1131 :
1132 573646 : if (scan->rs_base.rs_parallel)
1133 3856 : cb = heap_scan_stream_read_next_parallel;
1134 : else
1135 569790 : cb = heap_scan_stream_read_next_serial;
1136 :
1137 573646 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL,
1138 : scan->rs_strategy,
1139 : scan->rs_base.rs_rd,
1140 : MAIN_FORKNUM,
1141 : cb,
1142 : scan,
1143 : 0);
1144 : }
1145 :
1146 :
1147 604482 : return (TableScanDesc) scan;
1148 : }
1149 :
1150 : void
1151 980248 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1152 : bool allow_strat, bool allow_sync, bool allow_pagemode)
1153 : {
1154 980248 : HeapScanDesc scan = (HeapScanDesc) sscan;
1155 :
1156 980248 : if (set_params)
1157 : {
1158 30 : if (allow_strat)
1159 30 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1160 : else
1161 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1162 :
1163 30 : if (allow_sync)
1164 12 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1165 : else
1166 18 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1167 :
1168 30 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1169 30 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1170 30 : scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
1171 : else
1172 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1173 : }
1174 :
1175 : /*
1176 : * unpin scan buffers
1177 : */
1178 980248 : if (BufferIsValid(scan->rs_cbuf))
1179 5482 : ReleaseBuffer(scan->rs_cbuf);
1180 :
1181 980248 : if (BufferIsValid(scan->rs_vmbuffer))
1182 : {
1183 54 : ReleaseBuffer(scan->rs_vmbuffer);
1184 54 : scan->rs_vmbuffer = InvalidBuffer;
1185 : }
1186 :
1187 : Assert(scan->rs_empty_tuples_pending == 0);
1188 :
1189 : /*
1190 : * The read stream is reset on rescan. This must be done before
1191 : * initscan(), as some state referred to by read_stream_reset() is reset
1192 : * in initscan().
1193 : */
1194 980248 : if (scan->rs_read_stream)
1195 976188 : read_stream_reset(scan->rs_read_stream);
1196 :
1197 : /*
1198 : * reinitialize scan descriptor
1199 : */
1200 980248 : initscan(scan, key, true);
1201 980248 : }
1202 :
1203 : void
1204 601946 : heap_endscan(TableScanDesc sscan)
1205 : {
1206 601946 : HeapScanDesc scan = (HeapScanDesc) sscan;
1207 :
1208 : /* Note: no locking manipulations needed */
1209 :
1210 : /*
1211 : * unpin scan buffers
1212 : */
1213 601946 : if (BufferIsValid(scan->rs_cbuf))
1214 248798 : ReleaseBuffer(scan->rs_cbuf);
1215 :
1216 601946 : if (BufferIsValid(scan->rs_vmbuffer))
1217 30 : ReleaseBuffer(scan->rs_vmbuffer);
1218 :
1219 : Assert(scan->rs_empty_tuples_pending == 0);
1220 :
1221 : /*
1222 : * Must free the read stream before freeing the BufferAccessStrategy.
1223 : */
1224 601946 : if (scan->rs_read_stream)
1225 571296 : read_stream_end(scan->rs_read_stream);
1226 :
1227 : /*
1228 : * decrement relation reference count and free scan descriptor storage
1229 : */
1230 601946 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1231 :
1232 601946 : if (scan->rs_base.rs_key)
1233 337208 : pfree(scan->rs_base.rs_key);
1234 :
1235 601946 : if (scan->rs_strategy != NULL)
1236 18626 : FreeAccessStrategy(scan->rs_strategy);
1237 :
1238 601946 : if (scan->rs_parallelworkerdata != NULL)
1239 3856 : pfree(scan->rs_parallelworkerdata);
1240 :
1241 601946 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1242 82380 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1243 :
1244 601946 : pfree(scan);
1245 601946 : }
1246 :
1247 : HeapTuple
1248 16945644 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1249 : {
1250 16945644 : HeapScanDesc scan = (HeapScanDesc) sscan;
1251 :
1252 : /*
1253 : * This is still widely used directly, without going through table AM, so
1254 : * add a safety check. It's possible we should, at a later point,
1255 : * downgrade this to an assert. The reason for checking the AM routine,
1256 : * rather than the AM oid, is that this allows to write regression tests
1257 : * that create another AM reusing the heap handler.
1258 : */
1259 16945644 : if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
1260 0 : ereport(ERROR,
1261 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1262 : errmsg_internal("only heap AM is supported")));
1263 :
1264 : /*
1265 : * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1266 : * for catalog or regular tables. See detailed comments in xact.c where
1267 : * these variables are declared. Normally we have such a check at tableam
1268 : * level API but this is called from many places so we need to ensure it
1269 : * here.
1270 : */
1271 16945644 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
1272 0 : elog(ERROR, "unexpected heap_getnext call during logical decoding");
1273 :
1274 : /* Note: no locking manipulations needed */
1275 :
1276 16945644 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1277 2446586 : heapgettup_pagemode(scan, direction,
1278 2446586 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1279 : else
1280 14499058 : heapgettup(scan, direction,
1281 14499058 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1282 :
1283 16945644 : if (scan->rs_ctup.t_data == NULL)
1284 103714 : return NULL;
1285 :
1286 : /*
1287 : * if we get here it means we have a new current scan tuple, so point to
1288 : * the proper return buffer and return the tuple.
1289 : */
1290 :
1291 16841930 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
1292 :
1293 16841930 : return &scan->rs_ctup;
1294 : }
1295 :
1296 : bool
1297 73176328 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1298 : {
1299 73176328 : HeapScanDesc scan = (HeapScanDesc) sscan;
1300 :
1301 : /* Note: no locking manipulations needed */
1302 :
1303 73176328 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1304 72228238 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1305 : else
1306 948090 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1307 :
1308 73176306 : if (scan->rs_ctup.t_data == NULL)
1309 : {
1310 1203364 : ExecClearTuple(slot);
1311 1203364 : return false;
1312 : }
1313 :
1314 : /*
1315 : * if we get here it means we have a new current scan tuple, so point to
1316 : * the proper return buffer and return the tuple.
1317 : */
1318 :
1319 71972942 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
1320 :
1321 71972942 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1322 : scan->rs_cbuf);
1323 71972942 : return true;
1324 : }
1325 :
1326 : void
1327 178 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
1328 : ItemPointer maxtid)
1329 : {
1330 178 : HeapScanDesc scan = (HeapScanDesc) sscan;
1331 : BlockNumber startBlk;
1332 : BlockNumber numBlks;
1333 : ItemPointerData highestItem;
1334 : ItemPointerData lowestItem;
1335 :
1336 : /*
1337 : * For relations without any pages, we can simply leave the TID range
1338 : * unset. There will be no tuples to scan, therefore no tuples outside
1339 : * the given TID range.
1340 : */
1341 178 : if (scan->rs_nblocks == 0)
1342 48 : return;
1343 :
1344 : /*
1345 : * Set up some ItemPointers which point to the first and last possible
1346 : * tuples in the heap.
1347 : */
1348 166 : ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1349 166 : ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1350 :
1351 : /*
1352 : * If the given maximum TID is below the highest possible TID in the
1353 : * relation, then restrict the range to that, otherwise we scan to the end
1354 : * of the relation.
1355 : */
1356 166 : if (ItemPointerCompare(maxtid, &highestItem) < 0)
1357 132 : ItemPointerCopy(maxtid, &highestItem);
1358 :
1359 : /*
1360 : * If the given minimum TID is above the lowest possible TID in the
1361 : * relation, then restrict the range to only scan for TIDs above that.
1362 : */
1363 166 : if (ItemPointerCompare(mintid, &lowestItem) > 0)
1364 52 : ItemPointerCopy(mintid, &lowestItem);
1365 :
1366 : /*
1367 : * Check for an empty range and protect from would be negative results
1368 : * from the numBlks calculation below.
1369 : */
1370 166 : if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1371 : {
1372 : /* Set an empty range of blocks to scan */
1373 36 : heap_setscanlimits(sscan, 0, 0);
1374 36 : return;
1375 : }
1376 :
1377 : /*
1378 : * Calculate the first block and the number of blocks we must scan. We
1379 : * could be more aggressive here and perform some more validation to try
1380 : * and further narrow the scope of blocks to scan by checking if the
1381 : * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1382 : * advance startBlk by one. Likewise, if highestItem has an offset of 0
1383 : * we could scan one fewer blocks. However, such an optimization does not
1384 : * seem worth troubling over, currently.
1385 : */
1386 130 : startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1387 :
1388 130 : numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1389 130 : ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1390 :
1391 : /* Set the start block and number of blocks to scan */
1392 130 : heap_setscanlimits(sscan, startBlk, numBlks);
1393 :
1394 : /* Finally, set the TID range in sscan */
1395 130 : ItemPointerCopy(&lowestItem, &sscan->rs_mintid);
1396 130 : ItemPointerCopy(&highestItem, &sscan->rs_maxtid);
1397 : }
1398 :
1399 : bool
1400 5940 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1401 : TupleTableSlot *slot)
1402 : {
1403 5940 : HeapScanDesc scan = (HeapScanDesc) sscan;
1404 5940 : ItemPointer mintid = &sscan->rs_mintid;
1405 5940 : ItemPointer maxtid = &sscan->rs_maxtid;
1406 :
1407 : /* Note: no locking manipulations needed */
1408 : for (;;)
1409 : {
1410 6126 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1411 6126 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1412 : else
1413 0 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1414 :
1415 6126 : if (scan->rs_ctup.t_data == NULL)
1416 : {
1417 94 : ExecClearTuple(slot);
1418 94 : return false;
1419 : }
1420 :
1421 : /*
1422 : * heap_set_tidrange will have used heap_setscanlimits to limit the
1423 : * range of pages we scan to only ones that can contain the TID range
1424 : * we're scanning for. Here we must filter out any tuples from these
1425 : * pages that are outside of that range.
1426 : */
1427 6032 : if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1428 : {
1429 186 : ExecClearTuple(slot);
1430 :
1431 : /*
1432 : * When scanning backwards, the TIDs will be in descending order.
1433 : * Future tuples in this direction will be lower still, so we can
1434 : * just return false to indicate there will be no more tuples.
1435 : */
1436 186 : if (ScanDirectionIsBackward(direction))
1437 0 : return false;
1438 :
1439 186 : continue;
1440 : }
1441 :
1442 : /*
1443 : * Likewise for the final page, we must filter out TIDs greater than
1444 : * maxtid.
1445 : */
1446 5846 : if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1447 : {
1448 72 : ExecClearTuple(slot);
1449 :
1450 : /*
1451 : * When scanning forward, the TIDs will be in ascending order.
1452 : * Future tuples in this direction will be higher still, so we can
1453 : * just return false to indicate there will be no more tuples.
1454 : */
1455 72 : if (ScanDirectionIsForward(direction))
1456 72 : return false;
1457 0 : continue;
1458 : }
1459 :
1460 5774 : break;
1461 : }
1462 :
1463 : /*
1464 : * if we get here it means we have a new current scan tuple, so point to
1465 : * the proper return buffer and return the tuple.
1466 : */
1467 5774 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
1468 :
1469 5774 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1470 5774 : return true;
1471 : }
1472 :
1473 : /*
1474 : * heap_fetch - retrieve tuple with given tid
1475 : *
1476 : * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1477 : * the tuple, fill in the remaining fields of *tuple, and check the tuple
1478 : * against the specified snapshot.
1479 : *
1480 : * If successful (tuple found and passes snapshot time qual), then *userbuf
1481 : * is set to the buffer holding the tuple and true is returned. The caller
1482 : * must unpin the buffer when done with the tuple.
1483 : *
1484 : * If the tuple is not found (ie, item number references a deleted slot),
1485 : * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1486 : * and false is returned.
1487 : *
1488 : * If the tuple is found but fails the time qual check, then the behavior
1489 : * depends on the keep_buf parameter. If keep_buf is false, the results
1490 : * are the same as for the tuple-not-found case. If keep_buf is true,
1491 : * then tuple->t_data and *userbuf are returned as for the success case,
1492 : * and again the caller must unpin the buffer; but false is returned.
1493 : *
1494 : * heap_fetch does not follow HOT chains: only the exact TID requested will
1495 : * be fetched.
1496 : *
1497 : * It is somewhat inconsistent that we ereport() on invalid block number but
1498 : * return false on invalid item number. There are a couple of reasons though.
1499 : * One is that the caller can relatively easily check the block number for
1500 : * validity, but cannot check the item number without reading the page
1501 : * himself. Another is that when we are following a t_ctid link, we can be
1502 : * reasonably confident that the page number is valid (since VACUUM shouldn't
1503 : * truncate off the destination page without having killed the referencing
1504 : * tuple first), but the item number might well not be good.
1505 : */
1506 : bool
1507 614774 : heap_fetch(Relation relation,
1508 : Snapshot snapshot,
1509 : HeapTuple tuple,
1510 : Buffer *userbuf,
1511 : bool keep_buf)
1512 : {
1513 614774 : ItemPointer tid = &(tuple->t_self);
1514 : ItemId lp;
1515 : Buffer buffer;
1516 : Page page;
1517 : OffsetNumber offnum;
1518 : bool valid;
1519 :
1520 : /*
1521 : * Fetch and pin the appropriate page of the relation.
1522 : */
1523 614774 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1524 :
1525 : /*
1526 : * Need share lock on buffer to examine tuple commit status.
1527 : */
1528 614774 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
1529 614774 : page = BufferGetPage(buffer);
1530 :
1531 : /*
1532 : * We'd better check for out-of-range offnum in case of VACUUM since the
1533 : * TID was obtained.
1534 : */
1535 614774 : offnum = ItemPointerGetOffsetNumber(tid);
1536 614774 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1537 : {
1538 6 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1539 6 : ReleaseBuffer(buffer);
1540 6 : *userbuf = InvalidBuffer;
1541 6 : tuple->t_data = NULL;
1542 6 : return false;
1543 : }
1544 :
1545 : /*
1546 : * get the item line pointer corresponding to the requested tid
1547 : */
1548 614768 : lp = PageGetItemId(page, offnum);
1549 :
1550 : /*
1551 : * Must check for deleted tuple.
1552 : */
1553 614768 : if (!ItemIdIsNormal(lp))
1554 : {
1555 3714 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1556 3714 : ReleaseBuffer(buffer);
1557 3714 : *userbuf = InvalidBuffer;
1558 3714 : tuple->t_data = NULL;
1559 3714 : return false;
1560 : }
1561 :
1562 : /*
1563 : * fill in *tuple fields
1564 : */
1565 611054 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1566 611054 : tuple->t_len = ItemIdGetLength(lp);
1567 611054 : tuple->t_tableOid = RelationGetRelid(relation);
1568 :
1569 : /*
1570 : * check tuple visibility, then release lock
1571 : */
1572 611054 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1573 :
1574 611054 : if (valid)
1575 610932 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1576 610932 : HeapTupleHeaderGetXmin(tuple->t_data));
1577 :
1578 611054 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1579 :
1580 611054 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1581 :
1582 611054 : if (valid)
1583 : {
1584 : /*
1585 : * All checks passed, so return the tuple as valid. Caller is now
1586 : * responsible for releasing the buffer.
1587 : */
1588 610932 : *userbuf = buffer;
1589 :
1590 610932 : return true;
1591 : }
1592 :
1593 : /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1594 122 : if (keep_buf)
1595 58 : *userbuf = buffer;
1596 : else
1597 : {
1598 64 : ReleaseBuffer(buffer);
1599 64 : *userbuf = InvalidBuffer;
1600 64 : tuple->t_data = NULL;
1601 : }
1602 :
1603 122 : return false;
1604 : }
1605 :
1606 : /*
1607 : * heap_hot_search_buffer - search HOT chain for tuple satisfying snapshot
1608 : *
1609 : * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1610 : * of a HOT chain), and buffer is the buffer holding this tuple. We search
1611 : * for the first chain member satisfying the given snapshot. If one is
1612 : * found, we update *tid to reference that tuple's offset number, and
1613 : * return true. If no match, return false without modifying *tid.
1614 : *
1615 : * heapTuple is a caller-supplied buffer. When a match is found, we return
1616 : * the tuple here, in addition to updating *tid. If no match is found, the
1617 : * contents of this buffer on return are undefined.
1618 : *
1619 : * If all_dead is not NULL, we check non-visible tuples to see if they are
1620 : * globally dead; *all_dead is set true if all members of the HOT chain
1621 : * are vacuumable, false if not.
1622 : *
1623 : * Unlike heap_fetch, the caller must already have pin and (at least) share
1624 : * lock on the buffer; it is still pinned/locked at exit.
1625 : */
1626 : bool
1627 36961036 : heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
1628 : Snapshot snapshot, HeapTuple heapTuple,
1629 : bool *all_dead, bool first_call)
1630 : {
1631 36961036 : Page page = BufferGetPage(buffer);
1632 36961036 : TransactionId prev_xmax = InvalidTransactionId;
1633 : BlockNumber blkno;
1634 : OffsetNumber offnum;
1635 : bool at_chain_start;
1636 : bool valid;
1637 : bool skip;
1638 36961036 : GlobalVisState *vistest = NULL;
1639 :
1640 : /* If this is not the first call, previous call returned a (live!) tuple */
1641 36961036 : if (all_dead)
1642 31278598 : *all_dead = first_call;
1643 :
1644 36961036 : blkno = ItemPointerGetBlockNumber(tid);
1645 36961036 : offnum = ItemPointerGetOffsetNumber(tid);
1646 36961036 : at_chain_start = first_call;
1647 36961036 : skip = !first_call;
1648 :
1649 : /* XXX: we should assert that a snapshot is pushed or registered */
1650 : Assert(TransactionIdIsValid(RecentXmin));
1651 : Assert(BufferGetBlockNumber(buffer) == blkno);
1652 :
1653 : /* Scan through possible multiple members of HOT-chain */
1654 : for (;;)
1655 1614684 : {
1656 : ItemId lp;
1657 :
1658 : /* check for bogus TID */
1659 38575720 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1660 : break;
1661 :
1662 38575720 : lp = PageGetItemId(page, offnum);
1663 :
1664 : /* check for unused, dead, or redirected items */
1665 38575720 : if (!ItemIdIsNormal(lp))
1666 : {
1667 : /* We should only see a redirect at start of chain */
1668 1349360 : if (ItemIdIsRedirected(lp) && at_chain_start)
1669 : {
1670 : /* Follow the redirect */
1671 606582 : offnum = ItemIdGetRedirect(lp);
1672 606582 : at_chain_start = false;
1673 606582 : continue;
1674 : }
1675 : /* else must be end of chain */
1676 742778 : break;
1677 : }
1678 :
1679 : /*
1680 : * Update heapTuple to point to the element of the HOT chain we're
1681 : * currently investigating. Having t_self set correctly is important
1682 : * because the SSI checks and the *Satisfies routine for historical
1683 : * MVCC snapshots need the correct tid to decide about the visibility.
1684 : */
1685 37226360 : heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1686 37226360 : heapTuple->t_len = ItemIdGetLength(lp);
1687 37226360 : heapTuple->t_tableOid = RelationGetRelid(relation);
1688 37226360 : ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1689 :
1690 : /*
1691 : * Shouldn't see a HEAP_ONLY tuple at chain start.
1692 : */
1693 37226360 : if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1694 0 : break;
1695 :
1696 : /*
1697 : * The xmin should match the previous xmax value, else chain is
1698 : * broken.
1699 : */
1700 38234462 : if (TransactionIdIsValid(prev_xmax) &&
1701 1008102 : !TransactionIdEquals(prev_xmax,
1702 : HeapTupleHeaderGetXmin(heapTuple->t_data)))
1703 0 : break;
1704 :
1705 : /*
1706 : * When first_call is true (and thus, skip is initially false) we'll
1707 : * return the first tuple we find. But on later passes, heapTuple
1708 : * will initially be pointing to the tuple we returned last time.
1709 : * Returning it again would be incorrect (and would loop forever), so
1710 : * we skip it and return the next match we find.
1711 : */
1712 37226360 : if (!skip)
1713 : {
1714 : /* If it's visible per the snapshot, we must return it */
1715 37082892 : valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1716 37082892 : HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1717 : buffer, snapshot);
1718 :
1719 37082882 : if (valid)
1720 : {
1721 23877916 : ItemPointerSetOffsetNumber(tid, offnum);
1722 23877916 : PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1723 23877916 : HeapTupleHeaderGetXmin(heapTuple->t_data));
1724 23877916 : if (all_dead)
1725 18733496 : *all_dead = false;
1726 23877916 : return true;
1727 : }
1728 : }
1729 13348434 : skip = false;
1730 :
1731 : /*
1732 : * If we can't see it, maybe no one else can either. At caller
1733 : * request, check whether all chain members are dead to all
1734 : * transactions.
1735 : *
1736 : * Note: if you change the criterion here for what is "dead", fix the
1737 : * planner's get_actual_variable_range() function to match.
1738 : */
1739 13348434 : if (all_dead && *all_dead)
1740 : {
1741 12716050 : if (!vistest)
1742 12534210 : vistest = GlobalVisTestFor(relation);
1743 :
1744 12716050 : if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1745 12127710 : *all_dead = false;
1746 : }
1747 :
1748 : /*
1749 : * Check to see if HOT chain continues past this tuple; if so fetch
1750 : * the next offnum and loop around.
1751 : */
1752 13348434 : if (HeapTupleIsHotUpdated(heapTuple))
1753 : {
1754 : Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
1755 : blkno);
1756 1008102 : offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1757 1008102 : at_chain_start = false;
1758 1008102 : prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1759 : }
1760 : else
1761 : break; /* end of chain */
1762 : }
1763 :
1764 13083110 : return false;
1765 : }
1766 :
1767 : /*
1768 : * heap_get_latest_tid - get the latest tid of a specified tuple
1769 : *
1770 : * Actually, this gets the latest version that is visible according to the
1771 : * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1772 : * possibly uncommitted version.
1773 : *
1774 : * *tid is both an input and an output parameter: it is updated to
1775 : * show the latest version of the row. Note that it will not be changed
1776 : * if no version of the row passes the snapshot test.
1777 : */
1778 : void
1779 300 : heap_get_latest_tid(TableScanDesc sscan,
1780 : ItemPointer tid)
1781 : {
1782 300 : Relation relation = sscan->rs_rd;
1783 300 : Snapshot snapshot = sscan->rs_snapshot;
1784 : ItemPointerData ctid;
1785 : TransactionId priorXmax;
1786 :
1787 : /*
1788 : * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1789 : * Assume that t_ctid links are valid however - there shouldn't be invalid
1790 : * ones in the table.
1791 : */
1792 : Assert(ItemPointerIsValid(tid));
1793 :
1794 : /*
1795 : * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1796 : * need to examine, and *tid is the TID we will return if ctid turns out
1797 : * to be bogus.
1798 : *
1799 : * Note that we will loop until we reach the end of the t_ctid chain.
1800 : * Depending on the snapshot passed, there might be at most one visible
1801 : * version of the row, but we don't try to optimize for that.
1802 : */
1803 300 : ctid = *tid;
1804 300 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1805 : for (;;)
1806 90 : {
1807 : Buffer buffer;
1808 : Page page;
1809 : OffsetNumber offnum;
1810 : ItemId lp;
1811 : HeapTupleData tp;
1812 : bool valid;
1813 :
1814 : /*
1815 : * Read, pin, and lock the page.
1816 : */
1817 390 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1818 390 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
1819 390 : page = BufferGetPage(buffer);
1820 :
1821 : /*
1822 : * Check for bogus item number. This is not treated as an error
1823 : * condition because it can happen while following a t_ctid link. We
1824 : * just assume that the prior tid is OK and return it unchanged.
1825 : */
1826 390 : offnum = ItemPointerGetOffsetNumber(&ctid);
1827 390 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1828 : {
1829 0 : UnlockReleaseBuffer(buffer);
1830 0 : break;
1831 : }
1832 390 : lp = PageGetItemId(page, offnum);
1833 390 : if (!ItemIdIsNormal(lp))
1834 : {
1835 0 : UnlockReleaseBuffer(buffer);
1836 0 : break;
1837 : }
1838 :
1839 : /* OK to access the tuple */
1840 390 : tp.t_self = ctid;
1841 390 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1842 390 : tp.t_len = ItemIdGetLength(lp);
1843 390 : tp.t_tableOid = RelationGetRelid(relation);
1844 :
1845 : /*
1846 : * After following a t_ctid link, we might arrive at an unrelated
1847 : * tuple. Check for XMIN match.
1848 : */
1849 480 : if (TransactionIdIsValid(priorXmax) &&
1850 90 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1851 : {
1852 0 : UnlockReleaseBuffer(buffer);
1853 0 : break;
1854 : }
1855 :
1856 : /*
1857 : * Check tuple visibility; if visible, set it as the new result
1858 : * candidate.
1859 : */
1860 390 : valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1861 390 : HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1862 390 : if (valid)
1863 276 : *tid = ctid;
1864 :
1865 : /*
1866 : * If there's a valid t_ctid link, follow it, else we're done.
1867 : */
1868 552 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1869 276 : HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
1870 228 : HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
1871 114 : ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1872 : {
1873 300 : UnlockReleaseBuffer(buffer);
1874 300 : break;
1875 : }
1876 :
1877 90 : ctid = tp.t_data->t_ctid;
1878 90 : priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1879 90 : UnlockReleaseBuffer(buffer);
1880 : } /* end of loop */
1881 300 : }
1882 :
1883 :
1884 : /*
1885 : * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1886 : *
1887 : * This is called after we have waited for the XMAX transaction to terminate.
1888 : * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1889 : * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1890 : * hint bit if possible --- but beware that that may not yet be possible,
1891 : * if the transaction committed asynchronously.
1892 : *
1893 : * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1894 : * even if it commits.
1895 : *
1896 : * Hence callers should look only at XMAX_INVALID.
1897 : *
1898 : * Note this is not allowed for tuples whose xmax is a multixact.
1899 : */
1900 : static void
1901 338 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1902 : {
1903 : Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1904 : Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1905 :
1906 338 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1907 : {
1908 616 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1909 278 : TransactionIdDidCommit(xid))
1910 226 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1911 : xid);
1912 : else
1913 112 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1914 : InvalidTransactionId);
1915 : }
1916 338 : }
1917 :
1918 :
1919 : /*
1920 : * GetBulkInsertState - prepare status object for a bulk insert
1921 : */
1922 : BulkInsertState
1923 4692 : GetBulkInsertState(void)
1924 : {
1925 : BulkInsertState bistate;
1926 :
1927 4692 : bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1928 4692 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1929 4692 : bistate->current_buf = InvalidBuffer;
1930 4692 : bistate->next_free = InvalidBlockNumber;
1931 4692 : bistate->last_free = InvalidBlockNumber;
1932 4692 : bistate->already_extended_by = 0;
1933 4692 : return bistate;
1934 : }
1935 :
1936 : /*
1937 : * FreeBulkInsertState - clean up after finishing a bulk insert
1938 : */
1939 : void
1940 4460 : FreeBulkInsertState(BulkInsertState bistate)
1941 : {
1942 4460 : if (bistate->current_buf != InvalidBuffer)
1943 3490 : ReleaseBuffer(bistate->current_buf);
1944 4460 : FreeAccessStrategy(bistate->strategy);
1945 4460 : pfree(bistate);
1946 4460 : }
1947 :
1948 : /*
1949 : * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
1950 : */
1951 : void
1952 161512 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
1953 : {
1954 161512 : if (bistate->current_buf != InvalidBuffer)
1955 60042 : ReleaseBuffer(bistate->current_buf);
1956 161512 : bistate->current_buf = InvalidBuffer;
1957 :
1958 : /*
1959 : * Despite the name, we also reset bulk relation extension state.
1960 : * Otherwise we can end up erroring out due to looking for free space in
1961 : * ->next_free of one partition, even though ->next_free was set when
1962 : * extending another partition. It could obviously also be bad for
1963 : * efficiency to look at existing blocks at offsets from another
1964 : * partition, even if we don't error out.
1965 : */
1966 161512 : bistate->next_free = InvalidBlockNumber;
1967 161512 : bistate->last_free = InvalidBlockNumber;
1968 161512 : }
1969 :
1970 :
1971 : /*
1972 : * heap_insert - insert tuple into a heap
1973 : *
1974 : * The new tuple is stamped with current transaction ID and the specified
1975 : * command ID.
1976 : *
1977 : * See table_tuple_insert for comments about most of the input flags, except
1978 : * that this routine directly takes a tuple rather than a slot.
1979 : *
1980 : * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
1981 : * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
1982 : * implement table_tuple_insert_speculative().
1983 : *
1984 : * On return the header fields of *tup are updated to match the stored tuple;
1985 : * in particular tup->t_self receives the actual TID where the tuple was
1986 : * stored. But note that any toasting of fields within the tuple data is NOT
1987 : * reflected into *tup.
1988 : */
1989 : void
1990 15115088 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
1991 : int options, BulkInsertState bistate)
1992 : {
1993 15115088 : TransactionId xid = GetCurrentTransactionId();
1994 : HeapTuple heaptup;
1995 : Buffer buffer;
1996 15115088 : Buffer vmbuffer = InvalidBuffer;
1997 15115088 : bool all_visible_cleared = false;
1998 :
1999 : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2000 : Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
2001 : RelationGetNumberOfAttributes(relation));
2002 :
2003 : /*
2004 : * Fill in tuple header fields and toast the tuple if necessary.
2005 : *
2006 : * Note: below this point, heaptup is the data we actually intend to store
2007 : * into the relation; tup is the caller's original untoasted data.
2008 : */
2009 15115088 : heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2010 :
2011 : /*
2012 : * Find buffer to insert this tuple into. If the page is all visible,
2013 : * this will also pin the requisite visibility map page.
2014 : */
2015 15115088 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2016 : InvalidBuffer, options, bistate,
2017 : &vmbuffer, NULL,
2018 : 0);
2019 :
2020 : /*
2021 : * We're about to do the actual insert -- but check for conflict first, to
2022 : * avoid possibly having to roll back work we've just done.
2023 : *
2024 : * This is safe without a recheck as long as there is no possibility of
2025 : * another process scanning the page between this check and the insert
2026 : * being visible to the scan (i.e., an exclusive buffer content lock is
2027 : * continuously held from this point until the tuple insert is visible).
2028 : *
2029 : * For a heap insert, we only need to check for table-level SSI locks. Our
2030 : * new tuple can't possibly conflict with existing tuple locks, and heap
2031 : * page locks are only consolidated versions of tuple locks; they do not
2032 : * lock "gaps" as index page locks do. So we don't need to specify a
2033 : * buffer when making the call, which makes for a faster check.
2034 : */
2035 15115088 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2036 :
2037 : /* NO EREPORT(ERROR) from here till changes are logged */
2038 15115064 : START_CRIT_SECTION();
2039 :
2040 15115064 : RelationPutHeapTuple(relation, buffer, heaptup,
2041 15115064 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2042 :
2043 15115064 : if (PageIsAllVisible(BufferGetPage(buffer)))
2044 : {
2045 11276 : all_visible_cleared = true;
2046 11276 : PageClearAllVisible(BufferGetPage(buffer));
2047 11276 : visibilitymap_clear(relation,
2048 11276 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2049 : vmbuffer, VISIBILITYMAP_VALID_BITS);
2050 : }
2051 :
2052 : /*
2053 : * XXX Should we set PageSetPrunable on this page ?
2054 : *
2055 : * The inserting transaction may eventually abort thus making this tuple
2056 : * DEAD and hence available for pruning. Though we don't want to optimize
2057 : * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2058 : * aborted tuple will never be pruned until next vacuum is triggered.
2059 : *
2060 : * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2061 : */
2062 :
2063 15115064 : MarkBufferDirty(buffer);
2064 :
2065 : /* XLOG stuff */
2066 15115064 : if (RelationNeedsWAL(relation))
2067 : {
2068 : xl_heap_insert xlrec;
2069 : xl_heap_header xlhdr;
2070 : XLogRecPtr recptr;
2071 13121084 : Page page = BufferGetPage(buffer);
2072 13121084 : uint8 info = XLOG_HEAP_INSERT;
2073 13121084 : int bufflags = 0;
2074 :
2075 : /*
2076 : * If this is a catalog, we need to transmit combo CIDs to properly
2077 : * decode, so log that as well.
2078 : */
2079 13121084 : if (RelationIsAccessibleInLogicalDecoding(relation))
2080 5666 : log_heap_new_cid(relation, heaptup);
2081 :
2082 : /*
2083 : * If this is the single and first tuple on page, we can reinit the
2084 : * page instead of restoring the whole thing. Set flag, and hide
2085 : * buffer references from XLogInsert.
2086 : */
2087 13276936 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2088 155852 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2089 : {
2090 154826 : info |= XLOG_HEAP_INIT_PAGE;
2091 154826 : bufflags |= REGBUF_WILL_INIT;
2092 : }
2093 :
2094 13121084 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2095 13121084 : xlrec.flags = 0;
2096 13121084 : if (all_visible_cleared)
2097 11270 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2098 13121084 : if (options & HEAP_INSERT_SPECULATIVE)
2099 4014 : xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
2100 : Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2101 :
2102 : /*
2103 : * For logical decoding, we need the tuple even if we're doing a full
2104 : * page write, so make sure it's included even if we take a full-page
2105 : * image. (XXX We could alternatively store a pointer into the FPW).
2106 : */
2107 13121084 : if (RelationIsLogicallyLogged(relation) &&
2108 489382 : !(options & HEAP_INSERT_NO_LOGICAL))
2109 : {
2110 489328 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2111 489328 : bufflags |= REGBUF_KEEP_DATA;
2112 :
2113 489328 : if (IsToastRelation(relation))
2114 3368 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2115 : }
2116 :
2117 13121084 : XLogBeginInsert();
2118 13121084 : XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2119 :
2120 13121084 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2121 13121084 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2122 13121084 : xlhdr.t_hoff = heaptup->t_data->t_hoff;
2123 :
2124 : /*
2125 : * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2126 : * write the whole page to the xlog, we don't need to store
2127 : * xl_heap_header in the xlog.
2128 : */
2129 13121084 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2130 13121084 : XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2131 : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2132 13121084 : XLogRegisterBufData(0,
2133 13121084 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2134 13121084 : heaptup->t_len - SizeofHeapTupleHeader);
2135 :
2136 : /* filtering by origin on a row level is much more efficient */
2137 13121084 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2138 :
2139 13121084 : recptr = XLogInsert(RM_HEAP_ID, info);
2140 :
2141 13121084 : PageSetLSN(page, recptr);
2142 : }
2143 :
2144 15115064 : END_CRIT_SECTION();
2145 :
2146 15115064 : UnlockReleaseBuffer(buffer);
2147 15115064 : if (vmbuffer != InvalidBuffer)
2148 11546 : ReleaseBuffer(vmbuffer);
2149 :
2150 : /*
2151 : * If tuple is cachable, mark it for invalidation from the caches in case
2152 : * we abort. Note it is OK to do this after releasing the buffer, because
2153 : * the heaptup data structure is all in local memory, not in the shared
2154 : * buffer.
2155 : */
2156 15115064 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2157 :
2158 : /* Note: speculative insertions are counted too, even if aborted later */
2159 15115064 : pgstat_count_heap_insert(relation, 1);
2160 :
2161 : /*
2162 : * If heaptup is a private copy, release it. Don't forget to copy t_self
2163 : * back to the caller's image, too.
2164 : */
2165 15115064 : if (heaptup != tup)
2166 : {
2167 31646 : tup->t_self = heaptup->t_self;
2168 31646 : heap_freetuple(heaptup);
2169 : }
2170 15115064 : }
2171 :
2172 : /*
2173 : * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2174 : * tuple header fields and toasts the tuple if necessary. Returns a toasted
2175 : * version of the tuple if it was toasted, or the original tuple if not. Note
2176 : * that in any case, the header fields are also set in the original tuple.
2177 : */
2178 : static HeapTuple
2179 17839220 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2180 : CommandId cid, int options)
2181 : {
2182 : /*
2183 : * To allow parallel inserts, we need to ensure that they are safe to be
2184 : * performed in workers. We have the infrastructure to allow parallel
2185 : * inserts in general except for the cases where inserts generate a new
2186 : * CommandId (eg. inserts into a table having a foreign key column).
2187 : */
2188 17839220 : if (IsParallelWorker())
2189 0 : ereport(ERROR,
2190 : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2191 : errmsg("cannot insert tuples in a parallel worker")));
2192 :
2193 17839220 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2194 17839220 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2195 17839220 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
2196 17839220 : HeapTupleHeaderSetXmin(tup->t_data, xid);
2197 17839220 : if (options & HEAP_INSERT_FROZEN)
2198 200724 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2199 :
2200 17839220 : HeapTupleHeaderSetCmin(tup->t_data, cid);
2201 17839220 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2202 17839220 : tup->t_tableOid = RelationGetRelid(relation);
2203 :
2204 : /*
2205 : * If the new tuple is too big for storage or contains already toasted
2206 : * out-of-line attributes from some other relation, invoke the toaster.
2207 : */
2208 17839220 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2209 55190 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2210 : {
2211 : /* toast table entries should never be recursively toasted */
2212 : Assert(!HeapTupleHasExternal(tup));
2213 51866 : return tup;
2214 : }
2215 17787354 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2216 31728 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2217 : else
2218 17755626 : return tup;
2219 : }
2220 :
2221 : /*
2222 : * Helper for heap_multi_insert() that computes the number of entire pages
2223 : * that inserting the remaining heaptuples requires. Used to determine how
2224 : * much the relation needs to be extended by.
2225 : */
2226 : static int
2227 624064 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2228 : {
2229 624064 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2230 624064 : int npages = 1;
2231 :
2232 4527106 : for (int i = done; i < ntuples; i++)
2233 : {
2234 3903042 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2235 :
2236 3903042 : if (page_avail < tup_sz)
2237 : {
2238 31082 : npages++;
2239 31082 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2240 : }
2241 3903042 : page_avail -= tup_sz;
2242 : }
2243 :
2244 624064 : return npages;
2245 : }
2246 :
2247 : /*
2248 : * heap_multi_insert - insert multiple tuples into a heap
2249 : *
2250 : * This is like heap_insert(), but inserts multiple tuples in one operation.
2251 : * That's faster than calling heap_insert() in a loop, because when multiple
2252 : * tuples can be inserted on a single page, we can write just a single WAL
2253 : * record covering all of them, and only need to lock/unlock the page once.
2254 : *
2255 : * Note: this leaks memory into the current memory context. You can create a
2256 : * temporary context before calling this, if that's a problem.
2257 : */
2258 : void
2259 612484 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2260 : CommandId cid, int options, BulkInsertState bistate)
2261 : {
2262 612484 : TransactionId xid = GetCurrentTransactionId();
2263 : HeapTuple *heaptuples;
2264 : int i;
2265 : int ndone;
2266 : PGAlignedBlock scratch;
2267 : Page page;
2268 612484 : Buffer vmbuffer = InvalidBuffer;
2269 : bool needwal;
2270 : Size saveFreeSpace;
2271 612484 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
2272 612484 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2273 612484 : bool starting_with_empty_page = false;
2274 612484 : int npages = 0;
2275 612484 : int npages_used = 0;
2276 :
2277 : /* currently not needed (thus unsupported) for heap_multi_insert() */
2278 : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2279 :
2280 612484 : needwal = RelationNeedsWAL(relation);
2281 612484 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2282 : HEAP_DEFAULT_FILLFACTOR);
2283 :
2284 : /* Toast and set header data in all the slots */
2285 612484 : heaptuples = palloc(ntuples * sizeof(HeapTuple));
2286 3336616 : for (i = 0; i < ntuples; i++)
2287 : {
2288 : HeapTuple tuple;
2289 :
2290 2724132 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2291 2724132 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2292 2724132 : tuple->t_tableOid = slots[i]->tts_tableOid;
2293 2724132 : heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2294 : options);
2295 : }
2296 :
2297 : /*
2298 : * We're about to do the actual inserts -- but check for conflict first,
2299 : * to minimize the possibility of having to roll back work we've just
2300 : * done.
2301 : *
2302 : * A check here does not definitively prevent a serialization anomaly;
2303 : * that check MUST be done at least past the point of acquiring an
2304 : * exclusive buffer content lock on every buffer that will be affected,
2305 : * and MAY be done after all inserts are reflected in the buffers and
2306 : * those locks are released; otherwise there is a race condition. Since
2307 : * multiple buffers can be locked and unlocked in the loop below, and it
2308 : * would not be feasible to identify and lock all of those buffers before
2309 : * the loop, we must do a final check at the end.
2310 : *
2311 : * The check here could be omitted with no loss of correctness; it is
2312 : * present strictly as an optimization.
2313 : *
2314 : * For heap inserts, we only need to check for table-level SSI locks. Our
2315 : * new tuples can't possibly conflict with existing tuple locks, and heap
2316 : * page locks are only consolidated versions of tuple locks; they do not
2317 : * lock "gaps" as index page locks do. So we don't need to specify a
2318 : * buffer when making the call, which makes for a faster check.
2319 : */
2320 612484 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2321 :
2322 612484 : ndone = 0;
2323 1252712 : while (ndone < ntuples)
2324 : {
2325 : Buffer buffer;
2326 640228 : bool all_visible_cleared = false;
2327 640228 : bool all_frozen_set = false;
2328 : int nthispage;
2329 :
2330 640228 : CHECK_FOR_INTERRUPTS();
2331 :
2332 : /*
2333 : * Compute number of pages needed to fit the to-be-inserted tuples in
2334 : * the worst case. This will be used to determine how much to extend
2335 : * the relation by in RelationGetBufferForTuple(), if needed. If we
2336 : * filled a prior page from scratch, we can just update our last
2337 : * computation, but if we started with a partially filled page,
2338 : * recompute from scratch, the number of potentially required pages
2339 : * can vary due to tuples needing to fit onto the page, page headers
2340 : * etc.
2341 : */
2342 640228 : if (ndone == 0 || !starting_with_empty_page)
2343 : {
2344 624064 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2345 : saveFreeSpace);
2346 624064 : npages_used = 0;
2347 : }
2348 : else
2349 16164 : npages_used++;
2350 :
2351 : /*
2352 : * Find buffer where at least the next tuple will fit. If the page is
2353 : * all-visible, this will also pin the requisite visibility map page.
2354 : *
2355 : * Also pin visibility map page if COPY FREEZE inserts tuples into an
2356 : * empty page. See all_frozen_set below.
2357 : */
2358 640228 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2359 : InvalidBuffer, options, bistate,
2360 : &vmbuffer, NULL,
2361 : npages - npages_used);
2362 640228 : page = BufferGetPage(buffer);
2363 :
2364 640228 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2365 :
2366 640228 : if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2367 3322 : all_frozen_set = true;
2368 :
2369 : /* NO EREPORT(ERROR) from here till changes are logged */
2370 640228 : START_CRIT_SECTION();
2371 :
2372 : /*
2373 : * RelationGetBufferForTuple has ensured that the first tuple fits.
2374 : * Put that on the page, and then as many other tuples as fit.
2375 : */
2376 640228 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2377 :
2378 : /*
2379 : * For logical decoding we need combo CIDs to properly decode the
2380 : * catalog.
2381 : */
2382 640228 : if (needwal && need_cids)
2383 8528 : log_heap_new_cid(relation, heaptuples[ndone]);
2384 :
2385 2724132 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2386 : {
2387 2111648 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2388 :
2389 2111648 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2390 27744 : break;
2391 :
2392 2083904 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2393 :
2394 : /*
2395 : * For logical decoding we need combo CIDs to properly decode the
2396 : * catalog.
2397 : */
2398 2083904 : if (needwal && need_cids)
2399 8456 : log_heap_new_cid(relation, heaptup);
2400 : }
2401 :
2402 : /*
2403 : * If the page is all visible, need to clear that, unless we're only
2404 : * going to add further frozen rows to it.
2405 : *
2406 : * If we're only adding already frozen rows to a previously empty
2407 : * page, mark it as all-visible.
2408 : */
2409 640228 : if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2410 : {
2411 4232 : all_visible_cleared = true;
2412 4232 : PageClearAllVisible(page);
2413 4232 : visibilitymap_clear(relation,
2414 : BufferGetBlockNumber(buffer),
2415 : vmbuffer, VISIBILITYMAP_VALID_BITS);
2416 : }
2417 635996 : else if (all_frozen_set)
2418 3322 : PageSetAllVisible(page);
2419 :
2420 : /*
2421 : * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2422 : */
2423 :
2424 640228 : MarkBufferDirty(buffer);
2425 :
2426 : /* XLOG stuff */
2427 640228 : if (needwal)
2428 : {
2429 : XLogRecPtr recptr;
2430 : xl_heap_multi_insert *xlrec;
2431 632592 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2432 : char *tupledata;
2433 : int totaldatalen;
2434 632592 : char *scratchptr = scratch.data;
2435 : bool init;
2436 632592 : int bufflags = 0;
2437 :
2438 : /*
2439 : * If the page was previously empty, we can reinit the page
2440 : * instead of restoring the whole thing.
2441 : */
2442 632592 : init = starting_with_empty_page;
2443 :
2444 : /* allocate xl_heap_multi_insert struct from the scratch area */
2445 632592 : xlrec = (xl_heap_multi_insert *) scratchptr;
2446 632592 : scratchptr += SizeOfHeapMultiInsert;
2447 :
2448 : /*
2449 : * Allocate offsets array. Unless we're reinitializing the page,
2450 : * in that case the tuples are stored in order starting at
2451 : * FirstOffsetNumber and we don't need to store the offsets
2452 : * explicitly.
2453 : */
2454 632592 : if (!init)
2455 607632 : scratchptr += nthispage * sizeof(OffsetNumber);
2456 :
2457 : /* the rest of the scratch space is used for tuple data */
2458 632592 : tupledata = scratchptr;
2459 :
2460 : /* check that the mutually exclusive flags are not both set */
2461 : Assert(!(all_visible_cleared && all_frozen_set));
2462 :
2463 632592 : xlrec->flags = 0;
2464 632592 : if (all_visible_cleared)
2465 4232 : xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
2466 632592 : if (all_frozen_set)
2467 26 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2468 :
2469 632592 : xlrec->ntuples = nthispage;
2470 :
2471 : /*
2472 : * Write out an xl_multi_insert_tuple and the tuple data itself
2473 : * for each tuple.
2474 : */
2475 2945940 : for (i = 0; i < nthispage; i++)
2476 : {
2477 2313348 : HeapTuple heaptup = heaptuples[ndone + i];
2478 : xl_multi_insert_tuple *tuphdr;
2479 : int datalen;
2480 :
2481 2313348 : if (!init)
2482 1296600 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2483 : /* xl_multi_insert_tuple needs two-byte alignment. */
2484 2313348 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2485 2313348 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2486 :
2487 2313348 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2488 2313348 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2489 2313348 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2490 :
2491 : /* write bitmap [+ padding] [+ oid] + data */
2492 2313348 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
2493 2313348 : memcpy(scratchptr,
2494 2313348 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2495 : datalen);
2496 2313348 : tuphdr->datalen = datalen;
2497 2313348 : scratchptr += datalen;
2498 : }
2499 632592 : totaldatalen = scratchptr - tupledata;
2500 : Assert((scratchptr - scratch.data) < BLCKSZ);
2501 :
2502 632592 : if (need_tuple_data)
2503 146 : xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2504 :
2505 : /*
2506 : * Signal that this is the last xl_heap_multi_insert record
2507 : * emitted by this call to heap_multi_insert(). Needed for logical
2508 : * decoding so it knows when to cleanup temporary data.
2509 : */
2510 632592 : if (ndone + nthispage == ntuples)
2511 611666 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2512 :
2513 632592 : if (init)
2514 : {
2515 24960 : info |= XLOG_HEAP_INIT_PAGE;
2516 24960 : bufflags |= REGBUF_WILL_INIT;
2517 : }
2518 :
2519 : /*
2520 : * If we're doing logical decoding, include the new tuple data
2521 : * even if we take a full-page image of the page.
2522 : */
2523 632592 : if (need_tuple_data)
2524 146 : bufflags |= REGBUF_KEEP_DATA;
2525 :
2526 632592 : XLogBeginInsert();
2527 632592 : XLogRegisterData((char *) xlrec, tupledata - scratch.data);
2528 632592 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2529 :
2530 632592 : XLogRegisterBufData(0, tupledata, totaldatalen);
2531 :
2532 : /* filtering by origin on a row level is much more efficient */
2533 632592 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2534 :
2535 632592 : recptr = XLogInsert(RM_HEAP2_ID, info);
2536 :
2537 632592 : PageSetLSN(page, recptr);
2538 : }
2539 :
2540 640228 : END_CRIT_SECTION();
2541 :
2542 : /*
2543 : * If we've frozen everything on the page, update the visibilitymap.
2544 : * We're already holding pin on the vmbuffer.
2545 : */
2546 640228 : if (all_frozen_set)
2547 : {
2548 : Assert(PageIsAllVisible(page));
2549 : Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
2550 :
2551 : /*
2552 : * It's fine to use InvalidTransactionId here - this is only used
2553 : * when HEAP_INSERT_FROZEN is specified, which intentionally
2554 : * violates visibility rules.
2555 : */
2556 3322 : visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
2557 : InvalidXLogRecPtr, vmbuffer,
2558 : InvalidTransactionId,
2559 : VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
2560 : }
2561 :
2562 640228 : UnlockReleaseBuffer(buffer);
2563 640228 : ndone += nthispage;
2564 :
2565 : /*
2566 : * NB: Only release vmbuffer after inserting all tuples - it's fairly
2567 : * likely that we'll insert into subsequent heap pages that are likely
2568 : * to use the same vm page.
2569 : */
2570 : }
2571 :
2572 : /* We're done with inserting all tuples, so release the last vmbuffer. */
2573 612484 : if (vmbuffer != InvalidBuffer)
2574 4450 : ReleaseBuffer(vmbuffer);
2575 :
2576 : /*
2577 : * We're done with the actual inserts. Check for conflicts again, to
2578 : * ensure that all rw-conflicts in to these inserts are detected. Without
2579 : * this final check, a sequential scan of the heap may have locked the
2580 : * table after the "before" check, missing one opportunity to detect the
2581 : * conflict, and then scanned the table before the new tuples were there,
2582 : * missing the other chance to detect the conflict.
2583 : *
2584 : * For heap inserts, we only need to check for table-level SSI locks. Our
2585 : * new tuples can't possibly conflict with existing tuple locks, and heap
2586 : * page locks are only consolidated versions of tuple locks; they do not
2587 : * lock "gaps" as index page locks do. So we don't need to specify a
2588 : * buffer when making the call.
2589 : */
2590 612484 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2591 :
2592 : /*
2593 : * If tuples are cachable, mark them for invalidation from the caches in
2594 : * case we abort. Note it is OK to do this after releasing the buffer,
2595 : * because the heaptuples data structure is all in local memory, not in
2596 : * the shared buffer.
2597 : */
2598 612484 : if (IsCatalogRelation(relation))
2599 : {
2600 2146412 : for (i = 0; i < ntuples; i++)
2601 1536250 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2602 : }
2603 :
2604 : /* copy t_self fields back to the caller's slots */
2605 3336616 : for (i = 0; i < ntuples; i++)
2606 2724132 : slots[i]->tts_tid = heaptuples[i]->t_self;
2607 :
2608 612484 : pgstat_count_heap_insert(relation, ntuples);
2609 612484 : }
2610 :
2611 : /*
2612 : * simple_heap_insert - insert a tuple
2613 : *
2614 : * Currently, this routine differs from heap_insert only in supplying
2615 : * a default command ID and not allowing access to the speedup options.
2616 : *
2617 : * This should be used rather than using heap_insert directly in most places
2618 : * where we are modifying system catalogs.
2619 : */
2620 : void
2621 1434036 : simple_heap_insert(Relation relation, HeapTuple tup)
2622 : {
2623 1434036 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2624 1434036 : }
2625 :
2626 : /*
2627 : * Given infomask/infomask2, compute the bits that must be saved in the
2628 : * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2629 : * xl_heap_lock_updated WAL records.
2630 : *
2631 : * See fix_infomask_from_infobits.
2632 : */
2633 : static uint8
2634 3605484 : compute_infobits(uint16 infomask, uint16 infomask2)
2635 : {
2636 : return
2637 3605484 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2638 3605484 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2639 3605484 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2640 : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2641 7210968 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2642 : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2643 3605484 : XLHL_KEYS_UPDATED : 0);
2644 : }
2645 :
2646 : /*
2647 : * Given two versions of the same t_infomask for a tuple, compare them and
2648 : * return whether the relevant status for a tuple Xmax has changed. This is
2649 : * used after a buffer lock has been released and reacquired: we want to ensure
2650 : * that the tuple state continues to be the same it was when we previously
2651 : * examined it.
2652 : *
2653 : * Note the Xmax field itself must be compared separately.
2654 : */
2655 : static inline bool
2656 10640 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2657 : {
2658 10640 : const uint16 interesting =
2659 : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2660 :
2661 10640 : if ((new_infomask & interesting) != (old_infomask & interesting))
2662 28 : return true;
2663 :
2664 10612 : return false;
2665 : }
2666 :
2667 : /*
2668 : * heap_delete - delete a tuple
2669 : *
2670 : * See table_tuple_delete() for an explanation of the parameters, except that
2671 : * this routine directly takes a tuple rather than a slot.
2672 : *
2673 : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2674 : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2675 : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2676 : * generated by another transaction).
2677 : */
2678 : TM_Result
2679 2758910 : heap_delete(Relation relation, ItemPointer tid,
2680 : CommandId cid, Snapshot crosscheck, bool wait,
2681 : TM_FailureData *tmfd, bool changingPart)
2682 : {
2683 : TM_Result result;
2684 2758910 : TransactionId xid = GetCurrentTransactionId();
2685 : ItemId lp;
2686 : HeapTupleData tp;
2687 : Page page;
2688 : BlockNumber block;
2689 : Buffer buffer;
2690 2758910 : Buffer vmbuffer = InvalidBuffer;
2691 : TransactionId new_xmax;
2692 : uint16 new_infomask,
2693 : new_infomask2;
2694 2758910 : bool have_tuple_lock = false;
2695 : bool iscombo;
2696 2758910 : bool all_visible_cleared = false;
2697 2758910 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2698 2758910 : bool old_key_copied = false;
2699 :
2700 : Assert(ItemPointerIsValid(tid));
2701 :
2702 : /*
2703 : * Forbid this during a parallel operation, lest it allocate a combo CID.
2704 : * Other workers might need that combo CID for visibility checks, and we
2705 : * have no provision for broadcasting it to them.
2706 : */
2707 2758910 : if (IsInParallelMode())
2708 0 : ereport(ERROR,
2709 : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2710 : errmsg("cannot delete tuples during a parallel operation")));
2711 :
2712 2758910 : block = ItemPointerGetBlockNumber(tid);
2713 2758910 : buffer = ReadBuffer(relation, block);
2714 2758910 : page = BufferGetPage(buffer);
2715 :
2716 : /*
2717 : * Before locking the buffer, pin the visibility map page if it appears to
2718 : * be necessary. Since we haven't got the lock yet, someone else might be
2719 : * in the middle of changing this, so we'll need to recheck after we have
2720 : * the lock.
2721 : */
2722 2758910 : if (PageIsAllVisible(page))
2723 156 : visibilitymap_pin(relation, block, &vmbuffer);
2724 :
2725 2758910 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2726 :
2727 2758910 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2728 : Assert(ItemIdIsNormal(lp));
2729 :
2730 2758910 : tp.t_tableOid = RelationGetRelid(relation);
2731 2758910 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2732 2758910 : tp.t_len = ItemIdGetLength(lp);
2733 2758910 : tp.t_self = *tid;
2734 :
2735 2758912 : l1:
2736 :
2737 : /*
2738 : * If we didn't pin the visibility map page and the page has become all
2739 : * visible while we were busy locking the buffer, we'll have to unlock and
2740 : * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2741 : * unfortunate, but hopefully shouldn't happen often.
2742 : */
2743 2758912 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2744 : {
2745 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2746 0 : visibilitymap_pin(relation, block, &vmbuffer);
2747 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2748 : }
2749 :
2750 2758912 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2751 :
2752 2758912 : if (result == TM_Invisible)
2753 : {
2754 0 : UnlockReleaseBuffer(buffer);
2755 0 : ereport(ERROR,
2756 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2757 : errmsg("attempted to delete invisible tuple")));
2758 : }
2759 2758912 : else if (result == TM_BeingModified && wait)
2760 : {
2761 : TransactionId xwait;
2762 : uint16 infomask;
2763 :
2764 : /* must copy state data before unlocking buffer */
2765 81078 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2766 81078 : infomask = tp.t_data->t_infomask;
2767 :
2768 : /*
2769 : * Sleep until concurrent transaction ends -- except when there's a
2770 : * single locker and it's our own transaction. Note we don't care
2771 : * which lock mode the locker has, because we need the strongest one.
2772 : *
2773 : * Before sleeping, we need to acquire tuple lock to establish our
2774 : * priority for the tuple (see heap_lock_tuple). LockTuple will
2775 : * release us when we are next-in-line for the tuple.
2776 : *
2777 : * If we are forced to "start over" below, we keep the tuple lock;
2778 : * this arranges that we stay at the head of the line while rechecking
2779 : * tuple state.
2780 : */
2781 81078 : if (infomask & HEAP_XMAX_IS_MULTI)
2782 : {
2783 16 : bool current_is_member = false;
2784 :
2785 16 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2786 : LockTupleExclusive, ¤t_is_member))
2787 : {
2788 16 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2789 :
2790 : /*
2791 : * Acquire the lock, if necessary (but skip it when we're
2792 : * requesting a lock and already have one; avoids deadlock).
2793 : */
2794 16 : if (!current_is_member)
2795 12 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2796 : LockWaitBlock, &have_tuple_lock);
2797 :
2798 : /* wait for multixact */
2799 16 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2800 : relation, &(tp.t_self), XLTW_Delete,
2801 : NULL);
2802 16 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2803 :
2804 : /*
2805 : * If xwait had just locked the tuple then some other xact
2806 : * could update this tuple before we get to this point. Check
2807 : * for xmax change, and start over if so.
2808 : *
2809 : * We also must start over if we didn't pin the VM page, and
2810 : * the page has become all visible.
2811 : */
2812 32 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2813 16 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2814 16 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2815 : xwait))
2816 0 : goto l1;
2817 : }
2818 :
2819 : /*
2820 : * You might think the multixact is necessarily done here, but not
2821 : * so: it could have surviving members, namely our own xact or
2822 : * other subxacts of this backend. It is legal for us to delete
2823 : * the tuple in either case, however (the latter case is
2824 : * essentially a situation of upgrading our former shared lock to
2825 : * exclusive). We don't bother changing the on-disk hint bits
2826 : * since we are about to overwrite the xmax altogether.
2827 : */
2828 : }
2829 81062 : else if (!TransactionIdIsCurrentTransactionId(xwait))
2830 : {
2831 : /*
2832 : * Wait for regular transaction to end; but first, acquire tuple
2833 : * lock.
2834 : */
2835 80 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2836 80 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2837 : LockWaitBlock, &have_tuple_lock);
2838 80 : XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2839 72 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2840 :
2841 : /*
2842 : * xwait is done, but if xwait had just locked the tuple then some
2843 : * other xact could update this tuple before we get to this point.
2844 : * Check for xmax change, and start over if so.
2845 : *
2846 : * We also must start over if we didn't pin the VM page, and the
2847 : * page has become all visible.
2848 : */
2849 144 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2850 72 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2851 70 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2852 : xwait))
2853 2 : goto l1;
2854 :
2855 : /* Otherwise check if it committed or aborted */
2856 70 : UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2857 : }
2858 :
2859 : /*
2860 : * We may overwrite if previous xmax aborted, or if it committed but
2861 : * only locked the tuple without updating it.
2862 : */
2863 81068 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2864 81090 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2865 50 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2866 81026 : result = TM_Ok;
2867 42 : else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2868 34 : result = TM_Updated;
2869 : else
2870 8 : result = TM_Deleted;
2871 : }
2872 :
2873 : /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2874 : if (result != TM_Ok)
2875 : {
2876 : Assert(result == TM_SelfModified ||
2877 : result == TM_Updated ||
2878 : result == TM_Deleted ||
2879 : result == TM_BeingModified);
2880 : Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2881 : Assert(result != TM_Updated ||
2882 : !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2883 : }
2884 :
2885 2758902 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
2886 : {
2887 : /* Perform additional check for transaction-snapshot mode RI updates */
2888 2 : if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2889 2 : result = TM_Updated;
2890 : }
2891 :
2892 2758902 : if (result != TM_Ok)
2893 : {
2894 112 : tmfd->ctid = tp.t_data->t_ctid;
2895 112 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2896 112 : if (result == TM_SelfModified)
2897 42 : tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2898 : else
2899 70 : tmfd->cmax = InvalidCommandId;
2900 112 : UnlockReleaseBuffer(buffer);
2901 112 : if (have_tuple_lock)
2902 42 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2903 112 : if (vmbuffer != InvalidBuffer)
2904 0 : ReleaseBuffer(vmbuffer);
2905 112 : return result;
2906 : }
2907 :
2908 : /*
2909 : * We're about to do the actual delete -- check for conflict first, to
2910 : * avoid possibly having to roll back work we've just done.
2911 : *
2912 : * This is safe without a recheck as long as there is no possibility of
2913 : * another process scanning the page between this check and the delete
2914 : * being visible to the scan (i.e., an exclusive buffer content lock is
2915 : * continuously held from this point until the tuple delete is visible).
2916 : */
2917 2758790 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2918 :
2919 : /* replace cid with a combo CID if necessary */
2920 2758762 : HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2921 :
2922 : /*
2923 : * Compute replica identity tuple before entering the critical section so
2924 : * we don't PANIC upon a memory allocation failure.
2925 : */
2926 2758762 : old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2927 :
2928 : /*
2929 : * If this is the first possibly-multixact-able operation in the current
2930 : * transaction, set my per-backend OldestMemberMXactId setting. We can be
2931 : * certain that the transaction will never become a member of any older
2932 : * MultiXactIds than that. (We have to do this even if we end up just
2933 : * using our own TransactionId below, since some other backend could
2934 : * incorporate our XID into a MultiXact immediately afterwards.)
2935 : */
2936 2758762 : MultiXactIdSetOldestMember();
2937 :
2938 2758762 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
2939 2758762 : tp.t_data->t_infomask, tp.t_data->t_infomask2,
2940 : xid, LockTupleExclusive, true,
2941 : &new_xmax, &new_infomask, &new_infomask2);
2942 :
2943 2758762 : START_CRIT_SECTION();
2944 :
2945 : /*
2946 : * If this transaction commits, the tuple will become DEAD sooner or
2947 : * later. Set flag that this page is a candidate for pruning once our xid
2948 : * falls below the OldestXmin horizon. If the transaction finally aborts,
2949 : * the subsequent page pruning will be a no-op and the hint will be
2950 : * cleared.
2951 : */
2952 2758762 : PageSetPrunable(page, xid);
2953 :
2954 2758762 : if (PageIsAllVisible(page))
2955 : {
2956 156 : all_visible_cleared = true;
2957 156 : PageClearAllVisible(page);
2958 156 : visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2959 : vmbuffer, VISIBILITYMAP_VALID_BITS);
2960 : }
2961 :
2962 : /* store transaction information of xact deleting the tuple */
2963 2758762 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
2964 2758762 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
2965 2758762 : tp.t_data->t_infomask |= new_infomask;
2966 2758762 : tp.t_data->t_infomask2 |= new_infomask2;
2967 2758762 : HeapTupleHeaderClearHotUpdated(tp.t_data);
2968 2758762 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2969 2758762 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2970 : /* Make sure there is no forward chain link in t_ctid */
2971 2758762 : tp.t_data->t_ctid = tp.t_self;
2972 :
2973 : /* Signal that this is actually a move into another partition */
2974 2758762 : if (changingPart)
2975 892 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
2976 :
2977 2758762 : MarkBufferDirty(buffer);
2978 :
2979 : /*
2980 : * XLOG stuff
2981 : *
2982 : * NB: heap_abort_speculative() uses the same xlog record and replay
2983 : * routines.
2984 : */
2985 2758762 : if (RelationNeedsWAL(relation))
2986 : {
2987 : xl_heap_delete xlrec;
2988 : xl_heap_header xlhdr;
2989 : XLogRecPtr recptr;
2990 :
2991 : /*
2992 : * For logical decode we need combo CIDs to properly decode the
2993 : * catalog
2994 : */
2995 2637598 : if (RelationIsAccessibleInLogicalDecoding(relation))
2996 10572 : log_heap_new_cid(relation, &tp);
2997 :
2998 2637598 : xlrec.flags = 0;
2999 2637598 : if (all_visible_cleared)
3000 156 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3001 2637598 : if (changingPart)
3002 892 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
3003 5275196 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3004 2637598 : tp.t_data->t_infomask2);
3005 2637598 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
3006 2637598 : xlrec.xmax = new_xmax;
3007 :
3008 2637598 : if (old_key_tuple != NULL)
3009 : {
3010 94000 : if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3011 242 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
3012 : else
3013 93758 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
3014 : }
3015 :
3016 2637598 : XLogBeginInsert();
3017 2637598 : XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
3018 :
3019 2637598 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3020 :
3021 : /*
3022 : * Log replica identity of the deleted tuple if there is one
3023 : */
3024 2637598 : if (old_key_tuple != NULL)
3025 : {
3026 94000 : xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3027 94000 : xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3028 94000 : xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3029 :
3030 94000 : XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
3031 94000 : XLogRegisterData((char *) old_key_tuple->t_data
3032 : + SizeofHeapTupleHeader,
3033 94000 : old_key_tuple->t_len
3034 : - SizeofHeapTupleHeader);
3035 : }
3036 :
3037 : /* filtering by origin on a row level is much more efficient */
3038 2637598 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3039 :
3040 2637598 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3041 :
3042 2637598 : PageSetLSN(page, recptr);
3043 : }
3044 :
3045 2758762 : END_CRIT_SECTION();
3046 :
3047 2758762 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3048 :
3049 2758762 : if (vmbuffer != InvalidBuffer)
3050 156 : ReleaseBuffer(vmbuffer);
3051 :
3052 : /*
3053 : * If the tuple has toasted out-of-line attributes, we need to delete
3054 : * those items too. We have to do this before releasing the buffer
3055 : * because we need to look at the contents of the tuple, but it's OK to
3056 : * release the content lock on the buffer first.
3057 : */
3058 2758762 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3059 3284 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3060 : {
3061 : /* toast table entries should never be recursively toasted */
3062 : Assert(!HeapTupleHasExternal(&tp));
3063 : }
3064 2755498 : else if (HeapTupleHasExternal(&tp))
3065 512 : heap_toast_delete(relation, &tp, false);
3066 :
3067 : /*
3068 : * Mark tuple for invalidation from system caches at next command
3069 : * boundary. We have to do this before releasing the buffer because we
3070 : * need to look at the contents of the tuple.
3071 : */
3072 2758762 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3073 :
3074 : /* Now we can release the buffer */
3075 2758762 : ReleaseBuffer(buffer);
3076 :
3077 : /*
3078 : * Release the lmgr tuple lock, if we had it.
3079 : */
3080 2758762 : if (have_tuple_lock)
3081 40 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3082 :
3083 2758762 : pgstat_count_heap_delete(relation);
3084 :
3085 2758762 : if (old_key_tuple != NULL && old_key_copied)
3086 93760 : heap_freetuple(old_key_tuple);
3087 :
3088 2758762 : return TM_Ok;
3089 : }
3090 :
3091 : /*
3092 : * simple_heap_delete - delete a tuple
3093 : *
3094 : * This routine may be used to delete a tuple when concurrent updates of
3095 : * the target tuple are not expected (for example, because we have a lock
3096 : * on the relation associated with the tuple). Any failure is reported
3097 : * via ereport().
3098 : */
3099 : void
3100 1152328 : simple_heap_delete(Relation relation, ItemPointer tid)
3101 : {
3102 : TM_Result result;
3103 : TM_FailureData tmfd;
3104 :
3105 1152328 : result = heap_delete(relation, tid,
3106 : GetCurrentCommandId(true), InvalidSnapshot,
3107 : true /* wait for commit */ ,
3108 : &tmfd, false /* changingPart */ );
3109 1152328 : switch (result)
3110 : {
3111 0 : case TM_SelfModified:
3112 : /* Tuple was already updated in current command? */
3113 0 : elog(ERROR, "tuple already updated by self");
3114 : break;
3115 :
3116 1152328 : case TM_Ok:
3117 : /* done successfully */
3118 1152328 : break;
3119 :
3120 0 : case TM_Updated:
3121 0 : elog(ERROR, "tuple concurrently updated");
3122 : break;
3123 :
3124 0 : case TM_Deleted:
3125 0 : elog(ERROR, "tuple concurrently deleted");
3126 : break;
3127 :
3128 0 : default:
3129 0 : elog(ERROR, "unrecognized heap_delete status: %u", result);
3130 : break;
3131 : }
3132 1152328 : }
3133 :
3134 : /*
3135 : * heap_update - replace a tuple
3136 : *
3137 : * See table_tuple_update() for an explanation of the parameters, except that
3138 : * this routine directly takes a tuple rather than a slot.
3139 : *
3140 : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3141 : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3142 : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3143 : * generated by another transaction).
3144 : */
3145 : TM_Result
3146 566470 : heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
3147 : CommandId cid, Snapshot crosscheck, bool wait,
3148 : TM_FailureData *tmfd, LockTupleMode *lockmode,
3149 : TU_UpdateIndexes *update_indexes)
3150 : {
3151 : TM_Result result;
3152 566470 : TransactionId xid = GetCurrentTransactionId();
3153 : Bitmapset *hot_attrs;
3154 : Bitmapset *sum_attrs;
3155 : Bitmapset *key_attrs;
3156 : Bitmapset *id_attrs;
3157 : Bitmapset *interesting_attrs;
3158 : Bitmapset *modified_attrs;
3159 : ItemId lp;
3160 : HeapTupleData oldtup;
3161 : HeapTuple heaptup;
3162 566470 : HeapTuple old_key_tuple = NULL;
3163 566470 : bool old_key_copied = false;
3164 : Page page;
3165 : BlockNumber block;
3166 : MultiXactStatus mxact_status;
3167 : Buffer buffer,
3168 : newbuf,
3169 566470 : vmbuffer = InvalidBuffer,
3170 566470 : vmbuffer_new = InvalidBuffer;
3171 : bool need_toast;
3172 : Size newtupsize,
3173 : pagefree;
3174 566470 : bool have_tuple_lock = false;
3175 : bool iscombo;
3176 566470 : bool use_hot_update = false;
3177 566470 : bool summarized_update = false;
3178 : bool key_intact;
3179 566470 : bool all_visible_cleared = false;
3180 566470 : bool all_visible_cleared_new = false;
3181 : bool checked_lockers;
3182 : bool locker_remains;
3183 566470 : bool id_has_external = false;
3184 : TransactionId xmax_new_tuple,
3185 : xmax_old_tuple;
3186 : uint16 infomask_old_tuple,
3187 : infomask2_old_tuple,
3188 : infomask_new_tuple,
3189 : infomask2_new_tuple;
3190 :
3191 : Assert(ItemPointerIsValid(otid));
3192 :
3193 : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3194 : Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
3195 : RelationGetNumberOfAttributes(relation));
3196 :
3197 : /*
3198 : * Forbid this during a parallel operation, lest it allocate a combo CID.
3199 : * Other workers might need that combo CID for visibility checks, and we
3200 : * have no provision for broadcasting it to them.
3201 : */
3202 566470 : if (IsInParallelMode())
3203 0 : ereport(ERROR,
3204 : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3205 : errmsg("cannot update tuples during a parallel operation")));
3206 :
3207 : /*
3208 : * Fetch the list of attributes to be checked for various operations.
3209 : *
3210 : * For HOT considerations, this is wasted effort if we fail to update or
3211 : * have to put the new tuple on a different page. But we must compute the
3212 : * list before obtaining buffer lock --- in the worst case, if we are
3213 : * doing an update on one of the relevant system catalogs, we could
3214 : * deadlock if we try to fetch the list later. In any case, the relcache
3215 : * caches the data so this is usually pretty cheap.
3216 : *
3217 : * We also need columns used by the replica identity and columns that are
3218 : * considered the "key" of rows in the table.
3219 : *
3220 : * Note that we get copies of each bitmap, so we need not worry about
3221 : * relcache flush happening midway through.
3222 : */
3223 566470 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3224 : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3225 566470 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3226 : INDEX_ATTR_BITMAP_SUMMARIZED);
3227 566470 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3228 566470 : id_attrs = RelationGetIndexAttrBitmap(relation,
3229 : INDEX_ATTR_BITMAP_IDENTITY_KEY);
3230 566470 : interesting_attrs = NULL;
3231 566470 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3232 566470 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
3233 566470 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3234 566470 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3235 :
3236 566470 : block = ItemPointerGetBlockNumber(otid);
3237 566470 : buffer = ReadBuffer(relation, block);
3238 566470 : page = BufferGetPage(buffer);
3239 :
3240 : /*
3241 : * Before locking the buffer, pin the visibility map page if it appears to
3242 : * be necessary. Since we haven't got the lock yet, someone else might be
3243 : * in the middle of changing this, so we'll need to recheck after we have
3244 : * the lock.
3245 : */
3246 566470 : if (PageIsAllVisible(page))
3247 2056 : visibilitymap_pin(relation, block, &vmbuffer);
3248 :
3249 566470 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3250 :
3251 566470 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3252 : Assert(ItemIdIsNormal(lp));
3253 :
3254 : /*
3255 : * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3256 : * properly.
3257 : */
3258 566470 : oldtup.t_tableOid = RelationGetRelid(relation);
3259 566470 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3260 566470 : oldtup.t_len = ItemIdGetLength(lp);
3261 566470 : oldtup.t_self = *otid;
3262 :
3263 : /* the new tuple is ready, except for this: */
3264 566470 : newtup->t_tableOid = RelationGetRelid(relation);
3265 :
3266 : /*
3267 : * Determine columns modified by the update. Additionally, identify
3268 : * whether any of the unmodified replica identity key attributes in the
3269 : * old tuple is externally stored or not. This is required because for
3270 : * such attributes the flattened value won't be WAL logged as part of the
3271 : * new tuple so we must include it as part of the old_key_tuple. See
3272 : * ExtractReplicaIdentity.
3273 : */
3274 566470 : modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3275 : id_attrs, &oldtup,
3276 : newtup, &id_has_external);
3277 :
3278 : /*
3279 : * If we're not updating any "key" column, we can grab a weaker lock type.
3280 : * This allows for more concurrency when we are running simultaneously
3281 : * with foreign key checks.
3282 : *
3283 : * Note that if a column gets detoasted while executing the update, but
3284 : * the value ends up being the same, this test will fail and we will use
3285 : * the stronger lock. This is acceptable; the important case to optimize
3286 : * is updates that don't manipulate key columns, not those that
3287 : * serendipitously arrive at the same key values.
3288 : */
3289 566470 : if (!bms_overlap(modified_attrs, key_attrs))
3290 : {
3291 558898 : *lockmode = LockTupleNoKeyExclusive;
3292 558898 : mxact_status = MultiXactStatusNoKeyUpdate;
3293 558898 : key_intact = true;
3294 :
3295 : /*
3296 : * If this is the first possibly-multixact-able operation in the
3297 : * current transaction, set my per-backend OldestMemberMXactId
3298 : * setting. We can be certain that the transaction will never become a
3299 : * member of any older MultiXactIds than that. (We have to do this
3300 : * even if we end up just using our own TransactionId below, since
3301 : * some other backend could incorporate our XID into a MultiXact
3302 : * immediately afterwards.)
3303 : */
3304 558898 : MultiXactIdSetOldestMember();
3305 : }
3306 : else
3307 : {
3308 7572 : *lockmode = LockTupleExclusive;
3309 7572 : mxact_status = MultiXactStatusUpdate;
3310 7572 : key_intact = false;
3311 : }
3312 :
3313 : /*
3314 : * Note: beyond this point, use oldtup not otid to refer to old tuple.
3315 : * otid may very well point at newtup->t_self, which we will overwrite
3316 : * with the new tuple's location, so there's great risk of confusion if we
3317 : * use otid anymore.
3318 : */
3319 :
3320 566470 : l2:
3321 566472 : checked_lockers = false;
3322 566472 : locker_remains = false;
3323 566472 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3324 :
3325 : /* see below about the "no wait" case */
3326 : Assert(result != TM_BeingModified || wait);
3327 :
3328 566472 : if (result == TM_Invisible)
3329 : {
3330 0 : UnlockReleaseBuffer(buffer);
3331 0 : ereport(ERROR,
3332 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3333 : errmsg("attempted to update invisible tuple")));
3334 : }
3335 566472 : else if (result == TM_BeingModified && wait)
3336 : {
3337 : TransactionId xwait;
3338 : uint16 infomask;
3339 71770 : bool can_continue = false;
3340 :
3341 : /*
3342 : * XXX note that we don't consider the "no wait" case here. This
3343 : * isn't a problem currently because no caller uses that case, but it
3344 : * should be fixed if such a caller is introduced. It wasn't a
3345 : * problem previously because this code would always wait, but now
3346 : * that some tuple locks do not conflict with one of the lock modes we
3347 : * use, it is possible that this case is interesting to handle
3348 : * specially.
3349 : *
3350 : * This may cause failures with third-party code that calls
3351 : * heap_update directly.
3352 : */
3353 :
3354 : /* must copy state data before unlocking buffer */
3355 71770 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3356 71770 : infomask = oldtup.t_data->t_infomask;
3357 :
3358 : /*
3359 : * Now we have to do something about the existing locker. If it's a
3360 : * multi, sleep on it; we might be awakened before it is completely
3361 : * gone (or even not sleep at all in some cases); we need to preserve
3362 : * it as locker, unless it is gone completely.
3363 : *
3364 : * If it's not a multi, we need to check for sleeping conditions
3365 : * before actually going to sleep. If the update doesn't conflict
3366 : * with the locks, we just continue without sleeping (but making sure
3367 : * it is preserved).
3368 : *
3369 : * Before sleeping, we need to acquire tuple lock to establish our
3370 : * priority for the tuple (see heap_lock_tuple). LockTuple will
3371 : * release us when we are next-in-line for the tuple. Note we must
3372 : * not acquire the tuple lock until we're sure we're going to sleep;
3373 : * otherwise we're open for race conditions with other transactions
3374 : * holding the tuple lock which sleep on us.
3375 : *
3376 : * If we are forced to "start over" below, we keep the tuple lock;
3377 : * this arranges that we stay at the head of the line while rechecking
3378 : * tuple state.
3379 : */
3380 71770 : if (infomask & HEAP_XMAX_IS_MULTI)
3381 : {
3382 : TransactionId update_xact;
3383 : int remain;
3384 120 : bool current_is_member = false;
3385 :
3386 120 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3387 : *lockmode, ¤t_is_member))
3388 : {
3389 16 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3390 :
3391 : /*
3392 : * Acquire the lock, if necessary (but skip it when we're
3393 : * requesting a lock and already have one; avoids deadlock).
3394 : */
3395 16 : if (!current_is_member)
3396 0 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3397 : LockWaitBlock, &have_tuple_lock);
3398 :
3399 : /* wait for multixact */
3400 16 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3401 : relation, &oldtup.t_self, XLTW_Update,
3402 : &remain);
3403 16 : checked_lockers = true;
3404 16 : locker_remains = remain != 0;
3405 16 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3406 :
3407 : /*
3408 : * If xwait had just locked the tuple then some other xact
3409 : * could update this tuple before we get to this point. Check
3410 : * for xmax change, and start over if so.
3411 : */
3412 16 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3413 16 : infomask) ||
3414 16 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3415 : xwait))
3416 0 : goto l2;
3417 : }
3418 :
3419 : /*
3420 : * Note that the multixact may not be done by now. It could have
3421 : * surviving members; our own xact or other subxacts of this
3422 : * backend, and also any other concurrent transaction that locked
3423 : * the tuple with LockTupleKeyShare if we only got
3424 : * LockTupleNoKeyExclusive. If this is the case, we have to be
3425 : * careful to mark the updated tuple with the surviving members in
3426 : * Xmax.
3427 : *
3428 : * Note that there could have been another update in the
3429 : * MultiXact. In that case, we need to check whether it committed
3430 : * or aborted. If it aborted we are safe to update it again;
3431 : * otherwise there is an update conflict, and we have to return
3432 : * TableTuple{Deleted, Updated} below.
3433 : *
3434 : * In the LockTupleExclusive case, we still need to preserve the
3435 : * surviving members: those would include the tuple locks we had
3436 : * before this one, which are important to keep in case this
3437 : * subxact aborts.
3438 : */
3439 120 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3440 16 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3441 : else
3442 104 : update_xact = InvalidTransactionId;
3443 :
3444 : /*
3445 : * There was no UPDATE in the MultiXact; or it aborted. No
3446 : * TransactionIdIsInProgress() call needed here, since we called
3447 : * MultiXactIdWait() above.
3448 : */
3449 136 : if (!TransactionIdIsValid(update_xact) ||
3450 16 : TransactionIdDidAbort(update_xact))
3451 106 : can_continue = true;
3452 : }
3453 71650 : else if (TransactionIdIsCurrentTransactionId(xwait))
3454 : {
3455 : /*
3456 : * The only locker is ourselves; we can avoid grabbing the tuple
3457 : * lock here, but must preserve our locking information.
3458 : */
3459 71474 : checked_lockers = true;
3460 71474 : locker_remains = true;
3461 71474 : can_continue = true;
3462 : }
3463 176 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3464 : {
3465 : /*
3466 : * If it's just a key-share locker, and we're not changing the key
3467 : * columns, we don't need to wait for it to end; but we need to
3468 : * preserve it as locker.
3469 : */
3470 58 : checked_lockers = true;
3471 58 : locker_remains = true;
3472 58 : can_continue = true;
3473 : }
3474 : else
3475 : {
3476 : /*
3477 : * Wait for regular transaction to end; but first, acquire tuple
3478 : * lock.
3479 : */
3480 118 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3481 118 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3482 : LockWaitBlock, &have_tuple_lock);
3483 118 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3484 : XLTW_Update);
3485 118 : checked_lockers = true;
3486 118 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3487 :
3488 : /*
3489 : * xwait is done, but if xwait had just locked the tuple then some
3490 : * other xact could update this tuple before we get to this point.
3491 : * Check for xmax change, and start over if so.
3492 : */
3493 118 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3494 116 : !TransactionIdEquals(xwait,
3495 : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3496 2 : goto l2;
3497 :
3498 : /* Otherwise check if it committed or aborted */
3499 116 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3500 116 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3501 24 : can_continue = true;
3502 : }
3503 :
3504 71768 : if (can_continue)
3505 71662 : result = TM_Ok;
3506 106 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3507 96 : result = TM_Updated;
3508 : else
3509 10 : result = TM_Deleted;
3510 : }
3511 :
3512 : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3513 : if (result != TM_Ok)
3514 : {
3515 : Assert(result == TM_SelfModified ||
3516 : result == TM_Updated ||
3517 : result == TM_Deleted ||
3518 : result == TM_BeingModified);
3519 : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3520 : Assert(result != TM_Updated ||
3521 : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3522 : }
3523 :
3524 566470 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3525 : {
3526 : /* Perform additional check for transaction-snapshot mode RI updates */
3527 2 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3528 2 : result = TM_Updated;
3529 : }
3530 :
3531 566470 : if (result != TM_Ok)
3532 : {
3533 300 : tmfd->ctid = oldtup.t_data->t_ctid;
3534 300 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3535 300 : if (result == TM_SelfModified)
3536 104 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3537 : else
3538 196 : tmfd->cmax = InvalidCommandId;
3539 300 : UnlockReleaseBuffer(buffer);
3540 300 : if (have_tuple_lock)
3541 92 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3542 300 : if (vmbuffer != InvalidBuffer)
3543 0 : ReleaseBuffer(vmbuffer);
3544 300 : *update_indexes = TU_None;
3545 :
3546 300 : bms_free(hot_attrs);
3547 300 : bms_free(sum_attrs);
3548 300 : bms_free(key_attrs);
3549 300 : bms_free(id_attrs);
3550 300 : bms_free(modified_attrs);
3551 300 : bms_free(interesting_attrs);
3552 300 : return result;
3553 : }
3554 :
3555 : /*
3556 : * If we didn't pin the visibility map page and the page has become all
3557 : * visible while we were busy locking the buffer, or during some
3558 : * subsequent window during which we had it unlocked, we'll have to unlock
3559 : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3560 : * bit unfortunate, especially since we'll now have to recheck whether the
3561 : * tuple has been locked or updated under us, but hopefully it won't
3562 : * happen very often.
3563 : */
3564 566170 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3565 : {
3566 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3567 0 : visibilitymap_pin(relation, block, &vmbuffer);
3568 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3569 0 : goto l2;
3570 : }
3571 :
3572 : /* Fill in transaction status data */
3573 :
3574 : /*
3575 : * If the tuple we're updating is locked, we need to preserve the locking
3576 : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3577 : */
3578 566170 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3579 566170 : oldtup.t_data->t_infomask,
3580 566170 : oldtup.t_data->t_infomask2,
3581 : xid, *lockmode, true,
3582 : &xmax_old_tuple, &infomask_old_tuple,
3583 : &infomask2_old_tuple);
3584 :
3585 : /*
3586 : * And also prepare an Xmax value for the new copy of the tuple. If there
3587 : * was no xmax previously, or there was one but all lockers are now gone,
3588 : * then use InvalidTransactionId; otherwise, get the xmax from the old
3589 : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3590 : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3591 : */
3592 566170 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3593 71638 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
3594 71534 : (checked_lockers && !locker_remains))
3595 494532 : xmax_new_tuple = InvalidTransactionId;
3596 : else
3597 71638 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3598 :
3599 566170 : if (!TransactionIdIsValid(xmax_new_tuple))
3600 : {
3601 494532 : infomask_new_tuple = HEAP_XMAX_INVALID;
3602 494532 : infomask2_new_tuple = 0;
3603 : }
3604 : else
3605 : {
3606 : /*
3607 : * If we found a valid Xmax for the new tuple, then the infomask bits
3608 : * to use on the new tuple depend on what was there on the old one.
3609 : * Note that since we're doing an update, the only possibility is that
3610 : * the lockers had FOR KEY SHARE lock.
3611 : */
3612 71638 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3613 : {
3614 106 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3615 : &infomask2_new_tuple);
3616 : }
3617 : else
3618 : {
3619 71532 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3620 71532 : infomask2_new_tuple = 0;
3621 : }
3622 : }
3623 :
3624 : /*
3625 : * Prepare the new tuple with the appropriate initial values of Xmin and
3626 : * Xmax, as well as initial infomask bits as computed above.
3627 : */
3628 566170 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3629 566170 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3630 566170 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
3631 566170 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
3632 566170 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3633 566170 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3634 566170 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3635 :
3636 : /*
3637 : * Replace cid with a combo CID if necessary. Note that we already put
3638 : * the plain cid into the new tuple.
3639 : */
3640 566170 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3641 :
3642 : /*
3643 : * If the toaster needs to be activated, OR if the new tuple will not fit
3644 : * on the same page as the old, then we need to release the content lock
3645 : * (but not the pin!) on the old tuple's buffer while we are off doing
3646 : * TOAST and/or table-file-extension work. We must mark the old tuple to
3647 : * show that it's locked, else other processes may try to update it
3648 : * themselves.
3649 : *
3650 : * We need to invoke the toaster if there are already any out-of-line
3651 : * toasted values present, or if the new tuple is over-threshold.
3652 : */
3653 566170 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3654 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3655 : {
3656 : /* toast table entries should never be recursively toasted */
3657 : Assert(!HeapTupleHasExternal(&oldtup));
3658 : Assert(!HeapTupleHasExternal(newtup));
3659 0 : need_toast = false;
3660 : }
3661 : else
3662 566170 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3663 1131846 : HeapTupleHasExternal(newtup) ||
3664 565676 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3665 :
3666 566170 : pagefree = PageGetHeapFreeSpace(page);
3667 :
3668 566170 : newtupsize = MAXALIGN(newtup->t_len);
3669 :
3670 566170 : if (need_toast || newtupsize > pagefree)
3671 281656 : {
3672 : TransactionId xmax_lock_old_tuple;
3673 : uint16 infomask_lock_old_tuple,
3674 : infomask2_lock_old_tuple;
3675 281656 : bool cleared_all_frozen = false;
3676 :
3677 : /*
3678 : * To prevent concurrent sessions from updating the tuple, we have to
3679 : * temporarily mark it locked, while we release the page-level lock.
3680 : *
3681 : * To satisfy the rule that any xid potentially appearing in a buffer
3682 : * written out to disk, we unfortunately have to WAL log this
3683 : * temporary modification. We can reuse xl_heap_lock for this
3684 : * purpose. If we crash/error before following through with the
3685 : * actual update, xmax will be of an aborted transaction, allowing
3686 : * other sessions to proceed.
3687 : */
3688 :
3689 : /*
3690 : * Compute xmax / infomask appropriate for locking the tuple. This has
3691 : * to be done separately from the combo that's going to be used for
3692 : * updating, because the potentially created multixact would otherwise
3693 : * be wrong.
3694 : */
3695 281656 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3696 281656 : oldtup.t_data->t_infomask,
3697 281656 : oldtup.t_data->t_infomask2,
3698 : xid, *lockmode, false,
3699 : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3700 : &infomask2_lock_old_tuple);
3701 :
3702 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3703 :
3704 281656 : START_CRIT_SECTION();
3705 :
3706 : /* Clear obsolete visibility flags ... */
3707 281656 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3708 281656 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3709 281656 : HeapTupleClearHotUpdated(&oldtup);
3710 : /* ... and store info about transaction updating this tuple */
3711 : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3712 281656 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3713 281656 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3714 281656 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3715 281656 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3716 :
3717 : /* temporarily make it look not-updated, but locked */
3718 281656 : oldtup.t_data->t_ctid = oldtup.t_self;
3719 :
3720 : /*
3721 : * Clear all-frozen bit on visibility map if needed. We could
3722 : * immediately reset ALL_VISIBLE, but given that the WAL logging
3723 : * overhead would be unchanged, that doesn't seem necessarily
3724 : * worthwhile.
3725 : */
3726 282648 : if (PageIsAllVisible(page) &&
3727 992 : visibilitymap_clear(relation, block, vmbuffer,
3728 : VISIBILITYMAP_ALL_FROZEN))
3729 746 : cleared_all_frozen = true;
3730 :
3731 281656 : MarkBufferDirty(buffer);
3732 :
3733 281656 : if (RelationNeedsWAL(relation))
3734 : {
3735 : xl_heap_lock xlrec;
3736 : XLogRecPtr recptr;
3737 :
3738 261392 : XLogBeginInsert();
3739 261392 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3740 :
3741 261392 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3742 261392 : xlrec.xmax = xmax_lock_old_tuple;
3743 522784 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3744 261392 : oldtup.t_data->t_infomask2);
3745 261392 : xlrec.flags =
3746 261392 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
3747 261392 : XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
3748 261392 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3749 261392 : PageSetLSN(page, recptr);
3750 : }
3751 :
3752 281656 : END_CRIT_SECTION();
3753 :
3754 281656 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3755 :
3756 : /*
3757 : * Let the toaster do its thing, if needed.
3758 : *
3759 : * Note: below this point, heaptup is the data we actually intend to
3760 : * store into the relation; newtup is the caller's original untoasted
3761 : * data.
3762 : */
3763 281656 : if (need_toast)
3764 : {
3765 : /* Note we always use WAL and FSM during updates */
3766 1896 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
3767 1896 : newtupsize = MAXALIGN(heaptup->t_len);
3768 : }
3769 : else
3770 279760 : heaptup = newtup;
3771 :
3772 : /*
3773 : * Now, do we need a new page for the tuple, or not? This is a bit
3774 : * tricky since someone else could have added tuples to the page while
3775 : * we weren't looking. We have to recheck the available space after
3776 : * reacquiring the buffer lock. But don't bother to do that if the
3777 : * former amount of free space is still not enough; it's unlikely
3778 : * there's more free now than before.
3779 : *
3780 : * What's more, if we need to get a new page, we will need to acquire
3781 : * buffer locks on both old and new pages. To avoid deadlock against
3782 : * some other backend trying to get the same two locks in the other
3783 : * order, we must be consistent about the order we get the locks in.
3784 : * We use the rule "lock the lower-numbered page of the relation
3785 : * first". To implement this, we must do RelationGetBufferForTuple
3786 : * while not holding the lock on the old page, and we must rely on it
3787 : * to get the locks on both pages in the correct order.
3788 : *
3789 : * Another consideration is that we need visibility map page pin(s) if
3790 : * we will have to clear the all-visible flag on either page. If we
3791 : * call RelationGetBufferForTuple, we rely on it to acquire any such
3792 : * pins; but if we don't, we have to handle that here. Hence we need
3793 : * a loop.
3794 : */
3795 : for (;;)
3796 : {
3797 281656 : if (newtupsize > pagefree)
3798 : {
3799 : /* It doesn't fit, must use RelationGetBufferForTuple. */
3800 281006 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3801 : buffer, 0, NULL,
3802 : &vmbuffer_new, &vmbuffer,
3803 : 0);
3804 : /* We're all done. */
3805 281006 : break;
3806 : }
3807 : /* Acquire VM page pin if needed and we don't have it. */
3808 650 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3809 0 : visibilitymap_pin(relation, block, &vmbuffer);
3810 : /* Re-acquire the lock on the old tuple's page. */
3811 650 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3812 : /* Re-check using the up-to-date free space */
3813 650 : pagefree = PageGetHeapFreeSpace(page);
3814 650 : if (newtupsize > pagefree ||
3815 650 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3816 : {
3817 : /*
3818 : * Rats, it doesn't fit anymore, or somebody just now set the
3819 : * all-visible flag. We must now unlock and loop to avoid
3820 : * deadlock. Fortunately, this path should seldom be taken.
3821 : */
3822 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3823 : }
3824 : else
3825 : {
3826 : /* We're all done. */
3827 650 : newbuf = buffer;
3828 650 : break;
3829 : }
3830 : }
3831 : }
3832 : else
3833 : {
3834 : /* No TOAST work needed, and it'll fit on same page */
3835 284514 : newbuf = buffer;
3836 284514 : heaptup = newtup;
3837 : }
3838 :
3839 : /*
3840 : * We're about to do the actual update -- check for conflict first, to
3841 : * avoid possibly having to roll back work we've just done.
3842 : *
3843 : * This is safe without a recheck as long as there is no possibility of
3844 : * another process scanning the pages between this check and the update
3845 : * being visible to the scan (i.e., exclusive buffer content lock(s) are
3846 : * continuously held from this point until the tuple update is visible).
3847 : *
3848 : * For the new tuple the only check needed is at the relation level, but
3849 : * since both tuples are in the same relation and the check for oldtup
3850 : * will include checking the relation level, there is no benefit to a
3851 : * separate check for the new tuple.
3852 : */
3853 566170 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
3854 : BufferGetBlockNumber(buffer));
3855 :
3856 : /*
3857 : * At this point newbuf and buffer are both pinned and locked, and newbuf
3858 : * has enough space for the new tuple. If they are the same buffer, only
3859 : * one pin is held.
3860 : */
3861 :
3862 566146 : if (newbuf == buffer)
3863 : {
3864 : /*
3865 : * Since the new tuple is going into the same page, we might be able
3866 : * to do a HOT update. Check if any of the index columns have been
3867 : * changed.
3868 : */
3869 285140 : if (!bms_overlap(modified_attrs, hot_attrs))
3870 : {
3871 264116 : use_hot_update = true;
3872 :
3873 : /*
3874 : * If none of the columns that are used in hot-blocking indexes
3875 : * were updated, we can apply HOT, but we do still need to check
3876 : * if we need to update the summarizing indexes, and update those
3877 : * indexes if the columns were updated, or we may fail to detect
3878 : * e.g. value bound changes in BRIN minmax indexes.
3879 : */
3880 264116 : if (bms_overlap(modified_attrs, sum_attrs))
3881 3282 : summarized_update = true;
3882 : }
3883 : }
3884 : else
3885 : {
3886 : /* Set a hint that the old page could use prune/defrag */
3887 281006 : PageSetFull(page);
3888 : }
3889 :
3890 : /*
3891 : * Compute replica identity tuple before entering the critical section so
3892 : * we don't PANIC upon a memory allocation failure.
3893 : * ExtractReplicaIdentity() will return NULL if nothing needs to be
3894 : * logged. Pass old key required as true only if the replica identity key
3895 : * columns are modified or it has external data.
3896 : */
3897 566146 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
3898 566146 : bms_overlap(modified_attrs, id_attrs) ||
3899 : id_has_external,
3900 : &old_key_copied);
3901 :
3902 : /* NO EREPORT(ERROR) from here till changes are logged */
3903 566146 : START_CRIT_SECTION();
3904 :
3905 : /*
3906 : * If this transaction commits, the old tuple will become DEAD sooner or
3907 : * later. Set flag that this page is a candidate for pruning once our xid
3908 : * falls below the OldestXmin horizon. If the transaction finally aborts,
3909 : * the subsequent page pruning will be a no-op and the hint will be
3910 : * cleared.
3911 : *
3912 : * XXX Should we set hint on newbuf as well? If the transaction aborts,
3913 : * there would be a prunable tuple in the newbuf; but for now we choose
3914 : * not to optimize for aborts. Note that heap_xlog_update must be kept in
3915 : * sync if this decision changes.
3916 : */
3917 566146 : PageSetPrunable(page, xid);
3918 :
3919 566146 : if (use_hot_update)
3920 : {
3921 : /* Mark the old tuple as HOT-updated */
3922 264116 : HeapTupleSetHotUpdated(&oldtup);
3923 : /* And mark the new tuple as heap-only */
3924 264116 : HeapTupleSetHeapOnly(heaptup);
3925 : /* Mark the caller's copy too, in case different from heaptup */
3926 264116 : HeapTupleSetHeapOnly(newtup);
3927 : }
3928 : else
3929 : {
3930 : /* Make sure tuples are correctly marked as not-HOT */
3931 302030 : HeapTupleClearHotUpdated(&oldtup);
3932 302030 : HeapTupleClearHeapOnly(heaptup);
3933 302030 : HeapTupleClearHeapOnly(newtup);
3934 : }
3935 :
3936 566146 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
3937 :
3938 :
3939 : /* Clear obsolete visibility flags, possibly set by ourselves above... */
3940 566146 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3941 566146 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3942 : /* ... and store info about transaction updating this tuple */
3943 : Assert(TransactionIdIsValid(xmax_old_tuple));
3944 566146 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3945 566146 : oldtup.t_data->t_infomask |= infomask_old_tuple;
3946 566146 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3947 566146 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3948 :
3949 : /* record address of new tuple in t_ctid of old one */
3950 566146 : oldtup.t_data->t_ctid = heaptup->t_self;
3951 :
3952 : /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
3953 566146 : if (PageIsAllVisible(BufferGetPage(buffer)))
3954 : {
3955 2056 : all_visible_cleared = true;
3956 2056 : PageClearAllVisible(BufferGetPage(buffer));
3957 2056 : visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3958 : vmbuffer, VISIBILITYMAP_VALID_BITS);
3959 : }
3960 566146 : if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
3961 : {
3962 908 : all_visible_cleared_new = true;
3963 908 : PageClearAllVisible(BufferGetPage(newbuf));
3964 908 : visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
3965 : vmbuffer_new, VISIBILITYMAP_VALID_BITS);
3966 : }
3967 :
3968 566146 : if (newbuf != buffer)
3969 281006 : MarkBufferDirty(newbuf);
3970 566146 : MarkBufferDirty(buffer);
3971 :
3972 : /* XLOG stuff */
3973 566146 : if (RelationNeedsWAL(relation))
3974 : {
3975 : XLogRecPtr recptr;
3976 :
3977 : /*
3978 : * For logical decoding we need combo CIDs to properly decode the
3979 : * catalog.
3980 : */
3981 543496 : if (RelationIsAccessibleInLogicalDecoding(relation))
3982 : {
3983 4936 : log_heap_new_cid(relation, &oldtup);
3984 4936 : log_heap_new_cid(relation, heaptup);
3985 : }
3986 :
3987 543496 : recptr = log_heap_update(relation, buffer,
3988 : newbuf, &oldtup, heaptup,
3989 : old_key_tuple,
3990 : all_visible_cleared,
3991 : all_visible_cleared_new);
3992 543496 : if (newbuf != buffer)
3993 : {
3994 260754 : PageSetLSN(BufferGetPage(newbuf), recptr);
3995 : }
3996 543496 : PageSetLSN(BufferGetPage(buffer), recptr);
3997 : }
3998 :
3999 566146 : END_CRIT_SECTION();
4000 :
4001 566146 : if (newbuf != buffer)
4002 281006 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
4003 566146 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4004 :
4005 : /*
4006 : * Mark old tuple for invalidation from system caches at next command
4007 : * boundary, and mark the new tuple for invalidation in case we abort. We
4008 : * have to do this before releasing the buffer because oldtup is in the
4009 : * buffer. (heaptup is all in local memory, but it's necessary to process
4010 : * both tuple versions in one call to inval.c so we can avoid redundant
4011 : * sinval messages.)
4012 : */
4013 566146 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4014 :
4015 : /* Now we can release the buffer(s) */
4016 566146 : if (newbuf != buffer)
4017 281006 : ReleaseBuffer(newbuf);
4018 566146 : ReleaseBuffer(buffer);
4019 566146 : if (BufferIsValid(vmbuffer_new))
4020 908 : ReleaseBuffer(vmbuffer_new);
4021 566146 : if (BufferIsValid(vmbuffer))
4022 2056 : ReleaseBuffer(vmbuffer);
4023 :
4024 : /*
4025 : * Release the lmgr tuple lock, if we had it.
4026 : */
4027 566146 : if (have_tuple_lock)
4028 24 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4029 :
4030 566146 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4031 :
4032 : /*
4033 : * If heaptup is a private copy, release it. Don't forget to copy t_self
4034 : * back to the caller's image, too.
4035 : */
4036 566146 : if (heaptup != newtup)
4037 : {
4038 1802 : newtup->t_self = heaptup->t_self;
4039 1802 : heap_freetuple(heaptup);
4040 : }
4041 :
4042 : /*
4043 : * If it is a HOT update, the update may still need to update summarized
4044 : * indexes, lest we fail to update those summaries and get incorrect
4045 : * results (for example, minmax bounds of the block may change with this
4046 : * update).
4047 : */
4048 566146 : if (use_hot_update)
4049 : {
4050 264116 : if (summarized_update)
4051 3282 : *update_indexes = TU_Summarizing;
4052 : else
4053 260834 : *update_indexes = TU_None;
4054 : }
4055 : else
4056 302030 : *update_indexes = TU_All;
4057 :
4058 566146 : if (old_key_tuple != NULL && old_key_copied)
4059 160 : heap_freetuple(old_key_tuple);
4060 :
4061 566146 : bms_free(hot_attrs);
4062 566146 : bms_free(sum_attrs);
4063 566146 : bms_free(key_attrs);
4064 566146 : bms_free(id_attrs);
4065 566146 : bms_free(modified_attrs);
4066 566146 : bms_free(interesting_attrs);
4067 :
4068 566146 : return TM_Ok;
4069 : }
4070 :
4071 : /*
4072 : * Check if the specified attribute's values are the same. Subroutine for
4073 : * HeapDetermineColumnsInfo.
4074 : */
4075 : static bool
4076 1278490 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4077 : bool isnull1, bool isnull2)
4078 : {
4079 : Form_pg_attribute att;
4080 :
4081 : /*
4082 : * If one value is NULL and other is not, then they are certainly not
4083 : * equal
4084 : */
4085 1278490 : if (isnull1 != isnull2)
4086 6 : return false;
4087 :
4088 : /*
4089 : * If both are NULL, they can be considered equal.
4090 : */
4091 1278484 : if (isnull1)
4092 9982 : return true;
4093 :
4094 : /*
4095 : * We do simple binary comparison of the two datums. This may be overly
4096 : * strict because there can be multiple binary representations for the
4097 : * same logical value. But we should be OK as long as there are no false
4098 : * positives. Using a type-specific equality operator is messy because
4099 : * there could be multiple notions of equality in different operator
4100 : * classes; furthermore, we cannot safely invoke user-defined functions
4101 : * while holding exclusive buffer lock.
4102 : */
4103 1268502 : if (attrnum <= 0)
4104 : {
4105 : /* The only allowed system columns are OIDs, so do this */
4106 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4107 : }
4108 : else
4109 : {
4110 : Assert(attrnum <= tupdesc->natts);
4111 1268502 : att = TupleDescAttr(tupdesc, attrnum - 1);
4112 1268502 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4113 : }
4114 : }
4115 :
4116 : /*
4117 : * Check which columns are being updated.
4118 : *
4119 : * Given an updated tuple, determine (and return into the output bitmapset),
4120 : * from those listed as interesting, the set of columns that changed.
4121 : *
4122 : * has_external indicates if any of the unmodified attributes (from those
4123 : * listed as interesting) of the old tuple is a member of external_cols and is
4124 : * stored externally.
4125 : */
4126 : static Bitmapset *
4127 566470 : HeapDetermineColumnsInfo(Relation relation,
4128 : Bitmapset *interesting_cols,
4129 : Bitmapset *external_cols,
4130 : HeapTuple oldtup, HeapTuple newtup,
4131 : bool *has_external)
4132 : {
4133 : int attidx;
4134 566470 : Bitmapset *modified = NULL;
4135 566470 : TupleDesc tupdesc = RelationGetDescr(relation);
4136 :
4137 566470 : attidx = -1;
4138 1844960 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4139 : {
4140 : /* attidx is zero-based, attrnum is the normal attribute number */
4141 1278490 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4142 : Datum value1,
4143 : value2;
4144 : bool isnull1,
4145 : isnull2;
4146 :
4147 : /*
4148 : * If it's a whole-tuple reference, say "not equal". It's not really
4149 : * worth supporting this case, since it could only succeed after a
4150 : * no-op update, which is hardly a case worth optimizing for.
4151 : */
4152 1278490 : if (attrnum == 0)
4153 : {
4154 0 : modified = bms_add_member(modified, attidx);
4155 1219688 : continue;
4156 : }
4157 :
4158 : /*
4159 : * Likewise, automatically say "not equal" for any system attribute
4160 : * other than tableOID; we cannot expect these to be consistent in a
4161 : * HOT chain, or even to be set correctly yet in the new tuple.
4162 : */
4163 1278490 : if (attrnum < 0)
4164 : {
4165 0 : if (attrnum != TableOidAttributeNumber)
4166 : {
4167 0 : modified = bms_add_member(modified, attidx);
4168 0 : continue;
4169 : }
4170 : }
4171 :
4172 : /*
4173 : * Extract the corresponding values. XXX this is pretty inefficient
4174 : * if there are many indexed columns. Should we do a single
4175 : * heap_deform_tuple call on each tuple, instead? But that doesn't
4176 : * work for system columns ...
4177 : */
4178 1278490 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4179 1278490 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4180 :
4181 1278490 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4182 : value2, isnull1, isnull2))
4183 : {
4184 50500 : modified = bms_add_member(modified, attidx);
4185 50500 : continue;
4186 : }
4187 :
4188 : /*
4189 : * No need to check attributes that can't be stored externally. Note
4190 : * that system attributes can't be stored externally.
4191 : */
4192 1227990 : if (attrnum < 0 || isnull1 ||
4193 1218008 : TupleDescAttr(tupdesc, attrnum - 1)->attlen != -1)
4194 1169188 : continue;
4195 :
4196 : /*
4197 : * Check if the old tuple's attribute is stored externally and is a
4198 : * member of external_cols.
4199 : */
4200 58812 : if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
4201 10 : bms_is_member(attidx, external_cols))
4202 4 : *has_external = true;
4203 : }
4204 :
4205 566470 : return modified;
4206 : }
4207 :
4208 : /*
4209 : * simple_heap_update - replace a tuple
4210 : *
4211 : * This routine may be used to update a tuple when concurrent updates of
4212 : * the target tuple are not expected (for example, because we have a lock
4213 : * on the relation associated with the tuple). Any failure is reported
4214 : * via ereport().
4215 : */
4216 : void
4217 189930 : simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup,
4218 : TU_UpdateIndexes *update_indexes)
4219 : {
4220 : TM_Result result;
4221 : TM_FailureData tmfd;
4222 : LockTupleMode lockmode;
4223 :
4224 189930 : result = heap_update(relation, otid, tup,
4225 : GetCurrentCommandId(true), InvalidSnapshot,
4226 : true /* wait for commit */ ,
4227 : &tmfd, &lockmode, update_indexes);
4228 189930 : switch (result)
4229 : {
4230 0 : case TM_SelfModified:
4231 : /* Tuple was already updated in current command? */
4232 0 : elog(ERROR, "tuple already updated by self");
4233 : break;
4234 :
4235 189930 : case TM_Ok:
4236 : /* done successfully */
4237 189930 : break;
4238 :
4239 0 : case TM_Updated:
4240 0 : elog(ERROR, "tuple concurrently updated");
4241 : break;
4242 :
4243 0 : case TM_Deleted:
4244 0 : elog(ERROR, "tuple concurrently deleted");
4245 : break;
4246 :
4247 0 : default:
4248 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4249 : break;
4250 : }
4251 189930 : }
4252 :
4253 :
4254 : /*
4255 : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4256 : */
4257 : static MultiXactStatus
4258 2394 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4259 : {
4260 : int retval;
4261 :
4262 2394 : if (is_update)
4263 192 : retval = tupleLockExtraInfo[mode].updstatus;
4264 : else
4265 2202 : retval = tupleLockExtraInfo[mode].lockstatus;
4266 :
4267 2394 : if (retval == -1)
4268 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4269 : is_update ? "true" : "false");
4270 :
4271 2394 : return (MultiXactStatus) retval;
4272 : }
4273 :
4274 : /*
4275 : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4276 : *
4277 : * Note that this acquires a buffer pin, which the caller must release.
4278 : *
4279 : * Input parameters:
4280 : * relation: relation containing tuple (caller must hold suitable lock)
4281 : * tid: TID of tuple to lock
4282 : * cid: current command ID (used for visibility test, and stored into
4283 : * tuple's cmax if lock is successful)
4284 : * mode: indicates if shared or exclusive tuple lock is desired
4285 : * wait_policy: what to do if tuple lock is not available
4286 : * follow_updates: if true, follow the update chain to also lock descendant
4287 : * tuples.
4288 : *
4289 : * Output parameters:
4290 : * *tuple: all fields filled in
4291 : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4292 : * *tmfd: filled in failure cases (see below)
4293 : *
4294 : * Function results are the same as the ones for table_tuple_lock().
4295 : *
4296 : * In the failure cases other than TM_Invisible, the routine fills
4297 : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4298 : * if necessary), and t_cmax (the last only for TM_SelfModified,
4299 : * since we cannot obtain cmax from a combo CID generated by another
4300 : * transaction).
4301 : * See comments for struct TM_FailureData for additional info.
4302 : *
4303 : * See README.tuplock for a thorough explanation of this mechanism.
4304 : */
4305 : TM_Result
4306 165818 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4307 : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4308 : bool follow_updates,
4309 : Buffer *buffer, TM_FailureData *tmfd)
4310 : {
4311 : TM_Result result;
4312 165818 : ItemPointer tid = &(tuple->t_self);
4313 : ItemId lp;
4314 : Page page;
4315 165818 : Buffer vmbuffer = InvalidBuffer;
4316 : BlockNumber block;
4317 : TransactionId xid,
4318 : xmax;
4319 : uint16 old_infomask,
4320 : new_infomask,
4321 : new_infomask2;
4322 165818 : bool first_time = true;
4323 165818 : bool skip_tuple_lock = false;
4324 165818 : bool have_tuple_lock = false;
4325 165818 : bool cleared_all_frozen = false;
4326 :
4327 165818 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4328 165818 : block = ItemPointerGetBlockNumber(tid);
4329 :
4330 : /*
4331 : * Before locking the buffer, pin the visibility map page if it appears to
4332 : * be necessary. Since we haven't got the lock yet, someone else might be
4333 : * in the middle of changing this, so we'll need to recheck after we have
4334 : * the lock.
4335 : */
4336 165818 : if (PageIsAllVisible(BufferGetPage(*buffer)))
4337 3316 : visibilitymap_pin(relation, block, &vmbuffer);
4338 :
4339 165818 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4340 :
4341 165818 : page = BufferGetPage(*buffer);
4342 165818 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4343 : Assert(ItemIdIsNormal(lp));
4344 :
4345 165818 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4346 165818 : tuple->t_len = ItemIdGetLength(lp);
4347 165818 : tuple->t_tableOid = RelationGetRelid(relation);
4348 :
4349 165846 : l3:
4350 165846 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4351 :
4352 165846 : if (result == TM_Invisible)
4353 : {
4354 : /*
4355 : * This is possible, but only when locking a tuple for ON CONFLICT
4356 : * UPDATE. We return this value here rather than throwing an error in
4357 : * order to give that case the opportunity to throw a more specific
4358 : * error.
4359 : */
4360 24 : result = TM_Invisible;
4361 24 : goto out_locked;
4362 : }
4363 165822 : else if (result == TM_BeingModified ||
4364 151758 : result == TM_Updated ||
4365 : result == TM_Deleted)
4366 : {
4367 : TransactionId xwait;
4368 : uint16 infomask;
4369 : uint16 infomask2;
4370 : bool require_sleep;
4371 : ItemPointerData t_ctid;
4372 :
4373 : /* must copy state data before unlocking buffer */
4374 14066 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4375 14066 : infomask = tuple->t_data->t_infomask;
4376 14066 : infomask2 = tuple->t_data->t_infomask2;
4377 14066 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4378 :
4379 14066 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4380 :
4381 : /*
4382 : * If any subtransaction of the current top transaction already holds
4383 : * a lock as strong as or stronger than what we're requesting, we
4384 : * effectively hold the desired lock already. We *must* succeed
4385 : * without trying to take the tuple lock, else we will deadlock
4386 : * against anyone wanting to acquire a stronger lock.
4387 : *
4388 : * Note we only do this the first time we loop on the HTSU result;
4389 : * there is no point in testing in subsequent passes, because
4390 : * evidently our own transaction cannot have acquired a new lock after
4391 : * the first time we checked.
4392 : */
4393 14066 : if (first_time)
4394 : {
4395 14048 : first_time = false;
4396 :
4397 14048 : if (infomask & HEAP_XMAX_IS_MULTI)
4398 : {
4399 : int i;
4400 : int nmembers;
4401 : MultiXactMember *members;
4402 :
4403 : /*
4404 : * We don't need to allow old multixacts here; if that had
4405 : * been the case, HeapTupleSatisfiesUpdate would have returned
4406 : * MayBeUpdated and we wouldn't be here.
4407 : */
4408 : nmembers =
4409 164 : GetMultiXactIdMembers(xwait, &members, false,
4410 164 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4411 :
4412 488 : for (i = 0; i < nmembers; i++)
4413 : {
4414 : /* only consider members of our own transaction */
4415 352 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4416 254 : continue;
4417 :
4418 98 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4419 : {
4420 28 : pfree(members);
4421 28 : result = TM_Ok;
4422 28 : goto out_unlocked;
4423 : }
4424 : else
4425 : {
4426 : /*
4427 : * Disable acquisition of the heavyweight tuple lock.
4428 : * Otherwise, when promoting a weaker lock, we might
4429 : * deadlock with another locker that has acquired the
4430 : * heavyweight tuple lock and is waiting for our
4431 : * transaction to finish.
4432 : *
4433 : * Note that in this case we still need to wait for
4434 : * the multixact if required, to avoid acquiring
4435 : * conflicting locks.
4436 : */
4437 70 : skip_tuple_lock = true;
4438 : }
4439 : }
4440 :
4441 136 : if (members)
4442 136 : pfree(members);
4443 : }
4444 13884 : else if (TransactionIdIsCurrentTransactionId(xwait))
4445 : {
4446 11446 : switch (mode)
4447 : {
4448 272 : case LockTupleKeyShare:
4449 : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4450 : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4451 : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4452 272 : result = TM_Ok;
4453 272 : goto out_unlocked;
4454 232 : case LockTupleShare:
4455 232 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4456 12 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4457 : {
4458 220 : result = TM_Ok;
4459 220 : goto out_unlocked;
4460 : }
4461 12 : break;
4462 122 : case LockTupleNoKeyExclusive:
4463 122 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4464 : {
4465 100 : result = TM_Ok;
4466 100 : goto out_unlocked;
4467 : }
4468 22 : break;
4469 10820 : case LockTupleExclusive:
4470 10820 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4471 742 : infomask2 & HEAP_KEYS_UPDATED)
4472 : {
4473 700 : result = TM_Ok;
4474 700 : goto out_unlocked;
4475 : }
4476 10120 : break;
4477 : }
4478 2456 : }
4479 : }
4480 :
4481 : /*
4482 : * Initially assume that we will have to wait for the locking
4483 : * transaction(s) to finish. We check various cases below in which
4484 : * this can be turned off.
4485 : */
4486 12746 : require_sleep = true;
4487 12746 : if (mode == LockTupleKeyShare)
4488 : {
4489 : /*
4490 : * If we're requesting KeyShare, and there's no update present, we
4491 : * don't need to wait. Even if there is an update, we can still
4492 : * continue if the key hasn't been modified.
4493 : *
4494 : * However, if there are updates, we need to walk the update chain
4495 : * to mark future versions of the row as locked, too. That way,
4496 : * if somebody deletes that future version, we're protected
4497 : * against the key going away. This locking of future versions
4498 : * could block momentarily, if a concurrent transaction is
4499 : * deleting a key; or it could return a value to the effect that
4500 : * the transaction deleting the key has already committed. So we
4501 : * do this before re-locking the buffer; otherwise this would be
4502 : * prone to deadlocks.
4503 : *
4504 : * Note that the TID we're locking was grabbed before we unlocked
4505 : * the buffer. For it to change while we're not looking, the
4506 : * other properties we're testing for below after re-locking the
4507 : * buffer would also change, in which case we would restart this
4508 : * loop above.
4509 : */
4510 1158 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4511 : {
4512 : bool updated;
4513 :
4514 1096 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4515 :
4516 : /*
4517 : * If there are updates, follow the update chain; bail out if
4518 : * that cannot be done.
4519 : */
4520 1096 : if (follow_updates && updated)
4521 : {
4522 : TM_Result res;
4523 :
4524 100 : res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4525 : GetCurrentTransactionId(),
4526 : mode);
4527 100 : if (res != TM_Ok)
4528 : {
4529 12 : result = res;
4530 : /* recovery code expects to have buffer lock held */
4531 12 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4532 356 : goto failed;
4533 : }
4534 : }
4535 :
4536 1084 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4537 :
4538 : /*
4539 : * Make sure it's still an appropriate lock, else start over.
4540 : * Also, if it wasn't updated before we released the lock, but
4541 : * is updated now, we start over too; the reason is that we
4542 : * now need to follow the update chain to lock the new
4543 : * versions.
4544 : */
4545 1084 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4546 86 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4547 86 : !updated))
4548 28 : goto l3;
4549 :
4550 : /* Things look okay, so we can skip sleeping */
4551 1084 : require_sleep = false;
4552 :
4553 : /*
4554 : * Note we allow Xmax to change here; other updaters/lockers
4555 : * could have modified it before we grabbed the buffer lock.
4556 : * However, this is not a problem, because with the recheck we
4557 : * just did we ensure that they still don't conflict with the
4558 : * lock we want.
4559 : */
4560 : }
4561 : }
4562 11588 : else if (mode == LockTupleShare)
4563 : {
4564 : /*
4565 : * If we're requesting Share, we can similarly avoid sleeping if
4566 : * there's no update and no exclusive lock present.
4567 : */
4568 882 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4569 882 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4570 : {
4571 870 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4572 :
4573 : /*
4574 : * Make sure it's still an appropriate lock, else start over.
4575 : * See above about allowing xmax to change.
4576 : */
4577 870 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4578 870 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
4579 0 : goto l3;
4580 870 : require_sleep = false;
4581 : }
4582 : }
4583 10706 : else if (mode == LockTupleNoKeyExclusive)
4584 : {
4585 : /*
4586 : * If we're requesting NoKeyExclusive, we might also be able to
4587 : * avoid sleeping; just ensure that there no conflicting lock
4588 : * already acquired.
4589 : */
4590 302 : if (infomask & HEAP_XMAX_IS_MULTI)
4591 : {
4592 52 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4593 : mode, NULL))
4594 : {
4595 : /*
4596 : * No conflict, but if the xmax changed under us in the
4597 : * meantime, start over.
4598 : */
4599 26 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4600 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4601 26 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4602 : xwait))
4603 0 : goto l3;
4604 :
4605 : /* otherwise, we're good */
4606 26 : require_sleep = false;
4607 : }
4608 : }
4609 250 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4610 : {
4611 30 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4612 :
4613 : /* if the xmax changed in the meantime, start over */
4614 30 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4615 30 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4616 : xwait))
4617 0 : goto l3;
4618 : /* otherwise, we're good */
4619 30 : require_sleep = false;
4620 : }
4621 : }
4622 :
4623 : /*
4624 : * As a check independent from those above, we can also avoid sleeping
4625 : * if the current transaction is the sole locker of the tuple. Note
4626 : * that the strength of the lock already held is irrelevant; this is
4627 : * not about recording the lock in Xmax (which will be done regardless
4628 : * of this optimization, below). Also, note that the cases where we
4629 : * hold a lock stronger than we are requesting are already handled
4630 : * above by not doing anything.
4631 : *
4632 : * Note we only deal with the non-multixact case here; MultiXactIdWait
4633 : * is well equipped to deal with this situation on its own.
4634 : */
4635 23376 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4636 10642 : TransactionIdIsCurrentTransactionId(xwait))
4637 : {
4638 : /* ... but if the xmax changed in the meantime, start over */
4639 10120 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4640 10120 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4641 10120 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4642 : xwait))
4643 0 : goto l3;
4644 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
4645 10120 : require_sleep = false;
4646 : }
4647 :
4648 : /*
4649 : * Time to sleep on the other transaction/multixact, if necessary.
4650 : *
4651 : * If the other transaction is an update/delete that's already
4652 : * committed, then sleeping cannot possibly do any good: if we're
4653 : * required to sleep, get out to raise an error instead.
4654 : *
4655 : * By here, we either have already acquired the buffer exclusive lock,
4656 : * or we must wait for the locking transaction or multixact; so below
4657 : * we ensure that we grab buffer lock after the sleep.
4658 : */
4659 12734 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4660 : {
4661 268 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4662 268 : goto failed;
4663 : }
4664 12466 : else if (require_sleep)
4665 : {
4666 : /*
4667 : * Acquire tuple lock to establish our priority for the tuple, or
4668 : * die trying. LockTuple will release us when we are next-in-line
4669 : * for the tuple. We must do this even if we are share-locking,
4670 : * but not if we already have a weaker lock on the tuple.
4671 : *
4672 : * If we are forced to "start over" below, we keep the tuple lock;
4673 : * this arranges that we stay at the head of the line while
4674 : * rechecking tuple state.
4675 : */
4676 336 : if (!skip_tuple_lock &&
4677 304 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4678 : &have_tuple_lock))
4679 : {
4680 : /*
4681 : * This can only happen if wait_policy is Skip and the lock
4682 : * couldn't be obtained.
4683 : */
4684 2 : result = TM_WouldBlock;
4685 : /* recovery code expects to have buffer lock held */
4686 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4687 2 : goto failed;
4688 : }
4689 :
4690 332 : if (infomask & HEAP_XMAX_IS_MULTI)
4691 : {
4692 80 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
4693 :
4694 : /* We only ever lock tuples, never update them */
4695 80 : if (status >= MultiXactStatusNoKeyUpdate)
4696 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
4697 :
4698 : /* wait for multixact to end, or die trying */
4699 80 : switch (wait_policy)
4700 : {
4701 72 : case LockWaitBlock:
4702 72 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
4703 : relation, &tuple->t_self, XLTW_Lock, NULL);
4704 72 : break;
4705 4 : case LockWaitSkip:
4706 4 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4707 : status, infomask, relation,
4708 : NULL))
4709 : {
4710 4 : result = TM_WouldBlock;
4711 : /* recovery code expects to have buffer lock held */
4712 4 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4713 4 : goto failed;
4714 : }
4715 0 : break;
4716 4 : case LockWaitError:
4717 4 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4718 : status, infomask, relation,
4719 : NULL))
4720 4 : ereport(ERROR,
4721 : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4722 : errmsg("could not obtain lock on row in relation \"%s\"",
4723 : RelationGetRelationName(relation))));
4724 :
4725 0 : break;
4726 : }
4727 :
4728 : /*
4729 : * Of course, the multixact might not be done here: if we're
4730 : * requesting a light lock mode, other transactions with light
4731 : * locks could still be alive, as well as locks owned by our
4732 : * own xact or other subxacts of this backend. We need to
4733 : * preserve the surviving MultiXact members. Note that it
4734 : * isn't absolutely necessary in the latter case, but doing so
4735 : * is simpler.
4736 : */
4737 72 : }
4738 : else
4739 : {
4740 : /* wait for regular transaction to end, or die trying */
4741 252 : switch (wait_policy)
4742 : {
4743 174 : case LockWaitBlock:
4744 174 : XactLockTableWait(xwait, relation, &tuple->t_self,
4745 : XLTW_Lock);
4746 174 : break;
4747 66 : case LockWaitSkip:
4748 66 : if (!ConditionalXactLockTableWait(xwait))
4749 : {
4750 66 : result = TM_WouldBlock;
4751 : /* recovery code expects to have buffer lock held */
4752 66 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4753 66 : goto failed;
4754 : }
4755 0 : break;
4756 12 : case LockWaitError:
4757 12 : if (!ConditionalXactLockTableWait(xwait))
4758 12 : ereport(ERROR,
4759 : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4760 : errmsg("could not obtain lock on row in relation \"%s\"",
4761 : RelationGetRelationName(relation))));
4762 0 : break;
4763 : }
4764 246 : }
4765 :
4766 : /* if there are updates, follow the update chain */
4767 246 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4768 : {
4769 : TM_Result res;
4770 :
4771 76 : res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4772 : GetCurrentTransactionId(),
4773 : mode);
4774 76 : if (res != TM_Ok)
4775 : {
4776 4 : result = res;
4777 : /* recovery code expects to have buffer lock held */
4778 4 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4779 4 : goto failed;
4780 : }
4781 : }
4782 :
4783 242 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4784 :
4785 : /*
4786 : * xwait is done, but if xwait had just locked the tuple then some
4787 : * other xact could update this tuple before we get to this point.
4788 : * Check for xmax change, and start over if so.
4789 : */
4790 242 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4791 218 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4792 : xwait))
4793 28 : goto l3;
4794 :
4795 214 : if (!(infomask & HEAP_XMAX_IS_MULTI))
4796 : {
4797 : /*
4798 : * Otherwise check if it committed or aborted. Note we cannot
4799 : * be here if the tuple was only locked by somebody who didn't
4800 : * conflict with us; that would have been handled above. So
4801 : * that transaction must necessarily be gone by now. But
4802 : * don't check for this in the multixact case, because some
4803 : * locker transactions might still be running.
4804 : */
4805 152 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4806 : }
4807 : }
4808 :
4809 : /* By here, we're certain that we hold buffer exclusive lock again */
4810 :
4811 : /*
4812 : * We may lock if previous xmax aborted, or if it committed but only
4813 : * locked the tuple without updating it; or if we didn't have to wait
4814 : * at all for whatever reason.
4815 : */
4816 12344 : if (!require_sleep ||
4817 214 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4818 278 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4819 124 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
4820 12232 : result = TM_Ok;
4821 112 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4822 90 : result = TM_Updated;
4823 : else
4824 22 : result = TM_Deleted;
4825 : }
4826 :
4827 151756 : failed:
4828 164456 : if (result != TM_Ok)
4829 : {
4830 : Assert(result == TM_SelfModified || result == TM_Updated ||
4831 : result == TM_Deleted || result == TM_WouldBlock);
4832 :
4833 : /*
4834 : * When locking a tuple under LockWaitSkip semantics and we fail with
4835 : * TM_WouldBlock above, it's possible for concurrent transactions to
4836 : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4837 : * this assert is slightly different from the equivalent one in
4838 : * heap_delete and heap_update.
4839 : */
4840 : Assert((result == TM_WouldBlock) ||
4841 : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4842 : Assert(result != TM_Updated ||
4843 : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4844 480 : tmfd->ctid = tuple->t_data->t_ctid;
4845 480 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4846 480 : if (result == TM_SelfModified)
4847 12 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4848 : else
4849 468 : tmfd->cmax = InvalidCommandId;
4850 480 : goto out_locked;
4851 : }
4852 :
4853 : /*
4854 : * If we didn't pin the visibility map page and the page has become all
4855 : * visible while we were busy locking the buffer, or during some
4856 : * subsequent window during which we had it unlocked, we'll have to unlock
4857 : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4858 : * unfortunate, especially since we'll now have to recheck whether the
4859 : * tuple has been locked or updated under us, but hopefully it won't
4860 : * happen very often.
4861 : */
4862 163976 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4863 : {
4864 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4865 0 : visibilitymap_pin(relation, block, &vmbuffer);
4866 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4867 0 : goto l3;
4868 : }
4869 :
4870 163976 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4871 163976 : old_infomask = tuple->t_data->t_infomask;
4872 :
4873 : /*
4874 : * If this is the first possibly-multixact-able operation in the current
4875 : * transaction, set my per-backend OldestMemberMXactId setting. We can be
4876 : * certain that the transaction will never become a member of any older
4877 : * MultiXactIds than that. (We have to do this even if we end up just
4878 : * using our own TransactionId below, since some other backend could
4879 : * incorporate our XID into a MultiXact immediately afterwards.)
4880 : */
4881 163976 : MultiXactIdSetOldestMember();
4882 :
4883 : /*
4884 : * Compute the new xmax and infomask to store into the tuple. Note we do
4885 : * not modify the tuple just yet, because that would leave it in the wrong
4886 : * state if multixact.c elogs.
4887 : */
4888 163976 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4889 : GetCurrentTransactionId(), mode, false,
4890 : &xid, &new_infomask, &new_infomask2);
4891 :
4892 163976 : START_CRIT_SECTION();
4893 :
4894 : /*
4895 : * Store transaction information of xact locking the tuple.
4896 : *
4897 : * Note: Cmax is meaningless in this context, so don't set it; this avoids
4898 : * possibly generating a useless combo CID. Moreover, if we're locking a
4899 : * previously updated tuple, it's important to preserve the Cmax.
4900 : *
4901 : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4902 : * we would break the HOT chain.
4903 : */
4904 163976 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4905 163976 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4906 163976 : tuple->t_data->t_infomask |= new_infomask;
4907 163976 : tuple->t_data->t_infomask2 |= new_infomask2;
4908 163976 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4909 163898 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
4910 163976 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
4911 :
4912 : /*
4913 : * Make sure there is no forward chain link in t_ctid. Note that in the
4914 : * cases where the tuple has been updated, we must not overwrite t_ctid,
4915 : * because it was set by the updater. Moreover, if the tuple has been
4916 : * updated, we need to follow the update chain to lock the new versions of
4917 : * the tuple as well.
4918 : */
4919 163976 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4920 163898 : tuple->t_data->t_ctid = *tid;
4921 :
4922 : /* Clear only the all-frozen bit on visibility map if needed */
4923 167292 : if (PageIsAllVisible(page) &&
4924 3316 : visibilitymap_clear(relation, block, vmbuffer,
4925 : VISIBILITYMAP_ALL_FROZEN))
4926 28 : cleared_all_frozen = true;
4927 :
4928 :
4929 163976 : MarkBufferDirty(*buffer);
4930 :
4931 : /*
4932 : * XLOG stuff. You might think that we don't need an XLOG record because
4933 : * there is no state change worth restoring after a crash. You would be
4934 : * wrong however: we have just written either a TransactionId or a
4935 : * MultiXactId that may never have been seen on disk before, and we need
4936 : * to make sure that there are XLOG entries covering those ID numbers.
4937 : * Else the same IDs might be re-used after a crash, which would be
4938 : * disastrous if this page made it to disk before the crash. Essentially
4939 : * we have to enforce the WAL log-before-data rule even in this case.
4940 : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4941 : * entries for everything anyway.)
4942 : */
4943 163976 : if (RelationNeedsWAL(relation))
4944 : {
4945 : xl_heap_lock xlrec;
4946 : XLogRecPtr recptr;
4947 :
4948 162854 : XLogBeginInsert();
4949 162854 : XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4950 :
4951 162854 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4952 162854 : xlrec.xmax = xid;
4953 325708 : xlrec.infobits_set = compute_infobits(new_infomask,
4954 162854 : tuple->t_data->t_infomask2);
4955 162854 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
4956 162854 : XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4957 :
4958 : /* we don't decode row locks atm, so no need to log the origin */
4959 :
4960 162854 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4961 :
4962 162854 : PageSetLSN(page, recptr);
4963 : }
4964 :
4965 163976 : END_CRIT_SECTION();
4966 :
4967 163976 : result = TM_Ok;
4968 :
4969 164480 : out_locked:
4970 164480 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4971 :
4972 165800 : out_unlocked:
4973 165800 : if (BufferIsValid(vmbuffer))
4974 3316 : ReleaseBuffer(vmbuffer);
4975 :
4976 : /*
4977 : * Don't update the visibility map here. Locking a tuple doesn't change
4978 : * visibility info.
4979 : */
4980 :
4981 : /*
4982 : * Now that we have successfully marked the tuple as locked, we can
4983 : * release the lmgr tuple lock, if we had it.
4984 : */
4985 165800 : if (have_tuple_lock)
4986 274 : UnlockTupleTuplock(relation, tid, mode);
4987 :
4988 165800 : return result;
4989 : }
4990 :
4991 : /*
4992 : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
4993 : * its normal, Xmax-based tuple lock.
4994 : *
4995 : * have_tuple_lock is an input and output parameter: on input, it indicates
4996 : * whether the lock has previously been acquired (and this function does
4997 : * nothing in that case). If this function returns success, have_tuple_lock
4998 : * has been flipped to true.
4999 : *
5000 : * Returns false if it was unable to obtain the lock; this can only happen if
5001 : * wait_policy is Skip.
5002 : */
5003 : static bool
5004 514 : heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode,
5005 : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5006 : {
5007 514 : if (*have_tuple_lock)
5008 18 : return true;
5009 :
5010 496 : switch (wait_policy)
5011 : {
5012 414 : case LockWaitBlock:
5013 414 : LockTupleTuplock(relation, tid, mode);
5014 414 : break;
5015 :
5016 68 : case LockWaitSkip:
5017 68 : if (!ConditionalLockTupleTuplock(relation, tid, mode))
5018 2 : return false;
5019 66 : break;
5020 :
5021 14 : case LockWaitError:
5022 14 : if (!ConditionalLockTupleTuplock(relation, tid, mode))
5023 2 : ereport(ERROR,
5024 : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5025 : errmsg("could not obtain lock on row in relation \"%s\"",
5026 : RelationGetRelationName(relation))));
5027 12 : break;
5028 : }
5029 492 : *have_tuple_lock = true;
5030 :
5031 492 : return true;
5032 : }
5033 :
5034 : /*
5035 : * Given an original set of Xmax and infomask, and a transaction (identified by
5036 : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5037 : * corresponding infomasks to use on the tuple.
5038 : *
5039 : * Note that this might have side effects such as creating a new MultiXactId.
5040 : *
5041 : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5042 : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5043 : * but it was not running anymore. There is a race condition, which is that the
5044 : * MultiXactId may have finished since then, but that uncommon case is handled
5045 : * either here, or within MultiXactIdExpand.
5046 : *
5047 : * There is a similar race condition possible when the old xmax was a regular
5048 : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5049 : * window, but it's still possible to end up creating an unnecessary
5050 : * MultiXactId. Fortunately this is harmless.
5051 : */
5052 : static void
5053 3978390 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5054 : uint16 old_infomask2, TransactionId add_to_xmax,
5055 : LockTupleMode mode, bool is_update,
5056 : TransactionId *result_xmax, uint16 *result_infomask,
5057 : uint16 *result_infomask2)
5058 : {
5059 : TransactionId new_xmax;
5060 : uint16 new_infomask,
5061 : new_infomask2;
5062 :
5063 : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5064 :
5065 3978390 : l5:
5066 3978390 : new_infomask = 0;
5067 3978390 : new_infomask2 = 0;
5068 3978390 : if (old_infomask & HEAP_XMAX_INVALID)
5069 : {
5070 : /*
5071 : * No previous locker; we just insert our own TransactionId.
5072 : *
5073 : * Note that it's critical that this case be the first one checked,
5074 : * because there are several blocks below that come back to this one
5075 : * to implement certain optimizations; old_infomask might contain
5076 : * other dirty bits in those cases, but we don't really care.
5077 : */
5078 3768438 : if (is_update)
5079 : {
5080 3324740 : new_xmax = add_to_xmax;
5081 3324740 : if (mode == LockTupleExclusive)
5082 2830328 : new_infomask2 |= HEAP_KEYS_UPDATED;
5083 : }
5084 : else
5085 : {
5086 443698 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5087 443698 : switch (mode)
5088 : {
5089 4944 : case LockTupleKeyShare:
5090 4944 : new_xmax = add_to_xmax;
5091 4944 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5092 4944 : break;
5093 1416 : case LockTupleShare:
5094 1416 : new_xmax = add_to_xmax;
5095 1416 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5096 1416 : break;
5097 248138 : case LockTupleNoKeyExclusive:
5098 248138 : new_xmax = add_to_xmax;
5099 248138 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5100 248138 : break;
5101 189200 : case LockTupleExclusive:
5102 189200 : new_xmax = add_to_xmax;
5103 189200 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5104 189200 : new_infomask2 |= HEAP_KEYS_UPDATED;
5105 189200 : break;
5106 0 : default:
5107 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5108 0 : elog(ERROR, "invalid lock mode");
5109 : }
5110 : }
5111 : }
5112 209952 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5113 : {
5114 : MultiXactStatus new_status;
5115 :
5116 : /*
5117 : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5118 : * cross-check.
5119 : */
5120 : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5121 :
5122 : /*
5123 : * A multixact together with LOCK_ONLY set but neither lock bit set
5124 : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5125 : * anymore. This check is critical for databases upgraded by
5126 : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5127 : * that such multis are never passed.
5128 : */
5129 238 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5130 : {
5131 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5132 0 : old_infomask |= HEAP_XMAX_INVALID;
5133 0 : goto l5;
5134 : }
5135 :
5136 : /*
5137 : * If the XMAX is already a MultiXactId, then we need to expand it to
5138 : * include add_to_xmax; but if all the members were lockers and are
5139 : * all gone, we can do away with the IS_MULTI bit and just set
5140 : * add_to_xmax as the only locker/updater. If all lockers are gone
5141 : * and we have an updater that aborted, we can also do without a
5142 : * multi.
5143 : *
5144 : * The cost of doing GetMultiXactIdMembers would be paid by
5145 : * MultiXactIdExpand if we weren't to do this, so this check is not
5146 : * incurring extra work anyhow.
5147 : */
5148 238 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5149 : {
5150 46 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5151 16 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5152 : old_infomask)))
5153 : {
5154 : /*
5155 : * Reset these bits and restart; otherwise fall through to
5156 : * create a new multi below.
5157 : */
5158 46 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5159 46 : old_infomask |= HEAP_XMAX_INVALID;
5160 46 : goto l5;
5161 : }
5162 : }
5163 :
5164 192 : new_status = get_mxact_status_for_lock(mode, is_update);
5165 :
5166 192 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5167 : new_status);
5168 192 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5169 : }
5170 209714 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5171 : {
5172 : /*
5173 : * It's a committed update, so we need to preserve him as updater of
5174 : * the tuple.
5175 : */
5176 : MultiXactStatus status;
5177 : MultiXactStatus new_status;
5178 :
5179 26 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5180 0 : status = MultiXactStatusUpdate;
5181 : else
5182 26 : status = MultiXactStatusNoKeyUpdate;
5183 :
5184 26 : new_status = get_mxact_status_for_lock(mode, is_update);
5185 :
5186 : /*
5187 : * since it's not running, it's obviously impossible for the old
5188 : * updater to be identical to the current one, so we need not check
5189 : * for that case as we do in the block above.
5190 : */
5191 26 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5192 26 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5193 : }
5194 209688 : else if (TransactionIdIsInProgress(xmax))
5195 : {
5196 : /*
5197 : * If the XMAX is a valid, in-progress TransactionId, then we need to
5198 : * create a new MultiXactId that includes both the old locker or
5199 : * updater and our own TransactionId.
5200 : */
5201 : MultiXactStatus new_status;
5202 : MultiXactStatus old_status;
5203 : LockTupleMode old_mode;
5204 :
5205 209670 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5206 : {
5207 209618 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5208 11234 : old_status = MultiXactStatusForKeyShare;
5209 198384 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5210 862 : old_status = MultiXactStatusForShare;
5211 197522 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5212 : {
5213 197522 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5214 185366 : old_status = MultiXactStatusForUpdate;
5215 : else
5216 12156 : old_status = MultiXactStatusForNoKeyUpdate;
5217 : }
5218 : else
5219 : {
5220 : /*
5221 : * LOCK_ONLY can be present alone only when a page has been
5222 : * upgraded by pg_upgrade. But in that case,
5223 : * TransactionIdIsInProgress() should have returned false. We
5224 : * assume it's no longer locked in this case.
5225 : */
5226 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5227 0 : old_infomask |= HEAP_XMAX_INVALID;
5228 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5229 0 : goto l5;
5230 : }
5231 : }
5232 : else
5233 : {
5234 : /* it's an update, but which kind? */
5235 52 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5236 0 : old_status = MultiXactStatusUpdate;
5237 : else
5238 52 : old_status = MultiXactStatusNoKeyUpdate;
5239 : }
5240 :
5241 209670 : old_mode = TUPLOCK_from_mxstatus(old_status);
5242 :
5243 : /*
5244 : * If the lock to be acquired is for the same TransactionId as the
5245 : * existing lock, there's an optimization possible: consider only the
5246 : * strongest of both locks as the only one present, and restart.
5247 : */
5248 209670 : if (xmax == add_to_xmax)
5249 : {
5250 : /*
5251 : * Note that it's not possible for the original tuple to be
5252 : * updated: we wouldn't be here because the tuple would have been
5253 : * invisible and we wouldn't try to update it. As a subtlety,
5254 : * this code can also run when traversing an update chain to lock
5255 : * future versions of a tuple. But we wouldn't be here either,
5256 : * because the add_to_xmax would be different from the original
5257 : * updater.
5258 : */
5259 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5260 :
5261 : /* acquire the strongest of both */
5262 207640 : if (mode < old_mode)
5263 104266 : mode = old_mode;
5264 : /* mustn't touch is_update */
5265 :
5266 207640 : old_infomask |= HEAP_XMAX_INVALID;
5267 207640 : goto l5;
5268 : }
5269 :
5270 : /* otherwise, just fall back to creating a new multixact */
5271 2030 : new_status = get_mxact_status_for_lock(mode, is_update);
5272 2030 : new_xmax = MultiXactIdCreate(xmax, old_status,
5273 : add_to_xmax, new_status);
5274 2030 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5275 : }
5276 28 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5277 10 : TransactionIdDidCommit(xmax))
5278 2 : {
5279 : /*
5280 : * It's a committed update, so we gotta preserve him as updater of the
5281 : * tuple.
5282 : */
5283 : MultiXactStatus status;
5284 : MultiXactStatus new_status;
5285 :
5286 2 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5287 0 : status = MultiXactStatusUpdate;
5288 : else
5289 2 : status = MultiXactStatusNoKeyUpdate;
5290 :
5291 2 : new_status = get_mxact_status_for_lock(mode, is_update);
5292 :
5293 : /*
5294 : * since it's not running, it's obviously impossible for the old
5295 : * updater to be identical to the current one, so we need not check
5296 : * for that case as we do in the block above.
5297 : */
5298 2 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5299 2 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5300 : }
5301 : else
5302 : {
5303 : /*
5304 : * Can get here iff the locking/updating transaction was running when
5305 : * the infomask was extracted from the tuple, but finished before
5306 : * TransactionIdIsInProgress got to run. Deal with it as if there was
5307 : * no locker at all in the first place.
5308 : */
5309 16 : old_infomask |= HEAP_XMAX_INVALID;
5310 16 : goto l5;
5311 : }
5312 :
5313 3770688 : *result_infomask = new_infomask;
5314 3770688 : *result_infomask2 = new_infomask2;
5315 3770688 : *result_xmax = new_xmax;
5316 3770688 : }
5317 :
5318 : /*
5319 : * Subroutine for heap_lock_updated_tuple_rec.
5320 : *
5321 : * Given a hypothetical multixact status held by the transaction identified
5322 : * with the given xid, does the current transaction need to wait, fail, or can
5323 : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5324 : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5325 : * returned. If the lock is already held by the current transaction, return
5326 : * TM_SelfModified. In case of a conflict with another transaction, a
5327 : * different HeapTupleSatisfiesUpdate return code is returned.
5328 : *
5329 : * The held status is said to be hypothetical because it might correspond to a
5330 : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5331 : * way for simplicity of API.
5332 : */
5333 : static TM_Result
5334 64 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5335 : LockTupleMode mode, HeapTuple tup,
5336 : bool *needwait)
5337 : {
5338 : MultiXactStatus wantedstatus;
5339 :
5340 64 : *needwait = false;
5341 64 : wantedstatus = get_mxact_status_for_lock(mode, false);
5342 :
5343 : /*
5344 : * Note: we *must* check TransactionIdIsInProgress before
5345 : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5346 : * for an explanation.
5347 : */
5348 64 : if (TransactionIdIsCurrentTransactionId(xid))
5349 : {
5350 : /*
5351 : * The tuple has already been locked by our own transaction. This is
5352 : * very rare but can happen if multiple transactions are trying to
5353 : * lock an ancient version of the same tuple.
5354 : */
5355 0 : return TM_SelfModified;
5356 : }
5357 64 : else if (TransactionIdIsInProgress(xid))
5358 : {
5359 : /*
5360 : * If the locking transaction is running, what we do depends on
5361 : * whether the lock modes conflict: if they do, then we must wait for
5362 : * it to finish; otherwise we can fall through to lock this tuple
5363 : * version without waiting.
5364 : */
5365 32 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5366 32 : LOCKMODE_from_mxstatus(wantedstatus)))
5367 : {
5368 16 : *needwait = true;
5369 : }
5370 :
5371 : /*
5372 : * If we set needwait above, then this value doesn't matter;
5373 : * otherwise, this value signals to caller that it's okay to proceed.
5374 : */
5375 32 : return TM_Ok;
5376 : }
5377 32 : else if (TransactionIdDidAbort(xid))
5378 6 : return TM_Ok;
5379 26 : else if (TransactionIdDidCommit(xid))
5380 : {
5381 : /*
5382 : * The other transaction committed. If it was only a locker, then the
5383 : * lock is completely gone now and we can return success; but if it
5384 : * was an update, then what we do depends on whether the two lock
5385 : * modes conflict. If they conflict, then we must report error to
5386 : * caller. But if they don't, we can fall through to allow the current
5387 : * transaction to lock the tuple.
5388 : *
5389 : * Note: the reason we worry about ISUPDATE here is because as soon as
5390 : * a transaction ends, all its locks are gone and meaningless, and
5391 : * thus we can ignore them; whereas its updates persist. In the
5392 : * TransactionIdIsInProgress case, above, we don't need to check
5393 : * because we know the lock is still "alive" and thus a conflict needs
5394 : * always be checked.
5395 : */
5396 26 : if (!ISUPDATE_from_mxstatus(status))
5397 8 : return TM_Ok;
5398 :
5399 18 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5400 18 : LOCKMODE_from_mxstatus(wantedstatus)))
5401 : {
5402 : /* bummer */
5403 16 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5404 12 : return TM_Updated;
5405 : else
5406 4 : return TM_Deleted;
5407 : }
5408 :
5409 2 : return TM_Ok;
5410 : }
5411 :
5412 : /* Not in progress, not aborted, not committed -- must have crashed */
5413 0 : return TM_Ok;
5414 : }
5415 :
5416 :
5417 : /*
5418 : * Recursive part of heap_lock_updated_tuple
5419 : *
5420 : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5421 : * xid with the given mode; if this tuple is updated, recurse to lock the new
5422 : * version as well.
5423 : */
5424 : static TM_Result
5425 160 : heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid,
5426 : LockTupleMode mode)
5427 : {
5428 : TM_Result result;
5429 : ItemPointerData tupid;
5430 : HeapTupleData mytup;
5431 : Buffer buf;
5432 : uint16 new_infomask,
5433 : new_infomask2,
5434 : old_infomask,
5435 : old_infomask2;
5436 : TransactionId xmax,
5437 : new_xmax;
5438 160 : TransactionId priorXmax = InvalidTransactionId;
5439 160 : bool cleared_all_frozen = false;
5440 : bool pinned_desired_page;
5441 160 : Buffer vmbuffer = InvalidBuffer;
5442 : BlockNumber block;
5443 :
5444 160 : ItemPointerCopy(tid, &tupid);
5445 :
5446 : for (;;)
5447 : {
5448 166 : new_infomask = 0;
5449 166 : new_xmax = InvalidTransactionId;
5450 166 : block = ItemPointerGetBlockNumber(&tupid);
5451 166 : ItemPointerCopy(&tupid, &(mytup.t_self));
5452 :
5453 166 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5454 : {
5455 : /*
5456 : * if we fail to find the updated version of the tuple, it's
5457 : * because it was vacuumed/pruned away after its creator
5458 : * transaction aborted. So behave as if we got to the end of the
5459 : * chain, and there's no further tuple to lock: return success to
5460 : * caller.
5461 : */
5462 0 : result = TM_Ok;
5463 0 : goto out_unlocked;
5464 : }
5465 :
5466 166 : l4:
5467 182 : CHECK_FOR_INTERRUPTS();
5468 :
5469 : /*
5470 : * Before locking the buffer, pin the visibility map page if it
5471 : * appears to be necessary. Since we haven't got the lock yet,
5472 : * someone else might be in the middle of changing this, so we'll need
5473 : * to recheck after we have the lock.
5474 : */
5475 182 : if (PageIsAllVisible(BufferGetPage(buf)))
5476 : {
5477 0 : visibilitymap_pin(rel, block, &vmbuffer);
5478 0 : pinned_desired_page = true;
5479 : }
5480 : else
5481 182 : pinned_desired_page = false;
5482 :
5483 182 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5484 :
5485 : /*
5486 : * If we didn't pin the visibility map page and the page has become
5487 : * all visible while we were busy locking the buffer, we'll have to
5488 : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5489 : * That's a bit unfortunate, but hopefully shouldn't happen often.
5490 : *
5491 : * Note: in some paths through this function, we will reach here
5492 : * holding a pin on a vm page that may or may not be the one matching
5493 : * this page. If this page isn't all-visible, we won't use the vm
5494 : * page, but we hold onto such a pin till the end of the function.
5495 : */
5496 182 : if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5497 : {
5498 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5499 0 : visibilitymap_pin(rel, block, &vmbuffer);
5500 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5501 : }
5502 :
5503 : /*
5504 : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5505 : * end of the chain, we're done, so return success.
5506 : */
5507 188 : if (TransactionIdIsValid(priorXmax) &&
5508 6 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5509 : priorXmax))
5510 : {
5511 0 : result = TM_Ok;
5512 0 : goto out_locked;
5513 : }
5514 :
5515 : /*
5516 : * Also check Xmin: if this tuple was created by an aborted
5517 : * (sub)transaction, then we already locked the last live one in the
5518 : * chain, thus we're done, so return success.
5519 : */
5520 182 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
5521 : {
5522 26 : result = TM_Ok;
5523 26 : goto out_locked;
5524 : }
5525 :
5526 156 : old_infomask = mytup.t_data->t_infomask;
5527 156 : old_infomask2 = mytup.t_data->t_infomask2;
5528 156 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5529 :
5530 : /*
5531 : * If this tuple version has been updated or locked by some concurrent
5532 : * transaction(s), what we do depends on whether our lock mode
5533 : * conflicts with what those other transactions hold, and also on the
5534 : * status of them.
5535 : */
5536 156 : if (!(old_infomask & HEAP_XMAX_INVALID))
5537 : {
5538 : TransactionId rawxmax;
5539 : bool needwait;
5540 :
5541 60 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5542 60 : if (old_infomask & HEAP_XMAX_IS_MULTI)
5543 : {
5544 : int nmembers;
5545 : int i;
5546 : MultiXactMember *members;
5547 :
5548 : /*
5549 : * We don't need a test for pg_upgrade'd tuples: this is only
5550 : * applied to tuples after the first in an update chain. Said
5551 : * first tuple in the chain may well be locked-in-9.2-and-
5552 : * pg_upgraded, but that one was already locked by our caller,
5553 : * not us; and any subsequent ones cannot be because our
5554 : * caller must necessarily have obtained a snapshot later than
5555 : * the pg_upgrade itself.
5556 : */
5557 : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
5558 :
5559 2 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5560 2 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5561 8 : for (i = 0; i < nmembers; i++)
5562 : {
5563 6 : result = test_lockmode_for_conflict(members[i].status,
5564 6 : members[i].xid,
5565 : mode,
5566 : &mytup,
5567 : &needwait);
5568 :
5569 : /*
5570 : * If the tuple was already locked by ourselves in a
5571 : * previous iteration of this (say heap_lock_tuple was
5572 : * forced to restart the locking loop because of a change
5573 : * in xmax), then we hold the lock already on this tuple
5574 : * version and we don't need to do anything; and this is
5575 : * not an error condition either. We just need to skip
5576 : * this tuple and continue locking the next version in the
5577 : * update chain.
5578 : */
5579 6 : if (result == TM_SelfModified)
5580 : {
5581 0 : pfree(members);
5582 0 : goto next;
5583 : }
5584 :
5585 6 : if (needwait)
5586 : {
5587 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5588 0 : XactLockTableWait(members[i].xid, rel,
5589 : &mytup.t_self,
5590 : XLTW_LockUpdated);
5591 0 : pfree(members);
5592 0 : goto l4;
5593 : }
5594 6 : if (result != TM_Ok)
5595 : {
5596 0 : pfree(members);
5597 0 : goto out_locked;
5598 : }
5599 : }
5600 2 : if (members)
5601 2 : pfree(members);
5602 : }
5603 : else
5604 : {
5605 : MultiXactStatus status;
5606 :
5607 : /*
5608 : * For a non-multi Xmax, we first need to compute the
5609 : * corresponding MultiXactStatus by using the infomask bits.
5610 : */
5611 58 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5612 : {
5613 20 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5614 20 : status = MultiXactStatusForKeyShare;
5615 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5616 0 : status = MultiXactStatusForShare;
5617 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5618 : {
5619 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5620 0 : status = MultiXactStatusForUpdate;
5621 : else
5622 0 : status = MultiXactStatusForNoKeyUpdate;
5623 : }
5624 : else
5625 : {
5626 : /*
5627 : * LOCK_ONLY present alone (a pg_upgraded tuple marked
5628 : * as share-locked in the old cluster) shouldn't be
5629 : * seen in the middle of an update chain.
5630 : */
5631 0 : elog(ERROR, "invalid lock status in tuple");
5632 : }
5633 : }
5634 : else
5635 : {
5636 : /* it's an update, but which kind? */
5637 38 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5638 28 : status = MultiXactStatusUpdate;
5639 : else
5640 10 : status = MultiXactStatusNoKeyUpdate;
5641 : }
5642 :
5643 58 : result = test_lockmode_for_conflict(status, rawxmax, mode,
5644 : &mytup, &needwait);
5645 :
5646 : /*
5647 : * If the tuple was already locked by ourselves in a previous
5648 : * iteration of this (say heap_lock_tuple was forced to
5649 : * restart the locking loop because of a change in xmax), then
5650 : * we hold the lock already on this tuple version and we don't
5651 : * need to do anything; and this is not an error condition
5652 : * either. We just need to skip this tuple and continue
5653 : * locking the next version in the update chain.
5654 : */
5655 58 : if (result == TM_SelfModified)
5656 0 : goto next;
5657 :
5658 58 : if (needwait)
5659 : {
5660 16 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5661 16 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
5662 : XLTW_LockUpdated);
5663 16 : goto l4;
5664 : }
5665 42 : if (result != TM_Ok)
5666 : {
5667 16 : goto out_locked;
5668 : }
5669 : }
5670 : }
5671 :
5672 : /* compute the new Xmax and infomask values for the tuple ... */
5673 124 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5674 : xid, mode, false,
5675 : &new_xmax, &new_infomask, &new_infomask2);
5676 :
5677 124 : if (PageIsAllVisible(BufferGetPage(buf)) &&
5678 0 : visibilitymap_clear(rel, block, vmbuffer,
5679 : VISIBILITYMAP_ALL_FROZEN))
5680 0 : cleared_all_frozen = true;
5681 :
5682 124 : START_CRIT_SECTION();
5683 :
5684 : /* ... and set them */
5685 124 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5686 124 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5687 124 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5688 124 : mytup.t_data->t_infomask |= new_infomask;
5689 124 : mytup.t_data->t_infomask2 |= new_infomask2;
5690 :
5691 124 : MarkBufferDirty(buf);
5692 :
5693 : /* XLOG stuff */
5694 124 : if (RelationNeedsWAL(rel))
5695 : {
5696 : xl_heap_lock_updated xlrec;
5697 : XLogRecPtr recptr;
5698 124 : Page page = BufferGetPage(buf);
5699 :
5700 124 : XLogBeginInsert();
5701 124 : XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
5702 :
5703 124 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5704 124 : xlrec.xmax = new_xmax;
5705 124 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5706 124 : xlrec.flags =
5707 124 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5708 :
5709 124 : XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5710 :
5711 124 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5712 :
5713 124 : PageSetLSN(page, recptr);
5714 : }
5715 :
5716 124 : END_CRIT_SECTION();
5717 :
5718 124 : next:
5719 : /* if we find the end of update chain, we're done. */
5720 248 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
5721 248 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
5722 132 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5723 8 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
5724 : {
5725 118 : result = TM_Ok;
5726 118 : goto out_locked;
5727 : }
5728 :
5729 : /* tail recursion */
5730 6 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5731 6 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5732 6 : UnlockReleaseBuffer(buf);
5733 : }
5734 :
5735 : result = TM_Ok;
5736 :
5737 160 : out_locked:
5738 160 : UnlockReleaseBuffer(buf);
5739 :
5740 160 : out_unlocked:
5741 160 : if (vmbuffer != InvalidBuffer)
5742 0 : ReleaseBuffer(vmbuffer);
5743 :
5744 160 : return result;
5745 : }
5746 :
5747 : /*
5748 : * heap_lock_updated_tuple
5749 : * Follow update chain when locking an updated tuple, acquiring locks (row
5750 : * marks) on the updated versions.
5751 : *
5752 : * The initial tuple is assumed to be already locked.
5753 : *
5754 : * This function doesn't check visibility, it just unconditionally marks the
5755 : * tuple(s) as locked. If any tuple in the updated chain is being deleted
5756 : * concurrently (or updated with the key being modified), sleep until the
5757 : * transaction doing it is finished.
5758 : *
5759 : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
5760 : * when we have to wait for other transactions to release them, as opposed to
5761 : * what heap_lock_tuple does. The reason is that having more than one
5762 : * transaction walking the chain is probably uncommon enough that risk of
5763 : * starvation is not likely: one of the preconditions for being here is that
5764 : * the snapshot in use predates the update that created this tuple (because we
5765 : * started at an earlier version of the tuple), but at the same time such a
5766 : * transaction cannot be using repeatable read or serializable isolation
5767 : * levels, because that would lead to a serializability failure.
5768 : */
5769 : static TM_Result
5770 176 : heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid,
5771 : TransactionId xid, LockTupleMode mode)
5772 : {
5773 : /*
5774 : * If the tuple has not been updated, or has moved into another partition
5775 : * (effectively a delete) stop here.
5776 : */
5777 176 : if (!HeapTupleHeaderIndicatesMovedPartitions(tuple->t_data) &&
5778 172 : !ItemPointerEquals(&tuple->t_self, ctid))
5779 : {
5780 : /*
5781 : * If this is the first possibly-multixact-able operation in the
5782 : * current transaction, set my per-backend OldestMemberMXactId
5783 : * setting. We can be certain that the transaction will never become a
5784 : * member of any older MultiXactIds than that. (We have to do this
5785 : * even if we end up just using our own TransactionId below, since
5786 : * some other backend could incorporate our XID into a MultiXact
5787 : * immediately afterwards.)
5788 : */
5789 160 : MultiXactIdSetOldestMember();
5790 :
5791 160 : return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
5792 : }
5793 :
5794 : /* nothing to lock */
5795 16 : return TM_Ok;
5796 : }
5797 :
5798 : /*
5799 : * heap_finish_speculative - mark speculative insertion as successful
5800 : *
5801 : * To successfully finish a speculative insertion we have to clear speculative
5802 : * token from tuple. To do so the t_ctid field, which will contain a
5803 : * speculative token value, is modified in place to point to the tuple itself,
5804 : * which is characteristic of a newly inserted ordinary tuple.
5805 : *
5806 : * NB: It is not ok to commit without either finishing or aborting a
5807 : * speculative insertion. We could treat speculative tuples of committed
5808 : * transactions implicitly as completed, but then we would have to be prepared
5809 : * to deal with speculative tokens on committed tuples. That wouldn't be
5810 : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
5811 : * but clearing the token at completion isn't very expensive either.
5812 : * An explicit confirmation WAL record also makes logical decoding simpler.
5813 : */
5814 : void
5815 4010 : heap_finish_speculative(Relation relation, ItemPointer tid)
5816 : {
5817 : Buffer buffer;
5818 : Page page;
5819 : OffsetNumber offnum;
5820 4010 : ItemId lp = NULL;
5821 : HeapTupleHeader htup;
5822 :
5823 4010 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5824 4010 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5825 4010 : page = (Page) BufferGetPage(buffer);
5826 :
5827 4010 : offnum = ItemPointerGetOffsetNumber(tid);
5828 4010 : if (PageGetMaxOffsetNumber(page) >= offnum)
5829 4010 : lp = PageGetItemId(page, offnum);
5830 :
5831 4010 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5832 0 : elog(ERROR, "invalid lp");
5833 :
5834 4010 : htup = (HeapTupleHeader) PageGetItem(page, lp);
5835 :
5836 : /* NO EREPORT(ERROR) from here till changes are logged */
5837 4010 : START_CRIT_SECTION();
5838 :
5839 : Assert(HeapTupleHeaderIsSpeculative(htup));
5840 :
5841 4010 : MarkBufferDirty(buffer);
5842 :
5843 : /*
5844 : * Replace the speculative insertion token with a real t_ctid, pointing to
5845 : * itself like it does on regular tuples.
5846 : */
5847 4010 : htup->t_ctid = *tid;
5848 :
5849 : /* XLOG stuff */
5850 4010 : if (RelationNeedsWAL(relation))
5851 : {
5852 : xl_heap_confirm xlrec;
5853 : XLogRecPtr recptr;
5854 :
5855 3998 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5856 :
5857 3998 : XLogBeginInsert();
5858 :
5859 : /* We want the same filtering on this as on a plain insert */
5860 3998 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
5861 :
5862 3998 : XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5863 3998 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5864 :
5865 3998 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5866 :
5867 3998 : PageSetLSN(page, recptr);
5868 : }
5869 :
5870 4010 : END_CRIT_SECTION();
5871 :
5872 4010 : UnlockReleaseBuffer(buffer);
5873 4010 : }
5874 :
5875 : /*
5876 : * heap_abort_speculative - kill a speculatively inserted tuple
5877 : *
5878 : * Marks a tuple that was speculatively inserted in the same command as dead,
5879 : * by setting its xmin as invalid. That makes it immediately appear as dead
5880 : * to all transactions, including our own. In particular, it makes
5881 : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
5882 : * inserting a duplicate key value won't unnecessarily wait for our whole
5883 : * transaction to finish (it'll just wait for our speculative insertion to
5884 : * finish).
5885 : *
5886 : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
5887 : * that arise due to a mutual dependency that is not user visible. By
5888 : * definition, unprincipled deadlocks cannot be prevented by the user
5889 : * reordering lock acquisition in client code, because the implementation level
5890 : * lock acquisitions are not under the user's direct control. If speculative
5891 : * inserters did not take this precaution, then under high concurrency they
5892 : * could deadlock with each other, which would not be acceptable.
5893 : *
5894 : * This is somewhat redundant with heap_delete, but we prefer to have a
5895 : * dedicated routine with stripped down requirements. Note that this is also
5896 : * used to delete the TOAST tuples created during speculative insertion.
5897 : *
5898 : * This routine does not affect logical decoding as it only looks at
5899 : * confirmation records.
5900 : */
5901 : void
5902 20 : heap_abort_speculative(Relation relation, ItemPointer tid)
5903 : {
5904 20 : TransactionId xid = GetCurrentTransactionId();
5905 : ItemId lp;
5906 : HeapTupleData tp;
5907 : Page page;
5908 : BlockNumber block;
5909 : Buffer buffer;
5910 :
5911 : Assert(ItemPointerIsValid(tid));
5912 :
5913 20 : block = ItemPointerGetBlockNumber(tid);
5914 20 : buffer = ReadBuffer(relation, block);
5915 20 : page = BufferGetPage(buffer);
5916 :
5917 20 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5918 :
5919 : /*
5920 : * Page can't be all visible, we just inserted into it, and are still
5921 : * running.
5922 : */
5923 : Assert(!PageIsAllVisible(page));
5924 :
5925 20 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5926 : Assert(ItemIdIsNormal(lp));
5927 :
5928 20 : tp.t_tableOid = RelationGetRelid(relation);
5929 20 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5930 20 : tp.t_len = ItemIdGetLength(lp);
5931 20 : tp.t_self = *tid;
5932 :
5933 : /*
5934 : * Sanity check that the tuple really is a speculatively inserted tuple,
5935 : * inserted by us.
5936 : */
5937 20 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5938 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5939 20 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5940 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
5941 : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
5942 :
5943 : /*
5944 : * No need to check for serializable conflicts here. There is never a
5945 : * need for a combo CID, either. No need to extract replica identity, or
5946 : * do anything special with infomask bits.
5947 : */
5948 :
5949 20 : START_CRIT_SECTION();
5950 :
5951 : /*
5952 : * The tuple will become DEAD immediately. Flag that this page is a
5953 : * candidate for pruning by setting xmin to TransactionXmin. While not
5954 : * immediately prunable, it is the oldest xid we can cheaply determine
5955 : * that's safe against wraparound / being older than the table's
5956 : * relfrozenxid. To defend against the unlikely case of a new relation
5957 : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5958 : * if so (vacuum can't subsequently move relfrozenxid to beyond
5959 : * TransactionXmin, so there's no race here).
5960 : */
5961 : Assert(TransactionIdIsValid(TransactionXmin));
5962 : {
5963 20 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
5964 : TransactionId prune_xid;
5965 :
5966 20 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
5967 0 : prune_xid = relfrozenxid;
5968 : else
5969 20 : prune_xid = TransactionXmin;
5970 20 : PageSetPrunable(page, prune_xid);
5971 : }
5972 :
5973 : /* store transaction information of xact deleting the tuple */
5974 20 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
5975 20 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5976 :
5977 : /*
5978 : * Set the tuple header xmin to InvalidTransactionId. This makes the
5979 : * tuple immediately invisible everyone. (In particular, to any
5980 : * transactions waiting on the speculative token, woken up later.)
5981 : */
5982 20 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
5983 :
5984 : /* Clear the speculative insertion token too */
5985 20 : tp.t_data->t_ctid = tp.t_self;
5986 :
5987 20 : MarkBufferDirty(buffer);
5988 :
5989 : /*
5990 : * XLOG stuff
5991 : *
5992 : * The WAL records generated here match heap_delete(). The same recovery
5993 : * routines are used.
5994 : */
5995 20 : if (RelationNeedsWAL(relation))
5996 : {
5997 : xl_heap_delete xlrec;
5998 : XLogRecPtr recptr;
5999 :
6000 20 : xlrec.flags = XLH_DELETE_IS_SUPER;
6001 40 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6002 20 : tp.t_data->t_infomask2);
6003 20 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6004 20 : xlrec.xmax = xid;
6005 :
6006 20 : XLogBeginInsert();
6007 20 : XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
6008 20 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6009 :
6010 : /* No replica identity & replication origin logged */
6011 :
6012 20 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6013 :
6014 20 : PageSetLSN(page, recptr);
6015 : }
6016 :
6017 20 : END_CRIT_SECTION();
6018 :
6019 20 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6020 :
6021 20 : if (HeapTupleHasExternal(&tp))
6022 : {
6023 : Assert(!IsToastRelation(relation));
6024 2 : heap_toast_delete(relation, &tp, true);
6025 : }
6026 :
6027 : /*
6028 : * Never need to mark tuple for invalidation, since catalogs don't support
6029 : * speculative insertion
6030 : */
6031 :
6032 : /* Now we can release the buffer */
6033 20 : ReleaseBuffer(buffer);
6034 :
6035 : /* count deletion, as we counted the insertion too */
6036 20 : pgstat_count_heap_delete(relation);
6037 20 : }
6038 :
6039 : /*
6040 : * heap_inplace_update - update a tuple "in place" (ie, overwrite it)
6041 : *
6042 : * Overwriting violates both MVCC and transactional safety, so the uses
6043 : * of this function in Postgres are extremely limited. Nonetheless we
6044 : * find some places to use it.
6045 : *
6046 : * The tuple cannot change size, and therefore it's reasonable to assume
6047 : * that its null bitmap (if any) doesn't change either. So we just
6048 : * overwrite the data portion of the tuple without touching the null
6049 : * bitmap or any of the header fields.
6050 : *
6051 : * tuple is an in-memory tuple structure containing the data to be written
6052 : * over the target tuple. Also, tuple->t_self identifies the target tuple.
6053 : *
6054 : * Note that the tuple updated here had better not come directly from the
6055 : * syscache if the relation has a toast relation as this tuple could
6056 : * include toast values that have been expanded, causing a failure here.
6057 : */
6058 : void
6059 107590 : heap_inplace_update(Relation relation, HeapTuple tuple)
6060 : {
6061 : Buffer buffer;
6062 : Page page;
6063 : OffsetNumber offnum;
6064 107590 : ItemId lp = NULL;
6065 : HeapTupleHeader htup;
6066 : uint32 oldlen;
6067 : uint32 newlen;
6068 :
6069 : /*
6070 : * For now, we don't allow parallel updates. Unlike a regular update,
6071 : * this should never create a combo CID, so it might be possible to relax
6072 : * this restriction, but not without more thought and testing. It's not
6073 : * clear that it would be useful, anyway.
6074 : */
6075 107590 : if (IsInParallelMode())
6076 0 : ereport(ERROR,
6077 : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
6078 : errmsg("cannot update tuples during a parallel operation")));
6079 :
6080 107590 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
6081 107590 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6082 107590 : page = (Page) BufferGetPage(buffer);
6083 :
6084 107590 : offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
6085 107590 : if (PageGetMaxOffsetNumber(page) >= offnum)
6086 107590 : lp = PageGetItemId(page, offnum);
6087 :
6088 107590 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6089 0 : elog(ERROR, "invalid lp");
6090 :
6091 107590 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6092 :
6093 107590 : oldlen = ItemIdGetLength(lp) - htup->t_hoff;
6094 107590 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6095 107590 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6096 0 : elog(ERROR, "wrong tuple length");
6097 :
6098 : /* NO EREPORT(ERROR) from here till changes are logged */
6099 107590 : START_CRIT_SECTION();
6100 :
6101 107590 : memcpy((char *) htup + htup->t_hoff,
6102 107590 : (char *) tuple->t_data + tuple->t_data->t_hoff,
6103 : newlen);
6104 :
6105 107590 : MarkBufferDirty(buffer);
6106 :
6107 : /* XLOG stuff */
6108 107590 : if (RelationNeedsWAL(relation))
6109 : {
6110 : xl_heap_inplace xlrec;
6111 : XLogRecPtr recptr;
6112 :
6113 107574 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6114 :
6115 107574 : XLogBeginInsert();
6116 107574 : XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
6117 :
6118 107574 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6119 107574 : XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
6120 :
6121 : /* inplace updates aren't decoded atm, don't log the origin */
6122 :
6123 107574 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6124 :
6125 107574 : PageSetLSN(page, recptr);
6126 : }
6127 :
6128 107590 : END_CRIT_SECTION();
6129 :
6130 107590 : UnlockReleaseBuffer(buffer);
6131 :
6132 : /*
6133 : * Send out shared cache inval if necessary. Note that because we only
6134 : * pass the new version of the tuple, this mustn't be used for any
6135 : * operations that could change catcache lookup keys. But we aren't
6136 : * bothering with index updates either, so that's true a fortiori.
6137 : */
6138 107590 : if (!IsBootstrapProcessingMode())
6139 83910 : CacheInvalidateHeapTuple(relation, tuple, NULL);
6140 107590 : }
6141 :
6142 : #define FRM_NOOP 0x0001
6143 : #define FRM_INVALIDATE_XMAX 0x0002
6144 : #define FRM_RETURN_IS_XID 0x0004
6145 : #define FRM_RETURN_IS_MULTI 0x0008
6146 : #define FRM_MARK_COMMITTED 0x0010
6147 :
6148 : /*
6149 : * FreezeMultiXactId
6150 : * Determine what to do during freezing when a tuple is marked by a
6151 : * MultiXactId.
6152 : *
6153 : * "flags" is an output value; it's used to tell caller what to do on return.
6154 : * "pagefrz" is an input/output value, used to manage page level freezing.
6155 : *
6156 : * Possible values that we can set in "flags":
6157 : * FRM_NOOP
6158 : * don't do anything -- keep existing Xmax
6159 : * FRM_INVALIDATE_XMAX
6160 : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6161 : * FRM_RETURN_IS_XID
6162 : * The Xid return value is a single update Xid to set as xmax.
6163 : * FRM_MARK_COMMITTED
6164 : * Xmax can be marked as HEAP_XMAX_COMMITTED
6165 : * FRM_RETURN_IS_MULTI
6166 : * The return value is a new MultiXactId to set as new Xmax.
6167 : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6168 : *
6169 : * Caller delegates control of page freezing to us. In practice we always
6170 : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6171 : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6172 : * can never be left behind. We freely choose when and how to process each
6173 : * Multi, without ever violating the cutoff postconditions for freezing.
6174 : *
6175 : * It's useful to remove Multis on a proactive timeline (relative to freezing
6176 : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6177 : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6178 : * misses through eager processing.
6179 : *
6180 : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6181 : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6182 : * This can usually be put off, which is usually enough to avoid it altogether.
6183 : * Allocating new multis during VACUUM should be avoided on general principle;
6184 : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6185 : * its own special risks.
6186 : *
6187 : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6188 : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6189 : *
6190 : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6191 : * have already forced page-level freezing, since that might incur the same
6192 : * SLRU buffer misses that we specifically intended to avoid by freezing.
6193 : */
6194 : static TransactionId
6195 12 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6196 : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6197 : HeapPageFreeze *pagefrz)
6198 : {
6199 : TransactionId newxmax;
6200 : MultiXactMember *members;
6201 : int nmembers;
6202 : bool need_replace;
6203 : int nnewmembers;
6204 : MultiXactMember *newmembers;
6205 : bool has_lockers;
6206 : TransactionId update_xid;
6207 : bool update_committed;
6208 : TransactionId FreezePageRelfrozenXid;
6209 :
6210 12 : *flags = 0;
6211 :
6212 : /* We should only be called in Multis */
6213 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6214 :
6215 12 : if (!MultiXactIdIsValid(multi) ||
6216 12 : HEAP_LOCKED_UPGRADED(t_infomask))
6217 : {
6218 0 : *flags |= FRM_INVALIDATE_XMAX;
6219 0 : pagefrz->freeze_required = true;
6220 0 : return InvalidTransactionId;
6221 : }
6222 12 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6223 0 : ereport(ERROR,
6224 : (errcode(ERRCODE_DATA_CORRUPTED),
6225 : errmsg_internal("found multixact %u from before relminmxid %u",
6226 : multi, cutoffs->relminmxid)));
6227 12 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6228 : {
6229 : TransactionId update_xact;
6230 :
6231 : /*
6232 : * This old multi cannot possibly have members still running, but
6233 : * verify just in case. If it was a locker only, it can be removed
6234 : * without any further consideration; but if it contained an update,
6235 : * we might need to preserve it.
6236 : */
6237 8 : if (MultiXactIdIsRunning(multi,
6238 8 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6239 0 : ereport(ERROR,
6240 : (errcode(ERRCODE_DATA_CORRUPTED),
6241 : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6242 : multi, cutoffs->OldestMxact)));
6243 :
6244 8 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6245 : {
6246 8 : *flags |= FRM_INVALIDATE_XMAX;
6247 8 : pagefrz->freeze_required = true;
6248 8 : return InvalidTransactionId;
6249 : }
6250 :
6251 : /* replace multi with single XID for its updater? */
6252 0 : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6253 0 : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6254 0 : ereport(ERROR,
6255 : (errcode(ERRCODE_DATA_CORRUPTED),
6256 : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6257 : multi, update_xact,
6258 : cutoffs->relfrozenxid)));
6259 0 : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6260 : {
6261 : /*
6262 : * Updater XID has to have aborted (otherwise the tuple would have
6263 : * been pruned away instead, since updater XID is < OldestXmin).
6264 : * Just remove xmax.
6265 : */
6266 0 : if (TransactionIdDidCommit(update_xact))
6267 0 : ereport(ERROR,
6268 : (errcode(ERRCODE_DATA_CORRUPTED),
6269 : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6270 : multi, update_xact,
6271 : cutoffs->OldestXmin)));
6272 0 : *flags |= FRM_INVALIDATE_XMAX;
6273 0 : pagefrz->freeze_required = true;
6274 0 : return InvalidTransactionId;
6275 : }
6276 :
6277 : /* Have to keep updater XID as new xmax */
6278 0 : *flags |= FRM_RETURN_IS_XID;
6279 0 : pagefrz->freeze_required = true;
6280 0 : return update_xact;
6281 : }
6282 :
6283 : /*
6284 : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6285 : * need to walk the whole members array to figure out what to do, if
6286 : * anything.
6287 : */
6288 : nmembers =
6289 4 : GetMultiXactIdMembers(multi, &members, false,
6290 4 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6291 4 : if (nmembers <= 0)
6292 : {
6293 : /* Nothing worth keeping */
6294 0 : *flags |= FRM_INVALIDATE_XMAX;
6295 0 : pagefrz->freeze_required = true;
6296 0 : return InvalidTransactionId;
6297 : }
6298 :
6299 : /*
6300 : * The FRM_NOOP case is the only case where we might need to ratchet back
6301 : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6302 : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6303 : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6304 : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6305 : * trackers managed by VACUUM being ratcheting back by xmax to the degree
6306 : * required to make it safe to leave xmax undisturbed, independent of
6307 : * whether or not page freezing is triggered somewhere else.
6308 : *
6309 : * Our policy is to force freezing in every case other than FRM_NOOP,
6310 : * which obviates the need to maintain either set of trackers, anywhere.
6311 : * Every other case will reliably execute a freeze plan for xmax that
6312 : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6313 : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6314 : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6315 : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6316 : */
6317 4 : need_replace = false;
6318 4 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6319 8 : for (int i = 0; i < nmembers; i++)
6320 : {
6321 6 : TransactionId xid = members[i].xid;
6322 :
6323 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6324 :
6325 6 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6326 : {
6327 : /* Can't violate the FreezeLimit postcondition */
6328 2 : need_replace = true;
6329 2 : break;
6330 : }
6331 4 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6332 0 : FreezePageRelfrozenXid = xid;
6333 : }
6334 :
6335 : /* Can't violate the MultiXactCutoff postcondition, either */
6336 4 : if (!need_replace)
6337 2 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6338 :
6339 4 : if (!need_replace)
6340 : {
6341 : /*
6342 : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6343 : * both together to make it safe to retain this particular multi after
6344 : * freezing its page
6345 : */
6346 2 : *flags |= FRM_NOOP;
6347 2 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6348 2 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6349 0 : pagefrz->FreezePageRelminMxid = multi;
6350 2 : pfree(members);
6351 2 : return multi;
6352 : }
6353 :
6354 : /*
6355 : * Do a more thorough second pass over the multi to figure out which
6356 : * member XIDs actually need to be kept. Checking the precise status of
6357 : * individual members might even show that we don't need to keep anything.
6358 : * That is quite possible even though the Multi must be >= OldestMxact,
6359 : * since our second pass only keeps member XIDs when it's truly necessary;
6360 : * even member XIDs >= OldestXmin often won't be kept by second pass.
6361 : */
6362 2 : nnewmembers = 0;
6363 2 : newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6364 2 : has_lockers = false;
6365 2 : update_xid = InvalidTransactionId;
6366 2 : update_committed = false;
6367 :
6368 : /*
6369 : * Determine whether to keep each member xid, or to ignore it instead
6370 : */
6371 6 : for (int i = 0; i < nmembers; i++)
6372 : {
6373 4 : TransactionId xid = members[i].xid;
6374 4 : MultiXactStatus mstatus = members[i].status;
6375 :
6376 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6377 :
6378 4 : if (!ISUPDATE_from_mxstatus(mstatus))
6379 : {
6380 : /*
6381 : * Locker XID (not updater XID). We only keep lockers that are
6382 : * still running.
6383 : */
6384 8 : if (TransactionIdIsCurrentTransactionId(xid) ||
6385 4 : TransactionIdIsInProgress(xid))
6386 : {
6387 2 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6388 0 : ereport(ERROR,
6389 : (errcode(ERRCODE_DATA_CORRUPTED),
6390 : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6391 : multi, xid,
6392 : cutoffs->OldestXmin)));
6393 2 : newmembers[nnewmembers++] = members[i];
6394 2 : has_lockers = true;
6395 : }
6396 :
6397 4 : continue;
6398 : }
6399 :
6400 : /*
6401 : * Updater XID (not locker XID). Should we keep it?
6402 : *
6403 : * Since the tuple wasn't totally removed when vacuum pruned, the
6404 : * update Xid cannot possibly be older than OldestXmin cutoff unless
6405 : * the updater XID aborted. If the updater transaction is known
6406 : * aborted or crashed then it's okay to ignore it, otherwise not.
6407 : *
6408 : * In any case the Multi should never contain two updaters, whatever
6409 : * their individual commit status. Check for that first, in passing.
6410 : */
6411 0 : if (TransactionIdIsValid(update_xid))
6412 0 : ereport(ERROR,
6413 : (errcode(ERRCODE_DATA_CORRUPTED),
6414 : errmsg_internal("multixact %u has two or more updating members",
6415 : multi),
6416 : errdetail_internal("First updater XID=%u second updater XID=%u.",
6417 : update_xid, xid)));
6418 :
6419 : /*
6420 : * As with all tuple visibility routines, it's critical to test
6421 : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6422 : * race conditions explained in detail in heapam_visibility.c.
6423 : */
6424 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
6425 0 : TransactionIdIsInProgress(xid))
6426 0 : update_xid = xid;
6427 0 : else if (TransactionIdDidCommit(xid))
6428 : {
6429 : /*
6430 : * The transaction committed, so we can tell caller to set
6431 : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6432 : * transaction is not running.)
6433 : */
6434 0 : update_committed = true;
6435 0 : update_xid = xid;
6436 : }
6437 : else
6438 : {
6439 : /*
6440 : * Not in progress, not committed -- must be aborted or crashed;
6441 : * we can ignore it.
6442 : */
6443 0 : continue;
6444 : }
6445 :
6446 : /*
6447 : * We determined that updater must be kept -- add it to pending new
6448 : * members list
6449 : */
6450 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6451 0 : ereport(ERROR,
6452 : (errcode(ERRCODE_DATA_CORRUPTED),
6453 : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6454 : multi, xid, cutoffs->OldestXmin)));
6455 0 : newmembers[nnewmembers++] = members[i];
6456 : }
6457 :
6458 2 : pfree(members);
6459 :
6460 : /*
6461 : * Determine what to do with caller's multi based on information gathered
6462 : * during our second pass
6463 : */
6464 2 : if (nnewmembers == 0)
6465 : {
6466 : /* Nothing worth keeping */
6467 0 : *flags |= FRM_INVALIDATE_XMAX;
6468 0 : newxmax = InvalidTransactionId;
6469 : }
6470 2 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
6471 : {
6472 : /*
6473 : * If there's a single member and it's an update, pass it back alone
6474 : * without creating a new Multi. (XXX we could do this when there's a
6475 : * single remaining locker, too, but that would complicate the API too
6476 : * much; moreover, the case with the single updater is more
6477 : * interesting, because those are longer-lived.)
6478 : */
6479 : Assert(nnewmembers == 1);
6480 0 : *flags |= FRM_RETURN_IS_XID;
6481 0 : if (update_committed)
6482 0 : *flags |= FRM_MARK_COMMITTED;
6483 0 : newxmax = update_xid;
6484 : }
6485 : else
6486 : {
6487 : /*
6488 : * Create a new multixact with the surviving members of the previous
6489 : * one, to set as new Xmax in the tuple
6490 : */
6491 2 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
6492 2 : *flags |= FRM_RETURN_IS_MULTI;
6493 : }
6494 :
6495 2 : pfree(newmembers);
6496 :
6497 2 : pagefrz->freeze_required = true;
6498 2 : return newxmax;
6499 : }
6500 :
6501 : /*
6502 : * heap_prepare_freeze_tuple
6503 : *
6504 : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
6505 : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
6506 : * setup enough state (in the *frz output argument) to enable caller to
6507 : * process this tuple as part of freezing its page, and return true. Return
6508 : * false if nothing can be changed about the tuple right now.
6509 : *
6510 : * Also sets *totally_frozen to true if the tuple will be totally frozen once
6511 : * caller executes returned freeze plan (or if the tuple was already totally
6512 : * frozen by an earlier VACUUM). This indicates that there are no remaining
6513 : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
6514 : *
6515 : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
6516 : * tuple that we returned true for, and then execute freezing. Caller must
6517 : * initialize pagefrz fields for page as a whole before first call here for
6518 : * each heap page.
6519 : *
6520 : * VACUUM caller decides on whether or not to freeze the page as a whole.
6521 : * We'll often prepare freeze plans for a page that caller just discards.
6522 : * However, VACUUM doesn't always get to make a choice; it must freeze when
6523 : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
6524 : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
6525 : * that VACUUM always follows that rule.
6526 : *
6527 : * We sometimes force freezing of xmax MultiXactId values long before it is
6528 : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
6529 : * It's worth processing MultiXactIds proactively when it is cheap to do so,
6530 : * and it's convenient to make that happen by piggy-backing it on the "force
6531 : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
6532 : * because it is expensive right now (though only when it's still possible to
6533 : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
6534 : *
6535 : * It is assumed that the caller has checked the tuple with
6536 : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
6537 : * (else we should be removing the tuple, not freezing it).
6538 : *
6539 : * NB: This function has side effects: it might allocate a new MultiXactId.
6540 : * It will be set as tuple's new xmax when our *frz output is processed within
6541 : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
6542 : * then caller had better have an exclusive lock on it already.
6543 : */
6544 : bool
6545 6168824 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
6546 : const struct VacuumCutoffs *cutoffs,
6547 : HeapPageFreeze *pagefrz,
6548 : HeapTupleFreeze *frz, bool *totally_frozen)
6549 : {
6550 6168824 : bool xmin_already_frozen = false,
6551 6168824 : xmax_already_frozen = false;
6552 6168824 : bool freeze_xmin = false,
6553 6168824 : replace_xvac = false,
6554 6168824 : replace_xmax = false,
6555 6168824 : freeze_xmax = false;
6556 : TransactionId xid;
6557 :
6558 6168824 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
6559 6168824 : frz->t_infomask2 = tuple->t_infomask2;
6560 6168824 : frz->t_infomask = tuple->t_infomask;
6561 6168824 : frz->frzflags = 0;
6562 6168824 : frz->checkflags = 0;
6563 :
6564 : /*
6565 : * Process xmin, while keeping track of whether it's already frozen, or
6566 : * will become frozen iff our freeze plan is executed by caller (could be
6567 : * neither).
6568 : */
6569 6168824 : xid = HeapTupleHeaderGetXmin(tuple);
6570 6168824 : if (!TransactionIdIsNormal(xid))
6571 1847688 : xmin_already_frozen = true;
6572 : else
6573 : {
6574 4321136 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6575 0 : ereport(ERROR,
6576 : (errcode(ERRCODE_DATA_CORRUPTED),
6577 : errmsg_internal("found xmin %u from before relfrozenxid %u",
6578 : xid, cutoffs->relfrozenxid)));
6579 :
6580 : /* Will set freeze_xmin flags in freeze plan below */
6581 4321136 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6582 :
6583 : /* Verify that xmin committed if and when freeze plan is executed */
6584 4321136 : if (freeze_xmin)
6585 3155168 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
6586 : }
6587 :
6588 : /*
6589 : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
6590 : * as we support having MOVED_OFF/MOVED_IN tuples in the database
6591 : */
6592 6168824 : xid = HeapTupleHeaderGetXvac(tuple);
6593 6168824 : if (TransactionIdIsNormal(xid))
6594 : {
6595 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
6596 : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
6597 :
6598 : /*
6599 : * For Xvac, we always freeze proactively. This allows totally_frozen
6600 : * tracking to ignore xvac.
6601 : */
6602 0 : replace_xvac = pagefrz->freeze_required = true;
6603 :
6604 : /* Will set replace_xvac flags in freeze plan below */
6605 : }
6606 :
6607 : /* Now process xmax */
6608 6168824 : xid = frz->xmax;
6609 6168824 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6610 : {
6611 : /* Raw xmax is a MultiXactId */
6612 : TransactionId newxmax;
6613 : uint16 flags;
6614 :
6615 : /*
6616 : * We will either remove xmax completely (in the "freeze_xmax" path),
6617 : * process xmax by replacing it (in the "replace_xmax" path), or
6618 : * perform no-op xmax processing. The only constraint is that the
6619 : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
6620 : */
6621 12 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
6622 : &flags, pagefrz);
6623 :
6624 12 : if (flags & FRM_NOOP)
6625 : {
6626 : /*
6627 : * xmax is a MultiXactId, and nothing about it changes for now.
6628 : * This is the only case where 'freeze_required' won't have been
6629 : * set for us by FreezeMultiXactId, as well as the only case where
6630 : * neither freeze_xmax nor replace_xmax are set (given a multi).
6631 : *
6632 : * This is a no-op, but the call to FreezeMultiXactId might have
6633 : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
6634 : * for us (the "freeze page" variants, specifically). That'll
6635 : * make it safe for our caller to freeze the page later on, while
6636 : * leaving this particular xmax undisturbed.
6637 : *
6638 : * FreezeMultiXactId is _not_ responsible for the "no freeze"
6639 : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
6640 : * job. A call to heap_tuple_should_freeze for this same tuple
6641 : * will take place below if 'freeze_required' isn't set already.
6642 : * (This repeats work from FreezeMultiXactId, but allows "no
6643 : * freeze" tracker maintenance to happen in only one place.)
6644 : */
6645 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
6646 : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
6647 : }
6648 10 : else if (flags & FRM_RETURN_IS_XID)
6649 : {
6650 : /*
6651 : * xmax will become an updater Xid (original MultiXact's updater
6652 : * member Xid will be carried forward as a simple Xid in Xmax).
6653 : */
6654 : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
6655 :
6656 : /*
6657 : * NB -- some of these transformations are only valid because we
6658 : * know the return Xid is a tuple updater (i.e. not merely a
6659 : * locker.) Also note that the only reason we don't explicitly
6660 : * worry about HEAP_KEYS_UPDATED is because it lives in
6661 : * t_infomask2 rather than t_infomask.
6662 : */
6663 0 : frz->t_infomask &= ~HEAP_XMAX_BITS;
6664 0 : frz->xmax = newxmax;
6665 0 : if (flags & FRM_MARK_COMMITTED)
6666 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
6667 0 : replace_xmax = true;
6668 : }
6669 10 : else if (flags & FRM_RETURN_IS_MULTI)
6670 : {
6671 : uint16 newbits;
6672 : uint16 newbits2;
6673 :
6674 : /*
6675 : * xmax is an old MultiXactId that we have to replace with a new
6676 : * MultiXactId, to carry forward two or more original member XIDs.
6677 : */
6678 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
6679 :
6680 : /*
6681 : * We can't use GetMultiXactIdHintBits directly on the new multi
6682 : * here; that routine initializes the masks to all zeroes, which
6683 : * would lose other bits we need. Doing it this way ensures all
6684 : * unrelated bits remain untouched.
6685 : */
6686 2 : frz->t_infomask &= ~HEAP_XMAX_BITS;
6687 2 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6688 2 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
6689 2 : frz->t_infomask |= newbits;
6690 2 : frz->t_infomask2 |= newbits2;
6691 2 : frz->xmax = newxmax;
6692 2 : replace_xmax = true;
6693 : }
6694 : else
6695 : {
6696 : /*
6697 : * Freeze plan for tuple "freezes xmax" in the strictest sense:
6698 : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
6699 : */
6700 : Assert(flags & FRM_INVALIDATE_XMAX);
6701 : Assert(!TransactionIdIsValid(newxmax));
6702 :
6703 : /* Will set freeze_xmax flags in freeze plan below */
6704 8 : freeze_xmax = true;
6705 : }
6706 :
6707 : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
6708 : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
6709 : }
6710 6168812 : else if (TransactionIdIsNormal(xid))
6711 : {
6712 : /* Raw xmax is normal XID */
6713 507402 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6714 0 : ereport(ERROR,
6715 : (errcode(ERRCODE_DATA_CORRUPTED),
6716 : errmsg_internal("found xmax %u from before relfrozenxid %u",
6717 : xid, cutoffs->relfrozenxid)));
6718 :
6719 : /* Will set freeze_xmax flags in freeze plan below */
6720 507402 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6721 :
6722 : /*
6723 : * Verify that xmax aborted if and when freeze plan is executed,
6724 : * provided it's from an update. (A lock-only xmax can be removed
6725 : * independent of this, since the lock is released at xact end.)
6726 : */
6727 507402 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
6728 450 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
6729 : }
6730 5661410 : else if (!TransactionIdIsValid(xid))
6731 : {
6732 : /* Raw xmax is InvalidTransactionId XID */
6733 : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
6734 5661410 : xmax_already_frozen = true;
6735 : }
6736 : else
6737 0 : ereport(ERROR,
6738 : (errcode(ERRCODE_DATA_CORRUPTED),
6739 : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
6740 : xid, tuple->t_infomask)));
6741 :
6742 6168824 : if (freeze_xmin)
6743 : {
6744 : Assert(!xmin_already_frozen);
6745 :
6746 3155168 : frz->t_infomask |= HEAP_XMIN_FROZEN;
6747 : }
6748 6168824 : if (replace_xvac)
6749 : {
6750 : /*
6751 : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
6752 : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
6753 : * transaction succeeded.
6754 : */
6755 : Assert(pagefrz->freeze_required);
6756 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
6757 0 : frz->frzflags |= XLH_INVALID_XVAC;
6758 : else
6759 0 : frz->frzflags |= XLH_FREEZE_XVAC;
6760 : }
6761 : if (replace_xmax)
6762 : {
6763 : Assert(!xmax_already_frozen && !freeze_xmax);
6764 : Assert(pagefrz->freeze_required);
6765 :
6766 : /* Already set replace_xmax flags in freeze plan earlier */
6767 : }
6768 6168824 : if (freeze_xmax)
6769 : {
6770 : Assert(!xmax_already_frozen && !replace_xmax);
6771 :
6772 2150 : frz->xmax = InvalidTransactionId;
6773 :
6774 : /*
6775 : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
6776 : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
6777 : * Also get rid of the HEAP_KEYS_UPDATED bit.
6778 : */
6779 2150 : frz->t_infomask &= ~HEAP_XMAX_BITS;
6780 2150 : frz->t_infomask |= HEAP_XMAX_INVALID;
6781 2150 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
6782 2150 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6783 : }
6784 :
6785 : /*
6786 : * Determine if this tuple is already totally frozen, or will become
6787 : * totally frozen (provided caller executes freeze plans for the page)
6788 : */
6789 11169530 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
6790 5000706 : (freeze_xmax || xmax_already_frozen));
6791 :
6792 6168824 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
6793 : xmax_already_frozen))
6794 : {
6795 : /*
6796 : * So far no previous tuple from the page made freezing mandatory.
6797 : * Does this tuple force caller to freeze the entire page?
6798 : */
6799 2794066 : pagefrz->freeze_required =
6800 2794066 : heap_tuple_should_freeze(tuple, cutoffs,
6801 : &pagefrz->NoFreezePageRelfrozenXid,
6802 : &pagefrz->NoFreezePageRelminMxid);
6803 : }
6804 :
6805 : /* Tell caller if this tuple has a usable freeze plan set in *frz */
6806 6168824 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
6807 : }
6808 :
6809 : /*
6810 : * heap_execute_freeze_tuple
6811 : * Execute the prepared freezing of a tuple with caller's freeze plan.
6812 : *
6813 : * Caller is responsible for ensuring that no other backend can access the
6814 : * storage underlying this tuple, either by holding an exclusive lock on the
6815 : * buffer containing it (which is what lazy VACUUM does), or by having it be
6816 : * in private storage (which is what CLUSTER and friends do).
6817 : */
6818 : static inline void
6819 1456214 : heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
6820 : {
6821 1456214 : HeapTupleHeaderSetXmax(tuple, frz->xmax);
6822 :
6823 1456214 : if (frz->frzflags & XLH_FREEZE_XVAC)
6824 0 : HeapTupleHeaderSetXvac(tuple, FrozenTransactionId);
6825 :
6826 1456214 : if (frz->frzflags & XLH_INVALID_XVAC)
6827 0 : HeapTupleHeaderSetXvac(tuple, InvalidTransactionId);
6828 :
6829 1456214 : tuple->t_infomask = frz->t_infomask;
6830 1456214 : tuple->t_infomask2 = frz->t_infomask2;
6831 1456214 : }
6832 :
6833 : /*
6834 : * Perform xmin/xmax XID status sanity checks before actually executing freeze
6835 : * plans.
6836 : *
6837 : * heap_prepare_freeze_tuple doesn't perform these checks directly because
6838 : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
6839 : * successive VACUUMs that each decide against freezing the same page.
6840 : */
6841 : void
6842 21830 : heap_pre_freeze_checks(Buffer buffer,
6843 : HeapTupleFreeze *tuples, int ntuples)
6844 : {
6845 21830 : Page page = BufferGetPage(buffer);
6846 :
6847 967900 : for (int i = 0; i < ntuples; i++)
6848 : {
6849 946070 : HeapTupleFreeze *frz = tuples + i;
6850 946070 : ItemId itemid = PageGetItemId(page, frz->offset);
6851 : HeapTupleHeader htup;
6852 :
6853 946070 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
6854 :
6855 : /* Deliberately avoid relying on tuple hint bits here */
6856 946070 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
6857 : {
6858 946068 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
6859 :
6860 : Assert(!HeapTupleHeaderXminFrozen(htup));
6861 946068 : if (unlikely(!TransactionIdDidCommit(xmin)))
6862 0 : ereport(ERROR,
6863 : (errcode(ERRCODE_DATA_CORRUPTED),
6864 : errmsg_internal("uncommitted xmin %u needs to be frozen",
6865 : xmin)));
6866 : }
6867 :
6868 : /*
6869 : * TransactionIdDidAbort won't work reliably in the presence of XIDs
6870 : * left behind by transactions that were in progress during a crash,
6871 : * so we can only check that xmax didn't commit
6872 : */
6873 946070 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
6874 : {
6875 34 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
6876 :
6877 : Assert(TransactionIdIsNormal(xmax));
6878 34 : if (unlikely(TransactionIdDidCommit(xmax)))
6879 0 : ereport(ERROR,
6880 : (errcode(ERRCODE_DATA_CORRUPTED),
6881 : errmsg_internal("cannot freeze committed xmax %u",
6882 : xmax)));
6883 : }
6884 : }
6885 21830 : }
6886 :
6887 : /*
6888 : * Helper which executes freezing of one or more heap tuples on a page on
6889 : * behalf of caller. Caller passes an array of tuple plans from
6890 : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
6891 : * Must be called in a critical section that also marks the buffer dirty and,
6892 : * if needed, emits WAL.
6893 : */
6894 : void
6895 21830 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
6896 : {
6897 21830 : Page page = BufferGetPage(buffer);
6898 :
6899 967900 : for (int i = 0; i < ntuples; i++)
6900 : {
6901 946070 : HeapTupleFreeze *frz = tuples + i;
6902 946070 : ItemId itemid = PageGetItemId(page, frz->offset);
6903 : HeapTupleHeader htup;
6904 :
6905 946070 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
6906 946070 : heap_execute_freeze_tuple(htup, frz);
6907 : }
6908 21830 : }
6909 :
6910 : /*
6911 : * heap_freeze_tuple
6912 : * Freeze tuple in place, without WAL logging.
6913 : *
6914 : * Useful for callers like CLUSTER that perform their own WAL logging.
6915 : */
6916 : bool
6917 716204 : heap_freeze_tuple(HeapTupleHeader tuple,
6918 : TransactionId relfrozenxid, TransactionId relminmxid,
6919 : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
6920 : {
6921 : HeapTupleFreeze frz;
6922 : bool do_freeze;
6923 : bool totally_frozen;
6924 : struct VacuumCutoffs cutoffs;
6925 : HeapPageFreeze pagefrz;
6926 :
6927 716204 : cutoffs.relfrozenxid = relfrozenxid;
6928 716204 : cutoffs.relminmxid = relminmxid;
6929 716204 : cutoffs.OldestXmin = FreezeLimit;
6930 716204 : cutoffs.OldestMxact = MultiXactCutoff;
6931 716204 : cutoffs.FreezeLimit = FreezeLimit;
6932 716204 : cutoffs.MultiXactCutoff = MultiXactCutoff;
6933 :
6934 716204 : pagefrz.freeze_required = true;
6935 716204 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
6936 716204 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
6937 716204 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
6938 716204 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
6939 :
6940 716204 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
6941 : &pagefrz, &frz, &totally_frozen);
6942 :
6943 : /*
6944 : * Note that because this is not a WAL-logged operation, we don't need to
6945 : * fill in the offset in the freeze record.
6946 : */
6947 :
6948 716204 : if (do_freeze)
6949 506676 : heap_execute_freeze_tuple(tuple, &frz);
6950 716204 : return do_freeze;
6951 : }
6952 :
6953 : /*
6954 : * For a given MultiXactId, return the hint bits that should be set in the
6955 : * tuple's infomask.
6956 : *
6957 : * Normally this should be called for a multixact that was just created, and
6958 : * so is on our local cache, so the GetMembers call is fast.
6959 : */
6960 : static void
6961 2358 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
6962 : uint16 *new_infomask2)
6963 : {
6964 : int nmembers;
6965 : MultiXactMember *members;
6966 : int i;
6967 2358 : uint16 bits = HEAP_XMAX_IS_MULTI;
6968 2358 : uint16 bits2 = 0;
6969 2358 : bool has_update = false;
6970 2358 : LockTupleMode strongest = LockTupleKeyShare;
6971 :
6972 : /*
6973 : * We only use this in multis we just created, so they cannot be values
6974 : * pre-pg_upgrade.
6975 : */
6976 2358 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
6977 :
6978 7214 : for (i = 0; i < nmembers; i++)
6979 : {
6980 : LockTupleMode mode;
6981 :
6982 : /*
6983 : * Remember the strongest lock mode held by any member of the
6984 : * multixact.
6985 : */
6986 4856 : mode = TUPLOCK_from_mxstatus(members[i].status);
6987 4856 : if (mode > strongest)
6988 1312 : strongest = mode;
6989 :
6990 : /* See what other bits we need */
6991 4856 : switch (members[i].status)
6992 : {
6993 4474 : case MultiXactStatusForKeyShare:
6994 : case MultiXactStatusForShare:
6995 : case MultiXactStatusForNoKeyUpdate:
6996 4474 : break;
6997 :
6998 104 : case MultiXactStatusForUpdate:
6999 104 : bits2 |= HEAP_KEYS_UPDATED;
7000 104 : break;
7001 :
7002 258 : case MultiXactStatusNoKeyUpdate:
7003 258 : has_update = true;
7004 258 : break;
7005 :
7006 20 : case MultiXactStatusUpdate:
7007 20 : bits2 |= HEAP_KEYS_UPDATED;
7008 20 : has_update = true;
7009 20 : break;
7010 : }
7011 4856 : }
7012 :
7013 2358 : if (strongest == LockTupleExclusive ||
7014 : strongest == LockTupleNoKeyExclusive)
7015 432 : bits |= HEAP_XMAX_EXCL_LOCK;
7016 1926 : else if (strongest == LockTupleShare)
7017 874 : bits |= HEAP_XMAX_SHR_LOCK;
7018 1052 : else if (strongest == LockTupleKeyShare)
7019 1052 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7020 :
7021 2358 : if (!has_update)
7022 2080 : bits |= HEAP_XMAX_LOCK_ONLY;
7023 :
7024 2358 : if (nmembers > 0)
7025 2358 : pfree(members);
7026 :
7027 2358 : *new_infomask = bits;
7028 2358 : *new_infomask2 = bits2;
7029 2358 : }
7030 :
7031 : /*
7032 : * MultiXactIdGetUpdateXid
7033 : *
7034 : * Given a multixact Xmax and corresponding infomask, which does not have the
7035 : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7036 : * transaction.
7037 : *
7038 : * Caller is expected to check the status of the updating transaction, if
7039 : * necessary.
7040 : */
7041 : static TransactionId
7042 1026 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7043 : {
7044 1026 : TransactionId update_xact = InvalidTransactionId;
7045 : MultiXactMember *members;
7046 : int nmembers;
7047 :
7048 : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7049 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7050 :
7051 : /*
7052 : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7053 : * pre-pg_upgrade.
7054 : */
7055 1026 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7056 :
7057 1026 : if (nmembers > 0)
7058 : {
7059 : int i;
7060 :
7061 2686 : for (i = 0; i < nmembers; i++)
7062 : {
7063 : /* Ignore lockers */
7064 2686 : if (!ISUPDATE_from_mxstatus(members[i].status))
7065 1660 : continue;
7066 :
7067 : /* there can be at most one updater */
7068 : Assert(update_xact == InvalidTransactionId);
7069 1026 : update_xact = members[i].xid;
7070 : #ifndef USE_ASSERT_CHECKING
7071 :
7072 : /*
7073 : * in an assert-enabled build, walk the whole array to ensure
7074 : * there's no other updater.
7075 : */
7076 1026 : break;
7077 : #endif
7078 : }
7079 :
7080 1026 : pfree(members);
7081 : }
7082 :
7083 1026 : return update_xact;
7084 : }
7085 :
7086 : /*
7087 : * HeapTupleGetUpdateXid
7088 : * As above, but use a HeapTupleHeader
7089 : *
7090 : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7091 : * checking the hint bits.
7092 : */
7093 : TransactionId
7094 1010 : HeapTupleGetUpdateXid(HeapTupleHeader tuple)
7095 : {
7096 2020 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tuple),
7097 1010 : tuple->t_infomask);
7098 : }
7099 :
7100 : /*
7101 : * Does the given multixact conflict with the current transaction grabbing a
7102 : * tuple lock of the given strength?
7103 : *
7104 : * The passed infomask pairs up with the given multixact in the tuple header.
7105 : *
7106 : * If current_is_member is not NULL, it is set to 'true' if the current
7107 : * transaction is a member of the given multixact.
7108 : */
7109 : static bool
7110 188 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7111 : LockTupleMode lockmode, bool *current_is_member)
7112 : {
7113 : int nmembers;
7114 : MultiXactMember *members;
7115 188 : bool result = false;
7116 188 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7117 :
7118 188 : if (HEAP_LOCKED_UPGRADED(infomask))
7119 0 : return false;
7120 :
7121 188 : nmembers = GetMultiXactIdMembers(multi, &members, false,
7122 188 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7123 188 : if (nmembers >= 0)
7124 : {
7125 : int i;
7126 :
7127 590 : for (i = 0; i < nmembers; i++)
7128 : {
7129 : TransactionId memxid;
7130 : LOCKMODE memlockmode;
7131 :
7132 414 : if (result && (current_is_member == NULL || *current_is_member))
7133 : break;
7134 :
7135 402 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7136 :
7137 : /* ignore members from current xact (but track their presence) */
7138 402 : memxid = members[i].xid;
7139 402 : if (TransactionIdIsCurrentTransactionId(memxid))
7140 : {
7141 182 : if (current_is_member != NULL)
7142 156 : *current_is_member = true;
7143 182 : continue;
7144 : }
7145 220 : else if (result)
7146 16 : continue;
7147 :
7148 : /* ignore members that don't conflict with the lock we want */
7149 204 : if (!DoLockModesConflict(memlockmode, wanted))
7150 134 : continue;
7151 :
7152 70 : if (ISUPDATE_from_mxstatus(members[i].status))
7153 : {
7154 : /* ignore aborted updaters */
7155 34 : if (TransactionIdDidAbort(memxid))
7156 2 : continue;
7157 : }
7158 : else
7159 : {
7160 : /* ignore lockers-only that are no longer in progress */
7161 36 : if (!TransactionIdIsInProgress(memxid))
7162 10 : continue;
7163 : }
7164 :
7165 : /*
7166 : * Whatever remains are either live lockers that conflict with our
7167 : * wanted lock, and updaters that are not aborted. Those conflict
7168 : * with what we want. Set up to return true, but keep going to
7169 : * look for the current transaction among the multixact members,
7170 : * if needed.
7171 : */
7172 58 : result = true;
7173 : }
7174 188 : pfree(members);
7175 : }
7176 :
7177 188 : return result;
7178 : }
7179 :
7180 : /*
7181 : * Do_MultiXactIdWait
7182 : * Actual implementation for the two functions below.
7183 : *
7184 : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7185 : * needed to ensure we only sleep on conflicting members, and the infomask is
7186 : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7187 : * indicates whether to use conditional lock acquisition, to allow callers to
7188 : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7189 : * context information for error messages. 'remaining', if not NULL, receives
7190 : * the number of members that are still running, including any (non-aborted)
7191 : * subtransactions of our own transaction.
7192 : *
7193 : * We do this by sleeping on each member using XactLockTableWait. Any
7194 : * members that belong to the current backend are *not* waited for, however;
7195 : * this would not merely be useless but would lead to Assert failure inside
7196 : * XactLockTableWait. By the time this returns, it is certain that all
7197 : * transactions *of other backends* that were members of the MultiXactId
7198 : * that conflict with the requested status are dead (and no new ones can have
7199 : * been added, since it is not legal to add members to an existing
7200 : * MultiXactId).
7201 : *
7202 : * But by the time we finish sleeping, someone else may have changed the Xmax
7203 : * of the containing tuple, so the caller needs to iterate on us somehow.
7204 : *
7205 : * Note that in case we return false, the number of remaining members is
7206 : * not to be trusted.
7207 : */
7208 : static bool
7209 112 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7210 : uint16 infomask, bool nowait,
7211 : Relation rel, ItemPointer ctid, XLTW_Oper oper,
7212 : int *remaining)
7213 : {
7214 112 : bool result = true;
7215 : MultiXactMember *members;
7216 : int nmembers;
7217 112 : int remain = 0;
7218 :
7219 : /* for pre-pg_upgrade tuples, no need to sleep at all */
7220 112 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7221 112 : GetMultiXactIdMembers(multi, &members, false,
7222 112 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7223 :
7224 112 : if (nmembers >= 0)
7225 : {
7226 : int i;
7227 :
7228 362 : for (i = 0; i < nmembers; i++)
7229 : {
7230 258 : TransactionId memxid = members[i].xid;
7231 258 : MultiXactStatus memstatus = members[i].status;
7232 :
7233 258 : if (TransactionIdIsCurrentTransactionId(memxid))
7234 : {
7235 48 : remain++;
7236 48 : continue;
7237 : }
7238 :
7239 210 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7240 210 : LOCKMODE_from_mxstatus(status)))
7241 : {
7242 40 : if (remaining && TransactionIdIsInProgress(memxid))
7243 12 : remain++;
7244 40 : continue;
7245 : }
7246 :
7247 : /*
7248 : * This member conflicts with our multi, so we have to sleep (or
7249 : * return failure, if asked to avoid waiting.)
7250 : *
7251 : * Note that we don't set up an error context callback ourselves,
7252 : * but instead we pass the info down to XactLockTableWait. This
7253 : * might seem a bit wasteful because the context is set up and
7254 : * tore down for each member of the multixact, but in reality it
7255 : * should be barely noticeable, and it avoids duplicate code.
7256 : */
7257 170 : if (nowait)
7258 : {
7259 8 : result = ConditionalXactLockTableWait(memxid);
7260 8 : if (!result)
7261 8 : break;
7262 : }
7263 : else
7264 162 : XactLockTableWait(memxid, rel, ctid, oper);
7265 : }
7266 :
7267 112 : pfree(members);
7268 : }
7269 :
7270 112 : if (remaining)
7271 16 : *remaining = remain;
7272 :
7273 112 : return result;
7274 : }
7275 :
7276 : /*
7277 : * MultiXactIdWait
7278 : * Sleep on a MultiXactId.
7279 : *
7280 : * By the time we finish sleeping, someone else may have changed the Xmax
7281 : * of the containing tuple, so the caller needs to iterate on us somehow.
7282 : *
7283 : * We return (in *remaining, if not NULL) the number of members that are still
7284 : * running, including any (non-aborted) subtransactions of our own transaction.
7285 : */
7286 : static void
7287 104 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
7288 : Relation rel, ItemPointer ctid, XLTW_Oper oper,
7289 : int *remaining)
7290 : {
7291 104 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
7292 : rel, ctid, oper, remaining);
7293 104 : }
7294 :
7295 : /*
7296 : * ConditionalMultiXactIdWait
7297 : * As above, but only lock if we can get the lock without blocking.
7298 : *
7299 : * By the time we finish sleeping, someone else may have changed the Xmax
7300 : * of the containing tuple, so the caller needs to iterate on us somehow.
7301 : *
7302 : * If the multixact is now all gone, return true. Returns false if some
7303 : * transactions might still be running.
7304 : *
7305 : * We return (in *remaining, if not NULL) the number of members that are still
7306 : * running, including any (non-aborted) subtransactions of our own transaction.
7307 : */
7308 : static bool
7309 8 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7310 : uint16 infomask, Relation rel, int *remaining)
7311 : {
7312 8 : return Do_MultiXactIdWait(multi, status, infomask, true,
7313 : rel, NULL, XLTW_None, remaining);
7314 : }
7315 :
7316 : /*
7317 : * heap_tuple_needs_eventual_freeze
7318 : *
7319 : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7320 : * will eventually require freezing (if tuple isn't removed by pruning first).
7321 : */
7322 : bool
7323 159922 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
7324 : {
7325 : TransactionId xid;
7326 :
7327 : /*
7328 : * If xmin is a normal transaction ID, this tuple is definitely not
7329 : * frozen.
7330 : */
7331 159922 : xid = HeapTupleHeaderGetXmin(tuple);
7332 159922 : if (TransactionIdIsNormal(xid))
7333 4146 : return true;
7334 :
7335 : /*
7336 : * If xmax is a valid xact or multixact, this tuple is also not frozen.
7337 : */
7338 155776 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7339 : {
7340 : MultiXactId multi;
7341 :
7342 0 : multi = HeapTupleHeaderGetRawXmax(tuple);
7343 0 : if (MultiXactIdIsValid(multi))
7344 0 : return true;
7345 : }
7346 : else
7347 : {
7348 155776 : xid = HeapTupleHeaderGetRawXmax(tuple);
7349 155776 : if (TransactionIdIsNormal(xid))
7350 2 : return true;
7351 : }
7352 :
7353 155774 : if (tuple->t_infomask & HEAP_MOVED)
7354 : {
7355 0 : xid = HeapTupleHeaderGetXvac(tuple);
7356 0 : if (TransactionIdIsNormal(xid))
7357 0 : return true;
7358 : }
7359 :
7360 155774 : return false;
7361 : }
7362 :
7363 : /*
7364 : * heap_tuple_should_freeze
7365 : *
7366 : * Return value indicates if heap_prepare_freeze_tuple sibling function would
7367 : * (or should) force freezing of the heap page that contains caller's tuple.
7368 : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
7369 : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
7370 : *
7371 : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
7372 : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
7373 : * Our working assumption is that caller won't decide to freeze this tuple.
7374 : * It's up to caller to only ratchet back its own top-level trackers after the
7375 : * point that it fully commits to not freezing the tuple/page in question.
7376 : */
7377 : bool
7378 2794238 : heap_tuple_should_freeze(HeapTupleHeader tuple,
7379 : const struct VacuumCutoffs *cutoffs,
7380 : TransactionId *NoFreezePageRelfrozenXid,
7381 : MultiXactId *NoFreezePageRelminMxid)
7382 : {
7383 : TransactionId xid;
7384 : MultiXactId multi;
7385 2794238 : bool freeze = false;
7386 :
7387 : /* First deal with xmin */
7388 2794238 : xid = HeapTupleHeaderGetXmin(tuple);
7389 2794238 : if (TransactionIdIsNormal(xid))
7390 : {
7391 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7392 2793850 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7393 23202 : *NoFreezePageRelfrozenXid = xid;
7394 2793850 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7395 21698 : freeze = true;
7396 : }
7397 :
7398 : /* Now deal with xmax */
7399 2794238 : xid = InvalidTransactionId;
7400 2794238 : multi = InvalidMultiXactId;
7401 2794238 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7402 4 : multi = HeapTupleHeaderGetRawXmax(tuple);
7403 : else
7404 2794234 : xid = HeapTupleHeaderGetRawXmax(tuple);
7405 :
7406 2794238 : if (TransactionIdIsNormal(xid))
7407 : {
7408 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7409 : /* xmax is a non-permanent XID */
7410 473198 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7411 0 : *NoFreezePageRelfrozenXid = xid;
7412 473198 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7413 2 : freeze = true;
7414 : }
7415 2321040 : else if (!MultiXactIdIsValid(multi))
7416 : {
7417 : /* xmax is a permanent XID or invalid MultiXactId/XID */
7418 : }
7419 4 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7420 : {
7421 : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
7422 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7423 0 : *NoFreezePageRelminMxid = multi;
7424 : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
7425 0 : freeze = true;
7426 : }
7427 : else
7428 : {
7429 : /* xmax is a MultiXactId that may have an updater XID */
7430 : MultiXactMember *members;
7431 : int nmembers;
7432 :
7433 : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
7434 4 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7435 4 : *NoFreezePageRelminMxid = multi;
7436 4 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
7437 4 : freeze = true;
7438 :
7439 : /* need to check whether any member of the mxact is old */
7440 4 : nmembers = GetMultiXactIdMembers(multi, &members, false,
7441 4 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
7442 :
7443 10 : for (int i = 0; i < nmembers; i++)
7444 : {
7445 6 : xid = members[i].xid;
7446 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7447 6 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7448 0 : *NoFreezePageRelfrozenXid = xid;
7449 6 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7450 0 : freeze = true;
7451 : }
7452 4 : if (nmembers > 0)
7453 2 : pfree(members);
7454 : }
7455 :
7456 2794238 : if (tuple->t_infomask & HEAP_MOVED)
7457 : {
7458 0 : xid = HeapTupleHeaderGetXvac(tuple);
7459 0 : if (TransactionIdIsNormal(xid))
7460 : {
7461 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7462 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7463 0 : *NoFreezePageRelfrozenXid = xid;
7464 : /* heap_prepare_freeze_tuple forces xvac freezing */
7465 0 : freeze = true;
7466 : }
7467 : }
7468 :
7469 2794238 : return freeze;
7470 : }
7471 :
7472 : /*
7473 : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
7474 : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
7475 : * that caller is in the process of physically removing, e.g. via HOT pruning
7476 : * or index deletion.
7477 : *
7478 : * Caller must initialize its value to InvalidTransactionId, which is
7479 : * generally interpreted as "definitely no need for a recovery conflict".
7480 : * Final value must reflect all heap tuples that caller will physically remove
7481 : * (or remove TID references to) via its ongoing pruning/deletion operation.
7482 : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
7483 : * caller's WAL record) by REDO routine when it replays caller's operation.
7484 : */
7485 : void
7486 2838080 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
7487 : TransactionId *snapshotConflictHorizon)
7488 : {
7489 2838080 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
7490 2838080 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
7491 2838080 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
7492 :
7493 2838080 : if (tuple->t_infomask & HEAP_MOVED)
7494 : {
7495 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
7496 0 : *snapshotConflictHorizon = xvac;
7497 : }
7498 :
7499 : /*
7500 : * Ignore tuples inserted by an aborted transaction or if the tuple was
7501 : * updated/deleted by the inserting transaction.
7502 : *
7503 : * Look for a committed hint bit, or if no xmin bit is set, check clog.
7504 : */
7505 2838080 : if (HeapTupleHeaderXminCommitted(tuple) ||
7506 188938 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
7507 : {
7508 5064106 : if (xmax != xmin &&
7509 2364994 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
7510 164240 : *snapshotConflictHorizon = xmax;
7511 : }
7512 2838080 : }
7513 :
7514 : #ifdef USE_PREFETCH
7515 : /*
7516 : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
7517 : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
7518 : * we can prefetch, and which have already been prefetched; each call to this
7519 : * function picks up where the previous call left off.
7520 : *
7521 : * Note: we expect the deltids array to be sorted in an order that groups TIDs
7522 : * by heap block, with all TIDs for each block appearing together in exactly
7523 : * one group.
7524 : */
7525 : static void
7526 34740 : index_delete_prefetch_buffer(Relation rel,
7527 : IndexDeletePrefetchState *prefetch_state,
7528 : int prefetch_count)
7529 : {
7530 34740 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
7531 34740 : int count = 0;
7532 : int i;
7533 34740 : int ndeltids = prefetch_state->ndeltids;
7534 34740 : TM_IndexDelete *deltids = prefetch_state->deltids;
7535 :
7536 1221270 : for (i = prefetch_state->next_item;
7537 1194200 : i < ndeltids && count < prefetch_count;
7538 1186530 : i++)
7539 : {
7540 1186530 : ItemPointer htid = &deltids[i].tid;
7541 :
7542 2362460 : if (cur_hblkno == InvalidBlockNumber ||
7543 1175930 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
7544 : {
7545 31298 : cur_hblkno = ItemPointerGetBlockNumber(htid);
7546 31298 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
7547 31298 : count++;
7548 : }
7549 : }
7550 :
7551 : /*
7552 : * Save the prefetch position so that next time we can continue from that
7553 : * position.
7554 : */
7555 34740 : prefetch_state->next_item = i;
7556 34740 : prefetch_state->cur_hblkno = cur_hblkno;
7557 34740 : }
7558 : #endif
7559 :
7560 : /*
7561 : * Helper function for heap_index_delete_tuples. Checks for index corruption
7562 : * involving an invalid TID in index AM caller's index page.
7563 : *
7564 : * This is an ideal place for these checks. The index AM must hold a buffer
7565 : * lock on the index page containing the TIDs we examine here, so we don't
7566 : * have to worry about concurrent VACUUMs at all. We can be sure that the
7567 : * index is corrupt when htid points directly to an LP_UNUSED item or
7568 : * heap-only tuple, which is not the case during standard index scans.
7569 : */
7570 : static inline void
7571 989234 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
7572 : Page page, OffsetNumber maxoff,
7573 : ItemPointer htid, TM_IndexStatus *istatus)
7574 : {
7575 989234 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
7576 : ItemId iid;
7577 :
7578 : Assert(OffsetNumberIsValid(istatus->idxoffnum));
7579 :
7580 989234 : if (unlikely(indexpagehoffnum > maxoff))
7581 0 : ereport(ERROR,
7582 : (errcode(ERRCODE_INDEX_CORRUPTED),
7583 : errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
7584 : ItemPointerGetBlockNumber(htid),
7585 : indexpagehoffnum,
7586 : istatus->idxoffnum, delstate->iblknum,
7587 : RelationGetRelationName(delstate->irel))));
7588 :
7589 989234 : iid = PageGetItemId(page, indexpagehoffnum);
7590 989234 : if (unlikely(!ItemIdIsUsed(iid)))
7591 0 : ereport(ERROR,
7592 : (errcode(ERRCODE_INDEX_CORRUPTED),
7593 : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
7594 : ItemPointerGetBlockNumber(htid),
7595 : indexpagehoffnum,
7596 : istatus->idxoffnum, delstate->iblknum,
7597 : RelationGetRelationName(delstate->irel))));
7598 :
7599 989234 : if (ItemIdHasStorage(iid))
7600 : {
7601 : HeapTupleHeader htup;
7602 :
7603 : Assert(ItemIdIsNormal(iid));
7604 579150 : htup = (HeapTupleHeader) PageGetItem(page, iid);
7605 :
7606 579150 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
7607 0 : ereport(ERROR,
7608 : (errcode(ERRCODE_INDEX_CORRUPTED),
7609 : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
7610 : ItemPointerGetBlockNumber(htid),
7611 : indexpagehoffnum,
7612 : istatus->idxoffnum, delstate->iblknum,
7613 : RelationGetRelationName(delstate->irel))));
7614 : }
7615 989234 : }
7616 :
7617 : /*
7618 : * heapam implementation of tableam's index_delete_tuples interface.
7619 : *
7620 : * This helper function is called by index AMs during index tuple deletion.
7621 : * See tableam header comments for an explanation of the interface implemented
7622 : * here and a general theory of operation. Note that each call here is either
7623 : * a simple index deletion call, or a bottom-up index deletion call.
7624 : *
7625 : * It's possible for this to generate a fair amount of I/O, since we may be
7626 : * deleting hundreds of tuples from a single index block. To amortize that
7627 : * cost to some degree, this uses prefetching and combines repeat accesses to
7628 : * the same heap block.
7629 : */
7630 : TransactionId
7631 10600 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
7632 : {
7633 : /* Initial assumption is that earlier pruning took care of conflict */
7634 10600 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
7635 10600 : BlockNumber blkno = InvalidBlockNumber;
7636 10600 : Buffer buf = InvalidBuffer;
7637 10600 : Page page = NULL;
7638 10600 : OffsetNumber maxoff = InvalidOffsetNumber;
7639 : TransactionId priorXmax;
7640 : #ifdef USE_PREFETCH
7641 : IndexDeletePrefetchState prefetch_state;
7642 : int prefetch_distance;
7643 : #endif
7644 : SnapshotData SnapshotNonVacuumable;
7645 10600 : int finalndeltids = 0,
7646 10600 : nblocksaccessed = 0;
7647 :
7648 : /* State that's only used in bottom-up index deletion case */
7649 10600 : int nblocksfavorable = 0;
7650 10600 : int curtargetfreespace = delstate->bottomupfreespace,
7651 10600 : lastfreespace = 0,
7652 10600 : actualfreespace = 0;
7653 10600 : bool bottomup_final_block = false;
7654 :
7655 10600 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7656 :
7657 : /* Sort caller's deltids array by TID for further processing */
7658 10600 : index_delete_sort(delstate);
7659 :
7660 : /*
7661 : * Bottom-up case: resort deltids array in an order attuned to where the
7662 : * greatest number of promising TIDs are to be found, and determine how
7663 : * many blocks from the start of sorted array should be considered
7664 : * favorable. This will also shrink the deltids array in order to
7665 : * eliminate completely unfavorable blocks up front.
7666 : */
7667 10600 : if (delstate->bottomup)
7668 3630 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
7669 :
7670 : #ifdef USE_PREFETCH
7671 : /* Initialize prefetch state. */
7672 10600 : prefetch_state.cur_hblkno = InvalidBlockNumber;
7673 10600 : prefetch_state.next_item = 0;
7674 10600 : prefetch_state.ndeltids = delstate->ndeltids;
7675 10600 : prefetch_state.deltids = delstate->deltids;
7676 :
7677 : /*
7678 : * Determine the prefetch distance that we will attempt to maintain.
7679 : *
7680 : * Since the caller holds a buffer lock somewhere in rel, we'd better make
7681 : * sure that isn't a catalog relation before we call code that does
7682 : * syscache lookups, to avoid risk of deadlock.
7683 : */
7684 10600 : if (IsCatalogRelation(rel))
7685 7366 : prefetch_distance = maintenance_io_concurrency;
7686 : else
7687 : prefetch_distance =
7688 3234 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
7689 :
7690 : /* Cap initial prefetch distance for bottom-up deletion caller */
7691 10600 : if (delstate->bottomup)
7692 : {
7693 : Assert(nblocksfavorable >= 1);
7694 : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
7695 3630 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
7696 : }
7697 :
7698 : /* Start prefetching. */
7699 10600 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
7700 : #endif
7701 :
7702 : /* Iterate over deltids, determine which to delete, check their horizon */
7703 : Assert(delstate->ndeltids > 0);
7704 999834 : for (int i = 0; i < delstate->ndeltids; i++)
7705 : {
7706 992864 : TM_IndexDelete *ideltid = &delstate->deltids[i];
7707 992864 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
7708 992864 : ItemPointer htid = &ideltid->tid;
7709 : OffsetNumber offnum;
7710 :
7711 : /*
7712 : * Read buffer, and perform required extra steps each time a new block
7713 : * is encountered. Avoid refetching if it's the same block as the one
7714 : * from the last htid.
7715 : */
7716 1975128 : if (blkno == InvalidBlockNumber ||
7717 982264 : ItemPointerGetBlockNumber(htid) != blkno)
7718 : {
7719 : /*
7720 : * Consider giving up early for bottom-up index deletion caller
7721 : * first. (Only prefetch next-next block afterwards, when it
7722 : * becomes clear that we're at least going to access the next
7723 : * block in line.)
7724 : *
7725 : * Sometimes the first block frees so much space for bottom-up
7726 : * caller that the deletion process can end without accessing any
7727 : * more blocks. It is usually necessary to access 2 or 3 blocks
7728 : * per bottom-up deletion operation, though.
7729 : */
7730 27770 : if (delstate->bottomup)
7731 : {
7732 : /*
7733 : * We often allow caller to delete a few additional items
7734 : * whose entries we reached after the point that space target
7735 : * from caller was satisfied. The cost of accessing the page
7736 : * was already paid at that point, so it made sense to finish
7737 : * it off. When that happened, we finalize everything here
7738 : * (by finishing off the whole bottom-up deletion operation
7739 : * without needlessly paying the cost of accessing any more
7740 : * blocks).
7741 : */
7742 7892 : if (bottomup_final_block)
7743 324 : break;
7744 :
7745 : /*
7746 : * Give up when we didn't enable our caller to free any
7747 : * additional space as a result of processing the page that we
7748 : * just finished up with. This rule is the main way in which
7749 : * we keep the cost of bottom-up deletion under control.
7750 : */
7751 7568 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
7752 3306 : break;
7753 4262 : lastfreespace = actualfreespace; /* for next time */
7754 :
7755 : /*
7756 : * Deletion operation (which is bottom-up) will definitely
7757 : * access the next block in line. Prepare for that now.
7758 : *
7759 : * Decay target free space so that we don't hang on for too
7760 : * long with a marginal case. (Space target is only truly
7761 : * helpful when it allows us to recognize that we don't need
7762 : * to access more than 1 or 2 blocks to satisfy caller due to
7763 : * agreeable workload characteristics.)
7764 : *
7765 : * We are a bit more patient when we encounter contiguous
7766 : * blocks, though: these are treated as favorable blocks. The
7767 : * decay process is only applied when the next block in line
7768 : * is not a favorable/contiguous block. This is not an
7769 : * exception to the general rule; we still insist on finding
7770 : * at least one deletable item per block accessed. See
7771 : * bottomup_nblocksfavorable() for full details of the theory
7772 : * behind favorable blocks and heap block locality in general.
7773 : *
7774 : * Note: The first block in line is always treated as a
7775 : * favorable block, so the earliest possible point that the
7776 : * decay can be applied is just before we access the second
7777 : * block in line. The Assert() verifies this for us.
7778 : */
7779 : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
7780 4262 : if (nblocksfavorable > 0)
7781 3902 : nblocksfavorable--;
7782 : else
7783 360 : curtargetfreespace /= 2;
7784 : }
7785 :
7786 : /* release old buffer */
7787 24140 : if (BufferIsValid(buf))
7788 13540 : UnlockReleaseBuffer(buf);
7789 :
7790 24140 : blkno = ItemPointerGetBlockNumber(htid);
7791 24140 : buf = ReadBuffer(rel, blkno);
7792 24140 : nblocksaccessed++;
7793 : Assert(!delstate->bottomup ||
7794 : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
7795 :
7796 : #ifdef USE_PREFETCH
7797 :
7798 : /*
7799 : * To maintain the prefetch distance, prefetch one more page for
7800 : * each page we read.
7801 : */
7802 24140 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
7803 : #endif
7804 :
7805 24140 : LockBuffer(buf, BUFFER_LOCK_SHARE);
7806 :
7807 24140 : page = BufferGetPage(buf);
7808 24140 : maxoff = PageGetMaxOffsetNumber(page);
7809 : }
7810 :
7811 : /*
7812 : * In passing, detect index corruption involving an index page with a
7813 : * TID that points to a location in the heap that couldn't possibly be
7814 : * correct. We only do this with actual TIDs from caller's index page
7815 : * (not items reached by traversing through a HOT chain).
7816 : */
7817 989234 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
7818 :
7819 989234 : if (istatus->knowndeletable)
7820 : Assert(!delstate->bottomup && !istatus->promising);
7821 : else
7822 : {
7823 736906 : ItemPointerData tmp = *htid;
7824 : HeapTupleData heapTuple;
7825 :
7826 : /* Are any tuples from this HOT chain non-vacuumable? */
7827 736906 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
7828 : &heapTuple, NULL, true))
7829 446408 : continue; /* can't delete entry */
7830 :
7831 : /* Caller will delete, since whole HOT chain is vacuumable */
7832 290498 : istatus->knowndeletable = true;
7833 :
7834 : /* Maintain index free space info for bottom-up deletion case */
7835 290498 : if (delstate->bottomup)
7836 : {
7837 : Assert(istatus->freespace > 0);
7838 17142 : actualfreespace += istatus->freespace;
7839 17142 : if (actualfreespace >= curtargetfreespace)
7840 4888 : bottomup_final_block = true;
7841 : }
7842 : }
7843 :
7844 : /*
7845 : * Maintain snapshotConflictHorizon value for deletion operation as a
7846 : * whole by advancing current value using heap tuple headers. This is
7847 : * loosely based on the logic for pruning a HOT chain.
7848 : */
7849 542826 : offnum = ItemPointerGetOffsetNumber(htid);
7850 542826 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
7851 : for (;;)
7852 39440 : {
7853 : ItemId lp;
7854 : HeapTupleHeader htup;
7855 :
7856 : /* Sanity check (pure paranoia) */
7857 582266 : if (offnum < FirstOffsetNumber)
7858 0 : break;
7859 :
7860 : /*
7861 : * An offset past the end of page's line pointer array is possible
7862 : * when the array was truncated
7863 : */
7864 582266 : if (offnum > maxoff)
7865 0 : break;
7866 :
7867 582266 : lp = PageGetItemId(page, offnum);
7868 582266 : if (ItemIdIsRedirected(lp))
7869 : {
7870 17742 : offnum = ItemIdGetRedirect(lp);
7871 17742 : continue;
7872 : }
7873 :
7874 : /*
7875 : * We'll often encounter LP_DEAD line pointers (especially with an
7876 : * entry marked knowndeletable by our caller up front). No heap
7877 : * tuple headers get examined for an htid that leads us to an
7878 : * LP_DEAD item. This is okay because the earlier pruning
7879 : * operation that made the line pointer LP_DEAD in the first place
7880 : * must have considered the original tuple header as part of
7881 : * generating its own snapshotConflictHorizon value.
7882 : *
7883 : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
7884 : * the same strategy that index vacuuming uses in all cases. Index
7885 : * VACUUM WAL records don't even have a snapshotConflictHorizon
7886 : * field of their own for this reason.
7887 : */
7888 564524 : if (!ItemIdIsNormal(lp))
7889 366846 : break;
7890 :
7891 197678 : htup = (HeapTupleHeader) PageGetItem(page, lp);
7892 :
7893 : /*
7894 : * Check the tuple XMIN against prior XMAX, if any
7895 : */
7896 219376 : if (TransactionIdIsValid(priorXmax) &&
7897 21698 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
7898 0 : break;
7899 :
7900 197678 : HeapTupleHeaderAdvanceConflictHorizon(htup,
7901 : &snapshotConflictHorizon);
7902 :
7903 : /*
7904 : * If the tuple is not HOT-updated, then we are at the end of this
7905 : * HOT-chain. No need to visit later tuples from the same update
7906 : * chain (they get their own index entries) -- just move on to
7907 : * next htid from index AM caller.
7908 : */
7909 197678 : if (!HeapTupleHeaderIsHotUpdated(htup))
7910 : break;
7911 :
7912 : /* Advance to next HOT chain member */
7913 : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
7914 21698 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
7915 21698 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
7916 : }
7917 :
7918 : /* Enable further/final shrinking of deltids for caller */
7919 542826 : finalndeltids = i + 1;
7920 : }
7921 :
7922 10600 : UnlockReleaseBuffer(buf);
7923 :
7924 : /*
7925 : * Shrink deltids array to exclude non-deletable entries at the end. This
7926 : * is not just a minor optimization. Final deltids array size might be
7927 : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
7928 : * ndeltids being zero in all cases with zero total deletable entries.
7929 : */
7930 : Assert(finalndeltids > 0 || delstate->bottomup);
7931 10600 : delstate->ndeltids = finalndeltids;
7932 :
7933 10600 : return snapshotConflictHorizon;
7934 : }
7935 :
7936 : /*
7937 : * Specialized inlineable comparison function for index_delete_sort()
7938 : */
7939 : static inline int
7940 23851022 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
7941 : {
7942 23851022 : ItemPointer tid1 = &deltid1->tid;
7943 23851022 : ItemPointer tid2 = &deltid2->tid;
7944 :
7945 : {
7946 23851022 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
7947 23851022 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
7948 :
7949 23851022 : if (blk1 != blk2)
7950 9800566 : return (blk1 < blk2) ? -1 : 1;
7951 : }
7952 : {
7953 14050456 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
7954 14050456 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
7955 :
7956 14050456 : if (pos1 != pos2)
7957 14050456 : return (pos1 < pos2) ? -1 : 1;
7958 : }
7959 :
7960 : Assert(false);
7961 :
7962 0 : return 0;
7963 : }
7964 :
7965 : /*
7966 : * Sort deltids array from delstate by TID. This prepares it for further
7967 : * processing by heap_index_delete_tuples().
7968 : *
7969 : * This operation becomes a noticeable consumer of CPU cycles with some
7970 : * workloads, so we go to the trouble of specialization/micro optimization.
7971 : * We use shellsort for this because it's easy to specialize, compiles to
7972 : * relatively few instructions, and is adaptive to presorted inputs/subsets
7973 : * (which are typical here).
7974 : */
7975 : static void
7976 10600 : index_delete_sort(TM_IndexDeleteOp *delstate)
7977 : {
7978 10600 : TM_IndexDelete *deltids = delstate->deltids;
7979 10600 : int ndeltids = delstate->ndeltids;
7980 10600 : int low = 0;
7981 :
7982 : /*
7983 : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
7984 : *
7985 : * This implementation is fast with array sizes up to ~4500. This covers
7986 : * all supported BLCKSZ values.
7987 : */
7988 10600 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
7989 :
7990 : /* Think carefully before changing anything here -- keep swaps cheap */
7991 : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
7992 : "element size exceeds 8 bytes");
7993 :
7994 106000 : for (int g = 0; g < lengthof(gaps); g++)
7995 : {
7996 14299524 : for (int hi = gaps[g], i = low + hi; i < ndeltids; i++)
7997 : {
7998 14204124 : TM_IndexDelete d = deltids[i];
7999 14204124 : int j = i;
8000 :
8001 24522990 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8002 : {
8003 10318866 : deltids[j] = deltids[j - hi];
8004 10318866 : j -= hi;
8005 : }
8006 14204124 : deltids[j] = d;
8007 : }
8008 : }
8009 10600 : }
8010 :
8011 : /*
8012 : * Returns how many blocks should be considered favorable/contiguous for a
8013 : * bottom-up index deletion pass. This is a number of heap blocks that starts
8014 : * from and includes the first block in line.
8015 : *
8016 : * There is always at least one favorable block during bottom-up index
8017 : * deletion. In the worst case (i.e. with totally random heap blocks) the
8018 : * first block in line (the only favorable block) can be thought of as a
8019 : * degenerate array of contiguous blocks that consists of a single block.
8020 : * heap_index_delete_tuples() will expect this.
8021 : *
8022 : * Caller passes blockgroups, a description of the final order that deltids
8023 : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8024 : * processing. Note that deltids need not actually be sorted just yet (caller
8025 : * only passes deltids to us so that we can interpret blockgroups).
8026 : *
8027 : * You might guess that the existence of contiguous blocks cannot matter much,
8028 : * since in general the main factor that determines which blocks we visit is
8029 : * the number of promising TIDs, which is a fixed hint from the index AM.
8030 : * We're not really targeting the general case, though -- the actual goal is
8031 : * to adapt our behavior to a wide variety of naturally occurring conditions.
8032 : * The effects of most of the heuristics we apply are only noticeable in the
8033 : * aggregate, over time and across many _related_ bottom-up index deletion
8034 : * passes.
8035 : *
8036 : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8037 : * workloads where heap blocks visited during bottom-up index deletion can be
8038 : * accessed contiguously, in the sense that each newly visited block is the
8039 : * neighbor of the block that bottom-up deletion just finished processing (or
8040 : * close enough to it). It will likely be cheaper to access more favorable
8041 : * blocks sooner rather than later (e.g. in this pass, not across a series of
8042 : * related bottom-up passes). Either way it is probably only a matter of time
8043 : * (or a matter of further correlated version churn) before all blocks that
8044 : * appear together as a single large batch of favorable blocks get accessed by
8045 : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8046 : * appear almost constantly or not even once (it all depends on per-index
8047 : * workload characteristics).
8048 : *
8049 : * Note that the blockgroups sort order applies a power-of-two bucketing
8050 : * scheme that creates opportunities for contiguous groups of blocks to get
8051 : * batched together, at least with workloads that are naturally amenable to
8052 : * being driven by heap block locality. This doesn't just enhance the spatial
8053 : * locality of bottom-up heap block processing in the obvious way. It also
8054 : * enables temporal locality of access, since sorting by heap block number
8055 : * naturally tends to make the bottom-up processing order deterministic.
8056 : *
8057 : * Consider the following example to get a sense of how temporal locality
8058 : * might matter: There is a heap relation with several indexes, each of which
8059 : * is low to medium cardinality. It is subject to constant non-HOT updates.
8060 : * The updates are skewed (in one part of the primary key, perhaps). None of
8061 : * the indexes are logically modified by the UPDATE statements (if they were
8062 : * then bottom-up index deletion would not be triggered in the first place).
8063 : * Naturally, each new round of index tuples (for each heap tuple that gets a
8064 : * heap_update() call) will have the same heap TID in each and every index.
8065 : * Since these indexes are low cardinality and never get logically modified,
8066 : * heapam processing during bottom-up deletion passes will access heap blocks
8067 : * in approximately sequential order. Temporal locality of access occurs due
8068 : * to bottom-up deletion passes behaving very similarly across each of the
8069 : * indexes at any given moment. This keeps the number of buffer misses needed
8070 : * to visit heap blocks to a minimum.
8071 : */
8072 : static int
8073 3630 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8074 : TM_IndexDelete *deltids)
8075 : {
8076 3630 : int64 lastblock = -1;
8077 3630 : int nblocksfavorable = 0;
8078 :
8079 : Assert(nblockgroups >= 1);
8080 : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8081 :
8082 : /*
8083 : * We tolerate heap blocks that will be accessed only slightly out of
8084 : * physical order. Small blips occur when a pair of almost-contiguous
8085 : * blocks happen to fall into different buckets (perhaps due only to a
8086 : * small difference in npromisingtids that the bucketing scheme didn't
8087 : * quite manage to ignore). We effectively ignore these blips by applying
8088 : * a small tolerance. The precise tolerance we use is a little arbitrary,
8089 : * but it works well enough in practice.
8090 : */
8091 11344 : for (int b = 0; b < nblockgroups; b++)
8092 : {
8093 10904 : IndexDeleteCounts *group = blockgroups + b;
8094 10904 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8095 10904 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8096 :
8097 10904 : if (lastblock != -1 &&
8098 7274 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8099 6170 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8100 : break;
8101 :
8102 7714 : nblocksfavorable++;
8103 7714 : lastblock = block;
8104 : }
8105 :
8106 : /* Always indicate that there is at least 1 favorable block */
8107 : Assert(nblocksfavorable >= 1);
8108 :
8109 3630 : return nblocksfavorable;
8110 : }
8111 :
8112 : /*
8113 : * qsort comparison function for bottomup_sort_and_shrink()
8114 : */
8115 : static int
8116 388522 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8117 : {
8118 388522 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8119 388522 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8120 :
8121 : /*
8122 : * Most significant field is npromisingtids (which we invert the order of
8123 : * so as to sort in desc order).
8124 : *
8125 : * Caller should have already normalized npromisingtids fields into
8126 : * power-of-two values (buckets).
8127 : */
8128 388522 : if (group1->npromisingtids > group2->npromisingtids)
8129 17154 : return -1;
8130 371368 : if (group1->npromisingtids < group2->npromisingtids)
8131 20396 : return 1;
8132 :
8133 : /*
8134 : * Tiebreak: desc ntids sort order.
8135 : *
8136 : * We cannot expect power-of-two values for ntids fields. We should
8137 : * behave as if they were already rounded up for us instead.
8138 : */
8139 350972 : if (group1->ntids != group2->ntids)
8140 : {
8141 250404 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8142 250404 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8143 :
8144 250404 : if (ntids1 > ntids2)
8145 39390 : return -1;
8146 211014 : if (ntids1 < ntids2)
8147 46830 : return 1;
8148 : }
8149 :
8150 : /*
8151 : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8152 : * block in deltids array) order.
8153 : *
8154 : * This is equivalent to sorting in ascending heap block number order
8155 : * (among otherwise equal subsets of the array). This approach allows us
8156 : * to avoid accessing the out-of-line TID. (We rely on the assumption
8157 : * that the deltids array was sorted in ascending heap TID order when
8158 : * these offsets to the first TID from each heap block group were formed.)
8159 : */
8160 264752 : if (group1->ifirsttid > group2->ifirsttid)
8161 131406 : return 1;
8162 133346 : if (group1->ifirsttid < group2->ifirsttid)
8163 133346 : return -1;
8164 :
8165 0 : pg_unreachable();
8166 :
8167 : return 0;
8168 : }
8169 :
8170 : /*
8171 : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8172 : *
8173 : * Sorts deltids array in the order needed for useful processing by bottom-up
8174 : * deletion. The array should already be sorted in TID order when we're
8175 : * called. The sort process groups heap TIDs from deltids into heap block
8176 : * groupings. Earlier/more-promising groups/blocks are usually those that are
8177 : * known to have the most "promising" TIDs.
8178 : *
8179 : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8180 : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8181 : * return. This often means that deltids will be shrunk to a small fraction
8182 : * of its original size (we eliminate many heap blocks from consideration for
8183 : * caller up front).
8184 : *
8185 : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8186 : * for a definition and full details.
8187 : */
8188 : static int
8189 3630 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8190 : {
8191 : IndexDeleteCounts *blockgroups;
8192 : TM_IndexDelete *reordereddeltids;
8193 3630 : BlockNumber curblock = InvalidBlockNumber;
8194 3630 : int nblockgroups = 0;
8195 3630 : int ncopied = 0;
8196 3630 : int nblocksfavorable = 0;
8197 :
8198 : Assert(delstate->bottomup);
8199 : Assert(delstate->ndeltids > 0);
8200 :
8201 : /* Calculate per-heap-block count of TIDs */
8202 3630 : blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8203 1783610 : for (int i = 0; i < delstate->ndeltids; i++)
8204 : {
8205 1779980 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8206 1779980 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8207 1779980 : ItemPointer htid = &ideltid->tid;
8208 1779980 : bool promising = istatus->promising;
8209 :
8210 1779980 : if (curblock != ItemPointerGetBlockNumber(htid))
8211 : {
8212 : /* New block group */
8213 73628 : nblockgroups++;
8214 :
8215 : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8216 : !BlockNumberIsValid(curblock));
8217 :
8218 73628 : curblock = ItemPointerGetBlockNumber(htid);
8219 73628 : blockgroups[nblockgroups - 1].ifirsttid = i;
8220 73628 : blockgroups[nblockgroups - 1].ntids = 1;
8221 73628 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8222 : }
8223 : else
8224 : {
8225 1706352 : blockgroups[nblockgroups - 1].ntids++;
8226 : }
8227 :
8228 1779980 : if (promising)
8229 219744 : blockgroups[nblockgroups - 1].npromisingtids++;
8230 : }
8231 :
8232 : /*
8233 : * We're about ready to sort block groups to determine the optimal order
8234 : * for visiting heap blocks. But before we do, round the number of
8235 : * promising tuples for each block group up to the next power-of-two,
8236 : * unless it is very low (less than 4), in which case we round up to 4.
8237 : * npromisingtids is far too noisy to trust when choosing between a pair
8238 : * of block groups that both have very low values.
8239 : *
8240 : * This scheme divides heap blocks/block groups into buckets. Each bucket
8241 : * contains blocks that have _approximately_ the same number of promising
8242 : * TIDs as each other. The goal is to ignore relatively small differences
8243 : * in the total number of promising entries, so that the whole process can
8244 : * give a little weight to heapam factors (like heap block locality)
8245 : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8246 : * would be foolish to interpret small differences in npromisingtids
8247 : * values as anything more than noise.
8248 : *
8249 : * We tiebreak on nhtids when sorting block group subsets that have the
8250 : * same npromisingtids, but this has the same issues as npromisingtids,
8251 : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8252 : * only reason that we don't fix nhtids in the same way here too is that
8253 : * we'll need accurate nhtids values after the sort. We handle nhtids
8254 : * bucketization dynamically instead (in the sort comparator).
8255 : *
8256 : * See bottomup_nblocksfavorable() for a full explanation of when and how
8257 : * heap locality/favorable blocks can significantly influence when and how
8258 : * heap blocks are accessed.
8259 : */
8260 77258 : for (int b = 0; b < nblockgroups; b++)
8261 : {
8262 73628 : IndexDeleteCounts *group = blockgroups + b;
8263 :
8264 : /* Better off falling back on nhtids with low npromisingtids */
8265 73628 : if (group->npromisingtids <= 4)
8266 63280 : group->npromisingtids = 4;
8267 : else
8268 10348 : group->npromisingtids =
8269 10348 : pg_nextpower2_32((uint32) group->npromisingtids);
8270 : }
8271 :
8272 : /* Sort groups and rearrange caller's deltids array */
8273 3630 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8274 : bottomup_sort_and_shrink_cmp);
8275 3630 : reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8276 :
8277 3630 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8278 : /* Determine number of favorable blocks at the start of final deltids */
8279 3630 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8280 : delstate->deltids);
8281 :
8282 24192 : for (int b = 0; b < nblockgroups; b++)
8283 : {
8284 20562 : IndexDeleteCounts *group = blockgroups + b;
8285 20562 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8286 :
8287 20562 : memcpy(reordereddeltids + ncopied, firstdtid,
8288 20562 : sizeof(TM_IndexDelete) * group->ntids);
8289 20562 : ncopied += group->ntids;
8290 : }
8291 :
8292 : /* Copy final grouped and sorted TIDs back into start of caller's array */
8293 3630 : memcpy(delstate->deltids, reordereddeltids,
8294 : sizeof(TM_IndexDelete) * ncopied);
8295 3630 : delstate->ndeltids = ncopied;
8296 :
8297 3630 : pfree(reordereddeltids);
8298 3630 : pfree(blockgroups);
8299 :
8300 3630 : return nblocksfavorable;
8301 : }
8302 :
8303 : /*
8304 : * Perform XLogInsert for a heap-visible operation. 'block' is the block
8305 : * being marked all-visible, and vm_buffer is the buffer containing the
8306 : * corresponding visibility map block. Both should have already been modified
8307 : * and dirtied.
8308 : *
8309 : * snapshotConflictHorizon comes from the largest xmin on the page being
8310 : * marked all-visible. REDO routine uses it to generate recovery conflicts.
8311 : *
8312 : * If checksums or wal_log_hints are enabled, we may also generate a full-page
8313 : * image of heap_buffer. Otherwise, we optimize away the FPI (by specifying
8314 : * REGBUF_NO_IMAGE for the heap buffer), in which case the caller should *not*
8315 : * update the heap page's LSN.
8316 : */
8317 : XLogRecPtr
8318 62628 : log_heap_visible(Relation rel, Buffer heap_buffer, Buffer vm_buffer,
8319 : TransactionId snapshotConflictHorizon, uint8 vmflags)
8320 : {
8321 : xl_heap_visible xlrec;
8322 : XLogRecPtr recptr;
8323 : uint8 flags;
8324 :
8325 : Assert(BufferIsValid(heap_buffer));
8326 : Assert(BufferIsValid(vm_buffer));
8327 :
8328 62628 : xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
8329 62628 : xlrec.flags = vmflags;
8330 62628 : if (RelationIsAccessibleInLogicalDecoding(rel))
8331 256 : xlrec.flags |= VISIBILITYMAP_XLOG_CATALOG_REL;
8332 62628 : XLogBeginInsert();
8333 62628 : XLogRegisterData((char *) &xlrec, SizeOfHeapVisible);
8334 :
8335 62628 : XLogRegisterBuffer(0, vm_buffer, 0);
8336 :
8337 62628 : flags = REGBUF_STANDARD;
8338 62628 : if (!XLogHintBitIsNeeded())
8339 50772 : flags |= REGBUF_NO_IMAGE;
8340 62628 : XLogRegisterBuffer(1, heap_buffer, flags);
8341 :
8342 62628 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
8343 :
8344 62628 : return recptr;
8345 : }
8346 :
8347 : /*
8348 : * Perform XLogInsert for a heap-update operation. Caller must already
8349 : * have modified the buffer(s) and marked them dirty.
8350 : */
8351 : static XLogRecPtr
8352 543496 : log_heap_update(Relation reln, Buffer oldbuf,
8353 : Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
8354 : HeapTuple old_key_tuple,
8355 : bool all_visible_cleared, bool new_all_visible_cleared)
8356 : {
8357 : xl_heap_update xlrec;
8358 : xl_heap_header xlhdr;
8359 : xl_heap_header xlhdr_idx;
8360 : uint8 info;
8361 : uint16 prefix_suffix[2];
8362 543496 : uint16 prefixlen = 0,
8363 543496 : suffixlen = 0;
8364 : XLogRecPtr recptr;
8365 543496 : Page page = BufferGetPage(newbuf);
8366 543496 : bool need_tuple_data = RelationIsLogicallyLogged(reln);
8367 : bool init;
8368 : int bufflags;
8369 :
8370 : /* Caller should not call me on a non-WAL-logged relation */
8371 : Assert(RelationNeedsWAL(reln));
8372 :
8373 543496 : XLogBeginInsert();
8374 :
8375 543496 : if (HeapTupleIsHeapOnly(newtup))
8376 261828 : info = XLOG_HEAP_HOT_UPDATE;
8377 : else
8378 281668 : info = XLOG_HEAP_UPDATE;
8379 :
8380 : /*
8381 : * If the old and new tuple are on the same page, we only need to log the
8382 : * parts of the new tuple that were changed. That saves on the amount of
8383 : * WAL we need to write. Currently, we just count any unchanged bytes in
8384 : * the beginning and end of the tuple. That's quick to check, and
8385 : * perfectly covers the common case that only one field is updated.
8386 : *
8387 : * We could do this even if the old and new tuple are on different pages,
8388 : * but only if we don't make a full-page image of the old page, which is
8389 : * difficult to know in advance. Also, if the old tuple is corrupt for
8390 : * some reason, it would allow the corruption to propagate the new page,
8391 : * so it seems best to avoid. Under the general assumption that most
8392 : * updates tend to create the new tuple version on the same page, there
8393 : * isn't much to be gained by doing this across pages anyway.
8394 : *
8395 : * Skip this if we're taking a full-page image of the new page, as we
8396 : * don't include the new tuple in the WAL record in that case. Also
8397 : * disable if wal_level='logical', as logical decoding needs to be able to
8398 : * read the new tuple in whole from the WAL record alone.
8399 : */
8400 543496 : if (oldbuf == newbuf && !need_tuple_data &&
8401 258886 : !XLogCheckBufferNeedsBackup(newbuf))
8402 : {
8403 258314 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8404 258314 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8405 258314 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8406 258314 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
8407 :
8408 : /* Check for common prefix between old and new tuple */
8409 19566320 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8410 : {
8411 19524206 : if (newp[prefixlen] != oldp[prefixlen])
8412 216200 : break;
8413 : }
8414 :
8415 : /*
8416 : * Storing the length of the prefix takes 2 bytes, so we need to save
8417 : * at least 3 bytes or there's no point.
8418 : */
8419 258314 : if (prefixlen < 3)
8420 44056 : prefixlen = 0;
8421 :
8422 : /* Same for suffix */
8423 8492160 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
8424 : {
8425 8449612 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
8426 215766 : break;
8427 : }
8428 258314 : if (suffixlen < 3)
8429 60938 : suffixlen = 0;
8430 : }
8431 :
8432 : /* Prepare main WAL data chain */
8433 543496 : xlrec.flags = 0;
8434 543496 : if (all_visible_cleared)
8435 2054 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
8436 543496 : if (new_all_visible_cleared)
8437 908 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
8438 543496 : if (prefixlen > 0)
8439 214258 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
8440 543496 : if (suffixlen > 0)
8441 197376 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
8442 543496 : if (need_tuple_data)
8443 : {
8444 94016 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
8445 94016 : if (old_key_tuple)
8446 : {
8447 266 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
8448 112 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
8449 : else
8450 154 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
8451 : }
8452 : }
8453 :
8454 : /* If new tuple is the single and first tuple on page... */
8455 549682 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
8456 6186 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
8457 : {
8458 6050 : info |= XLOG_HEAP_INIT_PAGE;
8459 6050 : init = true;
8460 : }
8461 : else
8462 537446 : init = false;
8463 :
8464 : /* Prepare WAL data for the old page */
8465 543496 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
8466 543496 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
8467 1086992 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
8468 543496 : oldtup->t_data->t_infomask2);
8469 :
8470 : /* Prepare WAL data for the new page */
8471 543496 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
8472 543496 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
8473 :
8474 543496 : bufflags = REGBUF_STANDARD;
8475 543496 : if (init)
8476 6050 : bufflags |= REGBUF_WILL_INIT;
8477 543496 : if (need_tuple_data)
8478 94016 : bufflags |= REGBUF_KEEP_DATA;
8479 :
8480 543496 : XLogRegisterBuffer(0, newbuf, bufflags);
8481 543496 : if (oldbuf != newbuf)
8482 260754 : XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
8483 :
8484 543496 : XLogRegisterData((char *) &xlrec, SizeOfHeapUpdate);
8485 :
8486 : /*
8487 : * Prepare WAL data for the new tuple.
8488 : */
8489 543496 : if (prefixlen > 0 || suffixlen > 0)
8490 : {
8491 257452 : if (prefixlen > 0 && suffixlen > 0)
8492 : {
8493 154182 : prefix_suffix[0] = prefixlen;
8494 154182 : prefix_suffix[1] = suffixlen;
8495 154182 : XLogRegisterBufData(0, (char *) &prefix_suffix, sizeof(uint16) * 2);
8496 : }
8497 103270 : else if (prefixlen > 0)
8498 : {
8499 60076 : XLogRegisterBufData(0, (char *) &prefixlen, sizeof(uint16));
8500 : }
8501 : else
8502 : {
8503 43194 : XLogRegisterBufData(0, (char *) &suffixlen, sizeof(uint16));
8504 : }
8505 : }
8506 :
8507 543496 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
8508 543496 : xlhdr.t_infomask = newtup->t_data->t_infomask;
8509 543496 : xlhdr.t_hoff = newtup->t_data->t_hoff;
8510 : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
8511 :
8512 : /*
8513 : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
8514 : *
8515 : * The 'data' doesn't include the common prefix or suffix.
8516 : */
8517 543496 : XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
8518 543496 : if (prefixlen == 0)
8519 : {
8520 329238 : XLogRegisterBufData(0,
8521 329238 : ((char *) newtup->t_data) + SizeofHeapTupleHeader,
8522 329238 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
8523 : }
8524 : else
8525 : {
8526 : /*
8527 : * Have to write the null bitmap and data after the common prefix as
8528 : * two separate rdata entries.
8529 : */
8530 : /* bitmap [+ padding] [+ oid] */
8531 214258 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
8532 : {
8533 214258 : XLogRegisterBufData(0,
8534 214258 : ((char *) newtup->t_data) + SizeofHeapTupleHeader,
8535 214258 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
8536 : }
8537 :
8538 : /* data after common prefix */
8539 214258 : XLogRegisterBufData(0,
8540 214258 : ((char *) newtup->t_data) + newtup->t_data->t_hoff + prefixlen,
8541 214258 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
8542 : }
8543 :
8544 : /* We need to log a tuple identity */
8545 543496 : if (need_tuple_data && old_key_tuple)
8546 : {
8547 : /* don't really need this, but its more comfy to decode */
8548 266 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
8549 266 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
8550 266 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
8551 :
8552 266 : XLogRegisterData((char *) &xlhdr_idx, SizeOfHeapHeader);
8553 :
8554 : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
8555 266 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
8556 266 : old_key_tuple->t_len - SizeofHeapTupleHeader);
8557 : }
8558 :
8559 : /* filtering by origin on a row level is much more efficient */
8560 543496 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
8561 :
8562 543496 : recptr = XLogInsert(RM_HEAP_ID, info);
8563 :
8564 543496 : return recptr;
8565 : }
8566 :
8567 : /*
8568 : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
8569 : *
8570 : * This is only used in wal_level >= WAL_LEVEL_LOGICAL, and only for catalog
8571 : * tuples.
8572 : */
8573 : static XLogRecPtr
8574 43094 : log_heap_new_cid(Relation relation, HeapTuple tup)
8575 : {
8576 : xl_heap_new_cid xlrec;
8577 :
8578 : XLogRecPtr recptr;
8579 43094 : HeapTupleHeader hdr = tup->t_data;
8580 :
8581 : Assert(ItemPointerIsValid(&tup->t_self));
8582 : Assert(tup->t_tableOid != InvalidOid);
8583 :
8584 43094 : xlrec.top_xid = GetTopTransactionId();
8585 43094 : xlrec.target_locator = relation->rd_locator;
8586 43094 : xlrec.target_tid = tup->t_self;
8587 :
8588 : /*
8589 : * If the tuple got inserted & deleted in the same TX we definitely have a
8590 : * combo CID, set cmin and cmax.
8591 : */
8592 43094 : if (hdr->t_infomask & HEAP_COMBOCID)
8593 : {
8594 : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
8595 : Assert(!HeapTupleHeaderXminInvalid(hdr));
8596 3950 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
8597 3950 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
8598 3950 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
8599 : }
8600 : /* No combo CID, so only cmin or cmax can be set by this TX */
8601 : else
8602 : {
8603 : /*
8604 : * Tuple inserted.
8605 : *
8606 : * We need to check for LOCK ONLY because multixacts might be
8607 : * transferred to the new tuple in case of FOR KEY SHARE updates in
8608 : * which case there will be an xmax, although the tuple just got
8609 : * inserted.
8610 : */
8611 39144 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
8612 11560 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
8613 : {
8614 27586 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
8615 27586 : xlrec.cmax = InvalidCommandId;
8616 : }
8617 : /* Tuple from a different tx updated or deleted. */
8618 : else
8619 : {
8620 11558 : xlrec.cmin = InvalidCommandId;
8621 11558 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
8622 : }
8623 39144 : xlrec.combocid = InvalidCommandId;
8624 : }
8625 :
8626 : /*
8627 : * Note that we don't need to register the buffer here, because this
8628 : * operation does not modify the page. The insert/update/delete that
8629 : * called us certainly did, but that's WAL-logged separately.
8630 : */
8631 43094 : XLogBeginInsert();
8632 43094 : XLogRegisterData((char *) &xlrec, SizeOfHeapNewCid);
8633 :
8634 : /* will be looked at irrespective of origin */
8635 :
8636 43094 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
8637 :
8638 43094 : return recptr;
8639 : }
8640 :
8641 : /*
8642 : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
8643 : * the old tuple in an UPDATE or DELETE.
8644 : *
8645 : * Returns NULL if there's no need to log an identity or if there's no suitable
8646 : * key defined.
8647 : *
8648 : * Pass key_required true if any replica identity columns changed value, or if
8649 : * any of them have any external data. Delete must always pass true.
8650 : *
8651 : * *copy is set to true if the returned tuple is a modified copy rather than
8652 : * the same tuple that was passed in.
8653 : */
8654 : static HeapTuple
8655 3324908 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
8656 : bool *copy)
8657 : {
8658 3324908 : TupleDesc desc = RelationGetDescr(relation);
8659 3324908 : char replident = relation->rd_rel->relreplident;
8660 : Bitmapset *idattrs;
8661 : HeapTuple key_tuple;
8662 : bool nulls[MaxHeapAttributeNumber];
8663 : Datum values[MaxHeapAttributeNumber];
8664 :
8665 3324908 : *copy = false;
8666 :
8667 3324908 : if (!RelationIsLogicallyLogged(relation))
8668 3124388 : return NULL;
8669 :
8670 200520 : if (replident == REPLICA_IDENTITY_NOTHING)
8671 462 : return NULL;
8672 :
8673 200058 : if (replident == REPLICA_IDENTITY_FULL)
8674 : {
8675 : /*
8676 : * When logging the entire old tuple, it very well could contain
8677 : * toasted columns. If so, force them to be inlined.
8678 : */
8679 354 : if (HeapTupleHasExternal(tp))
8680 : {
8681 8 : *copy = true;
8682 8 : tp = toast_flatten_tuple(tp, desc);
8683 : }
8684 354 : return tp;
8685 : }
8686 :
8687 : /* if the key isn't required and we're only logging the key, we're done */
8688 199704 : if (!key_required)
8689 93750 : return NULL;
8690 :
8691 : /* find out the replica identity columns */
8692 105954 : idattrs = RelationGetIndexAttrBitmap(relation,
8693 : INDEX_ATTR_BITMAP_IDENTITY_KEY);
8694 :
8695 : /*
8696 : * If there's no defined replica identity columns, treat as !key_required.
8697 : * (This case should not be reachable from heap_update, since that should
8698 : * calculate key_required accurately. But heap_delete just passes
8699 : * constant true for key_required, so we can hit this case in deletes.)
8700 : */
8701 105954 : if (bms_is_empty(idattrs))
8702 12042 : return NULL;
8703 :
8704 : /*
8705 : * Construct a new tuple containing only the replica identity columns,
8706 : * with nulls elsewhere. While we're at it, assert that the replica
8707 : * identity columns aren't null.
8708 : */
8709 93912 : heap_deform_tuple(tp, desc, values, nulls);
8710 :
8711 301722 : for (int i = 0; i < desc->natts; i++)
8712 : {
8713 207810 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
8714 : idattrs))
8715 : Assert(!nulls[i]);
8716 : else
8717 113880 : nulls[i] = true;
8718 : }
8719 :
8720 93912 : key_tuple = heap_form_tuple(desc, values, nulls);
8721 93912 : *copy = true;
8722 :
8723 93912 : bms_free(idattrs);
8724 :
8725 : /*
8726 : * If the tuple, which by here only contains indexed columns, still has
8727 : * toasted columns, force them to be inlined. This is somewhat unlikely
8728 : * since there's limits on the size of indexed columns, so we don't
8729 : * duplicate toast_flatten_tuple()s functionality in the above loop over
8730 : * the indexed columns, even if it would be more efficient.
8731 : */
8732 93912 : if (HeapTupleHasExternal(key_tuple))
8733 : {
8734 8 : HeapTuple oldtup = key_tuple;
8735 :
8736 8 : key_tuple = toast_flatten_tuple(oldtup, desc);
8737 8 : heap_freetuple(oldtup);
8738 : }
8739 :
8740 93912 : return key_tuple;
8741 : }
8742 :
8743 : /*
8744 : * Replay XLOG_HEAP2_PRUNE_* records.
8745 : */
8746 : static void
8747 16398 : heap_xlog_prune_freeze(XLogReaderState *record)
8748 : {
8749 16398 : XLogRecPtr lsn = record->EndRecPtr;
8750 16398 : char *maindataptr = XLogRecGetData(record);
8751 : xl_heap_prune xlrec;
8752 : Buffer buffer;
8753 : RelFileLocator rlocator;
8754 : BlockNumber blkno;
8755 : XLogRedoAction action;
8756 :
8757 16398 : XLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);
8758 16398 : memcpy(&xlrec, maindataptr, SizeOfHeapPrune);
8759 16398 : maindataptr += SizeOfHeapPrune;
8760 :
8761 : /*
8762 : * We will take an ordinary exclusive lock or a cleanup lock depending on
8763 : * whether the XLHP_CLEANUP_LOCK flag is set. With an ordinary exclusive
8764 : * lock, we better not be doing anything that requires moving existing
8765 : * tuple data.
8766 : */
8767 : Assert((xlrec.flags & XLHP_CLEANUP_LOCK) != 0 ||
8768 : (xlrec.flags & (XLHP_HAS_REDIRECTIONS | XLHP_HAS_DEAD_ITEMS)) == 0);
8769 :
8770 : /*
8771 : * We are about to remove and/or freeze tuples. In Hot Standby mode,
8772 : * ensure that there are no queries running for which the removed tuples
8773 : * are still visible or which still consider the frozen xids as running.
8774 : * The conflict horizon XID comes after xl_heap_prune.
8775 : */
8776 16398 : if ((xlrec.flags & XLHP_HAS_CONFLICT_HORIZON) != 0)
8777 : {
8778 : TransactionId snapshot_conflict_horizon;
8779 :
8780 : /* memcpy() because snapshot_conflict_horizon is stored unaligned */
8781 13006 : memcpy(&snapshot_conflict_horizon, maindataptr, sizeof(TransactionId));
8782 13006 : maindataptr += sizeof(TransactionId);
8783 :
8784 13006 : if (InHotStandby)
8785 12626 : ResolveRecoveryConflictWithSnapshot(snapshot_conflict_horizon,
8786 12626 : (xlrec.flags & XLHP_IS_CATALOG_REL) != 0,
8787 : rlocator);
8788 : }
8789 :
8790 : /*
8791 : * If we have a full-page image, restore it and we're done.
8792 : */
8793 16398 : action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
8794 16398 : (xlrec.flags & XLHP_CLEANUP_LOCK) != 0,
8795 : &buffer);
8796 16398 : if (action == BLK_NEEDS_REDO)
8797 : {
8798 14942 : Page page = (Page) BufferGetPage(buffer);
8799 : OffsetNumber *redirected;
8800 : OffsetNumber *nowdead;
8801 : OffsetNumber *nowunused;
8802 : int nredirected;
8803 : int ndead;
8804 : int nunused;
8805 : int nplans;
8806 : Size datalen;
8807 : xlhp_freeze_plan *plans;
8808 : OffsetNumber *frz_offsets;
8809 14942 : char *dataptr = XLogRecGetBlockData(record, 0, &datalen);
8810 :
8811 14942 : heap_xlog_deserialize_prune_and_freeze(dataptr, xlrec.flags,
8812 : &nplans, &plans, &frz_offsets,
8813 : &nredirected, &redirected,
8814 : &ndead, &nowdead,
8815 : &nunused, &nowunused);
8816 :
8817 : /*
8818 : * Update all line pointers per the record, and repair fragmentation
8819 : * if needed.
8820 : */
8821 14942 : if (nredirected > 0 || ndead > 0 || nunused > 0)
8822 14880 : heap_page_prune_execute(buffer,
8823 14880 : (xlrec.flags & XLHP_CLEANUP_LOCK) == 0,
8824 : redirected, nredirected,
8825 : nowdead, ndead,
8826 : nowunused, nunused);
8827 :
8828 : /* Freeze tuples */
8829 15072 : for (int p = 0; p < nplans; p++)
8830 : {
8831 : HeapTupleFreeze frz;
8832 :
8833 : /*
8834 : * Convert freeze plan representation from WAL record into
8835 : * per-tuple format used by heap_execute_freeze_tuple
8836 : */
8837 130 : frz.xmax = plans[p].xmax;
8838 130 : frz.t_infomask2 = plans[p].t_infomask2;
8839 130 : frz.t_infomask = plans[p].t_infomask;
8840 130 : frz.frzflags = plans[p].frzflags;
8841 130 : frz.offset = InvalidOffsetNumber; /* unused, but be tidy */
8842 :
8843 3598 : for (int i = 0; i < plans[p].ntuples; i++)
8844 : {
8845 3468 : OffsetNumber offset = *(frz_offsets++);
8846 : ItemId lp;
8847 : HeapTupleHeader tuple;
8848 :
8849 3468 : lp = PageGetItemId(page, offset);
8850 3468 : tuple = (HeapTupleHeader) PageGetItem(page, lp);
8851 3468 : heap_execute_freeze_tuple(tuple, &frz);
8852 : }
8853 : }
8854 :
8855 : /* There should be no more data */
8856 : Assert((char *) frz_offsets == dataptr + datalen);
8857 :
8858 : /*
8859 : * Note: we don't worry about updating the page's prunability hints.
8860 : * At worst this will cause an extra prune cycle to occur soon.
8861 : */
8862 :
8863 14942 : PageSetLSN(page, lsn);
8864 14942 : MarkBufferDirty(buffer);
8865 : }
8866 :
8867 : /*
8868 : * If we released any space or line pointers, update the free space map.
8869 : *
8870 : * Do this regardless of a full-page image being applied, since the FSM
8871 : * data is not in the page anyway.
8872 : */
8873 16398 : if (BufferIsValid(buffer))
8874 : {
8875 16398 : if (xlrec.flags & (XLHP_HAS_REDIRECTIONS |
8876 : XLHP_HAS_DEAD_ITEMS |
8877 : XLHP_HAS_NOW_UNUSED_ITEMS))
8878 : {
8879 16336 : Size freespace = PageGetHeapFreeSpace(BufferGetPage(buffer));
8880 :
8881 16336 : UnlockReleaseBuffer(buffer);
8882 :
8883 16336 : XLogRecordPageWithFreeSpace(rlocator, blkno, freespace);
8884 : }
8885 : else
8886 62 : UnlockReleaseBuffer(buffer);
8887 : }
8888 16398 : }
8889 :
8890 : /*
8891 : * Replay XLOG_HEAP2_VISIBLE record.
8892 : *
8893 : * The critical integrity requirement here is that we must never end up with
8894 : * a situation where the visibility map bit is set, and the page-level
8895 : * PD_ALL_VISIBLE bit is clear. If that were to occur, then a subsequent
8896 : * page modification would fail to clear the visibility map bit.
8897 : */
8898 : static void
8899 7336 : heap_xlog_visible(XLogReaderState *record)
8900 : {
8901 7336 : XLogRecPtr lsn = record->EndRecPtr;
8902 7336 : xl_heap_visible *xlrec = (xl_heap_visible *) XLogRecGetData(record);
8903 7336 : Buffer vmbuffer = InvalidBuffer;
8904 : Buffer buffer;
8905 : Page page;
8906 : RelFileLocator rlocator;
8907 : BlockNumber blkno;
8908 : XLogRedoAction action;
8909 :
8910 : Assert((xlrec->flags & VISIBILITYMAP_XLOG_VALID_BITS) == xlrec->flags);
8911 :
8912 7336 : XLogRecGetBlockTag(record, 1, &rlocator, NULL, &blkno);
8913 :
8914 : /*
8915 : * If there are any Hot Standby transactions running that have an xmin
8916 : * horizon old enough that this page isn't all-visible for them, they
8917 : * might incorrectly decide that an index-only scan can skip a heap fetch.
8918 : *
8919 : * NB: It might be better to throw some kind of "soft" conflict here that
8920 : * forces any index-only scan that is in flight to perform heap fetches,
8921 : * rather than killing the transaction outright.
8922 : */
8923 7336 : if (InHotStandby)
8924 6988 : ResolveRecoveryConflictWithSnapshot(xlrec->snapshotConflictHorizon,
8925 6988 : xlrec->flags & VISIBILITYMAP_XLOG_CATALOG_REL,
8926 : rlocator);
8927 :
8928 : /*
8929 : * Read the heap page, if it still exists. If the heap file has dropped or
8930 : * truncated later in recovery, we don't need to update the page, but we'd
8931 : * better still update the visibility map.
8932 : */
8933 7336 : action = XLogReadBufferForRedo(record, 1, &buffer);
8934 7336 : if (action == BLK_NEEDS_REDO)
8935 : {
8936 : /*
8937 : * We don't bump the LSN of the heap page when setting the visibility
8938 : * map bit (unless checksums or wal_hint_bits is enabled, in which
8939 : * case we must). This exposes us to torn page hazards, but since
8940 : * we're not inspecting the existing page contents in any way, we
8941 : * don't care.
8942 : */
8943 5082 : page = BufferGetPage(buffer);
8944 :
8945 5082 : PageSetAllVisible(page);
8946 :
8947 5082 : if (XLogHintBitIsNeeded())
8948 4902 : PageSetLSN(page, lsn);
8949 :
8950 5082 : MarkBufferDirty(buffer);
8951 : }
8952 : else if (action == BLK_RESTORED)
8953 : {
8954 : /*
8955 : * If heap block was backed up, we already restored it and there's
8956 : * nothing more to do. (This can only happen with checksums or
8957 : * wal_log_hints enabled.)
8958 : */
8959 : }
8960 :
8961 7336 : if (BufferIsValid(buffer))
8962 : {
8963 7246 : Size space = PageGetFreeSpace(BufferGetPage(buffer));
8964 :
8965 7246 : UnlockReleaseBuffer(buffer);
8966 :
8967 : /*
8968 : * Since FSM is not WAL-logged and only updated heuristically, it
8969 : * easily becomes stale in standbys. If the standby is later promoted
8970 : * and runs VACUUM, it will skip updating individual free space
8971 : * figures for pages that became all-visible (or all-frozen, depending
8972 : * on the vacuum mode,) which is troublesome when FreeSpaceMapVacuum
8973 : * propagates too optimistic free space values to upper FSM layers;
8974 : * later inserters try to use such pages only to find out that they
8975 : * are unusable. This can cause long stalls when there are many such
8976 : * pages.
8977 : *
8978 : * Forestall those problems by updating FSM's idea about a page that
8979 : * is becoming all-visible or all-frozen.
8980 : *
8981 : * Do this regardless of a full-page image being applied, since the
8982 : * FSM data is not in the page anyway.
8983 : */
8984 7246 : if (xlrec->flags & VISIBILITYMAP_VALID_BITS)
8985 7246 : XLogRecordPageWithFreeSpace(rlocator, blkno, space);
8986 : }
8987 :
8988 : /*
8989 : * Even if we skipped the heap page update due to the LSN interlock, it's
8990 : * still safe to update the visibility map. Any WAL record that clears
8991 : * the visibility map bit does so before checking the page LSN, so any
8992 : * bits that need to be cleared will still be cleared.
8993 : */
8994 7336 : if (XLogReadBufferForRedoExtended(record, 0, RBM_ZERO_ON_ERROR, false,
8995 : &vmbuffer) == BLK_NEEDS_REDO)
8996 : {
8997 6920 : Page vmpage = BufferGetPage(vmbuffer);
8998 : Relation reln;
8999 : uint8 vmbits;
9000 :
9001 : /* initialize the page if it was read as zeros */
9002 6920 : if (PageIsNew(vmpage))
9003 0 : PageInit(vmpage, BLCKSZ, 0);
9004 :
9005 : /* remove VISIBILITYMAP_XLOG_* */
9006 6920 : vmbits = xlrec->flags & VISIBILITYMAP_VALID_BITS;
9007 :
9008 : /*
9009 : * XLogReadBufferForRedoExtended locked the buffer. But
9010 : * visibilitymap_set will handle locking itself.
9011 : */
9012 6920 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
9013 :
9014 6920 : reln = CreateFakeRelcacheEntry(rlocator);
9015 6920 : visibilitymap_pin(reln, blkno, &vmbuffer);
9016 :
9017 6920 : visibilitymap_set(reln, blkno, InvalidBuffer, lsn, vmbuffer,
9018 : xlrec->snapshotConflictHorizon, vmbits);
9019 :
9020 6920 : ReleaseBuffer(vmbuffer);
9021 6920 : FreeFakeRelcacheEntry(reln);
9022 : }
9023 416 : else if (BufferIsValid(vmbuffer))
9024 416 : UnlockReleaseBuffer(vmbuffer);
9025 7336 : }
9026 :
9027 : /*
9028 : * Given an "infobits" field from an XLog record, set the correct bits in the
9029 : * given infomask and infomask2 for the tuple touched by the record.
9030 : *
9031 : * (This is the reverse of compute_infobits).
9032 : */
9033 : static void
9034 877078 : fix_infomask_from_infobits(uint8 infobits, uint16 *infomask, uint16 *infomask2)
9035 : {
9036 877078 : *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
9037 : HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_EXCL_LOCK);
9038 877078 : *infomask2 &= ~HEAP_KEYS_UPDATED;
9039 :
9040 877078 : if (infobits & XLHL_XMAX_IS_MULTI)
9041 4 : *infomask |= HEAP_XMAX_IS_MULTI;
9042 877078 : if (infobits & XLHL_XMAX_LOCK_ONLY)
9043 109628 : *infomask |= HEAP_XMAX_LOCK_ONLY;
9044 877078 : if (infobits & XLHL_XMAX_EXCL_LOCK)
9045 108864 : *infomask |= HEAP_XMAX_EXCL_LOCK;
9046 : /* note HEAP_XMAX_SHR_LOCK isn't considered here */
9047 877078 : if (infobits & XLHL_XMAX_KEYSHR_LOCK)
9048 786 : *infomask |= HEAP_XMAX_KEYSHR_LOCK;
9049 :
9050 877078 : if (infobits & XLHL_KEYS_UPDATED)
9051 584476 : *infomask2 |= HEAP_KEYS_UPDATED;
9052 877078 : }
9053 :
9054 : static void
9055 582096 : heap_xlog_delete(XLogReaderState *record)
9056 : {
9057 582096 : XLogRecPtr lsn = record->EndRecPtr;
9058 582096 : xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
9059 : Buffer buffer;
9060 : Page page;
9061 582096 : ItemId lp = NULL;
9062 : HeapTupleHeader htup;
9063 : BlockNumber blkno;
9064 : RelFileLocator target_locator;
9065 : ItemPointerData target_tid;
9066 :
9067 582096 : XLogRecGetBlockTag(record, 0, &target_locator, NULL, &blkno);
9068 582096 : ItemPointerSetBlockNumber(&target_tid, blkno);
9069 582096 : ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
9070 :
9071 : /*
9072 : * The visibility map may need to be fixed even if the heap page is
9073 : * already up-to-date.
9074 : */
9075 582096 : if (xlrec->flags & XLH_DELETE_ALL_VISIBLE_CLEARED)
9076 : {
9077 2 : Relation reln = CreateFakeRelcacheEntry(target_locator);
9078 2 : Buffer vmbuffer = InvalidBuffer;
9079 :
9080 2 : visibilitymap_pin(reln, blkno, &vmbuffer);
9081 2 : visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
9082 2 : ReleaseBuffer(vmbuffer);
9083 2 : FreeFakeRelcacheEntry(reln);
9084 : }
9085 :
9086 582096 : if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9087 : {
9088 581902 : page = BufferGetPage(buffer);
9089 :
9090 581902 : if (PageGetMaxOffsetNumber(page) >= xlrec->offnum)
9091 581902 : lp = PageGetItemId(page, xlrec->offnum);
9092 :
9093 581902 : if (PageGetMaxOffsetNumber(page) < xlrec->offnum || !ItemIdIsNormal(lp))
9094 0 : elog(PANIC, "invalid lp");
9095 :
9096 581902 : htup = (HeapTupleHeader) PageGetItem(page, lp);
9097 :
9098 581902 : htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9099 581902 : htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9100 581902 : HeapTupleHeaderClearHotUpdated(htup);
9101 581902 : fix_infomask_from_infobits(xlrec->infobits_set,
9102 : &htup->t_infomask, &htup->t_infomask2);
9103 581902 : if (!(xlrec->flags & XLH_DELETE_IS_SUPER))
9104 581902 : HeapTupleHeaderSetXmax(htup, xlrec->xmax);
9105 : else
9106 0 : HeapTupleHeaderSetXmin(htup, InvalidTransactionId);
9107 581902 : HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
9108 :
9109 : /* Mark the page as a candidate for pruning */
9110 581902 : PageSetPrunable(page, XLogRecGetXid(record));
9111 :
9112 581902 : if (xlrec->flags & XLH_DELETE_ALL_VISIBLE_CLEARED)
9113 0 : PageClearAllVisible(page);
9114 :
9115 : /* Make sure t_ctid is set correctly */
9116 581902 : if (xlrec->flags & XLH_DELETE_IS_PARTITION_MOVE)
9117 264 : HeapTupleHeaderSetMovedPartitions(htup);
9118 : else
9119 581638 : htup->t_ctid = target_tid;
9120 581902 : PageSetLSN(page, lsn);
9121 581902 : MarkBufferDirty(buffer);
9122 : }
9123 582096 : if (BufferIsValid(buffer))
9124 582096 : UnlockReleaseBuffer(buffer);
9125 582096 : }
9126 :
9127 : static void
9128 2510334 : heap_xlog_insert(XLogReaderState *record)
9129 : {
9130 2510334 : XLogRecPtr lsn = record->EndRecPtr;
9131 2510334 : xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
9132 : Buffer buffer;
9133 : Page page;
9134 : union
9135 : {
9136 : HeapTupleHeaderData hdr;
9137 : char data[MaxHeapTupleSize];
9138 : } tbuf;
9139 : HeapTupleHeader htup;
9140 : xl_heap_header xlhdr;
9141 : uint32 newlen;
9142 2510334 : Size freespace = 0;
9143 : RelFileLocator target_locator;
9144 : BlockNumber blkno;
9145 : ItemPointerData target_tid;
9146 : XLogRedoAction action;
9147 :
9148 2510334 : XLogRecGetBlockTag(record, 0, &target_locator, NULL, &blkno);
9149 2510334 : ItemPointerSetBlockNumber(&target_tid, blkno);
9150 2510334 : ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
9151 :
9152 : /*
9153 : * The visibility map may need to be fixed even if the heap page is
9154 : * already up-to-date.
9155 : */
9156 2510334 : if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
9157 : {
9158 1040 : Relation reln = CreateFakeRelcacheEntry(target_locator);
9159 1040 : Buffer vmbuffer = InvalidBuffer;
9160 :
9161 1040 : visibilitymap_pin(reln, blkno, &vmbuffer);
9162 1040 : visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
9163 1040 : ReleaseBuffer(vmbuffer);
9164 1040 : FreeFakeRelcacheEntry(reln);
9165 : }
9166 :
9167 : /*
9168 : * If we inserted the first and only tuple on the page, re-initialize the
9169 : * page from scratch.
9170 : */
9171 2510334 : if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
9172 : {
9173 32764 : buffer = XLogInitBufferForRedo(record, 0);
9174 32764 : page = BufferGetPage(buffer);
9175 32764 : PageInit(page, BufferGetPageSize(buffer), 0);
9176 32764 : action = BLK_NEEDS_REDO;
9177 : }
9178 : else
9179 2477570 : action = XLogReadBufferForRedo(record, 0, &buffer);
9180 2510334 : if (action == BLK_NEEDS_REDO)
9181 : {
9182 : Size datalen;
9183 : char *data;
9184 :
9185 2509056 : page = BufferGetPage(buffer);
9186 :
9187 2509056 : if (PageGetMaxOffsetNumber(page) + 1 < xlrec->offnum)
9188 0 : elog(PANIC, "invalid max offset number");
9189 :
9190 2509056 : data = XLogRecGetBlockData(record, 0, &datalen);
9191 :
9192 2509056 : newlen = datalen - SizeOfHeapHeader;
9193 : Assert(datalen > SizeOfHeapHeader && newlen <= MaxHeapTupleSize);
9194 2509056 : memcpy((char *) &xlhdr, data, SizeOfHeapHeader);
9195 2509056 : data += SizeOfHeapHeader;
9196 :
9197 2509056 : htup = &tbuf.hdr;
9198 2509056 : MemSet((char *) htup, 0, SizeofHeapTupleHeader);
9199 : /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
9200 2509056 : memcpy((char *) htup + SizeofHeapTupleHeader,
9201 : data,
9202 : newlen);
9203 2509056 : newlen += SizeofHeapTupleHeader;
9204 2509056 : htup->t_infomask2 = xlhdr.t_infomask2;
9205 2509056 : htup->t_infomask = xlhdr.t_infomask;
9206 2509056 : htup->t_hoff = xlhdr.t_hoff;
9207 2509056 : HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
9208 2509056 : HeapTupleHeaderSetCmin(htup, FirstCommandId);
9209 2509056 : htup->t_ctid = target_tid;
9210 :
9211 2509056 : if (PageAddItem(page, (Item) htup, newlen, xlrec->offnum,
9212 : true, true) == InvalidOffsetNumber)
9213 0 : elog(PANIC, "failed to add tuple");
9214 :
9215 2509056 : freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
9216 :
9217 2509056 : PageSetLSN(page, lsn);
9218 :
9219 2509056 : if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
9220 530 : PageClearAllVisible(page);
9221 :
9222 : /* XLH_INSERT_ALL_FROZEN_SET implies that all tuples are visible */
9223 2509056 : if (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)
9224 0 : PageSetAllVisible(page);
9225 :
9226 2509056 : MarkBufferDirty(buffer);
9227 : }
9228 2510334 : if (BufferIsValid(buffer))
9229 2510334 : UnlockReleaseBuffer(buffer);
9230 :
9231 : /*
9232 : * If the page is running low on free space, update the FSM as well.
9233 : * Arbitrarily, our definition of "low" is less than 20%. We can't do much
9234 : * better than that without knowing the fill-factor for the table.
9235 : *
9236 : * XXX: Don't do this if the page was restored from full page image. We
9237 : * don't bother to update the FSM in that case, it doesn't need to be
9238 : * totally accurate anyway.
9239 : */
9240 2510334 : if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
9241 494286 : XLogRecordPageWithFreeSpace(target_locator, blkno, freespace);
9242 2510334 : }
9243 :
9244 : /*
9245 : * Handles MULTI_INSERT record type.
9246 : */
9247 : static void
9248 105748 : heap_xlog_multi_insert(XLogReaderState *record)
9249 : {
9250 105748 : XLogRecPtr lsn = record->EndRecPtr;
9251 : xl_heap_multi_insert *xlrec;
9252 : RelFileLocator rlocator;
9253 : BlockNumber blkno;
9254 : Buffer buffer;
9255 : Page page;
9256 : union
9257 : {
9258 : HeapTupleHeaderData hdr;
9259 : char data[MaxHeapTupleSize];
9260 : } tbuf;
9261 : HeapTupleHeader htup;
9262 : uint32 newlen;
9263 105748 : Size freespace = 0;
9264 : int i;
9265 105748 : bool isinit = (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE) != 0;
9266 : XLogRedoAction action;
9267 :
9268 : /*
9269 : * Insertion doesn't overwrite MVCC data, so no conflict processing is
9270 : * required.
9271 : */
9272 105748 : xlrec = (xl_heap_multi_insert *) XLogRecGetData(record);
9273 :
9274 105748 : XLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);
9275 :
9276 : /* check that the mutually exclusive flags are not both set */
9277 : Assert(!((xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED) &&
9278 : (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)));
9279 :
9280 : /*
9281 : * The visibility map may need to be fixed even if the heap page is
9282 : * already up-to-date.
9283 : */
9284 105748 : if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
9285 : {
9286 948 : Relation reln = CreateFakeRelcacheEntry(rlocator);
9287 948 : Buffer vmbuffer = InvalidBuffer;
9288 :
9289 948 : visibilitymap_pin(reln, blkno, &vmbuffer);
9290 948 : visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
9291 948 : ReleaseBuffer(vmbuffer);
9292 948 : FreeFakeRelcacheEntry(reln);
9293 : }
9294 :
9295 105748 : if (isinit)
9296 : {
9297 4160 : buffer = XLogInitBufferForRedo(record, 0);
9298 4160 : page = BufferGetPage(buffer);
9299 4160 : PageInit(page, BufferGetPageSize(buffer), 0);
9300 4160 : action = BLK_NEEDS_REDO;
9301 : }
9302 : else
9303 101588 : action = XLogReadBufferForRedo(record, 0, &buffer);
9304 105748 : if (action == BLK_NEEDS_REDO)
9305 : {
9306 : char *tupdata;
9307 : char *endptr;
9308 : Size len;
9309 :
9310 : /* Tuples are stored as block data */
9311 104824 : tupdata = XLogRecGetBlockData(record, 0, &len);
9312 104824 : endptr = tupdata + len;
9313 :
9314 104824 : page = (Page) BufferGetPage(buffer);
9315 :
9316 507190 : for (i = 0; i < xlrec->ntuples; i++)
9317 : {
9318 : OffsetNumber offnum;
9319 : xl_multi_insert_tuple *xlhdr;
9320 :
9321 : /*
9322 : * If we're reinitializing the page, the tuples are stored in
9323 : * order from FirstOffsetNumber. Otherwise there's an array of
9324 : * offsets in the WAL record, and the tuples come after that.
9325 : */
9326 402366 : if (isinit)
9327 199972 : offnum = FirstOffsetNumber + i;
9328 : else
9329 202394 : offnum = xlrec->offsets[i];
9330 402366 : if (PageGetMaxOffsetNumber(page) + 1 < offnum)
9331 0 : elog(PANIC, "invalid max offset number");
9332 :
9333 402366 : xlhdr = (xl_multi_insert_tuple *) SHORTALIGN(tupdata);
9334 402366 : tupdata = ((char *) xlhdr) + SizeOfMultiInsertTuple;
9335 :
9336 402366 : newlen = xlhdr->datalen;
9337 : Assert(newlen <= MaxHeapTupleSize);
9338 402366 : htup = &tbuf.hdr;
9339 402366 : MemSet((char *) htup, 0, SizeofHeapTupleHeader);
9340 : /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
9341 402366 : memcpy((char *) htup + SizeofHeapTupleHeader,
9342 : (char *) tupdata,
9343 : newlen);
9344 402366 : tupdata += newlen;
9345 :
9346 402366 : newlen += SizeofHeapTupleHeader;
9347 402366 : htup->t_infomask2 = xlhdr->t_infomask2;
9348 402366 : htup->t_infomask = xlhdr->t_infomask;
9349 402366 : htup->t_hoff = xlhdr->t_hoff;
9350 402366 : HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
9351 402366 : HeapTupleHeaderSetCmin(htup, FirstCommandId);
9352 402366 : ItemPointerSetBlockNumber(&htup->t_ctid, blkno);
9353 402366 : ItemPointerSetOffsetNumber(&htup->t_ctid, offnum);
9354 :
9355 402366 : offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
9356 402366 : if (offnum == InvalidOffsetNumber)
9357 0 : elog(PANIC, "failed to add tuple");
9358 : }
9359 104824 : if (tupdata != endptr)
9360 0 : elog(PANIC, "total tuple length mismatch");
9361 :
9362 104824 : freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
9363 :
9364 104824 : PageSetLSN(page, lsn);
9365 :
9366 104824 : if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
9367 270 : PageClearAllVisible(page);
9368 :
9369 : /* XLH_INSERT_ALL_FROZEN_SET implies that all tuples are visible */
9370 104824 : if (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)
9371 8 : PageSetAllVisible(page);
9372 :
9373 104824 : MarkBufferDirty(buffer);
9374 : }
9375 105748 : if (BufferIsValid(buffer))
9376 105748 : UnlockReleaseBuffer(buffer);
9377 :
9378 : /*
9379 : * If the page is running low on free space, update the FSM as well.
9380 : * Arbitrarily, our definition of "low" is less than 20%. We can't do much
9381 : * better than that without knowing the fill-factor for the table.
9382 : *
9383 : * XXX: Don't do this if the page was restored from full page image. We
9384 : * don't bother to update the FSM in that case, it doesn't need to be
9385 : * totally accurate anyway.
9386 : */
9387 105748 : if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
9388 26166 : XLogRecordPageWithFreeSpace(rlocator, blkno, freespace);
9389 105748 : }
9390 :
9391 : /*
9392 : * Handles UPDATE and HOT_UPDATE
9393 : */
9394 : static void
9395 185594 : heap_xlog_update(XLogReaderState *record, bool hot_update)
9396 : {
9397 185594 : XLogRecPtr lsn = record->EndRecPtr;
9398 185594 : xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
9399 : RelFileLocator rlocator;
9400 : BlockNumber oldblk;
9401 : BlockNumber newblk;
9402 : ItemPointerData newtid;
9403 : Buffer obuffer,
9404 : nbuffer;
9405 : Page page;
9406 : OffsetNumber offnum;
9407 185594 : ItemId lp = NULL;
9408 : HeapTupleData oldtup;
9409 : HeapTupleHeader htup;
9410 185594 : uint16 prefixlen = 0,
9411 185594 : suffixlen = 0;
9412 : char *newp;
9413 : union
9414 : {
9415 : HeapTupleHeaderData hdr;
9416 : char data[MaxHeapTupleSize];
9417 : } tbuf;
9418 : xl_heap_header xlhdr;
9419 : uint32 newlen;
9420 185594 : Size freespace = 0;
9421 : XLogRedoAction oldaction;
9422 : XLogRedoAction newaction;
9423 :
9424 : /* initialize to keep the compiler quiet */
9425 185594 : oldtup.t_data = NULL;
9426 185594 : oldtup.t_len = 0;
9427 :
9428 185594 : XLogRecGetBlockTag(record, 0, &rlocator, NULL, &newblk);
9429 185594 : if (XLogRecGetBlockTagExtended(record, 1, NULL, NULL, &oldblk, NULL))
9430 : {
9431 : /* HOT updates are never done across pages */
9432 : Assert(!hot_update);
9433 : }
9434 : else
9435 77584 : oldblk = newblk;
9436 :
9437 185594 : ItemPointerSet(&newtid, newblk, xlrec->new_offnum);
9438 :
9439 : /*
9440 : * The visibility map may need to be fixed even if the heap page is
9441 : * already up-to-date.
9442 : */
9443 185594 : if (xlrec->flags & XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED)
9444 : {
9445 470 : Relation reln = CreateFakeRelcacheEntry(rlocator);
9446 470 : Buffer vmbuffer = InvalidBuffer;
9447 :
9448 470 : visibilitymap_pin(reln, oldblk, &vmbuffer);
9449 470 : visibilitymap_clear(reln, oldblk, vmbuffer, VISIBILITYMAP_VALID_BITS);
9450 470 : ReleaseBuffer(vmbuffer);
9451 470 : FreeFakeRelcacheEntry(reln);
9452 : }
9453 :
9454 : /*
9455 : * In normal operation, it is important to lock the two pages in
9456 : * page-number order, to avoid possible deadlocks against other update
9457 : * operations going the other way. However, during WAL replay there can
9458 : * be no other update happening, so we don't need to worry about that. But
9459 : * we *do* need to worry that we don't expose an inconsistent state to Hot
9460 : * Standby queries --- so the original page can't be unlocked before we've
9461 : * added the new tuple to the new page.
9462 : */
9463 :
9464 : /* Deal with old tuple version */
9465 185594 : oldaction = XLogReadBufferForRedo(record, (oldblk == newblk) ? 0 : 1,
9466 : &obuffer);
9467 185594 : if (oldaction == BLK_NEEDS_REDO)
9468 : {
9469 185548 : page = BufferGetPage(obuffer);
9470 185548 : offnum = xlrec->old_offnum;
9471 185548 : if (PageGetMaxOffsetNumber(page) >= offnum)
9472 185548 : lp = PageGetItemId(page, offnum);
9473 :
9474 185548 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9475 0 : elog(PANIC, "invalid lp");
9476 :
9477 185548 : htup = (HeapTupleHeader) PageGetItem(page, lp);
9478 :
9479 185548 : oldtup.t_data = htup;
9480 185548 : oldtup.t_len = ItemIdGetLength(lp);
9481 :
9482 185548 : htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9483 185548 : htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9484 185548 : if (hot_update)
9485 72452 : HeapTupleHeaderSetHotUpdated(htup);
9486 : else
9487 113096 : HeapTupleHeaderClearHotUpdated(htup);
9488 185548 : fix_infomask_from_infobits(xlrec->old_infobits_set, &htup->t_infomask,
9489 : &htup->t_infomask2);
9490 185548 : HeapTupleHeaderSetXmax(htup, xlrec->old_xmax);
9491 185548 : HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
9492 : /* Set forward chain link in t_ctid */
9493 185548 : htup->t_ctid = newtid;
9494 :
9495 : /* Mark the page as a candidate for pruning */
9496 185548 : PageSetPrunable(page, XLogRecGetXid(record));
9497 :
9498 185548 : if (xlrec->flags & XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED)
9499 466 : PageClearAllVisible(page);
9500 :
9501 185548 : PageSetLSN(page, lsn);
9502 185548 : MarkBufferDirty(obuffer);
9503 : }
9504 :
9505 : /*
9506 : * Read the page the new tuple goes into, if different from old.
9507 : */
9508 185594 : if (oldblk == newblk)
9509 : {
9510 77584 : nbuffer = obuffer;
9511 77584 : newaction = oldaction;
9512 : }
9513 108010 : else if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
9514 : {
9515 1292 : nbuffer = XLogInitBufferForRedo(record, 0);
9516 1292 : page = (Page) BufferGetPage(nbuffer);
9517 1292 : PageInit(page, BufferGetPageSize(nbuffer), 0);
9518 1292 : newaction = BLK_NEEDS_REDO;
9519 : }
9520 : else
9521 106718 : newaction = XLogReadBufferForRedo(record, 0, &nbuffer);
9522 :
9523 : /*
9524 : * The visibility map may need to be fixed even if the heap page is
9525 : * already up-to-date.
9526 : */
9527 185594 : if (xlrec->flags & XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED)
9528 : {
9529 60 : Relation reln = CreateFakeRelcacheEntry(rlocator);
9530 60 : Buffer vmbuffer = InvalidBuffer;
9531 :
9532 60 : visibilitymap_pin(reln, newblk, &vmbuffer);
9533 60 : visibilitymap_clear(reln, newblk, vmbuffer, VISIBILITYMAP_VALID_BITS);
9534 60 : ReleaseBuffer(vmbuffer);
9535 60 : FreeFakeRelcacheEntry(reln);
9536 : }
9537 :
9538 : /* Deal with new tuple */
9539 185594 : if (newaction == BLK_NEEDS_REDO)
9540 : {
9541 : char *recdata;
9542 : char *recdata_end;
9543 : Size datalen;
9544 : Size tuplen;
9545 :
9546 185504 : recdata = XLogRecGetBlockData(record, 0, &datalen);
9547 185504 : recdata_end = recdata + datalen;
9548 :
9549 185504 : page = BufferGetPage(nbuffer);
9550 :
9551 185504 : offnum = xlrec->new_offnum;
9552 185504 : if (PageGetMaxOffsetNumber(page) + 1 < offnum)
9553 0 : elog(PANIC, "invalid max offset number");
9554 :
9555 185504 : if (xlrec->flags & XLH_UPDATE_PREFIX_FROM_OLD)
9556 : {
9557 : Assert(newblk == oldblk);
9558 30368 : memcpy(&prefixlen, recdata, sizeof(uint16));
9559 30368 : recdata += sizeof(uint16);
9560 : }
9561 185504 : if (xlrec->flags & XLH_UPDATE_SUFFIX_FROM_OLD)
9562 : {
9563 : Assert(newblk == oldblk);
9564 67384 : memcpy(&suffixlen, recdata, sizeof(uint16));
9565 67384 : recdata += sizeof(uint16);
9566 : }
9567 :
9568 185504 : memcpy((char *) &xlhdr, recdata, SizeOfHeapHeader);
9569 185504 : recdata += SizeOfHeapHeader;
9570 :
9571 185504 : tuplen = recdata_end - recdata;
9572 : Assert(tuplen <= MaxHeapTupleSize);
9573 :
9574 185504 : htup = &tbuf.hdr;
9575 185504 : MemSet((char *) htup, 0, SizeofHeapTupleHeader);
9576 :
9577 : /*
9578 : * Reconstruct the new tuple using the prefix and/or suffix from the
9579 : * old tuple, and the data stored in the WAL record.
9580 : */
9581 185504 : newp = (char *) htup + SizeofHeapTupleHeader;
9582 185504 : if (prefixlen > 0)
9583 : {
9584 : int len;
9585 :
9586 : /* copy bitmap [+ padding] [+ oid] from WAL record */
9587 30368 : len = xlhdr.t_hoff - SizeofHeapTupleHeader;
9588 30368 : memcpy(newp, recdata, len);
9589 30368 : recdata += len;
9590 30368 : newp += len;
9591 :
9592 : /* copy prefix from old tuple */
9593 30368 : memcpy(newp, (char *) oldtup.t_data + oldtup.t_data->t_hoff, prefixlen);
9594 30368 : newp += prefixlen;
9595 :
9596 : /* copy new tuple data from WAL record */
9597 30368 : len = tuplen - (xlhdr.t_hoff - SizeofHeapTupleHeader);
9598 30368 : memcpy(newp, recdata, len);
9599 30368 : recdata += len;
9600 30368 : newp += len;
9601 : }
9602 : else
9603 : {
9604 : /*
9605 : * copy bitmap [+ padding] [+ oid] + data from record, all in one
9606 : * go
9607 : */
9608 155136 : memcpy(newp, recdata, tuplen);
9609 155136 : recdata += tuplen;
9610 155136 : newp += tuplen;
9611 : }
9612 : Assert(recdata == recdata_end);
9613 :
9614 : /* copy suffix from old tuple */
9615 185504 : if (suffixlen > 0)
9616 67384 : memcpy(newp, (char *) oldtup.t_data + oldtup.t_len - suffixlen, suffixlen);
9617 :
9618 185504 : newlen = SizeofHeapTupleHeader + tuplen + prefixlen + suffixlen;
9619 185504 : htup->t_infomask2 = xlhdr.t_infomask2;
9620 185504 : htup->t_infomask = xlhdr.t_infomask;
9621 185504 : htup->t_hoff = xlhdr.t_hoff;
9622 :
9623 185504 : HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
9624 185504 : HeapTupleHeaderSetCmin(htup, FirstCommandId);
9625 185504 : HeapTupleHeaderSetXmax(htup, xlrec->new_xmax);
9626 : /* Make sure there is no forward chain link in t_ctid */
9627 185504 : htup->t_ctid = newtid;
9628 :
9629 185504 : offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
9630 185504 : if (offnum == InvalidOffsetNumber)
9631 0 : elog(PANIC, "failed to add tuple");
9632 :
9633 185504 : if (xlrec->flags & XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED)
9634 32 : PageClearAllVisible(page);
9635 :
9636 185504 : freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
9637 :
9638 185504 : PageSetLSN(page, lsn);
9639 185504 : MarkBufferDirty(nbuffer);
9640 : }
9641 :
9642 185594 : if (BufferIsValid(nbuffer) && nbuffer != obuffer)
9643 108010 : UnlockReleaseBuffer(nbuffer);
9644 185594 : if (BufferIsValid(obuffer))
9645 185594 : UnlockReleaseBuffer(obuffer);
9646 :
9647 : /*
9648 : * If the new page is running low on free space, update the FSM as well.
9649 : * Arbitrarily, our definition of "low" is less than 20%. We can't do much
9650 : * better than that without knowing the fill-factor for the table.
9651 : *
9652 : * However, don't update the FSM on HOT updates, because after crash
9653 : * recovery, either the old or the new tuple will certainly be dead and
9654 : * prunable. After pruning, the page will have roughly as much free space
9655 : * as it did before the update, assuming the new tuple is about the same
9656 : * size as the old one.
9657 : *
9658 : * XXX: Don't do this if the page was restored from full page image. We
9659 : * don't bother to update the FSM in that case, it doesn't need to be
9660 : * totally accurate anyway.
9661 : */
9662 185594 : if (newaction == BLK_NEEDS_REDO && !hot_update && freespace < BLCKSZ / 5)
9663 22986 : XLogRecordPageWithFreeSpace(rlocator, newblk, freespace);
9664 185594 : }
9665 :
9666 : static void
9667 122 : heap_xlog_confirm(XLogReaderState *record)
9668 : {
9669 122 : XLogRecPtr lsn = record->EndRecPtr;
9670 122 : xl_heap_confirm *xlrec = (xl_heap_confirm *) XLogRecGetData(record);
9671 : Buffer buffer;
9672 : Page page;
9673 : OffsetNumber offnum;
9674 122 : ItemId lp = NULL;
9675 : HeapTupleHeader htup;
9676 :
9677 122 : if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9678 : {
9679 122 : page = BufferGetPage(buffer);
9680 :
9681 122 : offnum = xlrec->offnum;
9682 122 : if (PageGetMaxOffsetNumber(page) >= offnum)
9683 122 : lp = PageGetItemId(page, offnum);
9684 :
9685 122 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9686 0 : elog(PANIC, "invalid lp");
9687 :
9688 122 : htup = (HeapTupleHeader) PageGetItem(page, lp);
9689 :
9690 : /*
9691 : * Confirm tuple as actually inserted
9692 : */
9693 122 : ItemPointerSet(&htup->t_ctid, BufferGetBlockNumber(buffer), offnum);
9694 :
9695 122 : PageSetLSN(page, lsn);
9696 122 : MarkBufferDirty(buffer);
9697 : }
9698 122 : if (BufferIsValid(buffer))
9699 122 : UnlockReleaseBuffer(buffer);
9700 122 : }
9701 :
9702 : static void
9703 109736 : heap_xlog_lock(XLogReaderState *record)
9704 : {
9705 109736 : XLogRecPtr lsn = record->EndRecPtr;
9706 109736 : xl_heap_lock *xlrec = (xl_heap_lock *) XLogRecGetData(record);
9707 : Buffer buffer;
9708 : Page page;
9709 : OffsetNumber offnum;
9710 109736 : ItemId lp = NULL;
9711 : HeapTupleHeader htup;
9712 :
9713 : /*
9714 : * The visibility map may need to be fixed even if the heap page is
9715 : * already up-to-date.
9716 : */
9717 109736 : if (xlrec->flags & XLH_LOCK_ALL_FROZEN_CLEARED)
9718 : {
9719 : RelFileLocator rlocator;
9720 22 : Buffer vmbuffer = InvalidBuffer;
9721 : BlockNumber block;
9722 : Relation reln;
9723 :
9724 22 : XLogRecGetBlockTag(record, 0, &rlocator, NULL, &block);
9725 22 : reln = CreateFakeRelcacheEntry(rlocator);
9726 :
9727 22 : visibilitymap_pin(reln, block, &vmbuffer);
9728 22 : visibilitymap_clear(reln, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN);
9729 :
9730 22 : ReleaseBuffer(vmbuffer);
9731 22 : FreeFakeRelcacheEntry(reln);
9732 : }
9733 :
9734 109736 : if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9735 : {
9736 109628 : page = (Page) BufferGetPage(buffer);
9737 :
9738 109628 : offnum = xlrec->offnum;
9739 109628 : if (PageGetMaxOffsetNumber(page) >= offnum)
9740 109628 : lp = PageGetItemId(page, offnum);
9741 :
9742 109628 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9743 0 : elog(PANIC, "invalid lp");
9744 :
9745 109628 : htup = (HeapTupleHeader) PageGetItem(page, lp);
9746 :
9747 109628 : htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9748 109628 : htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9749 109628 : fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
9750 : &htup->t_infomask2);
9751 :
9752 : /*
9753 : * Clear relevant update flags, but only if the modified infomask says
9754 : * there's no update.
9755 : */
9756 109628 : if (HEAP_XMAX_IS_LOCKED_ONLY(htup->t_infomask))
9757 : {
9758 109628 : HeapTupleHeaderClearHotUpdated(htup);
9759 : /* Make sure there is no forward chain link in t_ctid */
9760 109628 : ItemPointerSet(&htup->t_ctid,
9761 : BufferGetBlockNumber(buffer),
9762 : offnum);
9763 : }
9764 109628 : HeapTupleHeaderSetXmax(htup, xlrec->xmax);
9765 109628 : HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
9766 109628 : PageSetLSN(page, lsn);
9767 109628 : MarkBufferDirty(buffer);
9768 : }
9769 109736 : if (BufferIsValid(buffer))
9770 109736 : UnlockReleaseBuffer(buffer);
9771 109736 : }
9772 :
9773 : static void
9774 0 : heap_xlog_lock_updated(XLogReaderState *record)
9775 : {
9776 0 : XLogRecPtr lsn = record->EndRecPtr;
9777 : xl_heap_lock_updated *xlrec;
9778 : Buffer buffer;
9779 : Page page;
9780 : OffsetNumber offnum;
9781 0 : ItemId lp = NULL;
9782 : HeapTupleHeader htup;
9783 :
9784 0 : xlrec = (xl_heap_lock_updated *) XLogRecGetData(record);
9785 :
9786 : /*
9787 : * The visibility map may need to be fixed even if the heap page is
9788 : * already up-to-date.
9789 : */
9790 0 : if (xlrec->flags & XLH_LOCK_ALL_FROZEN_CLEARED)
9791 : {
9792 : RelFileLocator rlocator;
9793 0 : Buffer vmbuffer = InvalidBuffer;
9794 : BlockNumber block;
9795 : Relation reln;
9796 :
9797 0 : XLogRecGetBlockTag(record, 0, &rlocator, NULL, &block);
9798 0 : reln = CreateFakeRelcacheEntry(rlocator);
9799 :
9800 0 : visibilitymap_pin(reln, block, &vmbuffer);
9801 0 : visibilitymap_clear(reln, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN);
9802 :
9803 0 : ReleaseBuffer(vmbuffer);
9804 0 : FreeFakeRelcacheEntry(reln);
9805 : }
9806 :
9807 0 : if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9808 : {
9809 0 : page = BufferGetPage(buffer);
9810 :
9811 0 : offnum = xlrec->offnum;
9812 0 : if (PageGetMaxOffsetNumber(page) >= offnum)
9813 0 : lp = PageGetItemId(page, offnum);
9814 :
9815 0 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9816 0 : elog(PANIC, "invalid lp");
9817 :
9818 0 : htup = (HeapTupleHeader) PageGetItem(page, lp);
9819 :
9820 0 : htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9821 0 : htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9822 0 : fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
9823 : &htup->t_infomask2);
9824 0 : HeapTupleHeaderSetXmax(htup, xlrec->xmax);
9825 :
9826 0 : PageSetLSN(page, lsn);
9827 0 : MarkBufferDirty(buffer);
9828 : }
9829 0 : if (BufferIsValid(buffer))
9830 0 : UnlockReleaseBuffer(buffer);
9831 0 : }
9832 :
9833 : static void
9834 13780 : heap_xlog_inplace(XLogReaderState *record)
9835 : {
9836 13780 : XLogRecPtr lsn = record->EndRecPtr;
9837 13780 : xl_heap_inplace *xlrec = (xl_heap_inplace *) XLogRecGetData(record);
9838 : Buffer buffer;
9839 : Page page;
9840 : OffsetNumber offnum;
9841 13780 : ItemId lp = NULL;
9842 : HeapTupleHeader htup;
9843 : uint32 oldlen;
9844 : Size newlen;
9845 :
9846 13780 : if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9847 : {
9848 13720 : char *newtup = XLogRecGetBlockData(record, 0, &newlen);
9849 :
9850 13720 : page = BufferGetPage(buffer);
9851 :
9852 13720 : offnum = xlrec->offnum;
9853 13720 : if (PageGetMaxOffsetNumber(page) >= offnum)
9854 13720 : lp = PageGetItemId(page, offnum);
9855 :
9856 13720 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9857 0 : elog(PANIC, "invalid lp");
9858 :
9859 13720 : htup = (HeapTupleHeader) PageGetItem(page, lp);
9860 :
9861 13720 : oldlen = ItemIdGetLength(lp) - htup->t_hoff;
9862 13720 : if (oldlen != newlen)
9863 0 : elog(PANIC, "wrong tuple length");
9864 :
9865 13720 : memcpy((char *) htup + htup->t_hoff, newtup, newlen);
9866 :
9867 13720 : PageSetLSN(page, lsn);
9868 13720 : MarkBufferDirty(buffer);
9869 : }
9870 13780 : if (BufferIsValid(buffer))
9871 13780 : UnlockReleaseBuffer(buffer);
9872 13780 : }
9873 :
9874 : void
9875 3401666 : heap_redo(XLogReaderState *record)
9876 : {
9877 3401666 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9878 :
9879 : /*
9880 : * These operations don't overwrite MVCC data so no conflict processing is
9881 : * required. The ones in heap2 rmgr do.
9882 : */
9883 :
9884 3401666 : switch (info & XLOG_HEAP_OPMASK)
9885 : {
9886 2510334 : case XLOG_HEAP_INSERT:
9887 2510334 : heap_xlog_insert(record);
9888 2510334 : break;
9889 582096 : case XLOG_HEAP_DELETE:
9890 582096 : heap_xlog_delete(record);
9891 582096 : break;
9892 113110 : case XLOG_HEAP_UPDATE:
9893 113110 : heap_xlog_update(record, false);
9894 113110 : break;
9895 4 : case XLOG_HEAP_TRUNCATE:
9896 :
9897 : /*
9898 : * TRUNCATE is a no-op because the actions are already logged as
9899 : * SMGR WAL records. TRUNCATE WAL record only exists for logical
9900 : * decoding.
9901 : */
9902 4 : break;
9903 72484 : case XLOG_HEAP_HOT_UPDATE:
9904 72484 : heap_xlog_update(record, true);
9905 72484 : break;
9906 122 : case XLOG_HEAP_CONFIRM:
9907 122 : heap_xlog_confirm(record);
9908 122 : break;
9909 109736 : case XLOG_HEAP_LOCK:
9910 109736 : heap_xlog_lock(record);
9911 109736 : break;
9912 13780 : case XLOG_HEAP_INPLACE:
9913 13780 : heap_xlog_inplace(record);
9914 13780 : break;
9915 0 : default:
9916 0 : elog(PANIC, "heap_redo: unknown op code %u", info);
9917 : }
9918 3401666 : }
9919 :
9920 : void
9921 131182 : heap2_redo(XLogReaderState *record)
9922 : {
9923 131182 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9924 :
9925 131182 : switch (info & XLOG_HEAP_OPMASK)
9926 : {
9927 16398 : case XLOG_HEAP2_PRUNE_ON_ACCESS:
9928 : case XLOG_HEAP2_PRUNE_VACUUM_SCAN:
9929 : case XLOG_HEAP2_PRUNE_VACUUM_CLEANUP:
9930 16398 : heap_xlog_prune_freeze(record);
9931 16398 : break;
9932 7336 : case XLOG_HEAP2_VISIBLE:
9933 7336 : heap_xlog_visible(record);
9934 7336 : break;
9935 105748 : case XLOG_HEAP2_MULTI_INSERT:
9936 105748 : heap_xlog_multi_insert(record);
9937 105748 : break;
9938 0 : case XLOG_HEAP2_LOCK_UPDATED:
9939 0 : heap_xlog_lock_updated(record);
9940 0 : break;
9941 1700 : case XLOG_HEAP2_NEW_CID:
9942 :
9943 : /*
9944 : * Nothing to do on a real replay, only used during logical
9945 : * decoding.
9946 : */
9947 1700 : break;
9948 0 : case XLOG_HEAP2_REWRITE:
9949 0 : heap_xlog_logical_rewrite(record);
9950 0 : break;
9951 0 : default:
9952 0 : elog(PANIC, "heap2_redo: unknown op code %u", info);
9953 : }
9954 131182 : }
9955 :
9956 : /*
9957 : * Mask a heap page before performing consistency checks on it.
9958 : */
9959 : void
9960 0 : heap_mask(char *pagedata, BlockNumber blkno)
9961 : {
9962 0 : Page page = (Page) pagedata;
9963 : OffsetNumber off;
9964 :
9965 0 : mask_page_lsn_and_checksum(page);
9966 :
9967 0 : mask_page_hint_bits(page);
9968 0 : mask_unused_space(page);
9969 :
9970 0 : for (off = 1; off <= PageGetMaxOffsetNumber(page); off++)
9971 : {
9972 0 : ItemId iid = PageGetItemId(page, off);
9973 : char *page_item;
9974 :
9975 0 : page_item = (char *) (page + ItemIdGetOffset(iid));
9976 :
9977 0 : if (ItemIdIsNormal(iid))
9978 : {
9979 0 : HeapTupleHeader page_htup = (HeapTupleHeader) page_item;
9980 :
9981 : /*
9982 : * If xmin of a tuple is not yet frozen, we should ignore
9983 : * differences in hint bits, since they can be set without
9984 : * emitting WAL.
9985 : */
9986 0 : if (!HeapTupleHeaderXminFrozen(page_htup))
9987 0 : page_htup->t_infomask &= ~HEAP_XACT_MASK;
9988 : else
9989 : {
9990 : /* Still we need to mask xmax hint bits. */
9991 0 : page_htup->t_infomask &= ~HEAP_XMAX_INVALID;
9992 0 : page_htup->t_infomask &= ~HEAP_XMAX_COMMITTED;
9993 : }
9994 :
9995 : /*
9996 : * During replay, we set Command Id to FirstCommandId. Hence, mask
9997 : * it. See heap_xlog_insert() for details.
9998 : */
9999 0 : page_htup->t_choice.t_heap.t_field3.t_cid = MASK_MARKER;
10000 :
10001 : /*
10002 : * For a speculative tuple, heap_insert() does not set ctid in the
10003 : * caller-passed heap tuple itself, leaving the ctid field to
10004 : * contain a speculative token value - a per-backend monotonically
10005 : * increasing identifier. Besides, it does not WAL-log ctid under
10006 : * any circumstances.
10007 : *
10008 : * During redo, heap_xlog_insert() sets t_ctid to current block
10009 : * number and self offset number. It doesn't care about any
10010 : * speculative insertions on the primary. Hence, we set t_ctid to
10011 : * current block number and self offset number to ignore any
10012 : * inconsistency.
10013 : */
10014 0 : if (HeapTupleHeaderIsSpeculative(page_htup))
10015 0 : ItemPointerSet(&page_htup->t_ctid, blkno, off);
10016 :
10017 : /*
10018 : * NB: Not ignoring ctid changes due to the tuple having moved
10019 : * (i.e. HeapTupleHeaderIndicatesMovedPartitions), because that's
10020 : * important information that needs to be in-sync between primary
10021 : * and standby, and thus is WAL logged.
10022 : */
10023 : }
10024 :
10025 : /*
10026 : * Ignore any padding bytes after the tuple, when the length of the
10027 : * item is not MAXALIGNed.
10028 : */
10029 0 : if (ItemIdHasStorage(iid))
10030 : {
10031 0 : int len = ItemIdGetLength(iid);
10032 0 : int padlen = MAXALIGN(len) - len;
10033 :
10034 0 : if (padlen > 0)
10035 0 : memset(page_item + len, MASK_MARKER, padlen);
10036 : }
10037 : }
10038 0 : }
10039 :
10040 : /*
10041 : * HeapCheckForSerializableConflictOut
10042 : * We are reading a tuple. If it's not visible, there may be a
10043 : * rw-conflict out with the inserter. Otherwise, if it is visible to us
10044 : * but has been deleted, there may be a rw-conflict out with the deleter.
10045 : *
10046 : * We will determine the top level xid of the writing transaction with which
10047 : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
10048 : * for overlap with our own transaction.
10049 : *
10050 : * This function should be called just about anywhere in heapam.c where a
10051 : * tuple has been read. The caller must hold at least a shared lock on the
10052 : * buffer, because this function might set hint bits on the tuple. There is
10053 : * currently no known reason to call this function from an index AM.
10054 : */
10055 : void
10056 54169622 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
10057 : HeapTuple tuple, Buffer buffer,
10058 : Snapshot snapshot)
10059 : {
10060 : TransactionId xid;
10061 : HTSV_Result htsvResult;
10062 :
10063 54169622 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
10064 54118928 : return;
10065 :
10066 : /*
10067 : * Check to see whether the tuple has been written to by a concurrent
10068 : * transaction, either to create it not visible to us, or to delete it
10069 : * while it is visible to us. The "visible" bool indicates whether the
10070 : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
10071 : * is going on with it.
10072 : *
10073 : * In the event of a concurrently inserted tuple that also happens to have
10074 : * been concurrently updated (by a separate transaction), the xmin of the
10075 : * tuple will be used -- not the updater's xid.
10076 : */
10077 50694 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
10078 50694 : switch (htsvResult)
10079 : {
10080 49090 : case HEAPTUPLE_LIVE:
10081 49090 : if (visible)
10082 49064 : return;
10083 26 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
10084 26 : break;
10085 704 : case HEAPTUPLE_RECENTLY_DEAD:
10086 : case HEAPTUPLE_DELETE_IN_PROGRESS:
10087 704 : if (visible)
10088 562 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
10089 : else
10090 142 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
10091 :
10092 704 : if (TransactionIdPrecedes(xid, TransactionXmin))
10093 : {
10094 : /* This is like the HEAPTUPLE_DEAD case */
10095 : Assert(!visible);
10096 130 : return;
10097 : }
10098 574 : break;
10099 652 : case HEAPTUPLE_INSERT_IN_PROGRESS:
10100 652 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
10101 652 : break;
10102 248 : case HEAPTUPLE_DEAD:
10103 : Assert(!visible);
10104 248 : return;
10105 0 : default:
10106 :
10107 : /*
10108 : * The only way to get to this default clause is if a new value is
10109 : * added to the enum type without adding it to this switch
10110 : * statement. That's a bug, so elog.
10111 : */
10112 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
10113 :
10114 : /*
10115 : * In spite of having all enum values covered and calling elog on
10116 : * this default, some compilers think this is a code path which
10117 : * allows xid to be used below without initialization. Silence
10118 : * that warning.
10119 : */
10120 : xid = InvalidTransactionId;
10121 : }
10122 :
10123 : Assert(TransactionIdIsValid(xid));
10124 : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
10125 :
10126 : /*
10127 : * Find top level xid. Bail out if xid is too early to be a conflict, or
10128 : * if it's our own xid.
10129 : */
10130 1252 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
10131 124 : return;
10132 1128 : xid = SubTransGetTopmostTransaction(xid);
10133 1128 : if (TransactionIdPrecedes(xid, TransactionXmin))
10134 0 : return;
10135 :
10136 1128 : CheckForSerializableConflictOut(relation, xid, snapshot);
10137 : }
|