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