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