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