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