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 : 16777881 : 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 : 16777881 : }
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 : 146228 : heap_scan_stream_read_next_parallel(ReadStream *stream,
256 : : void *callback_private_data,
257 : : void *per_buffer_data)
258 : : {
259 : 146228 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
260 : :
261 : : Assert(ScanDirectionIsForward(scan->rs_dir));
262 : : Assert(scan->rs_base.rs_parallel);
263 : :
264 [ + + ]: 146228 : if (unlikely(!scan->rs_inited))
265 : : {
266 : : /* parallel scan */
267 : 2767 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
268 : 2767 : scan->rs_parallelworkerdata,
269 : 2767 : (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 : 5534 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
275 : 2767 : scan->rs_parallelworkerdata,
276 : 2767 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
277 : 2767 : 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 : 146228 : 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 : 4208440 : heap_scan_stream_read_next_serial(ReadStream *stream,
296 : : void *callback_private_data,
297 : : void *per_buffer_data)
298 : : {
299 : 4208440 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
300 : :
301 [ + + ]: 4208440 : if (unlikely(!scan->rs_inited))
302 : : {
303 : 1091300 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
304 : 1091300 : scan->rs_inited = true;
305 : : }
306 : : else
307 : 3117140 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
308 : : scan->rs_prefetch_block,
309 : : scan->rs_dir);
310 : :
311 : 4208440 : 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 : 259802 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
321 : : void *per_buffer_data)
322 : : {
323 : 259802 : TBMIterateResult *tbmres = per_buffer_data;
324 : 259802 : BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
325 : 259802 : HeapScanDesc hscan = (HeapScanDesc) bscan;
326 : 259802 : TableScanDesc sscan = &hscan->rs_base;
327 : :
328 : : for (;;)
329 : : {
330 [ - + ]: 259802 : CHECK_FOR_INTERRUPTS();
331 : :
332 : : /* no more entries in the bitmap */
333 [ + + ]: 259802 : if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
334 : 15168 : 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 [ + + ]: 244634 : if (!IsolationIsSerializable() &&
345 [ - + ]: 244525 : tbmres->blockno >= hscan->rs_nblocks)
346 : 0 : continue;
347 : :
348 : 244634 : 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 : 1130623 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
361 : : {
362 : 1130623 : 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 [ + + ]: 1130623 : if (scan->rs_base.rs_parallel != NULL)
378 : : {
379 : 4628 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
380 : 4628 : scan->rs_nblocks = bpscan->phs_nblocks;
381 : : }
382 : : else
383 : 1125995 : 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 [ + + ]: 1130621 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
398 [ + + ]: 1112878 : scan->rs_nblocks > NBuffers / 4)
399 : : {
400 : 14663 : allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
401 : 14663 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
402 : : }
403 : : else
404 : 1115958 : allow_strat = allow_sync = false;
405 : :
406 [ + + ]: 1130621 : if (allow_strat)
407 : : {
408 : : /* During a rescan, keep the previous strategy object. */
409 [ + + ]: 13325 : if (scan->rs_strategy == NULL)
410 : 13096 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
411 : : }
412 : : else
413 : : {
414 [ - + ]: 1117296 : if (scan->rs_strategy != NULL)
415 : 0 : FreeAccessStrategy(scan->rs_strategy);
416 : 1117296 : scan->rs_strategy = NULL;
417 : : }
418 : :
419 [ + + ]: 1130621 : if (scan->rs_base.rs_parallel != NULL)
420 : : {
421 : : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
422 [ + + ]: 4628 : if (scan->rs_base.rs_parallel->phs_syncscan)
423 : 5 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
424 : : else
425 : 4623 : 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 [ + + ]: 4628 : if (!keep_startblock)
435 : 4476 : scan->rs_startblock = InvalidBlockNumber;
436 : : }
437 : : else
438 : : {
439 [ + + ]: 1125993 : 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 [ + + + + ]: 654362 : if (allow_sync && synchronize_seqscans)
447 : 84 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
448 : : else
449 : 654278 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
450 : : }
451 [ + + + + ]: 471631 : 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 : 471492 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
459 : 471492 : scan->rs_startblock = 0;
460 : : }
461 : : }
462 : :
463 : 1130621 : scan->rs_numblocks = InvalidBlockNumber;
464 : 1130621 : scan->rs_inited = false;
465 : 1130621 : scan->rs_ctup.t_data = NULL;
466 : 1130621 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
467 : 1130621 : scan->rs_cbuf = InvalidBuffer;
468 : 1130621 : scan->rs_cblock = InvalidBlockNumber;
469 : 1130621 : scan->rs_ntuples = 0;
470 : 1130621 : 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 : 1130621 : scan->rs_dir = ForwardScanDirection;
477 : 1130621 : 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 [ + + + + ]: 1130621 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
485 : 267117 : 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 [ + + ]: 1130621 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
493 [ + + + + : 1094618 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
+ + ]
494 : 1130621 : }
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 : 3275 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
504 : : {
505 : 3275 : 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 : 3275 : scan->rs_startblock = startBlk;
515 : 3275 : scan->rs_numblocks = numBlks;
516 : 3275 : }
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 : 3126974 : 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 : 3126974 : Oid relid = RelationGetRelid(scan->rs_base.rs_rd);
531 : 3126974 : int ntup = 0;
532 : 3126974 : 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 [ + + ]: 171111053 : for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
540 : : {
541 : 167984079 : ItemId lpp = PageGetItemId(page, lineoff);
542 : : HeapTuple tup;
543 : :
544 [ + + ]: 167984079 : if (unlikely(!ItemIdIsNormal(lpp)))
545 : 33911588 : 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 [ + + - + ]: 134072491 : if (!all_visible || check_serializable)
554 : : {
555 : 68930421 : tup = &batchmvcc.tuples[ntup];
556 : :
557 : 68930421 : tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
558 : 68930421 : tup->t_len = ItemIdGetLength(lpp);
559 : 68930421 : tup->t_tableOid = relid;
560 : 68930421 : 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 [ + + ]: 134072491 : if (all_visible)
568 : : {
569 [ - + ]: 65142070 : if (check_serializable)
570 : : {
571 : 0 : batchmvcc.visible[ntup] = true;
572 : : }
573 : 65142070 : scan->rs_vistuples[ntup] = lineoff;
574 : : }
575 : :
576 : 134072491 : 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 [ + + ]: 3126974 : if (all_visible)
587 : 1368815 : nvis = ntup;
588 : : else
589 : 1758159 : nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
590 : : ntup,
591 : : &batchmvcc,
592 : 1758159 : 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 [ + + ]: 3126678 : if (check_serializable)
599 : : {
600 [ + + ]: 2068 : for (int i = 0; i < ntup; i++)
601 : : {
602 : 1453 : HeapCheckForSerializableConflictOut(batchmvcc.visible[i],
603 : : scan->rs_base.rs_rd,
604 : : &batchmvcc.tuples[i],
605 : : buffer, snapshot);
606 : : }
607 : : }
608 : :
609 : 3126670 : 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 : 3126974 : heap_prepare_pagescan(TableScanDesc sscan)
620 : : {
621 : 3126974 : HeapScanDesc scan = (HeapScanDesc) sscan;
622 : 3126974 : Buffer buffer = scan->rs_cbuf;
623 : 3126974 : 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 : 3126974 : snapshot = scan->rs_base.rs_snapshot;
635 : :
636 : : /*
637 : : * Prune and repair fragmentation for the whole page, if possible.
638 : : */
639 : 3126974 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer, &scan->rs_vmbuffer,
640 : 3126974 : 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 : 3126974 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
648 : :
649 : 3126974 : page = BufferGetPage(buffer);
650 : 3126974 : 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 [ + + + + ]: 3126974 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
673 : : check_serializable =
674 : 3126974 : 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 [ + + ]: 3126974 : if (likely(all_visible))
683 : : {
684 [ + - ]: 1368815 : if (likely(!check_serializable))
685 : 1368815 : 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 [ + + ]: 1758159 : if (likely(!check_serializable))
694 : 1757536 : 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 : 3126966 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
702 : 3126966 : }
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 : 4137365 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
712 : : {
713 : : Assert(scan->rs_read_stream);
714 : :
715 : : /* release previous scan buffer, if any */
716 [ + + ]: 4137365 : if (BufferIsValid(scan->rs_cbuf))
717 : : {
718 : 3043258 : ReleaseBuffer(scan->rs_cbuf);
719 : 3043258 : 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 [ + + ]: 4137365 : 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 [ + + ]: 4137364 : 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 : 4137364 : scan->rs_dir = dir;
742 : :
743 : 4137364 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
744 [ + + ]: 4137336 : if (BufferIsValid(scan->rs_cbuf))
745 : 3238345 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
746 : 4137336 : }
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 : 1091340 : 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 [ + + + + ]: 1091340 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
763 : 529080 : return InvalidBlockNumber;
764 : :
765 [ + + ]: 562260 : if (ScanDirectionIsForward(dir))
766 : : {
767 : 562214 : 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 : 117058 : 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 : 117058 : page = BufferGetPage(scan->rs_cbuf);
813 : :
814 : 117058 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
815 : :
816 [ + - ]: 117058 : if (ScanDirectionIsForward(dir))
817 : 117058 : *lineoff = FirstOffsetNumber;
818 : : else
819 : 0 : *lineoff = (OffsetNumber) (*linesleft);
820 : :
821 : : /* lineoff now references the physically previous or next tid */
822 : 117058 : 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 : 9444982 : 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 : 9444982 : page = BufferGetPage(scan->rs_cbuf);
844 : :
845 [ + - ]: 9444982 : if (ScanDirectionIsForward(dir))
846 : : {
847 : 9444982 : *lineoff = OffsetNumberNext(scan->rs_coffset);
848 : 9444982 : *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 : 9444982 : 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 : 3117448 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
881 : : {
882 : : Assert(scan->rs_base.rs_parallel == NULL);
883 : :
884 [ + + ]: 3117448 : if (likely(ScanDirectionIsForward(dir)))
885 : : {
886 : 3117358 : block++;
887 : :
888 : : /* wrap back to the start of the heap */
889 [ + + ]: 3117358 : if (block >= scan->rs_nblocks)
890 : 442568 : 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 [ + + ]: 3117358 : 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 [ + + ]: 3117358 : if (block == scan->rs_startblock)
909 : 442518 : return InvalidBlockNumber;
910 : :
911 : : /* check if the limit imposed by heap_setscanlimits() is met */
912 [ + + ]: 2674840 : if (scan->rs_numblocks != InvalidBlockNumber)
913 : : {
914 : : BlockNumber endblock;
915 : :
916 : 2823 : endblock = (scan->rs_startblock + scan->rs_numblocks) %
917 : 2823 : scan->rs_nblocks;
918 [ + + ]: 2823 : if (block == endblock)
919 : 1602 : return InvalidBlockNumber;
920 : : }
921 : :
922 : 2673238 : 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 : 9471550 : heapgettup(HeapScanDesc scan,
967 : : ScanDirection dir,
968 : : int nkeys,
969 : : ScanKey key)
970 : : {
971 : 9471550 : HeapTuple tuple = &(scan->rs_ctup);
972 : : Page page;
973 : : OffsetNumber lineoff;
974 : : int linesleft;
975 : :
976 [ + + ]: 9471550 : if (likely(scan->rs_inited))
977 : : {
978 : : /* continue from previously returned page/tuple */
979 : 9444982 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
980 : 9444982 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
981 : 9444982 : 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 : 142741 : heap_fetch_next_buffer(scan, dir);
991 : :
992 : : /* did we run out of blocks to scan? */
993 [ + + ]: 142741 : if (!BufferIsValid(scan->rs_cbuf))
994 : 25683 : break;
995 : :
996 : : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
997 : :
998 : 117058 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
999 : 117058 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
1000 : 9562040 : 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 [ + + ]: 9628835 : for (; linesleft > 0; linesleft--, lineoff += dir)
1010 : : {
1011 : : bool visible;
1012 : 9512662 : ItemId lpp = PageGetItemId(page, lineoff);
1013 : :
1014 [ + + ]: 9512662 : if (!ItemIdIsNormal(lpp))
1015 : 46045 : continue;
1016 : :
1017 : 9466617 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1018 : 9466617 : tuple->t_len = ItemIdGetLength(lpp);
1019 : 9466617 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1020 : :
1021 : 9466617 : visible = HeapTupleSatisfiesVisibility(tuple,
1022 : : scan->rs_base.rs_snapshot,
1023 : : scan->rs_cbuf);
1024 : :
1025 : 9466617 : 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 [ + + ]: 9466617 : if (!visible)
1031 : 6792 : continue;
1032 : :
1033 : : /* skip any tuples that don't match the scan key */
1034 [ + + ]: 9459825 : if (key != NULL &&
1035 [ + + ]: 14693 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1036 : : nkeys, key))
1037 : 13958 : continue;
1038 : :
1039 : 9445867 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1040 : 9445867 : scan->rs_coffset = lineoff;
1041 : 9445867 : 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 [ - + ]: 25683 : if (BufferIsValid(scan->rs_cbuf))
1053 : 0 : ReleaseBuffer(scan->rs_cbuf);
1054 : :
1055 : 25683 : scan->rs_cbuf = InvalidBuffer;
1056 : 25683 : scan->rs_cblock = InvalidBlockNumber;
1057 : 25683 : scan->rs_prefetch_block = InvalidBlockNumber;
1058 : 25683 : tuple->t_data = NULL;
1059 : 25683 : 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 : 65119029 : heapgettup_pagemode(HeapScanDesc scan,
1077 : : ScanDirection dir,
1078 : : int nkeys,
1079 : : ScanKey key)
1080 : : {
1081 : 65119029 : HeapTuple tuple = &(scan->rs_ctup);
1082 : : Page page;
1083 : : uint32 lineindex;
1084 : : uint32 linesleft;
1085 : :
1086 [ + + ]: 65119029 : if (likely(scan->rs_inited))
1087 : : {
1088 : : /* continue from previously returned page/tuple */
1089 : 64051490 : page = BufferGetPage(scan->rs_cbuf);
1090 : :
1091 : 64051490 : lineindex = scan->rs_cindex + dir;
1092 [ + + ]: 64051490 : if (ScanDirectionIsForward(dir))
1093 : 64051032 : 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 : 64051490 : 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 : 3994624 : heap_fetch_next_buffer(scan, dir);
1108 : :
1109 : : /* did we run out of blocks to scan? */
1110 [ + + ]: 3994595 : if (!BufferIsValid(scan->rs_cbuf))
1111 : 873308 : break;
1112 : :
1113 : : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1114 : :
1115 : : /* prune the page and determine visible tuple offsets */
1116 : 3121287 : heap_prepare_pagescan((TableScanDesc) scan);
1117 : 3121279 : page = BufferGetPage(scan->rs_cbuf);
1118 : 3121279 : linesleft = scan->rs_ntuples;
1119 [ + + ]: 3121279 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1120 : :
1121 : : /* block is the same for all tuples, set it once outside the loop */
1122 : 3121279 : ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1123 : :
1124 : : /* lineindex now references the next or previous visible tid */
1125 : 67172769 : continue_page:
1126 : :
1127 [ + + ]: 125400216 : for (; linesleft > 0; linesleft--, lineindex += dir)
1128 : : {
1129 : : ItemId lpp;
1130 : : OffsetNumber lineoff;
1131 : :
1132 : : Assert(lineindex < scan->rs_ntuples);
1133 : 122473131 : lineoff = scan->rs_vistuples[lineindex];
1134 : 122473131 : lpp = PageGetItemId(page, lineoff);
1135 : : Assert(ItemIdIsNormal(lpp));
1136 : :
1137 : 122473131 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1138 : 122473131 : tuple->t_len = ItemIdGetLength(lpp);
1139 : 122473131 : ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1140 : :
1141 : : /* skip any tuples that don't match the scan key */
1142 [ + + ]: 122473131 : if (key != NULL &&
1143 [ + + ]: 58679671 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1144 : : nkeys, key))
1145 : 58227447 : continue;
1146 : :
1147 : 64245684 : scan->rs_cindex = lineindex;
1148 : 64245684 : return;
1149 : : }
1150 : : }
1151 : :
1152 : : /* end of scan */
1153 [ - + ]: 873308 : if (BufferIsValid(scan->rs_cbuf))
1154 : 0 : ReleaseBuffer(scan->rs_cbuf);
1155 : 873308 : scan->rs_cbuf = InvalidBuffer;
1156 : 873308 : scan->rs_cblock = InvalidBlockNumber;
1157 : 873308 : scan->rs_prefetch_block = InvalidBlockNumber;
1158 : 873308 : tuple->t_data = NULL;
1159 : 873308 : scan->rs_inited = false;
1160 : : }
1161 : :
1162 : :
1163 : : /* ----------------------------------------------------------------
1164 : : * heap access method interface
1165 : : * ----------------------------------------------------------------
1166 : : */
1167 : :
1168 : :
1169 : : TableScanDesc
1170 : 476149 : 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 : 476149 : RelationIncrementReferenceCount(relation);
1185 : :
1186 : : /*
1187 : : * allocate and initialize scan descriptor
1188 : : */
1189 [ + + ]: 476149 : if (flags & SO_TYPE_BITMAPSCAN)
1190 : : {
1191 : 13023 : 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 : 13023 : scan = (HeapScanDesc) bscan;
1198 : : }
1199 : : else
1200 : 463126 : scan = (HeapScanDesc) palloc_object(HeapScanDescData);
1201 : :
1202 : 476149 : scan->rs_base.rs_rd = relation;
1203 : 476149 : scan->rs_base.rs_snapshot = snapshot;
1204 : 476149 : scan->rs_base.rs_nkeys = nkeys;
1205 : 476149 : scan->rs_base.rs_flags = flags;
1206 : 476149 : scan->rs_base.rs_parallel = parallel_scan;
1207 : 476149 : scan->rs_base.rs_instrument = NULL;
1208 : 476149 : scan->rs_strategy = NULL; /* set in initscan */
1209 : 476149 : scan->rs_cbuf = InvalidBuffer;
1210 : :
1211 : : /*
1212 : : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1213 : : */
1214 [ + + + + ]: 476149 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
1215 : 37671 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1216 : :
1217 : : /* Check that a historic snapshot is not used for non-catalog tables */
1218 [ + + ]: 476149 : if (snapshot &&
1219 [ + + ]: 465046 : IsHistoricMVCCSnapshot(snapshot) &&
1220 [ + + + - : 735 : !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 [ + + ]: 476149 : 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 : 450239 : PredicateLockRelation(relation, snapshot);
1250 : : }
1251 : :
1252 : : /* we only need to set this up once */
1253 : 476149 : 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 [ + + ]: 476149 : if (parallel_scan != NULL)
1260 : 4476 : scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
1261 : : else
1262 : 471673 : 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 [ + + ]: 476149 : if (nkeys > 0)
1269 : 267156 : scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
1270 : : else
1271 : 208993 : scan->rs_base.rs_key = NULL;
1272 : :
1273 : 476149 : initscan(scan, key, false);
1274 : :
1275 : 476147 : 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 [ + + ]: 476147 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1283 [ + + ]: 26005 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
1284 : 451435 : {
1285 : : ReadStreamBlockNumberCB cb;
1286 : :
1287 [ + + ]: 451440 : if (scan->rs_base.rs_parallel)
1288 : 4476 : cb = heap_scan_stream_read_next_parallel;
1289 : : else
1290 : 446964 : 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 : 451440 : 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 [ + + ]: 24707 : else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1309 : : {
1310 : 13023 : 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 [ + + + - ]: 476142 : 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 : 476142 : scan->rs_vmbuffer = InvalidBuffer;
1329 : :
1330 : 476142 : return (TableScanDesc) scan;
1331 : : }
1332 : :
1333 : : void
1334 : 654514 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1335 : : bool allow_strat, bool allow_sync, bool allow_pagemode)
1336 : : {
1337 : 654514 : HeapScanDesc scan = (HeapScanDesc) sscan;
1338 : :
1339 [ + + ]: 654514 : if (set_params)
1340 : : {
1341 [ + - ]: 19 : if (allow_strat)
1342 : 19 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1343 : : else
1344 : 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1345 : :
1346 [ + + ]: 19 : if (allow_sync)
1347 : 8 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1348 : : else
1349 : 11 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1350 : :
1351 [ + - + - ]: 19 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1352 [ + - ]: 19 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1353 : 19 : 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 [ + + ]: 654514 : if (BufferIsValid(scan->rs_cbuf))
1362 : : {
1363 : 2143 : ReleaseBuffer(scan->rs_cbuf);
1364 : 2143 : scan->rs_cbuf = InvalidBuffer;
1365 : : }
1366 : :
1367 [ + + ]: 654514 : if (BufferIsValid(scan->rs_vmbuffer))
1368 : : {
1369 : 18 : ReleaseBuffer(scan->rs_vmbuffer);
1370 : 18 : 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 [ + + ]: 654514 : if (scan->rs_read_stream)
1384 : 646828 : read_stream_reset(scan->rs_read_stream);
1385 : :
1386 : : /*
1387 : : * reinitialize scan descriptor
1388 : : */
1389 : 654514 : initscan(scan, key, true);
1390 : 654514 : }
1391 : :
1392 : : void
1393 : 472906 : heap_endscan(TableScanDesc sscan)
1394 : : {
1395 : 472906 : HeapScanDesc scan = (HeapScanDesc) sscan;
1396 : :
1397 : : /* Note: no locking manipulations needed */
1398 : :
1399 : : /*
1400 : : * unpin scan buffers
1401 : : */
1402 [ + + ]: 472906 : if (BufferIsValid(scan->rs_cbuf))
1403 : 190682 : ReleaseBuffer(scan->rs_cbuf);
1404 : :
1405 [ + + ]: 472906 : if (BufferIsValid(scan->rs_vmbuffer))
1406 : 2748 : ReleaseBuffer(scan->rs_vmbuffer);
1407 : :
1408 : : /*
1409 : : * Must free the read stream before freeing the BufferAccessStrategy.
1410 : : */
1411 [ + + ]: 472906 : if (scan->rs_read_stream)
1412 : 461289 : read_stream_end(scan->rs_read_stream);
1413 : :
1414 : : /*
1415 : : * decrement relation reference count and free scan descriptor storage
1416 : : */
1417 : 472906 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1418 : :
1419 [ + + ]: 472906 : if (scan->rs_base.rs_key)
1420 : 267122 : pfree(scan->rs_base.rs_key);
1421 : :
1422 [ + + ]: 472906 : if (scan->rs_strategy != NULL)
1423 : 13086 : FreeAccessStrategy(scan->rs_strategy);
1424 : :
1425 [ + + ]: 472906 : if (scan->rs_parallelworkerdata != NULL)
1426 : 4476 : pfree(scan->rs_parallelworkerdata);
1427 : :
1428 [ + + ]: 472906 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1429 : 50943 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1430 : :
1431 [ + + ]: 472906 : if (scan->rs_base.rs_instrument)
1432 : 8 : pfree(scan->rs_base.rs_instrument);
1433 : :
1434 : 472906 : pfree(scan);
1435 : 472906 : }
1436 : :
1437 : : HeapTuple
1438 : 12641516 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1439 : : {
1440 : 12641516 : 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 [ - + ]: 12641516 : 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 [ + + ]: 12641516 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1457 : 3737978 : heapgettup_pagemode(scan, direction,
1458 : 3737978 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1459 : : else
1460 : 8903538 : heapgettup(scan, direction,
1461 : 8903538 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1462 : :
1463 [ + + ]: 12641516 : if (scan->rs_ctup.t_data == NULL)
1464 : 81429 : 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 [ - + - - : 12560087 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - ]
1472 : :
1473 : 12560087 : return &scan->rs_ctup;
1474 : : }
1475 : :
1476 : : bool
1477 : 61942199 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1478 : : {
1479 : 61942199 : HeapScanDesc scan = (HeapScanDesc) sscan;
1480 : :
1481 : : /* Note: no locking manipulations needed */
1482 : :
1483 [ + + ]: 61942199 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1484 : 61374187 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1485 : : else
1486 : 568012 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1487 : :
1488 [ + + ]: 61942172 : if (scan->rs_ctup.t_data == NULL)
1489 : : {
1490 : 817420 : ExecClearTuple(slot);
1491 : 817420 : 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 [ + + - + : 61124752 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ + ]
1500 : :
1501 : 61124752 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1502 : : scan->rs_cbuf);
1503 : 61124752 : 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 : 2863424 : heap_fetch(Relation relation,
1688 : : Snapshot snapshot,
1689 : : HeapTuple tuple,
1690 : : Buffer *userbuf,
1691 : : bool keep_buf)
1692 : : {
1693 : 2863424 : 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 : 2863424 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1704 : :
1705 : : /*
1706 : : * Need share lock on buffer to examine tuple commit status.
1707 : : */
1708 : 2863416 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
1709 : 2863416 : 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 : 2863416 : offnum = ItemPointerGetOffsetNumber(tid);
1716 [ + - + + ]: 2863416 : 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 : 2863412 : lp = PageGetItemId(page, offnum);
1728 : :
1729 : : /*
1730 : : * Must check for deleted tuple.
1731 : : */
1732 [ + + ]: 2863412 : 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 : 2863080 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1744 : 2863080 : tuple->t_len = ItemIdGetLength(lp);
1745 : 2863080 : tuple->t_tableOid = RelationGetRelid(relation);
1746 : :
1747 : : /*
1748 : : * check tuple visibility, then release lock
1749 : : */
1750 : 2863080 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1751 : :
1752 [ + + ]: 2863080 : if (valid)
1753 : 2862991 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1754 : 2862991 : HeapTupleHeaderGetXmin(tuple->t_data));
1755 : :
1756 : 2863080 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1757 : :
1758 : 2863080 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1759 : :
1760 [ + + ]: 2863080 : 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 : 2862991 : *userbuf = buffer;
1767 : :
1768 : 2862991 : 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 : 244 : 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 [ + + ]: 244 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1924 : : {
1925 [ + + + + ]: 435 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1926 : 192 : TransactionIdDidCommit(xid))
1927 : 165 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1928 : : xid);
1929 : : else
1930 : 78 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1931 : : InvalidTransactionId);
1932 : : }
1933 : 244 : }
1934 : :
1935 : :
1936 : : /*
1937 : : * GetBulkInsertState - prepare status object for a bulk insert
1938 : : */
1939 : : BulkInsertState
1940 : 3154 : GetBulkInsertState(void)
1941 : : {
1942 : : BulkInsertState bistate;
1943 : :
1944 : 3154 : bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
1945 : 3154 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1946 : 3154 : bistate->current_buf = InvalidBuffer;
1947 : 3154 : bistate->next_free = InvalidBlockNumber;
1948 : 3154 : bistate->last_free = InvalidBlockNumber;
1949 : 3154 : bistate->already_extended_by = 0;
1950 : 3154 : 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 : 2379 : 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 : 12016244 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2008 : : uint32 options, BulkInsertState bistate)
2009 : : {
2010 : 12016244 : TransactionId xid = GetCurrentTransactionId();
2011 : : HeapTuple heaptup;
2012 : : Buffer buffer;
2013 : : Page page;
2014 : 12016240 : Buffer vmbuffer = InvalidBuffer;
2015 : 12016240 : bool clear_all_visible = false;
2016 : 12016240 : 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 : 12016240 : 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 : 12016240 : 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 : 12016240 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2037 : : InvalidBuffer, options, bistate,
2038 : : &vmbuffer, NULL,
2039 : : 0);
2040 : :
2041 : 12016238 : 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 : 12016238 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2059 : :
2060 : : /* Lock the vmbuffer before the critical section */
2061 [ + + ]: 12016221 : if (PageIsAllVisible(page))
2062 : : {
2063 : 8739 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2064 : 8739 : clear_all_visible = true;
2065 : : }
2066 : :
2067 : : /* NO EREPORT(ERROR) from here till changes are logged */
2068 : 12016221 : START_CRIT_SECTION();
2069 : :
2070 : 12016221 : RelationPutHeapTuple(relation, buffer, heaptup,
2071 : 12016221 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2072 : :
2073 [ + + ]: 12016221 : if (clear_all_visible)
2074 : : {
2075 : : /* It's possible the VM bits were already clear */
2076 [ + + ]: 8739 : if (visibilitymap_clear(relation->rd_locator,
2077 : 8739 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2078 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
2079 : 8736 : vmbuffer_modified = true;
2080 : :
2081 : 8739 : 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 [ + + + + ]: 12016221 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
2098 [ + + + + ]: 11341046 : PageSetPrunable(page, xid);
2099 : :
2100 : 12016221 : MarkBufferDirty(buffer);
2101 : :
2102 : : /* XLOG stuff */
2103 [ + + + + : 12016221 : if (RelationNeedsWAL(relation))
+ + + + ]
2104 : : {
2105 : : xl_heap_insert xlrec;
2106 : : xl_heap_header xlhdr;
2107 : : XLogRecPtr recptr;
2108 : 10791604 : uint8 info = XLOG_HEAP_INSERT;
2109 : 10791604 : 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 [ + + + + : 10791604 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
2116 : 3852 : 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 [ + + + + ]: 10916760 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2124 : 125156 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2125 : : {
2126 : 123952 : info |= XLOG_HEAP_INIT_PAGE;
2127 : 123952 : bufflags |= REGBUF_WILL_INIT;
2128 : : }
2129 : :
2130 : 10791604 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2131 : 10791604 : xlrec.flags = 0;
2132 [ + + ]: 10791604 : if (clear_all_visible)
2133 : 8660 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2134 [ + + ]: 10791604 : 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 [ + + + + : 10791604 : if (RelationIsLogicallyLogged(relation) &&
+ - - + -
- - - + -
+ + ]
2144 [ + + ]: 278507 : !(options & HEAP_INSERT_NO_LOGICAL))
2145 : : {
2146 : 278358 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2147 : 278358 : bufflags |= REGBUF_KEEP_DATA;
2148 : :
2149 [ + + ]: 278358 : if (IsToastRelation(relation))
2150 : 1907 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2151 : : }
2152 : :
2153 : 10791604 : XLogBeginInsert();
2154 : 10791604 : XLogRegisterData(&xlrec, SizeOfHeapInsert);
2155 : :
2156 : 10791604 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2157 : 10791604 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2158 : 10791604 : 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 : 10791604 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_HEAP, buffer,
2166 : 10791604 : REGBUF_STANDARD | bufflags);
2167 : 10791604 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP, &xlhdr,
2168 : : SizeOfHeapHeader);
2169 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2170 : 10791604 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP,
2171 : 10791604 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2172 : 10791604 : heaptup->t_len - SizeofHeapTupleHeader);
2173 : :
2174 : : /* filtering by origin on a row level is much more efficient */
2175 : 10791604 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2176 : :
2177 [ + + ]: 10791604 : if (vmbuffer_modified)
2178 : 8657 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_VM, vmbuffer, 0);
2179 : :
2180 : 10791604 : recptr = XLogInsert(RM_HEAP_ID, info);
2181 : :
2182 : 10791604 : PageSetLSN(page, recptr);
2183 : :
2184 [ + + ]: 10791604 : if (vmbuffer_modified)
2185 : 8657 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2186 : : }
2187 : :
2188 : 12016221 : END_CRIT_SECTION();
2189 : :
2190 : 12016221 : 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 [ + + ]: 12016221 : if (clear_all_visible)
2197 : 8739 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2198 [ + + ]: 12016221 : if (BufferIsValid(vmbuffer))
2199 : 9101 : 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 : 12016221 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2208 : :
2209 : : /* Note: speculative insertions are counted too, even if aborted later */
2210 : 12016221 : 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 [ + + ]: 12016221 : if (heaptup != tup)
2217 : : {
2218 : 22443 : tup->t_self = heaptup->t_self;
2219 : 22443 : heap_freetuple(heaptup);
2220 : : }
2221 : 12016221 : }
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 : 13810978 : 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 [ - + ]: 13810978 : if (IsParallelWorker())
2240 [ # # ]: 0 : ereport(ERROR,
2241 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2242 : : errmsg("cannot insert tuples in a parallel worker")));
2243 : :
2244 : 13810978 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2245 : 13810978 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2246 : 13810978 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
2247 : 13810978 : HeapTupleHeaderSetXmin(tup->t_data, xid);
2248 [ + + ]: 13810978 : if (options & HEAP_INSERT_FROZEN)
2249 : 102652 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2250 : :
2251 : 13810978 : HeapTupleHeaderSetCmin(tup->t_data, cid);
2252 : 13810978 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2253 : 13810978 : 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 [ + + ]: 13810978 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2260 [ + + ]: 41166 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2261 : : {
2262 : : /* toast table entries should never be recursively toasted */
2263 : : Assert(!HeapTupleHasExternal(tup));
2264 : 41105 : return tup;
2265 : : }
2266 [ + + + + ]: 13769873 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2267 : 22518 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2268 : : else
2269 : 13747355 : 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 : 468355 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2279 : : {
2280 : 468355 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2281 : 468355 : int npages = 1;
2282 : :
2283 [ + + ]: 2937048 : for (int i = done; i < ntuples; i++)
2284 : : {
2285 : 2468693 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2286 : :
2287 [ + + ]: 2468693 : if (page_avail < tup_sz)
2288 : : {
2289 : 17493 : npages++;
2290 : 17493 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2291 : : }
2292 : 2468693 : page_avail -= tup_sz;
2293 : : }
2294 : :
2295 : 468355 : 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 : 460513 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2311 : : CommandId cid, uint32 options, BulkInsertState bistate)
2312 : : {
2313 : 460513 : TransactionId xid = GetCurrentTransactionId();
2314 : : HeapTuple *heaptuples;
2315 : : int i;
2316 : : int ndone;
2317 : : PGAlignedBlock scratch;
2318 : : Page page;
2319 : 460513 : Buffer vmbuffer = InvalidBuffer;
2320 : : bool needwal;
2321 : : Size saveFreeSpace;
2322 [ + + + + : 460513 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
+ - - + -
- - - + -
+ + ]
2323 [ + + + + : 460513 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
+ - - + -
- - - + +
- + - - -
- - - ]
2324 : 460513 : bool starting_with_empty_page = false;
2325 : 460513 : int npages = 0;
2326 : 460513 : int npages_used = 0;
2327 : :
2328 : : /* currently not needed (thus unsupported) for heap_multi_insert() */
2329 : : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2330 : :
2331 : 460513 : AssertHasSnapshotForToast(relation);
2332 : :
2333 [ + + + + : 460513 : needwal = RelationNeedsWAL(relation);
+ + + + ]
2334 [ + + ]: 460513 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2335 : : HEAP_DEFAULT_FILLFACTOR);
2336 : :
2337 : : /* Toast and set header data in all the slots */
2338 : 460513 : heaptuples = palloc_array(HeapTuple, ntuples);
2339 [ + + ]: 2255251 : for (i = 0; i < ntuples; i++)
2340 : : {
2341 : : HeapTuple tuple;
2342 : :
2343 : 1794738 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2344 : 1794738 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2345 : 1794738 : tuple->t_tableOid = slots[i]->tts_tableOid;
2346 : 1794738 : 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 : 460513 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2374 : :
2375 : 460513 : ndone = 0;
2376 [ + + ]: 938111 : while (ndone < ntuples)
2377 : : {
2378 : : Buffer buffer;
2379 : 477598 : bool clear_all_visible = false;
2380 : 477598 : bool all_frozen_set = false;
2381 : 477598 : bool vmbuffer_modified = false;
2382 : : int nthispage;
2383 : :
2384 [ + + ]: 477598 : 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 [ + + + + ]: 477598 : if (ndone == 0 || !starting_with_empty_page)
2397 : : {
2398 : 468355 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2399 : : saveFreeSpace);
2400 : 468355 : npages_used = 0;
2401 : : }
2402 : : else
2403 : 9243 : 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 : 477598 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2413 : : InvalidBuffer, options, bistate,
2414 : : &vmbuffer, NULL,
2415 : : npages - npages_used);
2416 : 477598 : page = BufferGetPage(buffer);
2417 : :
2418 : 477598 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2419 : :
2420 [ + + + + ]: 477598 : 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 [ + + + + ]: 475933 : else if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2427 : : {
2428 : 4843 : clear_all_visible = true;
2429 : : /* Lock the vmbuffer before entering the critical section */
2430 : 4843 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2431 : : }
2432 : :
2433 : : /* NO EREPORT(ERROR) from here till changes are logged */
2434 : 477598 : 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 : 477598 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2441 : :
2442 : : /*
2443 : : * For logical decoding we need combo CIDs to properly decode the
2444 : : * catalog.
2445 : : */
2446 [ + + + + ]: 477598 : if (needwal && need_cids)
2447 : 5620 : log_heap_new_cid(relation, heaptuples[ndone]);
2448 : :
2449 [ + + ]: 1794738 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2450 : : {
2451 : 1334225 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2452 : :
2453 [ + + ]: 1334225 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2454 : 17085 : break;
2455 : :
2456 : 1317140 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2457 : :
2458 : : /*
2459 : : * For logical decoding we need combo CIDs to properly decode the
2460 : : * catalog.
2461 : : */
2462 [ + + + + ]: 1317140 : if (needwal && need_cids)
2463 : 5194 : 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 [ + + ]: 477598 : if (clear_all_visible)
2475 : : {
2476 : : Assert(!(options & HEAP_INSERT_FROZEN));
2477 : : /* It's possible the VM bits were already clear */
2478 [ + + ]: 4843 : if (visibilitymap_clear(relation->rd_locator,
2479 : : BufferGetBlockNumber(buffer),
2480 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
2481 : 4842 : vmbuffer_modified = true;
2482 : :
2483 : 4843 : PageClearAllVisible(page);
2484 : : }
2485 [ + + ]: 472755 : 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 [ + + + + ]: 477598 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
2502 [ + + + + ]: 454239 : PageSetPrunable(page, xid);
2503 : :
2504 : 477598 : MarkBufferDirty(buffer);
2505 : :
2506 : : /* XLOG stuff */
2507 [ + + ]: 477598 : if (needwal)
2508 : : {
2509 : : XLogRecPtr recptr;
2510 : : xl_heap_multi_insert *xlrec;
2511 : 473698 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2512 : : char *tupledata;
2513 : : int totaldatalen;
2514 : 473698 : char *scratchptr = scratch.data;
2515 : : bool init;
2516 : 473698 : 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 : 473698 : init = starting_with_empty_page;
2523 : :
2524 : : /* allocate xl_heap_multi_insert struct from the scratch area */
2525 : 473698 : xlrec = (xl_heap_multi_insert *) scratchptr;
2526 : 473698 : 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 [ + + ]: 473698 : if (!init)
2535 : 458504 : scratchptr += nthispage * sizeof(OffsetNumber);
2536 : :
2537 : : /* the rest of the scratch space is used for tuple data */
2538 : 473698 : tupledata = scratchptr;
2539 : :
2540 : : /* check that the mutually exclusive flags are not both set */
2541 : : Assert(!(clear_all_visible && all_frozen_set));
2542 : :
2543 : 473698 : xlrec->flags = 0;
2544 [ + + ]: 473698 : if (clear_all_visible)
2545 : 4843 : 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 [ + + ]: 473698 : if (all_frozen_set)
2553 : 21 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2554 : :
2555 : 473698 : xlrec->ntuples = nthispage;
2556 : :
2557 : : /*
2558 : : * Write out an xl_multi_insert_tuple and the tuple data itself
2559 : : * for each tuple.
2560 : : */
2561 [ + + ]: 2061258 : for (i = 0; i < nthispage; i++)
2562 : : {
2563 : 1587560 : HeapTuple heaptup = heaptuples[ndone + i];
2564 : : xl_multi_insert_tuple *tuphdr;
2565 : : int datalen;
2566 : :
2567 [ + + ]: 1587560 : if (!init)
2568 : 958442 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2569 : : /* xl_multi_insert_tuple needs two-byte alignment. */
2570 : 1587560 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2571 : 1587560 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2572 : :
2573 : 1587560 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2574 : 1587560 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2575 : 1587560 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2576 : :
2577 : : /* write bitmap [+ padding] [+ oid] + data */
2578 : 1587560 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
2579 : 1587560 : memcpy(scratchptr,
2580 : 1587560 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2581 : : datalen);
2582 : 1587560 : tuphdr->datalen = datalen;
2583 : 1587560 : scratchptr += datalen;
2584 : : }
2585 : 473698 : totaldatalen = scratchptr - tupledata;
2586 : : Assert((scratchptr - scratch.data) < BLCKSZ);
2587 : :
2588 [ + + ]: 473698 : if (need_tuple_data)
2589 : 58 : 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 [ + + ]: 473698 : if (ndone + nthispage == ntuples)
2597 : 460058 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2598 : :
2599 [ + + ]: 473698 : if (init)
2600 : : {
2601 : 15194 : info |= XLOG_HEAP_INIT_PAGE;
2602 : 15194 : 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 [ + + ]: 473698 : if (need_tuple_data)
2610 : 58 : bufflags |= REGBUF_KEEP_DATA;
2611 : :
2612 : 473698 : XLogBeginInsert();
2613 : 473698 : XLogRegisterData(xlrec, tupledata - scratch.data);
2614 : 473698 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_HEAP, buffer,
2615 : 473698 : REGBUF_STANDARD | bufflags);
2616 [ + + + + ]: 473698 : if (all_frozen_set || vmbuffer_modified)
2617 : 4863 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_VM, vmbuffer, 0);
2618 : :
2619 : 473698 : XLogRegisterBufData(HEAP_MULTI_INSERT_BLKREF_HEAP, tupledata,
2620 : : totaldatalen);
2621 : :
2622 : : /* filtering by origin on a row level is much more efficient */
2623 : 473698 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2624 : :
2625 : 473698 : recptr = XLogInsert(RM_HEAP2_ID, info);
2626 : :
2627 : 473698 : PageSetLSN(page, recptr);
2628 [ + + + + ]: 473698 : if (all_frozen_set || vmbuffer_modified)
2629 : : {
2630 : : Assert(BufferIsDirty(vmbuffer));
2631 : 4863 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2632 : : }
2633 : : }
2634 : :
2635 : 477598 : 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 [ + + + + ]: 477598 : if (all_frozen_set || clear_all_visible)
2642 : 6508 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2643 : :
2644 : 477598 : UnlockReleaseBuffer(buffer);
2645 : 477598 : 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 [ + + ]: 460513 : if (vmbuffer != InvalidBuffer)
2656 : 4924 : 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 : 460513 : 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 [ + + ]: 460513 : if (IsCatalogRelation(relation))
2681 : : {
2682 [ + + ]: 1542623 : for (i = 0; i < ntuples; i++)
2683 : 1083587 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2684 : : }
2685 : :
2686 : : /* copy t_self fields back to the caller's slots */
2687 [ + + ]: 2255251 : for (i = 0; i < ntuples; i++)
2688 : 1794738 : slots[i]->tts_tid = heaptuples[i]->t_self;
2689 : :
2690 : 460513 : pgstat_count_heap_insert(relation, ntuples);
2691 : 460513 : }
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 : 1100430 : simple_heap_insert(Relation relation, HeapTuple tup)
2704 : : {
2705 : 1100430 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2706 : 1100430 : }
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 : 6543296 : compute_infobits(uint16 infomask, uint16 infomask2)
2717 : : {
2718 : : return
2719 : 6543296 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2720 : 6543296 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2721 : 6543296 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2722 : : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2723 : 13086592 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2724 : : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2725 : 6543296 : 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 : 5416 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2739 : : {
2740 : 5416 : const uint16 interesting =
2741 : : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2742 : :
2743 [ + + ]: 5416 : if ((new_infomask & interesting) != (old_infomask & interesting))
2744 : 16 : return true;
2745 : :
2746 : 5400 : 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 : 1907169 : 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 : 1907169 : TransactionId xid = GetCurrentTransactionId();
2767 : : ItemId lp;
2768 : : HeapTupleData tp;
2769 : : Page page;
2770 : : BlockNumber block;
2771 : : Buffer buffer;
2772 : 1907169 : Buffer vmbuffer = InvalidBuffer;
2773 : 1907169 : bool vmbuffer_modified = false;
2774 : : TransactionId new_xmax;
2775 : : uint16 new_infomask,
2776 : : new_infomask2;
2777 : 1907169 : bool changingPart = (options & TABLE_DELETE_CHANGING_PARTITION) != 0;
2778 : 1907169 : bool walLogical = (options & TABLE_DELETE_NO_LOGICAL) == 0;
2779 : 1907169 : bool have_tuple_lock = false;
2780 : : bool iscombo;
2781 : 1907169 : bool clear_all_visible = false;
2782 : 1907169 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2783 : 1907169 : bool old_key_copied = false;
2784 : :
2785 : : Assert(ItemPointerIsValid(tid));
2786 : :
2787 : 1907169 : 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 [ - + ]: 1907169 : if (IsInParallelMode())
2795 [ # # ]: 0 : ereport(ERROR,
2796 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2797 : : errmsg("cannot delete tuples during a parallel operation")));
2798 : :
2799 : 1907169 : block = ItemPointerGetBlockNumber(tid);
2800 : 1907169 : buffer = ReadBuffer(relation, block);
2801 : 1907169 : 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 [ + + ]: 1907169 : if (PageIsAllVisible(page))
2810 : 2976 : visibilitymap_pin(relation, block, &vmbuffer);
2811 : :
2812 : 1907169 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2813 : :
2814 : 1907169 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2815 : : Assert(ItemIdIsNormal(lp));
2816 : :
2817 : 1907169 : tp.t_tableOid = RelationGetRelid(relation);
2818 : 1907169 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2819 : 1907169 : tp.t_len = ItemIdGetLength(lp);
2820 : 1907169 : 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 [ + + - + ]: 1907170 : 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 : 1907170 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2838 : :
2839 [ - + ]: 1907170 : 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 [ + + + - ]: 1907170 : else if (result == TM_BeingModified && wait)
2847 : : {
2848 : : TransactionId xwait;
2849 : : uint16 infomask;
2850 : :
2851 : : /* must copy state data before unlocking buffer */
2852 : 40605 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2853 : 40605 : 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 [ + + ]: 40605 : if (infomask & HEAP_XMAX_IS_MULTI)
2869 : : {
2870 : 8 : bool current_is_member = false;
2871 : :
2872 [ + - ]: 8 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2873 : : LockTupleExclusive, ¤t_is_member))
2874 : : {
2875 : 8 : 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 [ + + ]: 8 : if (!current_is_member)
2882 : 6 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2883 : : LockWaitBlock, &have_tuple_lock);
2884 : :
2885 : : /* wait for multixact */
2886 : 8 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2887 : : relation, &(tp.t_self), XLTW_Delete,
2888 : : NULL);
2889 : 8 : 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 [ + - + - : 16 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ - ]
2900 [ - + ]: 16 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2901 : 8 : !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 [ + + ]: 40597 : 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 [ + + + + ]: 81180 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2951 [ + + ]: 40614 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2952 : 34 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2953 : 40570 : 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 [ + + + - ]: 1907165 : 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 [ + + ]: 1907165 : 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 : 1907093 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
3005 : :
3006 : : /* replace cid with a combo CID if necessary */
3007 : 1907079 : 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 : 1907079 : old_key_tuple = walLogical ?
3014 [ + + ]: 1907079 : 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 : 1907079 : MultiXactIdSetOldestMember();
3025 : :
3026 : 1907079 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
3027 : 1907079 : 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 [ + + ]: 1907079 : if (PageIsAllVisible(page))
3033 : : {
3034 : 2976 : clear_all_visible = true;
3035 : 2976 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3036 : : }
3037 : :
3038 : 1907079 : 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 [ + + + + ]: 1907079 : PageSetPrunable(page, xid);
3048 : :
3049 [ + + ]: 1907079 : if (clear_all_visible)
3050 : : {
3051 : : /* It's possible the VM bits were already clear */
3052 [ + - ]: 2976 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(buffer),
3053 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
3054 : 2976 : vmbuffer_modified = true;
3055 : :
3056 : 2976 : PageClearAllVisible(page);
3057 : : }
3058 : :
3059 : : /* store transaction information of xact deleting the tuple */
3060 : 1907079 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3061 : 1907079 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3062 : 1907079 : tp.t_data->t_infomask |= new_infomask;
3063 : 1907079 : tp.t_data->t_infomask2 |= new_infomask2;
3064 : 1907079 : HeapTupleHeaderClearHotUpdated(tp.t_data);
3065 : 1907079 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
3066 : 1907079 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3067 : : /* Make sure there is no forward chain link in t_ctid */
3068 : 1907079 : tp.t_data->t_ctid = tp.t_self;
3069 : :
3070 : : /* Signal that this is actually a move into another partition */
3071 [ + + ]: 1907079 : if (changingPart)
3072 : 635 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
3073 : :
3074 : 1907079 : MarkBufferDirty(buffer);
3075 : :
3076 : : /*
3077 : : * XLOG stuff
3078 : : *
3079 : : * NB: heap_abort_speculative() uses the same xlog record and replay
3080 : : * routines.
3081 : : */
3082 [ + + + + : 1907079 : 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 [ + + + + : 1798668 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- - + ]
3093 : 7388 : log_heap_new_cid(relation, &tp);
3094 : :
3095 : 1798668 : xlrec.flags = 0;
3096 [ + + ]: 1798668 : if (clear_all_visible)
3097 : 1926 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3098 [ + + ]: 1798668 : if (changingPart)
3099 : 635 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
3100 : 3597336 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3101 : 1798668 : tp.t_data->t_infomask2);
3102 : 1798668 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
3103 : 1798668 : xlrec.xmax = new_xmax;
3104 : :
3105 [ + + ]: 1798668 : 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 [ + + ]: 1798668 : if (!walLogical)
3121 : 3 : xlrec.flags |= XLH_DELETE_NO_LOGICAL;
3122 : :
3123 : 1798668 : XLogBeginInsert();
3124 : 1798668 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3125 : :
3126 : 1798668 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3127 : :
3128 : : /*
3129 : : * Log replica identity of the deleted tuple if there is one
3130 : : */
3131 [ + + ]: 1798668 : 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 : 1798668 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3146 : :
3147 [ + + ]: 1798668 : if (vmbuffer_modified)
3148 : 1926 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_VM, vmbuffer, 0);
3149 : :
3150 : 1798668 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3151 : :
3152 : 1798668 : PageSetLSN(page, recptr);
3153 : :
3154 [ + + ]: 1798668 : if (vmbuffer_modified)
3155 : 1926 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3156 : : }
3157 : :
3158 : 1907079 : 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 [ + + ]: 1907079 : if (clear_all_visible)
3166 : 2976 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3167 : :
3168 : 1907079 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3169 : :
3170 [ + + ]: 1907079 : if (vmbuffer != InvalidBuffer)
3171 : 2976 : 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 [ + + ]: 1911447 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3180 [ + + ]: 4381 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3181 : : {
3182 : : /* toast table entries should never be recursively toasted */
3183 : : Assert(!HeapTupleHasExternal(&tp));
3184 : : }
3185 [ + + ]: 1902711 : else if (HeapTupleHasExternal(&tp))
3186 : 525 : 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 : 1907079 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3194 : :
3195 : : /* Now we can release the buffer */
3196 : 1907079 : ReleaseBuffer(buffer);
3197 : :
3198 : : /*
3199 : : * Release the lmgr tuple lock, if we had it.
3200 : : */
3201 [ + + ]: 1907079 : if (have_tuple_lock)
3202 : 26 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3203 : :
3204 : 1907079 : pgstat_count_heap_delete(relation);
3205 : :
3206 [ + + + + ]: 1907079 : if (old_key_tuple != NULL && old_key_copied)
3207 : 46896 : heap_freetuple(old_key_tuple);
3208 : :
3209 : 1907079 : 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 : 798219 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
3222 : : {
3223 : : TM_Result result;
3224 : : TM_FailureData tmfd;
3225 : :
3226 : 798219 : result = heap_delete(relation, tid,
3227 : : GetCurrentCommandId(true),
3228 : : 0,
3229 : : InvalidSnapshot,
3230 : : true /* wait for commit */ ,
3231 : : &tmfd);
3232 [ - + - - : 798219 : 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 : 798219 : case TM_Ok:
3240 : : /* done successfully */
3241 : 798219 : 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 : 798219 : }
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 : 2393959 : 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 : 2393959 : 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 : 2393959 : HeapTuple old_key_tuple = NULL;
3286 : 2393959 : bool old_key_copied = false;
3287 : 2393959 : 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 : 2393959 : vmbuffer = InvalidBuffer,
3295 : 2393959 : vmbuffer_new = InvalidBuffer;
3296 : 2393959 : bool unlock_vmbuffer = false;
3297 : 2393959 : bool unlock_vmbuffer_new = false;
3298 : : bool need_toast;
3299 : : Size newtupsize,
3300 : : pagefree;
3301 : 2393959 : bool have_tuple_lock = false;
3302 : : bool iscombo;
3303 : 2393959 : bool use_hot_update = false;
3304 : 2393959 : bool summarized_update = false;
3305 : : bool key_intact;
3306 : 2393959 : bool clear_all_visible = false;
3307 : 2393959 : bool clear_all_visible_new = false;
3308 : 2393959 : bool vmbuffer_modified = false;
3309 : 2393959 : bool vmbuffer_new_modified = false;
3310 : : bool checked_lockers;
3311 : : bool locker_remains;
3312 : 2393959 : 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 : 2393959 : 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 [ - + ]: 2393959 : 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 : 2393959 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3359 : : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3360 : 2393959 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3361 : : INDEX_ATTR_BITMAP_SUMMARIZED);
3362 : 2393959 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3363 : 2393959 : id_attrs = RelationGetIndexAttrBitmap(relation,
3364 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
3365 : 2393959 : interesting_attrs = NULL;
3366 : 2393959 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3367 : 2393959 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
3368 : 2393959 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3369 : 2393959 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3370 : :
3371 : 2393959 : block = ItemPointerGetBlockNumber(otid);
3372 : 2393959 : INJECTION_POINT("heap_update-before-pin", NULL);
3373 : 2393959 : buffer = ReadBuffer(relation, block);
3374 : 2393959 : 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 [ + + ]: 2393959 : if (PageIsAllVisible(page))
3383 : 2588 : visibilitymap_pin(relation, block, &vmbuffer);
3384 : :
3385 : 2393959 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3386 : :
3387 : 2393959 : 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 [ + + ]: 2393959 : 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 : 2393958 : oldtup.t_tableOid = RelationGetRelid(relation);
3439 : 2393958 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3440 : 2393958 : oldtup.t_len = ItemIdGetLength(lp);
3441 : 2393958 : oldtup.t_self = *otid;
3442 : :
3443 : : /* the new tuple is ready, except for this: */
3444 : 2393958 : 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 : 2393958 : 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 [ + + ]: 2393958 : if (!bms_overlap(modified_attrs, key_attrs))
3470 : : {
3471 : 2388518 : *lockmode = LockTupleNoKeyExclusive;
3472 : 2388518 : mxact_status = MultiXactStatusNoKeyUpdate;
3473 : 2388518 : 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 : 2388518 : 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 : 2393959 : checked_lockers = false;
3502 : 2393959 : locker_remains = false;
3503 : 2393959 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3504 : :
3505 : : /* see below about the "no wait" case */
3506 : : Assert(result != TM_BeingModified || wait);
3507 : :
3508 [ - + ]: 2393959 : 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 [ + + + - ]: 2393959 : else if (result == TM_BeingModified && wait)
3516 : : {
3517 : : TransactionId xwait;
3518 : : uint16 infomask;
3519 : 36488 : 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 : 36488 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3536 : 36488 : 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 [ + + ]: 36488 : if (infomask & HEAP_XMAX_IS_MULTI)
3561 : : {
3562 : : TransactionId update_xact;
3563 : : int remain;
3564 : 179 : bool current_is_member = false;
3565 : :
3566 [ + + ]: 179 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3567 : : *lockmode, ¤t_is_member))
3568 : : {
3569 : 8 : 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 [ - + ]: 8 : if (!current_is_member)
3576 : 0 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3577 : : LockWaitBlock, &have_tuple_lock);
3578 : :
3579 : : /* wait for multixact */
3580 : 8 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3581 : : relation, &oldtup.t_self, XLTW_Update,
3582 : : &remain);
3583 : 8 : checked_lockers = true;
3584 : 8 : locker_remains = remain != 0;
3585 : 8 : 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 [ + - ]: 8 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3593 [ - + ]: 8 : infomask) ||
3594 : 8 : !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 [ + + ]: 179 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3620 : 8 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3621 : : else
3622 : 171 : update_xact = InvalidTransactionId;
3623 : :
3624 : : /*
3625 : : * There was no UPDATE in the MultiXact; or it aborted. No
3626 : : * TransactionIdIsInProgress() call needed here, since we called
3627 : : * MultiXactIdWait() above.
3628 : : */
3629 [ + + + + ]: 187 : if (!TransactionIdIsValid(update_xact) ||
3630 : 8 : TransactionIdDidAbort(update_xact))
3631 : 172 : can_continue = true;
3632 : : }
3633 [ + + ]: 36309 : else if (TransactionIdIsCurrentTransactionId(xwait))
3634 : : {
3635 : : /*
3636 : : * The only locker is ourselves; we can avoid grabbing the tuple
3637 : : * lock here, but must preserve our locking information.
3638 : : */
3639 : 36194 : checked_lockers = true;
3640 : 36194 : locker_remains = true;
3641 : 36194 : can_continue = true;
3642 : : }
3643 [ + + + + ]: 115 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3644 : : {
3645 : : /*
3646 : : * If it's just a key-share locker, and we're not changing the key
3647 : : * columns, we don't need to wait for it to end; but we need to
3648 : : * preserve it as locker.
3649 : : */
3650 : 30 : checked_lockers = true;
3651 : 30 : locker_remains = true;
3652 : 30 : can_continue = true;
3653 : : }
3654 : : else
3655 : : {
3656 : : /*
3657 : : * Wait for regular transaction to end; but first, acquire tuple
3658 : : * lock.
3659 : : */
3660 : 85 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3661 : 85 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3662 : : LockWaitBlock, &have_tuple_lock);
3663 : 85 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3664 : : XLTW_Update);
3665 : 85 : checked_lockers = true;
3666 : 85 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3667 : :
3668 : : /*
3669 : : * xwait is done, but if xwait had just locked the tuple then some
3670 : : * other xact could update this tuple before we get to this point.
3671 : : * Check for xmax change, and start over if so.
3672 : : */
3673 [ + + - + ]: 169 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3674 : 84 : !TransactionIdEquals(xwait,
3675 : : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3676 : 1 : goto l2;
3677 : :
3678 : : /* Otherwise check if it committed or aborted */
3679 : 84 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3680 [ + + ]: 84 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3681 : 23 : can_continue = true;
3682 : : }
3683 : :
3684 [ + + ]: 36487 : if (can_continue)
3685 : 36419 : result = TM_Ok;
3686 [ + + ]: 68 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3687 : 62 : result = TM_Updated;
3688 : : else
3689 : 6 : result = TM_Deleted;
3690 : : }
3691 : :
3692 : : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3693 : : if (result != TM_Ok)
3694 : : {
3695 : : Assert(result == TM_SelfModified ||
3696 : : result == TM_Updated ||
3697 : : result == TM_Deleted ||
3698 : : result == TM_BeingModified);
3699 : : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3700 : : Assert(result != TM_Updated ||
3701 : : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3702 : : }
3703 : :
3704 [ + + + - ]: 2393958 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3705 : : {
3706 : : /* Perform additional check for transaction-snapshot mode RI updates */
3707 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3708 : 1 : result = TM_Updated;
3709 : : }
3710 : :
3711 [ + + ]: 2393958 : if (result != TM_Ok)
3712 : : {
3713 : 184 : tmfd->ctid = oldtup.t_data->t_ctid;
3714 : 184 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3715 [ + + ]: 184 : if (result == TM_SelfModified)
3716 : 69 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3717 : : else
3718 : 115 : tmfd->cmax = InvalidCommandId;
3719 : 184 : UnlockReleaseBuffer(buffer);
3720 [ + + ]: 184 : if (have_tuple_lock)
3721 : 61 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3722 [ - + ]: 184 : if (vmbuffer != InvalidBuffer)
3723 : 0 : ReleaseBuffer(vmbuffer);
3724 : 184 : *update_indexes = TU_None;
3725 : :
3726 : 184 : bms_free(hot_attrs);
3727 : 184 : bms_free(sum_attrs);
3728 : 184 : bms_free(key_attrs);
3729 : 184 : bms_free(id_attrs);
3730 : 184 : bms_free(modified_attrs);
3731 : 184 : bms_free(interesting_attrs);
3732 : 184 : return result;
3733 : : }
3734 : :
3735 : : /*
3736 : : * If we didn't pin the visibility map page and the page has become all
3737 : : * visible while we were busy locking the buffer, or during some
3738 : : * subsequent window during which we had it unlocked, we'll have to unlock
3739 : : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3740 : : * bit unfortunate, especially since we'll now have to recheck whether the
3741 : : * tuple has been locked or updated under us, but hopefully it won't
3742 : : * happen very often.
3743 : : */
3744 [ + + - + ]: 2393774 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3745 : : {
3746 : 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3747 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
3748 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3749 : 0 : goto l2;
3750 : : }
3751 : :
3752 : : /* Fill in transaction status data */
3753 : :
3754 : : /*
3755 : : * If the tuple we're updating is locked, we need to preserve the locking
3756 : : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3757 : : */
3758 : 2393774 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3759 : 2393774 : oldtup.t_data->t_infomask,
3760 : 2393774 : oldtup.t_data->t_infomask2,
3761 : : xid, *lockmode, true,
3762 : : &xmax_old_tuple, &infomask_old_tuple,
3763 : : &infomask2_old_tuple);
3764 : :
3765 : : /*
3766 : : * And also prepare an Xmax value for the new copy of the tuple. If there
3767 : : * was no xmax previously, or there was one but all lockers are now gone,
3768 : : * then use InvalidTransactionId; otherwise, get the xmax from the old
3769 : : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3770 : : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3771 : : */
3772 [ + + + - ]: 2430170 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3773 [ + + ]: 72792 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
3774 [ - + ]: 36225 : (checked_lockers && !locker_remains))
3775 : 2357378 : xmax_new_tuple = InvalidTransactionId;
3776 : : else
3777 : 36396 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3778 : :
3779 [ + + ]: 2393774 : if (!TransactionIdIsValid(xmax_new_tuple))
3780 : : {
3781 : 2357378 : infomask_new_tuple = HEAP_XMAX_INVALID;
3782 : 2357378 : infomask2_new_tuple = 0;
3783 : : }
3784 : : else
3785 : : {
3786 : : /*
3787 : : * If we found a valid Xmax for the new tuple, then the infomask bits
3788 : : * to use on the new tuple depend on what was there on the old one.
3789 : : * Note that since we're doing an update, the only possibility is that
3790 : : * the lockers had FOR KEY SHARE lock.
3791 : : */
3792 [ + + ]: 36396 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3793 : : {
3794 : 172 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3795 : : &infomask2_new_tuple);
3796 : : }
3797 : : else
3798 : : {
3799 : 36224 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3800 : 36224 : infomask2_new_tuple = 0;
3801 : : }
3802 : : }
3803 : :
3804 : : /*
3805 : : * Prepare the new tuple with the appropriate initial values of Xmin and
3806 : : * Xmax, as well as initial infomask bits as computed above.
3807 : : */
3808 : 2393774 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3809 : 2393774 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3810 : 2393774 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
3811 : 2393774 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
3812 : 2393774 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3813 : 2393774 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3814 : 2393774 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3815 : :
3816 : : /*
3817 : : * Replace cid with a combo CID if necessary. Note that we already put
3818 : : * the plain cid into the new tuple.
3819 : : */
3820 : 2393774 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3821 : :
3822 : : /*
3823 : : * If the toaster needs to be activated, OR if the new tuple will not fit
3824 : : * on the same page as the old, then we need to release the content lock
3825 : : * (but not the pin!) on the old tuple's buffer while we are off doing
3826 : : * TOAST and/or table-file-extension work. We must mark the old tuple to
3827 : : * show that it's locked, else other processes may try to update it
3828 : : * themselves.
3829 : : *
3830 : : * We need to invoke the toaster if there are already any out-of-line
3831 : : * toasted values present, or if the new tuple is over-threshold.
3832 : : */
3833 [ - + ]: 2393774 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3834 [ # # ]: 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3835 : : {
3836 : : /* toast table entries should never be recursively toasted */
3837 : : Assert(!HeapTupleHasExternal(&oldtup));
3838 : : Assert(!HeapTupleHasExternal(newtup));
3839 : 0 : need_toast = false;
3840 : : }
3841 : : else
3842 [ + + ]: 7180746 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3843 [ + + ]: 4786972 : HeapTupleHasExternal(newtup) ||
3844 [ + + ]: 2393166 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3845 : :
3846 : 2393774 : pagefree = PageGetHeapFreeSpace(page);
3847 : :
3848 : 2393774 : newtupsize = MAXALIGN(newtup->t_len);
3849 : :
3850 [ + + + + ]: 2393774 : if (need_toast || newtupsize > pagefree)
3851 : 2210359 : {
3852 : : TransactionId xmax_lock_old_tuple;
3853 : : uint16 infomask_lock_old_tuple,
3854 : : infomask2_lock_old_tuple;
3855 : 2210359 : bool cleared_all_frozen = false;
3856 : :
3857 : : /*
3858 : : * To prevent concurrent sessions from updating the tuple, we have to
3859 : : * temporarily mark it locked, while we release the page-level lock.
3860 : : *
3861 : : * To satisfy the rule that any xid potentially appearing in a buffer
3862 : : * written out to disk, we unfortunately have to WAL log this
3863 : : * temporary modification. We can reuse xl_heap_lock for this
3864 : : * purpose. If we crash/error before following through with the
3865 : : * actual update, xmax will be of an aborted transaction, allowing
3866 : : * other sessions to proceed.
3867 : : */
3868 : :
3869 : : /*
3870 : : * Compute xmax / infomask appropriate for locking the tuple. This has
3871 : : * to be done separately from the combo that's going to be used for
3872 : : * updating, because the potentially created multixact would otherwise
3873 : : * be wrong.
3874 : : */
3875 : 2210359 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3876 : 2210359 : oldtup.t_data->t_infomask,
3877 : 2210359 : oldtup.t_data->t_infomask2,
3878 : : xid, *lockmode, false,
3879 : : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3880 : : &infomask2_lock_old_tuple);
3881 : :
3882 : : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3883 : :
3884 [ + + ]: 2210359 : if (PageIsAllVisible(page))
3885 : : {
3886 : 1530 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3887 : 1530 : unlock_vmbuffer = true;
3888 : : }
3889 : :
3890 : 2210359 : START_CRIT_SECTION();
3891 : :
3892 : : /* Clear obsolete visibility flags ... */
3893 : 2210359 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3894 : 2210359 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3895 : 2210359 : HeapTupleClearHotUpdated(&oldtup);
3896 : : /* ... and store info about transaction updating this tuple */
3897 : : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3898 : 2210359 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3899 : 2210359 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3900 : 2210359 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3901 : 2210359 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3902 : :
3903 : : /* temporarily make it look not-updated, but locked */
3904 : 2210359 : oldtup.t_data->t_ctid = oldtup.t_self;
3905 : :
3906 : : /*
3907 : : * Clear all-frozen bit on visibility map if needed. We could
3908 : : * immediately reset ALL_VISIBLE, but given that the WAL logging
3909 : : * overhead would be unchanged, that doesn't seem necessarily
3910 : : * worthwhile.
3911 : : */
3912 [ + + ]: 2210359 : if (PageIsAllVisible(page))
3913 : : {
3914 : : /* It's possible all-frozen was already clear */
3915 [ + + ]: 1530 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
3916 : : VISIBILITYMAP_ALL_FROZEN))
3917 : 843 : cleared_all_frozen = true;
3918 : : }
3919 : :
3920 : 2210359 : MarkBufferDirty(buffer);
3921 : :
3922 [ + + + + : 2210359 : if (RelationNeedsWAL(relation))
+ - + + ]
3923 : : {
3924 : : xl_heap_lock xlrec;
3925 : : XLogRecPtr recptr;
3926 : :
3927 : 2200227 : XLogBeginInsert();
3928 : 2200227 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3929 : :
3930 : 2200227 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3931 : 2200227 : xlrec.xmax = xmax_lock_old_tuple;
3932 : 4400454 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3933 : 2200227 : oldtup.t_data->t_infomask2);
3934 : 2200227 : xlrec.flags =
3935 : 2200227 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
3936 : 2200227 : XLogRegisterData(&xlrec, SizeOfHeapLock);
3937 : :
3938 [ + + ]: 2200227 : if (cleared_all_frozen)
3939 : 843 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
3940 : :
3941 : 2200227 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3942 : 2200227 : PageSetLSN(page, recptr);
3943 : :
3944 [ + + ]: 2200227 : if (cleared_all_frozen)
3945 : 843 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3946 : : }
3947 : :
3948 : 2210359 : END_CRIT_SECTION();
3949 : :
3950 : : /* release VM lock first, since it covers many heap blocks */
3951 [ + + ]: 2210359 : if (unlock_vmbuffer)
3952 : 1530 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3953 : 2210359 : unlock_vmbuffer = false;
3954 : :
3955 : 2210359 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3956 : :
3957 : : /*
3958 : : * Let the toaster do its thing, if needed.
3959 : : *
3960 : : * Note: below this point, heaptup is the data we actually intend to
3961 : : * store into the relation; newtup is the caller's original untoasted
3962 : : * data.
3963 : : */
3964 [ + + ]: 2210359 : if (need_toast)
3965 : : {
3966 : : /*
3967 : : * If logical decoding is not needed, suppress it for the TOAST
3968 : : * tuples too. We never skip the FSM here.
3969 : : */
3970 [ + + ]: 2075 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
3971 : : walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
3972 : 2075 : newtupsize = MAXALIGN(heaptup->t_len);
3973 : : }
3974 : : else
3975 : 2208284 : heaptup = newtup;
3976 : :
3977 : : /*
3978 : : * Now, do we need a new page for the tuple, or not? This is a bit
3979 : : * tricky since someone else could have added tuples to the page while
3980 : : * we weren't looking. We have to recheck the available space after
3981 : : * reacquiring the buffer lock. But don't bother to do that if the
3982 : : * former amount of free space is still not enough; it's unlikely
3983 : : * there's more free now than before.
3984 : : *
3985 : : * What's more, if we need to get a new page, we will need to acquire
3986 : : * buffer locks on both old and new pages. To avoid deadlock against
3987 : : * some other backend trying to get the same two locks in the other
3988 : : * order, we must be consistent about the order we get the locks in.
3989 : : * We use the rule "lock the lower-numbered page of the relation
3990 : : * first". To implement this, we must do RelationGetBufferForTuple
3991 : : * while not holding the lock on the old page, and we must rely on it
3992 : : * to get the locks on both pages in the correct order.
3993 : : *
3994 : : * Another consideration is that we need visibility map page pin(s) if
3995 : : * we will have to clear the all-visible flag on either page. If we
3996 : : * call RelationGetBufferForTuple, we rely on it to acquire any such
3997 : : * pins; but if we don't, we have to handle that here. Hence we need
3998 : : * a loop.
3999 : : */
4000 : : for (;;)
4001 : : {
4002 [ + + ]: 2210359 : if (newtupsize > pagefree)
4003 : : {
4004 : : /* It doesn't fit, must use RelationGetBufferForTuple. */
4005 : 2209560 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
4006 : : buffer, 0, NULL,
4007 : : &vmbuffer_new, &vmbuffer,
4008 : : 0);
4009 : : /* We're all done. */
4010 : 2209560 : break;
4011 : : }
4012 : : /* Acquire VM page pin if needed and we don't have it. */
4013 [ + + - + ]: 799 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4014 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
4015 : : /* Re-acquire the lock on the old tuple's page. */
4016 : 799 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4017 : : /* Re-check using the up-to-date free space */
4018 : 799 : pagefree = PageGetHeapFreeSpace(page);
4019 [ + - ]: 799 : if (newtupsize > pagefree ||
4020 [ + + - + ]: 799 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
4021 : : {
4022 : : /*
4023 : : * Rats, it doesn't fit anymore, or somebody just now set the
4024 : : * all-visible flag. We must now unlock and loop to avoid
4025 : : * deadlock. Fortunately, this path should seldom be taken.
4026 : : */
4027 : 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4028 : : }
4029 : : else
4030 : : {
4031 : : /* We're all done. */
4032 : 799 : newbuf = buffer;
4033 : 799 : break;
4034 : : }
4035 : : }
4036 : : }
4037 : : else
4038 : : {
4039 : : /* No TOAST work needed, and it'll fit on same page */
4040 : 183415 : newbuf = buffer;
4041 : 183415 : heaptup = newtup;
4042 : : }
4043 : :
4044 : 2393774 : newpage = BufferGetPage(newbuf);
4045 : :
4046 : : /*
4047 : : * We're about to do the actual update -- check for conflict first, to
4048 : : * avoid possibly having to roll back work we've just done.
4049 : : *
4050 : : * This is safe without a recheck as long as there is no possibility of
4051 : : * another process scanning the pages between this check and the update
4052 : : * being visible to the scan (i.e., exclusive buffer content lock(s) are
4053 : : * continuously held from this point until the tuple update is visible).
4054 : : *
4055 : : * For the new tuple the only check needed is at the relation level, but
4056 : : * since both tuples are in the same relation and the check for oldtup
4057 : : * will include checking the relation level, there is no benefit to a
4058 : : * separate check for the new tuple.
4059 : : */
4060 : 2393774 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
4061 : : BufferGetBlockNumber(buffer));
4062 : :
4063 : : /*
4064 : : * At this point newbuf and buffer are both pinned and locked, and newbuf
4065 : : * has enough space for the new tuple. If they are the same buffer, only
4066 : : * one pin is held.
4067 : : */
4068 : :
4069 [ + + ]: 2393761 : if (newbuf == buffer)
4070 : : {
4071 : : /*
4072 : : * Since the new tuple is going into the same page, we might be able
4073 : : * to do a HOT update. Check if any of the index columns have been
4074 : : * changed.
4075 : : */
4076 [ + + ]: 184201 : if (!bms_overlap(modified_attrs, hot_attrs))
4077 : : {
4078 : 167881 : use_hot_update = true;
4079 : :
4080 : : /*
4081 : : * If none of the columns that are used in hot-blocking indexes
4082 : : * were updated, we can apply HOT, but we do still need to check
4083 : : * if we need to update the summarizing indexes, and update those
4084 : : * indexes if the columns were updated, or we may fail to detect
4085 : : * e.g. value bound changes in BRIN minmax indexes.
4086 : : */
4087 [ + + ]: 167881 : if (bms_overlap(modified_attrs, sum_attrs))
4088 : 2188 : summarized_update = true;
4089 : : }
4090 : : }
4091 : : else
4092 : : {
4093 : : /* Set a hint that the old page could use prune/defrag */
4094 : 2209560 : PageSetFull(page);
4095 : : }
4096 : :
4097 : : /*
4098 : : * Compute replica identity tuple before entering the critical section so
4099 : : * we don't PANIC upon a memory allocation failure.
4100 : : * ExtractReplicaIdentity() will return NULL if nothing needs to be
4101 : : * logged. Pass old key required as true only if the replica identity key
4102 : : * columns are modified or it has external data.
4103 : : */
4104 : 2393761 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
4105 [ + + + + ]: 2393761 : bms_overlap(modified_attrs, id_attrs) ||
4106 : : id_has_external,
4107 : 2393761 : &old_key_copied);
4108 : :
4109 : 2393761 : clear_all_visible = PageIsAllVisible(page);
4110 [ + + + + ]: 2393761 : clear_all_visible_new = newbuf != buffer && PageIsAllVisible(newpage);
4111 : :
4112 : : /*
4113 : : * Clear PD_ALL_VISIBLE flags and reset visibility map bits for any heap
4114 : : * pages that were all-visible. If there are two heap pages, we may need
4115 : : * to clear VM bits for both.
4116 : : */
4117 [ + + + + ]: 2393761 : if (clear_all_visible && clear_all_visible_new &&
4118 [ + - ]: 145 : vmbuffer_new == vmbuffer)
4119 : : {
4120 : : /*
4121 : : * This is the more complicated case: both the new and old heap pages
4122 : : * are all-visible and both their VM bits are on the same page of the
4123 : : * VM, so we register a single VM buffer as HEAP_UPDATE_BLKREF_VM_NEW
4124 : : * in the WAL record. We must be careful to only lock and register one
4125 : : * buffer, even though we modify it twice -- once for each heap
4126 : : * block's VM bits.
4127 : : */
4128 : 145 : LockBuffer(vmbuffer_new, BUFFER_LOCK_EXCLUSIVE);
4129 : 145 : unlock_vmbuffer_new = true;
4130 : :
4131 : : /* We will not lock or attempt to modify old VM buffer */
4132 : : }
4133 : : else
4134 : : {
4135 : : /*
4136 : : * In all the remaining cases, we will clear at most one heap block's
4137 : : * VM bits per VM page.
4138 : : */
4139 : 4787232 : Buffer vmbuffers[2] = {
4140 [ + + ]: 2393616 : clear_all_visible ? vmbuffer : InvalidBuffer,
4141 [ + + ]: 2393616 : clear_all_visible_new ? vmbuffer_new : InvalidBuffer
4142 : : };
4143 : :
4144 : : /*
4145 : : * When both pages need different VM pages cleared, acquire the VM
4146 : : * buffer locks in VM block order to avoid deadlocks between backends
4147 : : * updating tuples in opposite directions across VM pages.
4148 : : */
4149 [ + + - + : 2393616 : if (clear_all_visible && clear_all_visible_new &&
- - ]
4150 : 0 : BufferGetBlockNumber(vmbuffers[0]) > BufferGetBlockNumber(vmbuffers[1]))
4151 : : {
4152 : 0 : Buffer swap = vmbuffers[0];
4153 : :
4154 : 0 : vmbuffers[0] = vmbuffers[1];
4155 : 0 : vmbuffers[1] = swap;
4156 : : }
4157 : :
4158 : : Assert((!BufferIsValid(vmbuffers[0]) && !BufferIsValid(vmbuffers[1])) ||
4159 : : vmbuffers[0] != vmbuffers[1]);
4160 : :
4161 [ + + ]: 2393616 : if (BufferIsValid(vmbuffers[0]))
4162 : 2442 : LockBuffer(vmbuffers[0], BUFFER_LOCK_EXCLUSIVE);
4163 [ + + ]: 2393616 : if (BufferIsValid(vmbuffers[1]))
4164 : 1086 : LockBuffer(vmbuffers[1], BUFFER_LOCK_EXCLUSIVE);
4165 : :
4166 [ + + ]: 2393616 : if (clear_all_visible)
4167 : 2442 : unlock_vmbuffer = true;
4168 [ + + ]: 2393616 : if (clear_all_visible_new)
4169 : 1086 : unlock_vmbuffer_new = true;
4170 : : }
4171 : :
4172 : : /* NO EREPORT(ERROR) from here till changes are logged */
4173 : 2393761 : START_CRIT_SECTION();
4174 : :
4175 : : /*
4176 : : * If this transaction commits, the old tuple will become DEAD sooner or
4177 : : * later. Set flag that this page is a candidate for pruning once our xid
4178 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
4179 : : * the subsequent page pruning will be a no-op and the hint will be
4180 : : * cleared.
4181 : : *
4182 : : * We set the new page prunable as well. See heap_insert() for more on why
4183 : : * we do this when inserting tuples.
4184 : : */
4185 [ + + + + ]: 2393761 : PageSetPrunable(page, xid);
4186 [ + + ]: 2393761 : if (newbuf != buffer)
4187 [ + + + + ]: 2209560 : PageSetPrunable(newpage, xid);
4188 : :
4189 [ + + ]: 2393761 : if (use_hot_update)
4190 : : {
4191 : : /* Mark the old tuple as HOT-updated */
4192 : 167881 : HeapTupleSetHotUpdated(&oldtup);
4193 : : /* And mark the new tuple as heap-only */
4194 : 167881 : HeapTupleSetHeapOnly(heaptup);
4195 : : /* Mark the caller's copy too, in case different from heaptup */
4196 : 167881 : HeapTupleSetHeapOnly(newtup);
4197 : : }
4198 : : else
4199 : : {
4200 : : /* Make sure tuples are correctly marked as not-HOT */
4201 : 2225880 : HeapTupleClearHotUpdated(&oldtup);
4202 : 2225880 : HeapTupleClearHeapOnly(heaptup);
4203 : 2225880 : HeapTupleClearHeapOnly(newtup);
4204 : : }
4205 : :
4206 : 2393761 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4207 : :
4208 : :
4209 : : /* Clear obsolete visibility flags, possibly set by ourselves above... */
4210 : 2393761 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4211 : 2393761 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4212 : : /* ... and store info about transaction updating this tuple */
4213 : : Assert(TransactionIdIsValid(xmax_old_tuple));
4214 : 2393761 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4215 : 2393761 : oldtup.t_data->t_infomask |= infomask_old_tuple;
4216 : 2393761 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4217 : 2393761 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4218 : :
4219 : : /* record address of new tuple in t_ctid of old one */
4220 : 2393761 : oldtup.t_data->t_ctid = heaptup->t_self;
4221 : :
4222 : : /*
4223 : : * Clear PD_ALL_VISIBLE flags and reset all visibilitymap bits. In all
4224 : : * cases, it's possible that PD_ALL_VISIBLE was set but the corresponding
4225 : : * visibility map bits were already clear.
4226 : : */
4227 [ + + ]: 2393761 : if (clear_all_visible)
4228 : : {
4229 [ + - ]: 2587 : if (visibilitymap_clear(relation->rd_locator, block,
4230 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
4231 : : {
4232 : : /*
4233 : : * When old and new heap blocks' VM bits are on the same VM page,
4234 : : * that page is registered in the WAL record only once. If both
4235 : : * heap pages were PD_ALL_VISIBLE and either VM bit needs
4236 : : * clearing, we register the VM buffer as
4237 : : * HEAP_UPDATE_BLKREF_VM_NEW.
4238 : : */
4239 [ + + + - ]: 2587 : if (clear_all_visible_new && vmbuffer == vmbuffer_new)
4240 : 145 : vmbuffer_new_modified = true;
4241 : : else
4242 : 2442 : vmbuffer_modified = true;
4243 : : }
4244 : :
4245 : 2587 : PageClearAllVisible(page);
4246 : : }
4247 [ + + ]: 2393761 : if (clear_all_visible_new)
4248 : : {
4249 : : /*
4250 : : * If both heap blocks' VM bits are on the same VM buffer, this will
4251 : : * clear the new heap block's VM bits from the shared vmbuffer.
4252 : : */
4253 [ + - ]: 1231 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(newbuf),
4254 : : vmbuffer_new, VISIBILITYMAP_VALID_BITS))
4255 : 1231 : vmbuffer_new_modified = true;
4256 : :
4257 : 1231 : PageClearAllVisible(newpage);
4258 : : }
4259 : :
4260 [ + + ]: 2393761 : if (newbuf != buffer)
4261 : 2209560 : MarkBufferDirty(newbuf);
4262 : 2393761 : MarkBufferDirty(buffer);
4263 : :
4264 : : /* XLOG stuff */
4265 [ + + + + : 2393761 : if (RelationNeedsWAL(relation))
+ - + + ]
4266 : : {
4267 : : XLogRecPtr recptr;
4268 : :
4269 : : /*
4270 : : * For logical decoding we need combo CIDs to properly decode the
4271 : : * catalog.
4272 : : */
4273 [ + + + + : 2381936 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
4274 : : {
4275 : 2735 : log_heap_new_cid(relation, &oldtup);
4276 : 2735 : log_heap_new_cid(relation, heaptup);
4277 : : }
4278 : :
4279 [ + + + + ]: 2381936 : recptr = log_heap_update(relation, buffer,
4280 : : vmbuffer_modified ? vmbuffer : InvalidBuffer,
4281 : : newbuf,
4282 : : vmbuffer_new_modified ? vmbuffer_new : InvalidBuffer,
4283 : : &oldtup, heaptup,
4284 : : old_key_tuple,
4285 : : clear_all_visible,
4286 : : clear_all_visible_new,
4287 : : walLogical);
4288 [ + + ]: 2381936 : if (newbuf != buffer)
4289 : : {
4290 : 2199436 : PageSetLSN(newpage, recptr);
4291 : : }
4292 : 2381936 : PageSetLSN(page, recptr);
4293 : :
4294 [ + + ]: 2381936 : if (vmbuffer_modified)
4295 : 2338 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
4296 [ + + ]: 2381936 : if (vmbuffer_new_modified)
4297 : 1231 : PageSetLSN(BufferGetPage(vmbuffer_new), recptr);
4298 : : }
4299 : :
4300 : 2393761 : END_CRIT_SECTION();
4301 : :
4302 [ + + ]: 2393761 : if (unlock_vmbuffer)
4303 : 2442 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
4304 [ + + ]: 2393761 : if (unlock_vmbuffer_new)
4305 : 1231 : LockBuffer(vmbuffer_new, BUFFER_LOCK_UNLOCK);
4306 : :
4307 [ + + ]: 2393761 : if (newbuf != buffer)
4308 : 2209560 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
4309 : 2393761 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4310 : :
4311 : : /*
4312 : : * Mark old tuple for invalidation from system caches at next command
4313 : : * boundary, and mark the new tuple for invalidation in case we abort. We
4314 : : * have to do this before releasing the buffer because oldtup is in the
4315 : : * buffer. (heaptup is all in local memory, but it's necessary to process
4316 : : * both tuple versions in one call to inval.c so we can avoid redundant
4317 : : * sinval messages.)
4318 : : */
4319 : 2393761 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4320 : :
4321 : : /* Now we can release the buffer(s) */
4322 [ + + ]: 2393761 : if (newbuf != buffer)
4323 : 2209560 : ReleaseBuffer(newbuf);
4324 : 2393761 : ReleaseBuffer(buffer);
4325 [ + + ]: 2393761 : if (BufferIsValid(vmbuffer_new))
4326 : 1233 : ReleaseBuffer(vmbuffer_new);
4327 [ + + ]: 2393761 : if (BufferIsValid(vmbuffer))
4328 : 2587 : ReleaseBuffer(vmbuffer);
4329 : :
4330 : : /*
4331 : : * Release the lmgr tuple lock, if we had it.
4332 : : */
4333 [ + + ]: 2393761 : if (have_tuple_lock)
4334 : 22 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4335 : :
4336 : 2393761 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4337 : :
4338 : : /*
4339 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
4340 : : * back to the caller's image, too.
4341 : : */
4342 [ + + ]: 2393761 : if (heaptup != newtup)
4343 : : {
4344 : 2006 : newtup->t_self = heaptup->t_self;
4345 : 2006 : heap_freetuple(heaptup);
4346 : : }
4347 : :
4348 : : /*
4349 : : * If it is a HOT update, the update may still need to update summarized
4350 : : * indexes, lest we fail to update those summaries and get incorrect
4351 : : * results (for example, minmax bounds of the block may change with this
4352 : : * update).
4353 : : */
4354 [ + + ]: 2393761 : if (use_hot_update)
4355 : : {
4356 [ + + ]: 167881 : if (summarized_update)
4357 : 2188 : *update_indexes = TU_Summarizing;
4358 : : else
4359 : 165693 : *update_indexes = TU_None;
4360 : : }
4361 : : else
4362 : 2225880 : *update_indexes = TU_All;
4363 : :
4364 [ + + + + ]: 2393761 : if (old_key_tuple != NULL && old_key_copied)
4365 : 93 : heap_freetuple(old_key_tuple);
4366 : :
4367 : 2393761 : bms_free(hot_attrs);
4368 : 2393761 : bms_free(sum_attrs);
4369 : 2393761 : bms_free(key_attrs);
4370 : 2393761 : bms_free(id_attrs);
4371 : 2393761 : bms_free(modified_attrs);
4372 : 2393761 : bms_free(interesting_attrs);
4373 : :
4374 : 2393761 : return TM_Ok;
4375 : : }
4376 : :
4377 : : #ifdef USE_ASSERT_CHECKING
4378 : : /*
4379 : : * Confirm adequate lock held during heap_update(), per rules from
4380 : : * README.tuplock section "Locking to write inplace-updated tables".
4381 : : */
4382 : : static void
4383 : : check_lock_if_inplace_updateable_rel(Relation relation,
4384 : : const ItemPointerData *otid,
4385 : : HeapTuple newtup)
4386 : : {
4387 : : /* LOCKTAG_TUPLE acceptable for any catalog */
4388 : : switch (RelationGetRelid(relation))
4389 : : {
4390 : : case RelationRelationId:
4391 : : case DatabaseRelationId:
4392 : : {
4393 : : LOCKTAG tuptag;
4394 : :
4395 : : SET_LOCKTAG_TUPLE(tuptag,
4396 : : relation->rd_lockInfo.lockRelId.dbId,
4397 : : relation->rd_lockInfo.lockRelId.relId,
4398 : : ItemPointerGetBlockNumber(otid),
4399 : : ItemPointerGetOffsetNumber(otid));
4400 : : if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
4401 : : return;
4402 : : }
4403 : : break;
4404 : : default:
4405 : : Assert(!IsInplaceUpdateRelation(relation));
4406 : : return;
4407 : : }
4408 : :
4409 : : switch (RelationGetRelid(relation))
4410 : : {
4411 : : case RelationRelationId:
4412 : : {
4413 : : /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4414 : : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
4415 : : Oid relid = classForm->oid;
4416 : : Oid dbid;
4417 : : LOCKTAG tag;
4418 : :
4419 : : if (IsSharedRelation(relid))
4420 : : dbid = InvalidOid;
4421 : : else
4422 : : dbid = MyDatabaseId;
4423 : :
4424 : : if (classForm->relkind == RELKIND_INDEX)
4425 : : {
4426 : : Relation irel = index_open(relid, AccessShareLock);
4427 : :
4428 : : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4429 : : index_close(irel, AccessShareLock);
4430 : : }
4431 : : else
4432 : : SET_LOCKTAG_RELATION(tag, dbid, relid);
4433 : :
4434 : : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4435 : : !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
4436 : : elog(WARNING,
4437 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4438 : : NameStr(classForm->relname),
4439 : : relid,
4440 : : classForm->relkind,
4441 : : ItemPointerGetBlockNumber(otid),
4442 : : ItemPointerGetOffsetNumber(otid));
4443 : : }
4444 : : break;
4445 : : case DatabaseRelationId:
4446 : : {
4447 : : /* LOCKTAG_TUPLE required */
4448 : : Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
4449 : :
4450 : : elog(WARNING,
4451 : : "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4452 : : NameStr(dbForm->datname),
4453 : : dbForm->oid,
4454 : : ItemPointerGetBlockNumber(otid),
4455 : : ItemPointerGetOffsetNumber(otid));
4456 : : }
4457 : : break;
4458 : : }
4459 : : }
4460 : :
4461 : : /*
4462 : : * Confirm adequate relation lock held, per rules from README.tuplock section
4463 : : * "Locking to write inplace-updated tables".
4464 : : */
4465 : : static void
4466 : : check_inplace_rel_lock(HeapTuple oldtup)
4467 : : {
4468 : : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
4469 : : Oid relid = classForm->oid;
4470 : : Oid dbid;
4471 : : LOCKTAG tag;
4472 : :
4473 : : if (IsSharedRelation(relid))
4474 : : dbid = InvalidOid;
4475 : : else
4476 : : dbid = MyDatabaseId;
4477 : :
4478 : : if (classForm->relkind == RELKIND_INDEX)
4479 : : {
4480 : : Relation irel = index_open(relid, AccessShareLock);
4481 : :
4482 : : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4483 : : index_close(irel, AccessShareLock);
4484 : : }
4485 : : else
4486 : : SET_LOCKTAG_RELATION(tag, dbid, relid);
4487 : :
4488 : : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
4489 : : elog(WARNING,
4490 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4491 : : NameStr(classForm->relname),
4492 : : relid,
4493 : : classForm->relkind,
4494 : : ItemPointerGetBlockNumber(&oldtup->t_self),
4495 : : ItemPointerGetOffsetNumber(&oldtup->t_self));
4496 : : }
4497 : : #endif
4498 : :
4499 : : /*
4500 : : * Check if the specified attribute's values are the same. Subroutine for
4501 : : * HeapDetermineColumnsInfo.
4502 : : */
4503 : : static bool
4504 : 1000265 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4505 : : bool isnull1, bool isnull2)
4506 : : {
4507 : : /*
4508 : : * If one value is NULL and other is not, then they are certainly not
4509 : : * equal
4510 : : */
4511 [ + + ]: 1000265 : if (isnull1 != isnull2)
4512 : 62 : return false;
4513 : :
4514 : : /*
4515 : : * If both are NULL, they can be considered equal.
4516 : : */
4517 [ + + ]: 1000203 : if (isnull1)
4518 : 6641 : return true;
4519 : :
4520 : : /*
4521 : : * We do simple binary comparison of the two datums. This may be overly
4522 : : * strict because there can be multiple binary representations for the
4523 : : * same logical value. But we should be OK as long as there are no false
4524 : : * positives. Using a type-specific equality operator is messy because
4525 : : * there could be multiple notions of equality in different operator
4526 : : * classes; furthermore, we cannot safely invoke user-defined functions
4527 : : * while holding exclusive buffer lock.
4528 : : */
4529 [ - + ]: 993562 : if (attrnum <= 0)
4530 : : {
4531 : : /* The only allowed system columns are OIDs, so do this */
4532 : 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4533 : : }
4534 : : else
4535 : : {
4536 : : CompactAttribute *att;
4537 : :
4538 : : Assert(attrnum <= tupdesc->natts);
4539 : 993562 : att = TupleDescCompactAttr(tupdesc, attrnum - 1);
4540 : 993562 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4541 : : }
4542 : : }
4543 : :
4544 : : /*
4545 : : * Check which columns are being updated.
4546 : : *
4547 : : * Given an updated tuple, determine (and return into the output bitmapset),
4548 : : * from those listed as interesting, the set of columns that changed.
4549 : : *
4550 : : * has_external indicates if any of the unmodified attributes (from those
4551 : : * listed as interesting) of the old tuple is a member of external_cols and is
4552 : : * stored externally.
4553 : : */
4554 : : static Bitmapset *
4555 : 2393958 : HeapDetermineColumnsInfo(Relation relation,
4556 : : Bitmapset *interesting_cols,
4557 : : Bitmapset *external_cols,
4558 : : HeapTuple oldtup, HeapTuple newtup,
4559 : : bool *has_external)
4560 : : {
4561 : : int attidx;
4562 : 2393958 : Bitmapset *modified = NULL;
4563 : 2393958 : TupleDesc tupdesc = RelationGetDescr(relation);
4564 : :
4565 : 2393958 : attidx = -1;
4566 [ + + ]: 3394223 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4567 : : {
4568 : : /* attidx is zero-based, attrnum is the normal attribute number */
4569 : 1000265 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4570 : : Datum value1,
4571 : : value2;
4572 : : bool isnull1,
4573 : : isnull2;
4574 : :
4575 : : /*
4576 : : * If it's a whole-tuple reference, say "not equal". It's not really
4577 : : * worth supporting this case, since it could only succeed after a
4578 : : * no-op update, which is hardly a case worth optimizing for.
4579 : : */
4580 [ - + ]: 1000265 : if (attrnum == 0)
4581 : : {
4582 : 0 : modified = bms_add_member(modified, attidx);
4583 : 968118 : continue;
4584 : : }
4585 : :
4586 : : /*
4587 : : * Likewise, automatically say "not equal" for any system attribute
4588 : : * other than tableOID; we cannot expect these to be consistent in a
4589 : : * HOT chain, or even to be set correctly yet in the new tuple.
4590 : : */
4591 [ - + ]: 1000265 : if (attrnum < 0)
4592 : : {
4593 [ # # ]: 0 : if (attrnum != TableOidAttributeNumber)
4594 : : {
4595 : 0 : modified = bms_add_member(modified, attidx);
4596 : 0 : continue;
4597 : : }
4598 : : }
4599 : :
4600 : : /*
4601 : : * Extract the corresponding values. XXX this is pretty inefficient
4602 : : * if there are many indexed columns. Should we do a single
4603 : : * heap_deform_tuple call on each tuple, instead? But that doesn't
4604 : : * work for system columns ...
4605 : : */
4606 : 1000265 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4607 : 1000265 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4608 : :
4609 [ + + ]: 1000265 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4610 : : value2, isnull1, isnull2))
4611 : : {
4612 : 64217 : modified = bms_add_member(modified, attidx);
4613 : 64217 : continue;
4614 : : }
4615 : :
4616 : : /*
4617 : : * No need to check attributes that can't be stored externally. Note
4618 : : * that system attributes can't be stored externally.
4619 : : */
4620 [ + - + + ]: 936048 : if (attrnum < 0 || isnull1 ||
4621 [ + + ]: 929407 : TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
4622 : 903901 : continue;
4623 : :
4624 : : /*
4625 : : * Check if the old tuple's attribute is stored externally and is a
4626 : : * member of external_cols.
4627 : : */
4628 [ + + + + ]: 32152 : if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
4629 : 5 : bms_is_member(attidx, external_cols))
4630 : 2 : *has_external = true;
4631 : : }
4632 : :
4633 : 2393958 : return modified;
4634 : : }
4635 : :
4636 : : /*
4637 : : * simple_heap_update - replace a tuple
4638 : : *
4639 : : * This routine may be used to update a tuple when concurrent updates of
4640 : : * the target tuple are not expected (for example, because we have a lock
4641 : : * on the relation associated with the tuple). Any failure is reported
4642 : : * via ereport().
4643 : : */
4644 : : void
4645 : 134923 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
4646 : : TU_UpdateIndexes *update_indexes)
4647 : : {
4648 : : TM_Result result;
4649 : : TM_FailureData tmfd;
4650 : : LockTupleMode lockmode;
4651 : :
4652 : 134923 : result = heap_update(relation, otid, tup,
4653 : : GetCurrentCommandId(true), 0,
4654 : : InvalidSnapshot,
4655 : : true /* wait for commit */ ,
4656 : : &tmfd, &lockmode, update_indexes);
4657 [ - + - + : 134923 : switch (result)
- ]
4658 : : {
4659 : 0 : case TM_SelfModified:
4660 : : /* Tuple was already updated in current command? */
4661 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
4662 : : break;
4663 : :
4664 : 134922 : case TM_Ok:
4665 : : /* done successfully */
4666 : 134922 : break;
4667 : :
4668 : 0 : case TM_Updated:
4669 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
4670 : : break;
4671 : :
4672 : 1 : case TM_Deleted:
4673 [ + - ]: 1 : elog(ERROR, "tuple concurrently deleted");
4674 : : break;
4675 : :
4676 : 0 : default:
4677 [ # # ]: 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4678 : : break;
4679 : : }
4680 : 134922 : }
4681 : :
4682 : :
4683 : : /*
4684 : : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4685 : : */
4686 : : static MultiXactStatus
4687 : 115450 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4688 : : {
4689 : : int retval;
4690 : :
4691 [ + + ]: 115450 : if (is_update)
4692 : 217 : retval = tupleLockExtraInfo[mode].updstatus;
4693 : : else
4694 : 115233 : retval = tupleLockExtraInfo[mode].lockstatus;
4695 : :
4696 [ - + ]: 115450 : if (retval == -1)
4697 [ # # # # ]: 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4698 : : is_update ? "true" : "false");
4699 : :
4700 : 115450 : return (MultiXactStatus) retval;
4701 : : }
4702 : :
4703 : : /*
4704 : : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4705 : : *
4706 : : * Note that this acquires a buffer pin, which the caller must release.
4707 : : *
4708 : : * Input parameters:
4709 : : * relation: relation containing tuple (caller must hold suitable lock)
4710 : : * cid: current command ID (used for visibility test, and stored into
4711 : : * tuple's cmax if lock is successful)
4712 : : * mode: indicates if shared or exclusive tuple lock is desired
4713 : : * wait_policy: what to do if tuple lock is not available
4714 : : * follow_updates: if true, follow the update chain to also lock descendant
4715 : : * tuples.
4716 : : *
4717 : : * Output parameters:
4718 : : * *tuple: all fields filled in
4719 : : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4720 : : * *tmfd: filled in failure cases (see below)
4721 : : *
4722 : : * Function results are the same as the ones for table_tuple_lock().
4723 : : *
4724 : : * In the failure cases other than TM_Invisible, the routine fills
4725 : : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4726 : : * if necessary), and t_cmax (the last only for TM_SelfModified,
4727 : : * since we cannot obtain cmax from a combo CID generated by another
4728 : : * transaction).
4729 : : * See comments for struct TM_FailureData for additional info.
4730 : : *
4731 : : * See README.tuplock for a thorough explanation of this mechanism.
4732 : : */
4733 : : TM_Result
4734 : 571734 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4735 : : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4736 : : bool follow_updates,
4737 : : Buffer *buffer, TM_FailureData *tmfd)
4738 : : {
4739 : : TM_Result result;
4740 : 571734 : ItemPointer tid = &(tuple->t_self);
4741 : : ItemId lp;
4742 : : Page page;
4743 : 571734 : Buffer vmbuffer = InvalidBuffer;
4744 : 571734 : bool unlock_vmbuffer = false;
4745 : : BlockNumber block;
4746 : : TransactionId xid,
4747 : : xmax;
4748 : : uint16 old_infomask,
4749 : : new_infomask,
4750 : : new_infomask2;
4751 : 571734 : bool first_time = true;
4752 : 571734 : bool skip_tuple_lock = false;
4753 : 571734 : bool have_tuple_lock = false;
4754 : 571734 : bool cleared_all_frozen = false;
4755 : :
4756 : 571734 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4757 : 571734 : block = ItemPointerGetBlockNumber(tid);
4758 : 571734 : page = BufferGetPage(*buffer);
4759 : :
4760 : : /*
4761 : : * Before locking the buffer, pin the visibility map page if it appears to
4762 : : * be necessary. Since we haven't got the lock yet, someone else might be
4763 : : * in the middle of changing this, so we'll need to recheck after we have
4764 : : * the lock.
4765 : : */
4766 [ + + ]: 571734 : if (PageIsAllVisible(page))
4767 : 413395 : visibilitymap_pin(relation, block, &vmbuffer);
4768 : :
4769 : 571734 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4770 : :
4771 : 571734 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4772 : : Assert(ItemIdIsNormal(lp));
4773 : :
4774 : 571734 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4775 : 571734 : tuple->t_len = ItemIdGetLength(lp);
4776 : 571734 : tuple->t_tableOid = RelationGetRelid(relation);
4777 : :
4778 : 15 : l3:
4779 : 571749 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4780 : :
4781 [ + + ]: 571749 : if (result == TM_Invisible)
4782 : : {
4783 : : /*
4784 : : * This is possible, but only when locking a tuple for ON CONFLICT DO
4785 : : * SELECT/UPDATE. We return this value here rather than throwing an
4786 : : * error in order to give that case the opportunity to throw a more
4787 : : * specific error.
4788 : : */
4789 : 28 : result = TM_Invisible;
4790 : 28 : goto out_locked;
4791 : : }
4792 [ + + + + ]: 571721 : else if (result == TM_BeingModified ||
4793 [ + + ]: 81290 : result == TM_Updated ||
4794 : : result == TM_Deleted)
4795 : : {
4796 : : TransactionId xwait;
4797 : : uint16 infomask;
4798 : : uint16 infomask2;
4799 : : bool require_sleep;
4800 : : ItemPointerData t_ctid;
4801 : :
4802 : : /* must copy state data before unlocking buffer */
4803 : 490433 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4804 : 490433 : infomask = tuple->t_data->t_infomask;
4805 : 490433 : infomask2 = tuple->t_data->t_infomask2;
4806 : 490433 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4807 : :
4808 : 490433 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4809 : :
4810 : : /*
4811 : : * If any subtransaction of the current top transaction already holds
4812 : : * a lock as strong as or stronger than what we're requesting, we
4813 : : * effectively hold the desired lock already. We *must* succeed
4814 : : * without trying to take the tuple lock, else we will deadlock
4815 : : * against anyone wanting to acquire a stronger lock.
4816 : : *
4817 : : * Note we only do this the first time we loop on the HTSU result;
4818 : : * there is no point in testing in subsequent passes, because
4819 : : * evidently our own transaction cannot have acquired a new lock after
4820 : : * the first time we checked.
4821 : : */
4822 [ + + ]: 490433 : if (first_time)
4823 : : {
4824 : 490422 : first_time = false;
4825 : :
4826 [ + + ]: 490422 : if (infomask & HEAP_XMAX_IS_MULTI)
4827 : : {
4828 : : int i;
4829 : : int nmembers;
4830 : : MultiXactMember *members;
4831 : :
4832 : : /*
4833 : : * We don't need to allow old multixacts here; if that had
4834 : : * been the case, HeapTupleSatisfiesUpdate would have returned
4835 : : * MayBeUpdated and we wouldn't be here.
4836 : : */
4837 : : nmembers =
4838 : 73294 : GetMultiXactIdMembers(xwait, &members, false,
4839 : 73294 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4840 : :
4841 [ + + ]: 1422654 : for (i = 0; i < nmembers; i++)
4842 : : {
4843 : : /* only consider members of our own transaction */
4844 [ + + ]: 1349374 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4845 : 1349324 : continue;
4846 : :
4847 [ + + ]: 50 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4848 : : {
4849 : 14 : pfree(members);
4850 : 14 : result = TM_Ok;
4851 : 14 : goto out_unlocked;
4852 : : }
4853 : : else
4854 : : {
4855 : : /*
4856 : : * Disable acquisition of the heavyweight tuple lock.
4857 : : * Otherwise, when promoting a weaker lock, we might
4858 : : * deadlock with another locker that has acquired the
4859 : : * heavyweight tuple lock and is waiting for our
4860 : : * transaction to finish.
4861 : : *
4862 : : * Note that in this case we still need to wait for
4863 : : * the multixact if required, to avoid acquiring
4864 : : * conflicting locks.
4865 : : */
4866 : 36 : skip_tuple_lock = true;
4867 : : }
4868 : : }
4869 : :
4870 [ + - ]: 73280 : if (members)
4871 : 73280 : pfree(members);
4872 : : }
4873 [ + + ]: 417128 : else if (TransactionIdIsCurrentTransactionId(xwait))
4874 : : {
4875 [ + + + + : 415776 : switch (mode)
- ]
4876 : : {
4877 : 409339 : case LockTupleKeyShare:
4878 : : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4879 : : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4880 : : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4881 : 409339 : result = TM_Ok;
4882 : 409339 : goto out_unlocked;
4883 : 35 : case LockTupleShare:
4884 [ + + - + ]: 41 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4885 : 6 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4886 : : {
4887 : 29 : result = TM_Ok;
4888 : 29 : goto out_unlocked;
4889 : : }
4890 : 6 : break;
4891 : 85 : case LockTupleNoKeyExclusive:
4892 [ + + ]: 85 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4893 : : {
4894 : 72 : result = TM_Ok;
4895 : 72 : goto out_unlocked;
4896 : : }
4897 : 13 : break;
4898 : 6317 : case LockTupleExclusive:
4899 [ + + ]: 6317 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4900 [ + + ]: 1274 : infomask2 & HEAP_KEYS_UPDATED)
4901 : : {
4902 : 1245 : result = TM_Ok;
4903 : 1245 : goto out_unlocked;
4904 : : }
4905 : 5072 : break;
4906 : : }
4907 : : }
4908 : : }
4909 : :
4910 : : /*
4911 : : * Initially assume that we will have to wait for the locking
4912 : : * transaction(s) to finish. We check various cases below in which
4913 : : * this can be turned off.
4914 : : */
4915 : 79734 : require_sleep = true;
4916 [ + + ]: 79734 : if (mode == LockTupleKeyShare)
4917 : : {
4918 : : /*
4919 : : * If we're requesting KeyShare, and there's no update present, we
4920 : : * don't need to wait. Even if there is an update, we can still
4921 : : * continue if the key hasn't been modified.
4922 : : *
4923 : : * However, if there are updates, we need to walk the update chain
4924 : : * to mark future versions of the row as locked, too. That way,
4925 : : * if somebody deletes that future version, we're protected
4926 : : * against the key going away. This locking of future versions
4927 : : * could block momentarily, if a concurrent transaction is
4928 : : * deleting a key; or it could return a value to the effect that
4929 : : * the transaction deleting the key has already committed. So we
4930 : : * do this before re-locking the buffer; otherwise this would be
4931 : : * prone to deadlocks.
4932 : : *
4933 : : * Note that the TID we're locking was grabbed before we unlocked
4934 : : * the buffer. For it to change while we're not looking, the
4935 : : * other properties we're testing for below after re-locking the
4936 : : * buffer would also change, in which case we would restart this
4937 : : * loop above.
4938 : : */
4939 [ + + ]: 73863 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4940 : : {
4941 : : bool updated;
4942 : :
4943 : 73811 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4944 : :
4945 : : /*
4946 : : * If there are updates, follow the update chain; bail out if
4947 : : * that cannot be done.
4948 : : */
4949 [ + + + + ]: 73811 : if (follow_updates && updated &&
4950 [ + - ]: 2171 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
4951 : : {
4952 : : TM_Result res;
4953 : :
4954 : 2171 : res = heap_lock_updated_tuple(relation,
4955 : : infomask, xwait, &t_ctid,
4956 : : GetCurrentTransactionId(),
4957 : : mode);
4958 [ + + ]: 2171 : if (res != TM_Ok)
4959 : : {
4960 : 6 : result = res;
4961 : : /* recovery code expects to have buffer lock held */
4962 : 6 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4963 : 207 : goto failed;
4964 : : }
4965 : : }
4966 : :
4967 : 73805 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4968 : :
4969 : : /*
4970 : : * Make sure it's still an appropriate lock, else start over.
4971 : : * Also, if it wasn't updated before we released the lock, but
4972 : : * is updated now, we start over too; the reason is that we
4973 : : * now need to follow the update chain to lock the new
4974 : : * versions.
4975 : : */
4976 [ + + ]: 73805 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4977 [ + - ]: 2154 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4978 [ - + ]: 2154 : !updated))
4979 : 15 : goto l3;
4980 : :
4981 : : /* Things look okay, so we can skip sleeping */
4982 : 73805 : require_sleep = false;
4983 : :
4984 : : /*
4985 : : * Note we allow Xmax to change here; other updaters/lockers
4986 : : * could have modified it before we grabbed the buffer lock.
4987 : : * However, this is not a problem, because with the recheck we
4988 : : * just did we ensure that they still don't conflict with the
4989 : : * lock we want.
4990 : : */
4991 : : }
4992 : : }
4993 [ + + ]: 5871 : else if (mode == LockTupleShare)
4994 : : {
4995 : : /*
4996 : : * If we're requesting Share, we can similarly avoid sleeping if
4997 : : * there's no update and no exclusive lock present.
4998 : : */
4999 [ + - ]: 451 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5000 [ + + ]: 451 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
5001 : : {
5002 : 445 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5003 : :
5004 : : /*
5005 : : * Make sure it's still an appropriate lock, else start over.
5006 : : * See above about allowing xmax to change.
5007 : : */
5008 [ + - - + ]: 890 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5009 : 445 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
5010 : 0 : goto l3;
5011 : 445 : require_sleep = false;
5012 : : }
5013 : : }
5014 [ + + ]: 5420 : else if (mode == LockTupleNoKeyExclusive)
5015 : : {
5016 : : /*
5017 : : * If we're requesting NoKeyExclusive, we might also be able to
5018 : : * avoid sleeping; just ensure that there no conflicting lock
5019 : : * already acquired.
5020 : : */
5021 [ + + ]: 176 : if (infomask & HEAP_XMAX_IS_MULTI)
5022 : : {
5023 [ + + ]: 26 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
5024 : : mode, NULL))
5025 : : {
5026 : : /*
5027 : : * No conflict, but if the xmax changed under us in the
5028 : : * meantime, start over.
5029 : : */
5030 : 13 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5031 [ + - - + ]: 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5032 : 13 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5033 : : xwait))
5034 : 0 : goto l3;
5035 : :
5036 : : /* otherwise, we're good */
5037 : 13 : require_sleep = false;
5038 : : }
5039 : : }
5040 [ + + ]: 150 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
5041 : : {
5042 : 19 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5043 : :
5044 : : /* if the xmax changed in the meantime, start over */
5045 [ + - - + ]: 38 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5046 : 19 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5047 : : xwait))
5048 : 0 : goto l3;
5049 : : /* otherwise, we're good */
5050 : 19 : require_sleep = false;
5051 : : }
5052 : : }
5053 : :
5054 : : /*
5055 : : * As a check independent from those above, we can also avoid sleeping
5056 : : * if the current transaction is the sole locker of the tuple. Note
5057 : : * that the strength of the lock already held is irrelevant; this is
5058 : : * not about recording the lock in Xmax (which will be done regardless
5059 : : * of this optimization, below). Also, note that the cases where we
5060 : : * hold a lock stronger than we are requesting are already handled
5061 : : * above by not doing anything.
5062 : : *
5063 : : * Note we only deal with the non-multixact case here; MultiXactIdWait
5064 : : * is well equipped to deal with this situation on its own.
5065 : : */
5066 [ + + + + : 85131 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
+ + ]
5067 : 5403 : TransactionIdIsCurrentTransactionId(xwait))
5068 : : {
5069 : : /* ... but if the xmax changed in the meantime, start over */
5070 : 5072 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5071 [ + - - + ]: 10144 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5072 : 5072 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5073 : : xwait))
5074 : 0 : goto l3;
5075 : : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
5076 : 5072 : require_sleep = false;
5077 : : }
5078 : :
5079 : : /*
5080 : : * Time to sleep on the other transaction/multixact, if necessary.
5081 : : *
5082 : : * If the other transaction is an update/delete that's already
5083 : : * committed, then sleeping cannot possibly do any good: if we're
5084 : : * required to sleep, get out to raise an error instead.
5085 : : *
5086 : : * By here, we either have already acquired the buffer exclusive lock,
5087 : : * or we must wait for the locking transaction or multixact; so below
5088 : : * we ensure that we grab buffer lock after the sleep.
5089 : : */
5090 [ + + + + : 79728 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
+ + ]
5091 : : {
5092 : 160 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5093 : 160 : goto failed;
5094 : : }
5095 [ + + ]: 79568 : else if (require_sleep)
5096 : : {
5097 : : /*
5098 : : * Acquire tuple lock to establish our priority for the tuple, or
5099 : : * die trying. LockTuple will release us when we are next-in-line
5100 : : * for the tuple. We must do this even if we are share-locking,
5101 : : * but not if we already have a weaker lock on the tuple.
5102 : : *
5103 : : * If we are forced to "start over" below, we keep the tuple lock;
5104 : : * this arranges that we stay at the head of the line while
5105 : : * rechecking tuple state.
5106 : : */
5107 [ + + ]: 214 : if (!skip_tuple_lock &&
5108 [ + + ]: 197 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
5109 : : &have_tuple_lock))
5110 : : {
5111 : : /*
5112 : : * This can only happen if wait_policy is Skip and the lock
5113 : : * couldn't be obtained.
5114 : : */
5115 : 1 : result = TM_WouldBlock;
5116 : : /* recovery code expects to have buffer lock held */
5117 : 1 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5118 : 1 : goto failed;
5119 : : }
5120 : :
5121 [ + + ]: 212 : if (infomask & HEAP_XMAX_IS_MULTI)
5122 : : {
5123 : 43 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
5124 : :
5125 : : /* We only ever lock tuples, never update them */
5126 [ - + ]: 43 : if (status >= MultiXactStatusNoKeyUpdate)
5127 [ # # ]: 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
5128 : :
5129 : : /* wait for multixact to end, or die trying */
5130 [ + + + - ]: 43 : switch (wait_policy)
5131 : : {
5132 : 37 : case LockWaitBlock:
5133 : 37 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
5134 : 37 : relation, &tuple->t_self, XLTW_Lock, NULL);
5135 : 37 : break;
5136 : 2 : case LockWaitSkip:
5137 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5138 : : status, infomask, relation,
5139 : : NULL, false))
5140 : : {
5141 : 2 : result = TM_WouldBlock;
5142 : : /* recovery code expects to have buffer lock held */
5143 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5144 : 2 : goto failed;
5145 : : }
5146 : 0 : break;
5147 : 4 : case LockWaitError:
5148 [ + - ]: 4 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5149 : : status, infomask, relation,
5150 : : NULL, log_lock_failures))
5151 [ + - ]: 4 : ereport(ERROR,
5152 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5153 : : errmsg("could not obtain lock on row in relation \"%s\"",
5154 : : RelationGetRelationName(relation))));
5155 : :
5156 : 0 : break;
5157 : : }
5158 : :
5159 : : /*
5160 : : * Of course, the multixact might not be done here: if we're
5161 : : * requesting a light lock mode, other transactions with light
5162 : : * locks could still be alive, as well as locks owned by our
5163 : : * own xact or other subxacts of this backend. We need to
5164 : : * preserve the surviving MultiXact members. Note that it
5165 : : * isn't absolutely necessary in the latter case, but doing so
5166 : : * is simpler.
5167 : : */
5168 : : }
5169 : : else
5170 : : {
5171 : : /* wait for regular transaction to end, or die trying */
5172 [ + + + - ]: 169 : switch (wait_policy)
5173 : : {
5174 : 128 : case LockWaitBlock:
5175 : 128 : XactLockTableWait(xwait, relation, &tuple->t_self,
5176 : : XLTW_Lock);
5177 : 128 : break;
5178 : 33 : case LockWaitSkip:
5179 [ + - ]: 33 : if (!ConditionalXactLockTableWait(xwait, false))
5180 : : {
5181 : 33 : result = TM_WouldBlock;
5182 : : /* recovery code expects to have buffer lock held */
5183 : 33 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5184 : 33 : goto failed;
5185 : : }
5186 : 0 : break;
5187 : 8 : case LockWaitError:
5188 [ + - ]: 8 : if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
5189 [ + - ]: 8 : ereport(ERROR,
5190 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5191 : : errmsg("could not obtain lock on row in relation \"%s\"",
5192 : : RelationGetRelationName(relation))));
5193 : 0 : break;
5194 : : }
5195 : : }
5196 : :
5197 : : /* if there are updates, follow the update chain */
5198 [ + + + + ]: 165 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5199 [ + + ]: 70 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
5200 : : {
5201 : : TM_Result res;
5202 : :
5203 : 54 : res = heap_lock_updated_tuple(relation,
5204 : : infomask, xwait, &t_ctid,
5205 : : GetCurrentTransactionId(),
5206 : : mode);
5207 [ + + ]: 54 : if (res != TM_Ok)
5208 : : {
5209 : 5 : result = res;
5210 : : /* recovery code expects to have buffer lock held */
5211 : 5 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5212 : 5 : goto failed;
5213 : : }
5214 : : }
5215 : :
5216 : 160 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5217 : :
5218 : : /*
5219 : : * xwait is done, but if xwait had just locked the tuple then some
5220 : : * other xact could update this tuple before we get to this point.
5221 : : * Check for xmax change, and start over if so.
5222 : : */
5223 [ + + + + ]: 306 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5224 : 146 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5225 : : xwait))
5226 : 15 : goto l3;
5227 : :
5228 [ + + ]: 145 : if (!(infomask & HEAP_XMAX_IS_MULTI))
5229 : : {
5230 : : /*
5231 : : * Otherwise check if it committed or aborted. Note we cannot
5232 : : * be here if the tuple was only locked by somebody who didn't
5233 : : * conflict with us; that would have been handled above. So
5234 : : * that transaction must necessarily be gone by now. But
5235 : : * don't check for this in the multixact case, because some
5236 : : * locker transactions might still be running.
5237 : : */
5238 : 110 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5239 : : }
5240 : : }
5241 : :
5242 : : /* By here, we're certain that we hold buffer exclusive lock again */
5243 : :
5244 : : /*
5245 : : * We may lock if previous xmax aborted, or if it committed but only
5246 : : * locked the tuple without updating it; or if we didn't have to wait
5247 : : * at all for whatever reason.
5248 : : */
5249 [ + + ]: 79499 : if (!require_sleep ||
5250 [ + + + + ]: 254 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5251 [ + + ]: 203 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5252 : 94 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
5253 : 79414 : result = TM_Ok;
5254 [ + + ]: 85 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
5255 : 64 : result = TM_Updated;
5256 : : else
5257 : 21 : result = TM_Deleted;
5258 : : }
5259 : :
5260 : 81288 : failed:
5261 [ + + ]: 160994 : if (result != TM_Ok)
5262 : : {
5263 : : Assert(result == TM_SelfModified || result == TM_Updated ||
5264 : : result == TM_Deleted || result == TM_WouldBlock);
5265 : :
5266 : : /*
5267 : : * When locking a tuple under LockWaitSkip semantics and we fail with
5268 : : * TM_WouldBlock above, it's possible for concurrent transactions to
5269 : : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5270 : : * this assert is slightly different from the equivalent one in
5271 : : * heap_delete and heap_update.
5272 : : */
5273 : : Assert((result == TM_WouldBlock) ||
5274 : : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
5275 : : Assert(result != TM_Updated ||
5276 : : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5277 : 300 : tmfd->ctid = tuple->t_data->t_ctid;
5278 : 300 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5279 [ + + ]: 300 : if (result == TM_SelfModified)
5280 : 8 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5281 : : else
5282 : 292 : tmfd->cmax = InvalidCommandId;
5283 : 300 : goto out_locked;
5284 : : }
5285 : :
5286 : : /*
5287 : : * If we didn't pin the visibility map page and the page has become all
5288 : : * visible while we were busy locking the buffer, or during some
5289 : : * subsequent window during which we had it unlocked, we'll have to unlock
5290 : : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5291 : : * unfortunate, especially since we'll now have to recheck whether the
5292 : : * tuple has been locked or updated under us, but hopefully it won't
5293 : : * happen very often.
5294 : : */
5295 [ + + - + ]: 160694 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5296 : : {
5297 : 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
5298 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
5299 : 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5300 : 0 : goto l3;
5301 : : }
5302 : :
5303 : 160694 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5304 : 160694 : old_infomask = tuple->t_data->t_infomask;
5305 : :
5306 : : /*
5307 : : * If this is the first possibly-multixact-able operation in the current
5308 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
5309 : : * certain that the transaction will never become a member of any older
5310 : : * MultiXactIds than that. (We have to do this even if we end up just
5311 : : * using our own TransactionId below, since some other backend could
5312 : : * incorporate our XID into a MultiXact immediately afterwards.)
5313 : : */
5314 : 160694 : MultiXactIdSetOldestMember();
5315 : :
5316 : : /*
5317 : : * Compute the new xmax and infomask to store into the tuple. Note we do
5318 : : * not modify the tuple just yet, because that would leave it in the wrong
5319 : : * state if multixact.c elogs.
5320 : : */
5321 : 160694 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5322 : : GetCurrentTransactionId(), mode, false,
5323 : : &xid, &new_infomask, &new_infomask2);
5324 : :
5325 : : /* Lock VM buffer before entering critical section */
5326 [ + + ]: 160694 : if (PageIsAllVisible(page))
5327 : : {
5328 : 3498 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
5329 : 3498 : unlock_vmbuffer = true;
5330 : : }
5331 : :
5332 : 160694 : START_CRIT_SECTION();
5333 : :
5334 : : /*
5335 : : * Store transaction information of xact locking the tuple.
5336 : : *
5337 : : * Note: Cmax is meaningless in this context, so don't set it; this avoids
5338 : : * possibly generating a useless combo CID. Moreover, if we're locking a
5339 : : * previously updated tuple, it's important to preserve the Cmax.
5340 : : *
5341 : : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5342 : : * we would break the HOT chain.
5343 : : */
5344 : 160694 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5345 : 160694 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5346 : 160694 : tuple->t_data->t_infomask |= new_infomask;
5347 : 160694 : tuple->t_data->t_infomask2 |= new_infomask2;
5348 [ + + ]: 160694 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5349 : 158544 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
5350 : 160694 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
5351 : :
5352 : : /*
5353 : : * Make sure there is no forward chain link in t_ctid. Note that in the
5354 : : * cases where the tuple has been updated, we must not overwrite t_ctid,
5355 : : * because it was set by the updater. Moreover, if the tuple has been
5356 : : * updated, we need to follow the update chain to lock the new versions of
5357 : : * the tuple as well.
5358 : : */
5359 [ + + ]: 160694 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5360 : 158544 : tuple->t_data->t_ctid = *tid;
5361 : :
5362 : : /* Clear only the all-frozen bit on visibility map if needed */
5363 [ + + ]: 160694 : if (PageIsAllVisible(page))
5364 : : {
5365 [ + + ]: 3498 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
5366 : : VISIBILITYMAP_ALL_FROZEN))
5367 : 18 : cleared_all_frozen = true;
5368 : : }
5369 : :
5370 : :
5371 : 160694 : MarkBufferDirty(*buffer);
5372 : :
5373 : : /*
5374 : : * XLOG stuff. You might think that we don't need an XLOG record because
5375 : : * there is no state change worth restoring after a crash. You would be
5376 : : * wrong however: we have just written either a TransactionId or a
5377 : : * MultiXactId that may never have been seen on disk before, and we need
5378 : : * to make sure that there are XLOG entries covering those ID numbers.
5379 : : * Else the same IDs might be re-used after a crash, which would be
5380 : : * disastrous if this page made it to disk before the crash. Essentially
5381 : : * we have to enforce the WAL log-before-data rule even in this case.
5382 : : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5383 : : * entries for everything anyway.)
5384 : : */
5385 [ + + + + : 160694 : if (RelationNeedsWAL(relation))
+ - + - ]
5386 : : {
5387 : : xl_heap_lock xlrec;
5388 : : XLogRecPtr recptr;
5389 : :
5390 : 160265 : XLogBeginInsert();
5391 : 160265 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, *buffer, REGBUF_STANDARD);
5392 : :
5393 : 160265 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5394 : 160265 : xlrec.xmax = xid;
5395 : 320530 : xlrec.infobits_set = compute_infobits(new_infomask,
5396 : 160265 : tuple->t_data->t_infomask2);
5397 : 160265 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5398 : 160265 : XLogRegisterData(&xlrec, SizeOfHeapLock);
5399 : :
5400 [ + + ]: 160265 : if (cleared_all_frozen)
5401 : 18 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
5402 : :
5403 : : /* we don't decode row locks atm, so no need to log the origin */
5404 : :
5405 : 160265 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5406 : :
5407 : 160265 : PageSetLSN(page, recptr);
5408 : :
5409 [ + + ]: 160265 : if (cleared_all_frozen)
5410 : 18 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
5411 : : }
5412 : :
5413 : 160694 : END_CRIT_SECTION();
5414 : :
5415 : : /* release VM lock first, since it covers many heap blocks */
5416 [ + + ]: 160694 : if (unlock_vmbuffer)
5417 : : {
5418 : 3498 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
5419 : 3498 : unlock_vmbuffer = false;
5420 : : }
5421 : :
5422 : 160694 : result = TM_Ok;
5423 : :
5424 : 161022 : out_locked:
5425 : 161022 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
5426 : : Assert(!unlock_vmbuffer);
5427 : :
5428 : 571721 : out_unlocked:
5429 [ + + ]: 571721 : if (BufferIsValid(vmbuffer))
5430 : 413395 : ReleaseBuffer(vmbuffer);
5431 : :
5432 : : /*
5433 : : * Don't update the visibility map here. Locking a tuple doesn't change
5434 : : * visibility info.
5435 : : */
5436 : :
5437 : : /*
5438 : : * Now that we have successfully marked the tuple as locked, we can
5439 : : * release the lmgr tuple lock, if we had it.
5440 : : */
5441 [ + + ]: 571721 : if (have_tuple_lock)
5442 : 178 : UnlockTupleTuplock(relation, tid, mode);
5443 : :
5444 : 571721 : return result;
5445 : : }
5446 : :
5447 : : /*
5448 : : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5449 : : * its normal, Xmax-based tuple lock.
5450 : : *
5451 : : * have_tuple_lock is an input and output parameter: on input, it indicates
5452 : : * whether the lock has previously been acquired (and this function does
5453 : : * nothing in that case). If this function returns success, have_tuple_lock
5454 : : * has been flipped to true.
5455 : : *
5456 : : * Returns false if it was unable to obtain the lock; this can only happen if
5457 : : * wait_policy is Skip.
5458 : : */
5459 : : static bool
5460 : 343 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
5461 : : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5462 : : {
5463 [ + + ]: 343 : if (*have_tuple_lock)
5464 : 9 : return true;
5465 : :
5466 [ + + + - ]: 334 : switch (wait_policy)
5467 : : {
5468 : 289 : case LockWaitBlock:
5469 : 289 : LockTupleTuplock(relation, tid, mode);
5470 : 289 : break;
5471 : :
5472 : 34 : case LockWaitSkip:
5473 [ + + ]: 34 : if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
5474 : 1 : return false;
5475 : 33 : break;
5476 : :
5477 : 11 : case LockWaitError:
5478 [ + + ]: 11 : if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
5479 [ + - ]: 1 : ereport(ERROR,
5480 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5481 : : errmsg("could not obtain lock on row in relation \"%s\"",
5482 : : RelationGetRelationName(relation))));
5483 : 10 : break;
5484 : : }
5485 : 332 : *have_tuple_lock = true;
5486 : :
5487 : 332 : return true;
5488 : : }
5489 : :
5490 : : /*
5491 : : * Given an original set of Xmax and infomask, and a transaction (identified by
5492 : : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5493 : : * corresponding infomasks to use on the tuple.
5494 : : *
5495 : : * Note that this might have side effects such as creating a new MultiXactId.
5496 : : *
5497 : : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5498 : : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5499 : : * but it was not running anymore. There is a race condition, which is that the
5500 : : * MultiXactId may have finished since then, but that uncommon case is handled
5501 : : * either here, or within MultiXactIdExpand.
5502 : : *
5503 : : * There is a similar race condition possible when the old xmax was a regular
5504 : : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5505 : : * window, but it's still possible to end up creating an unnecessary
5506 : : * MultiXactId. Fortunately this is harmless.
5507 : : */
5508 : : static void
5509 : 6674094 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5510 : : uint16 old_infomask2, TransactionId add_to_xmax,
5511 : : LockTupleMode mode, bool is_update,
5512 : : TransactionId *result_xmax, uint16 *result_infomask,
5513 : : uint16 *result_infomask2)
5514 : : {
5515 : : TransactionId new_xmax;
5516 : : uint16 new_infomask,
5517 : : new_infomask2;
5518 : :
5519 : : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5520 : :
5521 : 104398 : l5:
5522 : 6778492 : new_infomask = 0;
5523 : 6778492 : new_infomask2 = 0;
5524 [ + + ]: 6778492 : if (old_infomask & HEAP_XMAX_INVALID)
5525 : : {
5526 : : /*
5527 : : * No previous locker; we just insert our own TransactionId.
5528 : : *
5529 : : * Note that it's critical that this case be the first one checked,
5530 : : * because there are several blocks below that come back to this one
5531 : : * to implement certain optimizations; old_infomask might contain
5532 : : * other dirty bits in those cases, but we don't really care.
5533 : : */
5534 [ + + ]: 6597464 : if (is_update)
5535 : : {
5536 : 4300636 : new_xmax = add_to_xmax;
5537 [ + + ]: 4300636 : if (mode == LockTupleExclusive)
5538 : 1944599 : new_infomask2 |= HEAP_KEYS_UPDATED;
5539 : : }
5540 : : else
5541 : : {
5542 : 2296828 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5543 [ + + + + : 2296828 : switch (mode)
- ]
5544 : : {
5545 : 6176 : case LockTupleKeyShare:
5546 : 6176 : new_xmax = add_to_xmax;
5547 : 6176 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5548 : 6176 : break;
5549 : 783 : case LockTupleShare:
5550 : 783 : new_xmax = add_to_xmax;
5551 : 783 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5552 : 783 : break;
5553 : 2193961 : case LockTupleNoKeyExclusive:
5554 : 2193961 : new_xmax = add_to_xmax;
5555 : 2193961 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5556 : 2193961 : break;
5557 : 95908 : case LockTupleExclusive:
5558 : 95908 : new_xmax = add_to_xmax;
5559 : 95908 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5560 : 95908 : new_infomask2 |= HEAP_KEYS_UPDATED;
5561 : 95908 : break;
5562 : 0 : default:
5563 : 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5564 [ # # ]: 0 : elog(ERROR, "invalid lock mode");
5565 : : }
5566 : : }
5567 : : }
5568 [ + + ]: 181028 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5569 : : {
5570 : : MultiXactStatus new_status;
5571 : :
5572 : : /*
5573 : : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5574 : : * cross-check.
5575 : : */
5576 : : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5577 : :
5578 : : /*
5579 : : * A multixact together with LOCK_ONLY set but neither lock bit set
5580 : : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5581 : : * anymore. This check is critical for databases upgraded by
5582 : : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5583 : : * that such multis are never passed.
5584 : : */
5585 [ - + ]: 75557 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5586 : : {
5587 : 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5588 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5589 : 0 : goto l5;
5590 : : }
5591 : :
5592 : : /*
5593 : : * If the XMAX is already a MultiXactId, then we need to expand it to
5594 : : * include add_to_xmax; but if all the members were lockers and are
5595 : : * all gone, we can do away with the IS_MULTI bit and just set
5596 : : * add_to_xmax as the only locker/updater. If all lockers are gone
5597 : : * and we have an updater that aborted, we can also do without a
5598 : : * multi.
5599 : : *
5600 : : * The cost of doing GetMultiXactIdMembers would be paid by
5601 : : * MultiXactIdExpand if we weren't to do this, so this check is not
5602 : : * incurring extra work anyhow.
5603 : : */
5604 [ + + ]: 75557 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5605 : : {
5606 [ + + ]: 25 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5607 [ + - ]: 10 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5608 : : old_infomask)))
5609 : : {
5610 : : /*
5611 : : * Reset these bits and restart; otherwise fall through to
5612 : : * create a new multi below.
5613 : : */
5614 : 25 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5615 : 25 : old_infomask |= HEAP_XMAX_INVALID;
5616 : 25 : goto l5;
5617 : : }
5618 : : }
5619 : :
5620 : 75532 : new_status = get_mxact_status_for_lock(mode, is_update);
5621 : :
5622 : 75532 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5623 : : new_status);
5624 : 75532 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5625 : : }
5626 [ + + ]: 105471 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5627 : : {
5628 : : /*
5629 : : * It's a committed update, so we need to preserve him as updater of
5630 : : * the tuple.
5631 : : */
5632 : : MultiXactStatus status;
5633 : : MultiXactStatus new_status;
5634 : :
5635 [ - + ]: 14 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5636 : 0 : status = MultiXactStatusUpdate;
5637 : : else
5638 : 14 : status = MultiXactStatusNoKeyUpdate;
5639 : :
5640 : 14 : new_status = get_mxact_status_for_lock(mode, is_update);
5641 : :
5642 : : /*
5643 : : * since it's not running, it's obviously impossible for the old
5644 : : * updater to be identical to the current one, so we need not check
5645 : : * for that case as we do in the block above.
5646 : : */
5647 : 14 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5648 : 14 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5649 : : }
5650 [ + + ]: 105457 : else if (TransactionIdIsInProgress(xmax))
5651 : : {
5652 : : /*
5653 : : * If the XMAX is a valid, in-progress TransactionId, then we need to
5654 : : * create a new MultiXactId that includes both the old locker or
5655 : : * updater and our own TransactionId.
5656 : : */
5657 : : MultiXactStatus new_status;
5658 : : MultiXactStatus old_status;
5659 : : LockTupleMode old_mode;
5660 : :
5661 [ + + ]: 105448 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5662 : : {
5663 [ + + ]: 105420 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5664 : 5689 : old_status = MultiXactStatusForKeyShare;
5665 [ + + ]: 99731 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5666 : 442 : old_status = MultiXactStatusForShare;
5667 [ + - ]: 99289 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5668 : : {
5669 [ + + ]: 99289 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5670 : 92821 : old_status = MultiXactStatusForUpdate;
5671 : : else
5672 : 6468 : old_status = MultiXactStatusForNoKeyUpdate;
5673 : : }
5674 : : else
5675 : : {
5676 : : /*
5677 : : * LOCK_ONLY can be present alone only when a page has been
5678 : : * upgraded by pg_upgrade. But in that case,
5679 : : * TransactionIdIsInProgress() should have returned false. We
5680 : : * assume it's no longer locked in this case.
5681 : : */
5682 [ # # ]: 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5683 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5684 : 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5685 : 0 : goto l5;
5686 : : }
5687 : : }
5688 : : else
5689 : : {
5690 : : /* it's an update, but which kind? */
5691 [ - + ]: 28 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5692 : 0 : old_status = MultiXactStatusUpdate;
5693 : : else
5694 : 28 : old_status = MultiXactStatusNoKeyUpdate;
5695 : : }
5696 : :
5697 : 105448 : old_mode = TUPLOCK_from_mxstatus(old_status);
5698 : :
5699 : : /*
5700 : : * If the lock to be acquired is for the same TransactionId as the
5701 : : * existing lock, there's an optimization possible: consider only the
5702 : : * strongest of both locks as the only one present, and restart.
5703 : : */
5704 [ + + ]: 105448 : if (xmax == add_to_xmax)
5705 : : {
5706 : : /*
5707 : : * Note that it's not possible for the original tuple to be
5708 : : * updated: we wouldn't be here because the tuple would have been
5709 : : * invisible and we wouldn't try to update it. As a subtlety,
5710 : : * this code can also run when traversing an update chain to lock
5711 : : * future versions of a tuple. But we wouldn't be here either,
5712 : : * because the add_to_xmax would be different from the original
5713 : : * updater.
5714 : : */
5715 : : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5716 : :
5717 : : /* acquire the strongest of both */
5718 [ + + ]: 104365 : if (mode < old_mode)
5719 : 52216 : mode = old_mode;
5720 : : /* mustn't touch is_update */
5721 : :
5722 : 104365 : old_infomask |= HEAP_XMAX_INVALID;
5723 : 104365 : goto l5;
5724 : : }
5725 : :
5726 : : /* otherwise, just fall back to creating a new multixact */
5727 : 1083 : new_status = get_mxact_status_for_lock(mode, is_update);
5728 : 1083 : new_xmax = MultiXactIdCreate(xmax, old_status,
5729 : : add_to_xmax, new_status);
5730 : 1083 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5731 : : }
5732 [ + + + + ]: 14 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5733 : 5 : TransactionIdDidCommit(xmax))
5734 : 1 : {
5735 : : /*
5736 : : * It's a committed update, so we gotta preserve him as updater of the
5737 : : * tuple.
5738 : : */
5739 : : MultiXactStatus status;
5740 : : MultiXactStatus new_status;
5741 : :
5742 [ - + ]: 1 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5743 : 0 : status = MultiXactStatusUpdate;
5744 : : else
5745 : 1 : status = MultiXactStatusNoKeyUpdate;
5746 : :
5747 : 1 : new_status = get_mxact_status_for_lock(mode, is_update);
5748 : :
5749 : : /*
5750 : : * since it's not running, it's obviously impossible for the old
5751 : : * updater to be identical to the current one, so we need not check
5752 : : * for that case as we do in the block above.
5753 : : */
5754 : 1 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5755 : 1 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5756 : : }
5757 : : else
5758 : : {
5759 : : /*
5760 : : * Can get here iff the locking/updating transaction was running when
5761 : : * the infomask was extracted from the tuple, but finished before
5762 : : * TransactionIdIsInProgress got to run. Deal with it as if there was
5763 : : * no locker at all in the first place.
5764 : : */
5765 : 8 : old_infomask |= HEAP_XMAX_INVALID;
5766 : 8 : goto l5;
5767 : : }
5768 : :
5769 : 6674094 : *result_infomask = new_infomask;
5770 : 6674094 : *result_infomask2 = new_infomask2;
5771 : 6674094 : *result_xmax = new_xmax;
5772 : 6674094 : }
5773 : :
5774 : : /*
5775 : : * Subroutine for heap_lock_updated_tuple_rec.
5776 : : *
5777 : : * Given a hypothetical multixact status held by the transaction identified
5778 : : * with the given xid, does the current transaction need to wait, fail, or can
5779 : : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5780 : : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5781 : : * returned. If the lock is already held by the current transaction, return
5782 : : * TM_SelfModified. In case of a conflict with another transaction, a
5783 : : * different HeapTupleSatisfiesUpdate return code is returned.
5784 : : *
5785 : : * The held status is said to be hypothetical because it might correspond to a
5786 : : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5787 : : * way for simplicity of API.
5788 : : */
5789 : : static TM_Result
5790 : 38777 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5791 : : LockTupleMode mode, HeapTuple tup,
5792 : : bool *needwait)
5793 : : {
5794 : : MultiXactStatus wantedstatus;
5795 : :
5796 : 38777 : *needwait = false;
5797 : 38777 : wantedstatus = get_mxact_status_for_lock(mode, false);
5798 : :
5799 : : /*
5800 : : * Note: we *must* check TransactionIdIsInProgress before
5801 : : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5802 : : * for an explanation.
5803 : : */
5804 [ - + ]: 38777 : if (TransactionIdIsCurrentTransactionId(xid))
5805 : : {
5806 : : /*
5807 : : * The tuple has already been locked by our own transaction. This is
5808 : : * very rare but can happen if multiple transactions are trying to
5809 : : * lock an ancient version of the same tuple.
5810 : : */
5811 : 0 : return TM_SelfModified;
5812 : : }
5813 [ + + ]: 38777 : else if (TransactionIdIsInProgress(xid))
5814 : : {
5815 : : /*
5816 : : * If the locking transaction is running, what we do depends on
5817 : : * whether the lock modes conflict: if they do, then we must wait for
5818 : : * it to finish; otherwise we can fall through to lock this tuple
5819 : : * version without waiting.
5820 : : */
5821 [ + + ]: 36539 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5822 : 36539 : LOCKMODE_from_mxstatus(wantedstatus)))
5823 : : {
5824 : 8 : *needwait = true;
5825 : : }
5826 : :
5827 : : /*
5828 : : * If we set needwait above, then this value doesn't matter;
5829 : : * otherwise, this value signals to caller that it's okay to proceed.
5830 : : */
5831 : 36539 : return TM_Ok;
5832 : : }
5833 [ + + ]: 2238 : else if (TransactionIdDidAbort(xid))
5834 : 206 : return TM_Ok;
5835 [ + - ]: 2032 : else if (TransactionIdDidCommit(xid))
5836 : : {
5837 : : /*
5838 : : * The other transaction committed. If it was only a locker, then the
5839 : : * lock is completely gone now and we can return success; but if it
5840 : : * was an update, then what we do depends on whether the two lock
5841 : : * modes conflict. If they conflict, then we must report error to
5842 : : * caller. But if they don't, we can fall through to allow the current
5843 : : * transaction to lock the tuple.
5844 : : *
5845 : : * Note: the reason we worry about ISUPDATE here is because as soon as
5846 : : * a transaction ends, all its locks are gone and meaningless, and
5847 : : * thus we can ignore them; whereas its updates persist. In the
5848 : : * TransactionIdIsInProgress case, above, we don't need to check
5849 : : * because we know the lock is still "alive" and thus a conflict needs
5850 : : * always be checked.
5851 : : */
5852 [ + + ]: 2032 : if (!ISUPDATE_from_mxstatus(status))
5853 : 2020 : return TM_Ok;
5854 : :
5855 [ + + ]: 12 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5856 : 12 : LOCKMODE_from_mxstatus(wantedstatus)))
5857 : : {
5858 : : /* bummer */
5859 [ + + ]: 11 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5860 : 9 : return TM_Updated;
5861 : : else
5862 : 2 : return TM_Deleted;
5863 : : }
5864 : :
5865 : 1 : return TM_Ok;
5866 : : }
5867 : :
5868 : : /* Not in progress, not aborted, not committed -- must have crashed */
5869 : 0 : return TM_Ok;
5870 : : }
5871 : :
5872 : :
5873 : : /*
5874 : : * Recursive part of heap_lock_updated_tuple
5875 : : *
5876 : : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5877 : : * xid with the given mode; if this tuple is updated, recurse to lock the new
5878 : : * version as well.
5879 : : */
5880 : : static TM_Result
5881 : 2223 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
5882 : : const ItemPointerData *tid, TransactionId xid,
5883 : : LockTupleMode mode)
5884 : : {
5885 : : TM_Result result;
5886 : : ItemPointerData tupid;
5887 : : HeapTupleData mytup;
5888 : : Buffer buf;
5889 : : Page page;
5890 : : uint16 new_infomask,
5891 : : new_infomask2,
5892 : : old_infomask,
5893 : : old_infomask2;
5894 : : TransactionId xmax,
5895 : : new_xmax;
5896 : 2223 : bool cleared_all_frozen = false;
5897 : : bool pinned_desired_page;
5898 : 2223 : Buffer vmbuffer = InvalidBuffer;
5899 : 2223 : bool unlock_vmbuffer = false;
5900 : : BlockNumber block;
5901 : :
5902 : 2223 : ItemPointerCopy(tid, &tupid);
5903 : :
5904 : : for (;;)
5905 : : {
5906 : 2226 : new_infomask = 0;
5907 : 2226 : new_xmax = InvalidTransactionId;
5908 : 2226 : cleared_all_frozen = false;
5909 : 2226 : block = ItemPointerGetBlockNumber(&tupid);
5910 : 2226 : ItemPointerCopy(&tupid, &(mytup.t_self));
5911 : :
5912 [ + - ]: 2226 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5913 : : {
5914 : : /*
5915 : : * if we fail to find the updated version of the tuple, it's
5916 : : * because it was vacuumed/pruned away after its creator
5917 : : * transaction aborted. So behave as if we got to the end of the
5918 : : * chain, and there's no further tuple to lock: return success to
5919 : : * caller.
5920 : : */
5921 : 0 : result = TM_Ok;
5922 : 0 : goto out_unlocked;
5923 : : }
5924 : :
5925 : 2226 : l4:
5926 [ - + ]: 2234 : CHECK_FOR_INTERRUPTS();
5927 : :
5928 : 2234 : page = BufferGetPage(buf);
5929 : :
5930 : : /*
5931 : : * Before locking the buffer, pin the visibility map page if it
5932 : : * appears to be necessary. Since we haven't got the lock yet,
5933 : : * someone else might be in the middle of changing this, so we'll need
5934 : : * to recheck after we have the lock.
5935 : : */
5936 [ - + ]: 2234 : if (PageIsAllVisible(page))
5937 : : {
5938 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5939 : 0 : pinned_desired_page = true;
5940 : : }
5941 : : else
5942 : 2234 : pinned_desired_page = false;
5943 : :
5944 : 2234 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5945 : :
5946 : : /*
5947 : : * If we didn't pin the visibility map page and the page has become
5948 : : * all visible while we were busy locking the buffer, we'll have to
5949 : : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5950 : : * That's a bit unfortunate, but hopefully shouldn't happen often.
5951 : : *
5952 : : * Note: in some paths through this function, we will reach here
5953 : : * holding a pin on a vm page that may or may not be the one matching
5954 : : * this page. If this page isn't all-visible, we won't use the vm
5955 : : * page, but we hold onto such a pin till the end of the function.
5956 : : */
5957 [ + - - + ]: 2234 : if (!pinned_desired_page && PageIsAllVisible(page))
5958 : : {
5959 : 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5960 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5961 : 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5962 : : }
5963 : :
5964 : : /*
5965 : : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5966 : : * end of the chain, we're done, so return success.
5967 : : */
5968 [ + - + + ]: 4468 : if (TransactionIdIsValid(priorXmax) &&
5969 : 2234 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5970 : : priorXmax))
5971 : : {
5972 : 2 : result = TM_Ok;
5973 : 2 : goto out_locked;
5974 : : }
5975 : :
5976 : : /*
5977 : : * Also check Xmin: if this tuple was created by an aborted
5978 : : * (sub)transaction, then we already locked the last live one in the
5979 : : * chain, thus we're done, so return success.
5980 : : */
5981 [ + + ]: 2232 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
5982 : : {
5983 : 25 : result = TM_Ok;
5984 : 25 : goto out_locked;
5985 : : }
5986 : :
5987 : 2207 : old_infomask = mytup.t_data->t_infomask;
5988 : 2207 : old_infomask2 = mytup.t_data->t_infomask2;
5989 : 2207 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5990 : :
5991 : : /*
5992 : : * If this tuple version has been updated or locked by some concurrent
5993 : : * transaction(s), what we do depends on whether our lock mode
5994 : : * conflicts with what those other transactions hold, and also on the
5995 : : * status of them.
5996 : : */
5997 [ + + ]: 2207 : if (!(old_infomask & HEAP_XMAX_INVALID))
5998 : : {
5999 : : TransactionId rawxmax;
6000 : : bool needwait;
6001 : :
6002 : 2141 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
6003 [ + + ]: 2141 : if (old_infomask & HEAP_XMAX_IS_MULTI)
6004 : : {
6005 : : int nmembers;
6006 : : int i;
6007 : : MultiXactMember *members;
6008 : :
6009 : : /*
6010 : : * We don't need a test for pg_upgrade'd tuples: this is only
6011 : : * applied to tuples after the first in an update chain. Said
6012 : : * first tuple in the chain may well be locked-in-9.2-and-
6013 : : * pg_upgraded, but that one was already locked by our caller,
6014 : : * not us; and any subsequent ones cannot be because our
6015 : : * caller must necessarily have obtained a snapshot later than
6016 : : * the pg_upgrade itself.
6017 : : */
6018 : : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
6019 : :
6020 : 2109 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
6021 : 2109 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
6022 [ + + ]: 40854 : for (i = 0; i < nmembers; i++)
6023 : : {
6024 : 38745 : result = test_lockmode_for_conflict(members[i].status,
6025 : 38745 : members[i].xid,
6026 : : mode,
6027 : : &mytup,
6028 : : &needwait);
6029 : :
6030 : : /*
6031 : : * If the tuple was already locked by ourselves in a
6032 : : * previous iteration of this (say heap_lock_tuple was
6033 : : * forced to restart the locking loop because of a change
6034 : : * in xmax), then we hold the lock already on this tuple
6035 : : * version and we don't need to do anything; and this is
6036 : : * not an error condition either. We just need to skip
6037 : : * this tuple and continue locking the next version in the
6038 : : * update chain.
6039 : : */
6040 [ - + ]: 38745 : if (result == TM_SelfModified)
6041 : : {
6042 : 0 : pfree(members);
6043 : 0 : goto next;
6044 : : }
6045 : :
6046 [ - + ]: 38745 : if (needwait)
6047 : : {
6048 : 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
6049 : 0 : XactLockTableWait(members[i].xid, rel,
6050 : : &mytup.t_self,
6051 : : XLTW_LockUpdated);
6052 : 0 : pfree(members);
6053 : 0 : goto l4;
6054 : : }
6055 [ - + ]: 38745 : if (result != TM_Ok)
6056 : : {
6057 : 0 : pfree(members);
6058 : 0 : goto out_locked;
6059 : : }
6060 : : }
6061 [ + - ]: 2109 : if (members)
6062 : 2109 : pfree(members);
6063 : : }
6064 : : else
6065 : : {
6066 : : MultiXactStatus status;
6067 : :
6068 : : /*
6069 : : * For a non-multi Xmax, we first need to compute the
6070 : : * corresponding MultiXactStatus by using the infomask bits.
6071 : : */
6072 [ + + ]: 32 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
6073 : : {
6074 [ + - ]: 10 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
6075 : 10 : status = MultiXactStatusForKeyShare;
6076 [ # # ]: 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
6077 : 0 : status = MultiXactStatusForShare;
6078 [ # # ]: 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
6079 : : {
6080 [ # # ]: 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6081 : 0 : status = MultiXactStatusForUpdate;
6082 : : else
6083 : 0 : status = MultiXactStatusForNoKeyUpdate;
6084 : : }
6085 : : else
6086 : : {
6087 : : /*
6088 : : * LOCK_ONLY present alone (a pg_upgraded tuple marked
6089 : : * as share-locked in the old cluster) shouldn't be
6090 : : * seen in the middle of an update chain.
6091 : : */
6092 [ # # ]: 0 : elog(ERROR, "invalid lock status in tuple");
6093 : : }
6094 : : }
6095 : : else
6096 : : {
6097 : : /* it's an update, but which kind? */
6098 [ + + ]: 22 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6099 : 17 : status = MultiXactStatusUpdate;
6100 : : else
6101 : 5 : status = MultiXactStatusNoKeyUpdate;
6102 : : }
6103 : :
6104 : 32 : result = test_lockmode_for_conflict(status, rawxmax, mode,
6105 : : &mytup, &needwait);
6106 : :
6107 : : /*
6108 : : * If the tuple was already locked by ourselves in a previous
6109 : : * iteration of this (say heap_lock_tuple was forced to
6110 : : * restart the locking loop because of a change in xmax), then
6111 : : * we hold the lock already on this tuple version and we don't
6112 : : * need to do anything; and this is not an error condition
6113 : : * either. We just need to skip this tuple and continue
6114 : : * locking the next version in the update chain.
6115 : : */
6116 [ - + ]: 32 : if (result == TM_SelfModified)
6117 : 0 : goto next;
6118 : :
6119 [ + + ]: 32 : if (needwait)
6120 : : {
6121 : 8 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
6122 : 8 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
6123 : : XLTW_LockUpdated);
6124 : 8 : goto l4;
6125 : : }
6126 [ + + ]: 24 : if (result != TM_Ok)
6127 : : {
6128 : 11 : goto out_locked;
6129 : : }
6130 : : }
6131 : : }
6132 : :
6133 : : /* compute the new Xmax and infomask values for the tuple ... */
6134 : 2188 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
6135 : : xid, mode, false,
6136 : : &new_xmax, &new_infomask, &new_infomask2);
6137 : :
6138 [ - + ]: 2188 : if (PageIsAllVisible(page))
6139 : : {
6140 : 0 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
6141 : 0 : unlock_vmbuffer = true;
6142 : : }
6143 : :
6144 : 2188 : START_CRIT_SECTION();
6145 : :
6146 : : /* ... and set them */
6147 : 2188 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
6148 : 2188 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
6149 : 2188 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6150 : 2188 : mytup.t_data->t_infomask |= new_infomask;
6151 : 2188 : mytup.t_data->t_infomask2 |= new_infomask2;
6152 : :
6153 : 2188 : MarkBufferDirty(buf);
6154 : :
6155 [ - + ]: 2188 : if (PageIsAllVisible(page))
6156 : : {
6157 : : /* It's possible all-frozen was already clear */
6158 [ # # ]: 0 : if (visibilitymap_clear(rel->rd_locator, block, vmbuffer,
6159 : : VISIBILITYMAP_ALL_FROZEN))
6160 : 0 : cleared_all_frozen = true;
6161 : : }
6162 : :
6163 : : /* XLOG stuff */
6164 [ + - + + : 2188 : if (RelationNeedsWAL(rel))
+ - + - ]
6165 : : {
6166 : : xl_heap_lock_updated xlrec;
6167 : : XLogRecPtr recptr;
6168 : :
6169 : 2188 : XLogBeginInsert();
6170 : 2188 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buf, REGBUF_STANDARD);
6171 : :
6172 : 2188 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
6173 : 2188 : xlrec.xmax = new_xmax;
6174 : 2188 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
6175 : 2188 : xlrec.flags =
6176 : 2188 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
6177 : :
6178 : 2188 : XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
6179 : :
6180 [ - + ]: 2188 : if (cleared_all_frozen)
6181 : 0 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
6182 : :
6183 : 2188 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
6184 : :
6185 : 2188 : PageSetLSN(page, recptr);
6186 : :
6187 [ - + ]: 2188 : if (cleared_all_frozen)
6188 : 0 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
6189 : : }
6190 : :
6191 : 2188 : END_CRIT_SECTION();
6192 : :
6193 : : /* release VM lock first, since it covers many heap blocks */
6194 [ + - ]: 2188 : if (unlock_vmbuffer)
6195 : : {
6196 : 0 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
6197 : 0 : unlock_vmbuffer = false;
6198 : : }
6199 : :
6200 : 2188 : next:
6201 : : /* if we find the end of update chain, we're done. */
6202 [ + - + - ]: 4376 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
6203 [ + + ]: 4376 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
6204 [ + + ]: 2192 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
6205 : 4 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
6206 : : {
6207 : 2185 : result = TM_Ok;
6208 : 2185 : goto out_locked;
6209 : : }
6210 : :
6211 : : /* tail recursion */
6212 : 3 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
6213 : 3 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6214 : 3 : UnlockReleaseBuffer(buf);
6215 : : }
6216 : :
6217 : : result = TM_Ok;
6218 : :
6219 : 2223 : out_locked:
6220 : 2223 : UnlockReleaseBuffer(buf);
6221 : :
6222 : 2223 : out_unlocked:
6223 [ - + ]: 2223 : if (vmbuffer != InvalidBuffer)
6224 : 0 : ReleaseBuffer(vmbuffer);
6225 : : Assert(!unlock_vmbuffer);
6226 : :
6227 : 2223 : return result;
6228 : : }
6229 : :
6230 : : /*
6231 : : * heap_lock_updated_tuple
6232 : : * Follow update chain when locking an updated tuple, acquiring locks (row
6233 : : * marks) on the updated versions.
6234 : : *
6235 : : * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
6236 : : * fields from the initial tuple. We will lock the tuples starting from the
6237 : : * one that 'prior_ctid' points to. Note: This function does not lock the
6238 : : * initial tuple itself.
6239 : : *
6240 : : * This function doesn't check visibility, it just unconditionally marks the
6241 : : * tuple(s) as locked. If any tuple in the updated chain is being deleted
6242 : : * concurrently (or updated with the key being modified), sleep until the
6243 : : * transaction doing it is finished.
6244 : : *
6245 : : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6246 : : * when we have to wait for other transactions to release them, as opposed to
6247 : : * what heap_lock_tuple does. The reason is that having more than one
6248 : : * transaction walking the chain is probably uncommon enough that risk of
6249 : : * starvation is not likely: one of the preconditions for being here is that
6250 : : * the snapshot in use predates the update that created this tuple (because we
6251 : : * started at an earlier version of the tuple), but at the same time such a
6252 : : * transaction cannot be using repeatable read or serializable isolation
6253 : : * levels, because that would lead to a serializability failure.
6254 : : */
6255 : : static TM_Result
6256 : 2225 : heap_lock_updated_tuple(Relation rel,
6257 : : uint16 prior_infomask,
6258 : : TransactionId prior_raw_xmax,
6259 : : const ItemPointerData *prior_ctid,
6260 : : TransactionId xid, LockTupleMode mode)
6261 : : {
6262 : 2225 : INJECTION_POINT("heap_lock_updated_tuple", NULL);
6263 : :
6264 : : /*
6265 : : * If the tuple has moved into another partition (effectively a delete)
6266 : : * stop here.
6267 : : */
6268 [ + + ]: 2225 : if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
6269 : : {
6270 : : TransactionId prior_xmax;
6271 : :
6272 : : /*
6273 : : * If this is the first possibly-multixact-able operation in the
6274 : : * current transaction, set my per-backend OldestMemberMXactId
6275 : : * setting. We can be certain that the transaction will never become a
6276 : : * member of any older MultiXactIds than that. (We have to do this
6277 : : * even if we end up just using our own TransactionId below, since
6278 : : * some other backend could incorporate our XID into a MultiXact
6279 : : * immediately afterwards.)
6280 : : */
6281 : 2223 : MultiXactIdSetOldestMember();
6282 : :
6283 : 4446 : prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
6284 [ + + ]: 2223 : MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
6285 : 2223 : return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
6286 : : }
6287 : :
6288 : : /* nothing to lock */
6289 : 2 : return TM_Ok;
6290 : : }
6291 : :
6292 : : /*
6293 : : * heap_finish_speculative - mark speculative insertion as successful
6294 : : *
6295 : : * To successfully finish a speculative insertion we have to clear speculative
6296 : : * token from tuple. To do so the t_ctid field, which will contain a
6297 : : * speculative token value, is modified in place to point to the tuple itself,
6298 : : * which is characteristic of a newly inserted ordinary tuple.
6299 : : *
6300 : : * NB: It is not ok to commit without either finishing or aborting a
6301 : : * speculative insertion. We could treat speculative tuples of committed
6302 : : * transactions implicitly as completed, but then we would have to be prepared
6303 : : * to deal with speculative tokens on committed tuples. That wouldn't be
6304 : : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6305 : : * but clearing the token at completion isn't very expensive either.
6306 : : * An explicit confirmation WAL record also makes logical decoding simpler.
6307 : : */
6308 : : void
6309 : 2236 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
6310 : : {
6311 : : Buffer buffer;
6312 : : Page page;
6313 : : OffsetNumber offnum;
6314 : : ItemId lp;
6315 : : HeapTupleHeader htup;
6316 : :
6317 : 2236 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
6318 : 2236 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6319 : 2236 : page = BufferGetPage(buffer);
6320 : :
6321 : 2236 : offnum = ItemPointerGetOffsetNumber(tid);
6322 [ + - - + ]: 2236 : if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
6323 [ # # ]: 0 : elog(ERROR, "offnum out of range");
6324 : 2236 : lp = PageGetItemId(page, offnum);
6325 [ - + ]: 2236 : if (!ItemIdIsNormal(lp))
6326 [ # # ]: 0 : elog(ERROR, "invalid lp");
6327 : :
6328 : 2236 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6329 : :
6330 : : /* NO EREPORT(ERROR) from here till changes are logged */
6331 : 2236 : START_CRIT_SECTION();
6332 : :
6333 : : Assert(HeapTupleHeaderIsSpeculative(htup));
6334 : :
6335 : 2236 : MarkBufferDirty(buffer);
6336 : :
6337 : : /*
6338 : : * Replace the speculative insertion token with a real t_ctid, pointing to
6339 : : * itself like it does on regular tuples.
6340 : : */
6341 : 2236 : htup->t_ctid = *tid;
6342 : :
6343 : : /* XLOG stuff */
6344 [ + + + + : 2236 : if (RelationNeedsWAL(relation))
+ - + - ]
6345 : : {
6346 : : xl_heap_confirm xlrec;
6347 : : XLogRecPtr recptr;
6348 : :
6349 : 2216 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
6350 : :
6351 : 2216 : XLogBeginInsert();
6352 : :
6353 : : /* We want the same filtering on this as on a plain insert */
6354 : 2216 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6355 : :
6356 : 2216 : XLogRegisterData(&xlrec, SizeOfHeapConfirm);
6357 : 2216 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6358 : :
6359 : 2216 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6360 : :
6361 : 2216 : PageSetLSN(page, recptr);
6362 : : }
6363 : :
6364 : 2236 : END_CRIT_SECTION();
6365 : :
6366 : 2236 : UnlockReleaseBuffer(buffer);
6367 : 2236 : }
6368 : :
6369 : : /*
6370 : : * heap_abort_speculative - kill a speculatively inserted tuple
6371 : : *
6372 : : * Marks a tuple that was speculatively inserted in the same command as dead,
6373 : : * by setting its xmin as invalid. That makes it immediately appear as dead
6374 : : * to all transactions, including our own. In particular, it makes
6375 : : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6376 : : * inserting a duplicate key value won't unnecessarily wait for our whole
6377 : : * transaction to finish (it'll just wait for our speculative insertion to
6378 : : * finish).
6379 : : *
6380 : : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6381 : : * that arise due to a mutual dependency that is not user visible. By
6382 : : * definition, unprincipled deadlocks cannot be prevented by the user
6383 : : * reordering lock acquisition in client code, because the implementation level
6384 : : * lock acquisitions are not under the user's direct control. If speculative
6385 : : * inserters did not take this precaution, then under high concurrency they
6386 : : * could deadlock with each other, which would not be acceptable.
6387 : : *
6388 : : * This is somewhat redundant with heap_delete, but we prefer to have a
6389 : : * dedicated routine with stripped down requirements. Note that this is also
6390 : : * used to delete the TOAST tuples created during speculative insertion.
6391 : : *
6392 : : * This routine does not affect logical decoding as it only looks at
6393 : : * confirmation records.
6394 : : */
6395 : : void
6396 : 16 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
6397 : : {
6398 : 16 : TransactionId xid = GetCurrentTransactionId();
6399 : : ItemId lp;
6400 : : HeapTupleData tp;
6401 : : Page page;
6402 : : BlockNumber block;
6403 : : Buffer buffer;
6404 : :
6405 : : Assert(ItemPointerIsValid(tid));
6406 : :
6407 : 16 : block = ItemPointerGetBlockNumber(tid);
6408 : 16 : buffer = ReadBuffer(relation, block);
6409 : 16 : page = BufferGetPage(buffer);
6410 : :
6411 : 16 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6412 : :
6413 : : /*
6414 : : * Page can't be all visible, we just inserted into it, and are still
6415 : : * running.
6416 : : */
6417 : : Assert(!PageIsAllVisible(page));
6418 : :
6419 : 16 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6420 : : Assert(ItemIdIsNormal(lp));
6421 : :
6422 : 16 : tp.t_tableOid = RelationGetRelid(relation);
6423 : 16 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6424 : 16 : tp.t_len = ItemIdGetLength(lp);
6425 : 16 : tp.t_self = *tid;
6426 : :
6427 : : /*
6428 : : * Sanity check that the tuple really is a speculatively inserted tuple,
6429 : : * inserted by us.
6430 : : */
6431 [ - + ]: 16 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
6432 [ # # ]: 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
6433 [ + + - + ]: 16 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
6434 [ # # ]: 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
6435 : : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
6436 : :
6437 : : /*
6438 : : * No need to check for serializable conflicts here. There is never a
6439 : : * need for a combo CID, either. No need to extract replica identity, or
6440 : : * do anything special with infomask bits.
6441 : : */
6442 : :
6443 : 16 : START_CRIT_SECTION();
6444 : :
6445 : : /*
6446 : : * The tuple will become DEAD immediately. Flag that this page is a
6447 : : * candidate for pruning by setting xmin to TransactionXmin. While not
6448 : : * immediately prunable, it is the oldest xid we can cheaply determine
6449 : : * that's safe against wraparound / being older than the table's
6450 : : * relfrozenxid. To defend against the unlikely case of a new relation
6451 : : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6452 : : * if so (vacuum can't subsequently move relfrozenxid to beyond
6453 : : * TransactionXmin, so there's no race here).
6454 : : */
6455 : : Assert(TransactionIdIsValid(TransactionXmin));
6456 : : {
6457 : 16 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6458 : : TransactionId prune_xid;
6459 : :
6460 [ - + ]: 16 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
6461 : 0 : prune_xid = relfrozenxid;
6462 : : else
6463 : 16 : prune_xid = TransactionXmin;
6464 [ + - + + ]: 16 : PageSetPrunable(page, prune_xid);
6465 : : }
6466 : :
6467 : : /* store transaction information of xact deleting the tuple */
6468 : 16 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
6469 : 16 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6470 : :
6471 : : /*
6472 : : * Set the tuple header xmin to InvalidTransactionId. This makes the
6473 : : * tuple immediately invisible everyone. (In particular, to any
6474 : : * transactions waiting on the speculative token, woken up later.)
6475 : : */
6476 : 16 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
6477 : :
6478 : : /* Clear the speculative insertion token too */
6479 : 16 : tp.t_data->t_ctid = tp.t_self;
6480 : :
6481 : 16 : MarkBufferDirty(buffer);
6482 : :
6483 : : /*
6484 : : * XLOG stuff
6485 : : *
6486 : : * The WAL records generated here match heap_delete(). The same recovery
6487 : : * routines are used.
6488 : : */
6489 [ + + + + : 16 : if (RelationNeedsWAL(relation))
+ - + - ]
6490 : : {
6491 : : xl_heap_delete xlrec;
6492 : : XLogRecPtr recptr;
6493 : :
6494 : 12 : xlrec.flags = XLH_DELETE_IS_SUPER;
6495 : 24 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6496 : 12 : tp.t_data->t_infomask2);
6497 : 12 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6498 : 12 : xlrec.xmax = xid;
6499 : :
6500 : 12 : XLogBeginInsert();
6501 : 12 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
6502 : 12 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6503 : :
6504 : : /* No replica identity & replication origin logged */
6505 : :
6506 : 12 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6507 : :
6508 : 12 : PageSetLSN(page, recptr);
6509 : : }
6510 : :
6511 : 16 : END_CRIT_SECTION();
6512 : :
6513 : 16 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6514 : :
6515 [ + + ]: 16 : if (HeapTupleHasExternal(&tp))
6516 : : {
6517 : : Assert(!IsToastRelation(relation));
6518 : 1 : heap_toast_delete(relation, &tp, true);
6519 : : }
6520 : :
6521 : : /*
6522 : : * Never need to mark tuple for invalidation, since catalogs don't support
6523 : : * speculative insertion
6524 : : */
6525 : :
6526 : : /* Now we can release the buffer */
6527 : 16 : ReleaseBuffer(buffer);
6528 : :
6529 : : /* count deletion, as we counted the insertion too */
6530 : 16 : pgstat_count_heap_delete(relation);
6531 : 16 : }
6532 : :
6533 : : /*
6534 : : * heap_inplace_lock - protect inplace update from concurrent heap_update()
6535 : : *
6536 : : * Evaluate whether the tuple's state is compatible with a no-key update.
6537 : : * Current transaction rowmarks are fine, as is KEY SHARE from any
6538 : : * transaction. If compatible, return true with the buffer exclusive-locked,
6539 : : * and the caller must release that by calling
6540 : : * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6541 : : * an error. Otherwise, call release_callback(arg), wait for blocking
6542 : : * transactions to end, and return false.
6543 : : *
6544 : : * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6545 : : * DDL, this doesn't guarantee any particular predicate locking.
6546 : : *
6547 : : * heap_delete() is a rarer source of blocking transactions (xwait). We'll
6548 : : * wait for such a transaction just like for the normal heap_update() case.
6549 : : * Normal concurrent DROP commands won't cause that, because all inplace
6550 : : * updaters take some lock that conflicts with DROP. An explicit SQL "DELETE
6551 : : * FROM pg_class" can cause it. By waiting, if the concurrent transaction
6552 : : * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
6553 : : * can find the successor tuple.
6554 : : *
6555 : : * Readers of inplace-updated fields expect changes to those fields are
6556 : : * durable. For example, vac_truncate_clog() reads datfrozenxid from
6557 : : * pg_database tuples via catalog snapshots. A future snapshot must not
6558 : : * return a lower datfrozenxid for the same database OID (lower in the
6559 : : * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6560 : : * tuple can start while we hold a lock on its buffer. In cases like
6561 : : * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6562 : : * to this transaction. ROLLBACK then is one case where it's okay to lose
6563 : : * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6564 : : * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6565 : : * committed tuple.)
6566 : : *
6567 : : * In principle, we could avoid waiting by overwriting every tuple in the
6568 : : * updated tuple chain. Reader expectations permit updating a tuple only if
6569 : : * it's aborted, is the tail of the chain, or we already updated the tuple
6570 : : * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6571 : : * order from tail to head. That would imply either (a) mutating all tuples
6572 : : * in one critical section or (b) accepting a chance of partial completion.
6573 : : * Partial completion of a relfrozenxid update would have the weird
6574 : : * consequence that the table's next VACUUM could see the table's relfrozenxid
6575 : : * move forward between vacuum_get_cutoffs() and finishing.
6576 : : */
6577 : : bool
6578 : 222219 : heap_inplace_lock(Relation relation,
6579 : : HeapTuple oldtup_ptr, Buffer buffer,
6580 : : void (*release_callback) (void *), void *arg)
6581 : : {
6582 : 222219 : HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6583 : : TM_Result result;
6584 : : bool ret;
6585 : :
6586 : : #ifdef USE_ASSERT_CHECKING
6587 : : if (RelationGetRelid(relation) == RelationRelationId)
6588 : : check_inplace_rel_lock(oldtup_ptr);
6589 : : #endif
6590 : :
6591 : : Assert(BufferIsValid(buffer));
6592 : :
6593 : : /*
6594 : : * Register shared cache invals if necessary. Other sessions may finish
6595 : : * inplace updates of this tuple between this step and LockTuple(). Since
6596 : : * inplace updates don't change cache keys, that's harmless.
6597 : : *
6598 : : * While it's tempting to register invals only after confirming we can
6599 : : * return true, the following obstacle precludes reordering steps that
6600 : : * way. Registering invals might reach a CatalogCacheInitializeCache()
6601 : : * that locks "buffer". That would hang indefinitely if running after our
6602 : : * own LockBuffer(). Hence, we must register invals before LockBuffer().
6603 : : */
6604 : 222219 : CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
6605 : :
6606 : 222219 : LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6607 : 222219 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6608 : :
6609 : : /*----------
6610 : : * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6611 : : *
6612 : : * - wait unconditionally
6613 : : * - already locked tuple above, since inplace needs that unconditionally
6614 : : * - don't recheck header after wait: simpler to defer to next iteration
6615 : : * - don't try to continue even if the updater aborts: likewise
6616 : : * - no crosscheck
6617 : : */
6618 : 222219 : result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6619 : : buffer);
6620 : :
6621 [ - + ]: 222219 : if (result == TM_Invisible)
6622 : : {
6623 : : /* no known way this can happen */
6624 [ # # ]: 0 : ereport(ERROR,
6625 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6626 : : errmsg_internal("attempted to overwrite invisible tuple")));
6627 : : }
6628 [ - + ]: 222219 : else if (result == TM_SelfModified)
6629 : : {
6630 : : /*
6631 : : * CREATE INDEX might reach this if an expression is silly enough to
6632 : : * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6633 : : * statements might get here after a heap_update() of the same row, in
6634 : : * the absence of an intervening CommandCounterIncrement().
6635 : : */
6636 [ # # ]: 0 : ereport(ERROR,
6637 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6638 : : errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6639 : : }
6640 [ + + ]: 222219 : else if (result == TM_BeingModified)
6641 : : {
6642 : : TransactionId xwait;
6643 : : uint16 infomask;
6644 : :
6645 : 19 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6646 : 19 : infomask = oldtup.t_data->t_infomask;
6647 : :
6648 [ + + ]: 19 : if (infomask & HEAP_XMAX_IS_MULTI)
6649 : : {
6650 : 5 : LockTupleMode lockmode = LockTupleNoKeyExclusive;
6651 : 5 : MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
6652 : : int remain;
6653 : :
6654 [ + + ]: 5 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6655 : : lockmode, NULL))
6656 : : {
6657 : 2 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6658 : 2 : release_callback(arg);
6659 : 2 : ret = false;
6660 : 2 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6661 : : relation, &oldtup.t_self, XLTW_Update,
6662 : : &remain);
6663 : : }
6664 : : else
6665 : 3 : ret = true;
6666 : : }
6667 [ + + ]: 14 : else if (TransactionIdIsCurrentTransactionId(xwait))
6668 : 1 : ret = true;
6669 [ + + ]: 13 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6670 : 1 : ret = true;
6671 : : else
6672 : : {
6673 : 12 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6674 : 12 : release_callback(arg);
6675 : 12 : ret = false;
6676 : 12 : XactLockTableWait(xwait, relation, &oldtup.t_self,
6677 : : XLTW_Update);
6678 : : }
6679 : : }
6680 : : else
6681 : : {
6682 : 222200 : ret = (result == TM_Ok);
6683 [ - + ]: 222200 : if (!ret)
6684 : : {
6685 : 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6686 : 0 : release_callback(arg);
6687 : : }
6688 : : }
6689 : :
6690 : : /*
6691 : : * GetCatalogSnapshot() relies on invalidation messages to know when to
6692 : : * take a new snapshot. COMMIT of xwait is responsible for sending the
6693 : : * invalidation. We're not acquiring heavyweight locks sufficient to
6694 : : * block if not yet sent, so we must take a new snapshot to ensure a later
6695 : : * attempt has a fair chance. While we don't need this if xwait aborted,
6696 : : * don't bother optimizing that.
6697 : : */
6698 [ + + ]: 222219 : if (!ret)
6699 : : {
6700 : 14 : UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6701 : 14 : ForgetInplace_Inval();
6702 : 14 : InvalidateCatalogSnapshot();
6703 : : }
6704 : 222219 : return ret;
6705 : : }
6706 : :
6707 : : /*
6708 : : * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6709 : : *
6710 : : * The tuple cannot change size, and therefore its header fields and null
6711 : : * bitmap (if any) don't change either.
6712 : : *
6713 : : * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6714 : : */
6715 : : void
6716 : 97026 : heap_inplace_update_and_unlock(Relation relation,
6717 : : HeapTuple oldtup, HeapTuple tuple,
6718 : : Buffer buffer)
6719 : : {
6720 : 97026 : HeapTupleHeader htup = oldtup->t_data;
6721 : : uint32 oldlen;
6722 : : uint32 newlen;
6723 : : char *dst;
6724 : : char *src;
6725 : 97026 : int nmsgs = 0;
6726 : 97026 : SharedInvalidationMessage *invalMessages = NULL;
6727 : 97026 : bool RelcacheInitFileInval = false;
6728 : :
6729 : : Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6730 : 97026 : oldlen = oldtup->t_len - htup->t_hoff;
6731 : 97026 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6732 [ + - - + ]: 97026 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6733 [ # # ]: 0 : elog(ERROR, "wrong tuple length");
6734 : :
6735 : 97026 : dst = (char *) htup + htup->t_hoff;
6736 : 97026 : src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6737 : :
6738 : : /* Like RecordTransactionCommit(), log only if needed */
6739 [ + + ]: 97026 : if (XLogStandbyInfoActive())
6740 : 71445 : nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6741 : : &RelcacheInitFileInval);
6742 : :
6743 : : /*
6744 : : * Unlink relcache init files as needed. If unlinking, acquire
6745 : : * RelCacheInitLock until after associated invalidations. By doing this
6746 : : * in advance, if we checkpoint and then crash between inplace
6747 : : * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6748 : : * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6749 : : * neglect to PANIC on EIO.
6750 : : */
6751 : 97026 : PreInplace_Inval();
6752 : :
6753 : : /*----------
6754 : : * NO EREPORT(ERROR) from here till changes are complete
6755 : : *
6756 : : * Our exclusive buffer lock won't stop a reader having already pinned and
6757 : : * checked visibility for this tuple. With the usual order of changes
6758 : : * (i.e. updating the buffer contents before WAL logging), a reader could
6759 : : * observe our not-yet-persistent update to relfrozenxid and update
6760 : : * datfrozenxid based on that. A crash in that moment could allow
6761 : : * datfrozenxid to overtake relfrozenxid:
6762 : : *
6763 : : * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6764 : : * ["R" is a VACUUM tbl]
6765 : : * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6766 : : * D: systable_getnext() returns pg_class tuple of tbl
6767 : : * R: memcpy() into pg_class tuple of tbl
6768 : : * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6769 : : * [crash]
6770 : : * [recovery restores datfrozenxid w/o relfrozenxid]
6771 : : *
6772 : : * We avoid that by using a temporary copy of the buffer to hide our
6773 : : * change from other backends until the change has been WAL-logged. We
6774 : : * apply our change to the temporary copy and WAL-log it, before modifying
6775 : : * the real page. That way any action a reader of the in-place-updated
6776 : : * value takes will be WAL logged after this change.
6777 : : */
6778 : 97026 : START_CRIT_SECTION();
6779 : :
6780 : 97026 : MarkBufferDirty(buffer);
6781 : :
6782 : : /* XLOG stuff */
6783 [ + - + + : 97026 : if (RelationNeedsWAL(relation))
+ - + + ]
6784 : : {
6785 : : xl_heap_inplace xlrec;
6786 : : PGAlignedBlock copied_buffer;
6787 : 97022 : char *origdata = (char *) BufferGetBlock(buffer);
6788 : 97022 : Page page = BufferGetPage(buffer);
6789 : 97022 : uint16 lower = ((PageHeader) page)->pd_lower;
6790 : 97022 : uint16 upper = ((PageHeader) page)->pd_upper;
6791 : : uintptr_t dst_offset_in_block;
6792 : : RelFileLocator rlocator;
6793 : : ForkNumber forkno;
6794 : : BlockNumber blkno;
6795 : : XLogRecPtr recptr;
6796 : :
6797 : 97022 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6798 : 97022 : xlrec.dbId = MyDatabaseId;
6799 : 97022 : xlrec.tsId = MyDatabaseTableSpace;
6800 : 97022 : xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6801 : 97022 : xlrec.nmsgs = nmsgs;
6802 : :
6803 : 97022 : XLogBeginInsert();
6804 : 97022 : XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
6805 [ + + ]: 97022 : if (nmsgs != 0)
6806 : 54158 : XLogRegisterData(invalMessages,
6807 : : nmsgs * sizeof(SharedInvalidationMessage));
6808 : :
6809 : : /* register block matching what buffer will look like after changes */
6810 : 97022 : memcpy(copied_buffer.data, origdata, lower);
6811 : 97022 : memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6812 : 97022 : dst_offset_in_block = dst - origdata;
6813 : 97022 : memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6814 : 97022 : BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6815 : : Assert(forkno == MAIN_FORKNUM);
6816 : 97022 : XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6817 : : REGBUF_STANDARD);
6818 : 97022 : XLogRegisterBufData(0, src, newlen);
6819 : :
6820 : : /* inplace updates aren't decoded atm, don't log the origin */
6821 : :
6822 : 97022 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6823 : :
6824 : 97022 : PageSetLSN(page, recptr);
6825 : : }
6826 : :
6827 : 97026 : memcpy(dst, src, newlen);
6828 : :
6829 : 97026 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6830 : :
6831 : : /*
6832 : : * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6833 : : * do this before UnlockTuple().
6834 : : */
6835 : 97026 : AtInplace_Inval();
6836 : :
6837 : 97026 : END_CRIT_SECTION();
6838 : 97026 : UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6839 : :
6840 : 97026 : AcceptInvalidationMessages(); /* local processing of just-sent inval */
6841 : :
6842 : : /*
6843 : : * Queue a transactional inval, for logical decoding and for third-party
6844 : : * code that might have been relying on it since long before inplace
6845 : : * update adopted immediate invalidation. See README.tuplock section
6846 : : * "Reading inplace-updated columns" for logical decoding details.
6847 : : */
6848 [ + + ]: 97026 : if (!IsBootstrapProcessingMode())
6849 : 79739 : CacheInvalidateHeapTuple(relation, tuple, NULL);
6850 : 97026 : }
6851 : :
6852 : : /*
6853 : : * heap_inplace_unlock - reverse of heap_inplace_lock
6854 : : */
6855 : : void
6856 : 125179 : heap_inplace_unlock(Relation relation,
6857 : : HeapTuple oldtup, Buffer buffer)
6858 : : {
6859 : 125179 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6860 : 125179 : UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
6861 : 125179 : ForgetInplace_Inval();
6862 : 125179 : }
6863 : :
6864 : : #define FRM_NOOP 0x0001
6865 : : #define FRM_INVALIDATE_XMAX 0x0002
6866 : : #define FRM_RETURN_IS_XID 0x0004
6867 : : #define FRM_RETURN_IS_MULTI 0x0008
6868 : : #define FRM_MARK_COMMITTED 0x0010
6869 : :
6870 : : /*
6871 : : * FreezeMultiXactId
6872 : : * Determine what to do during freezing when a tuple is marked by a
6873 : : * MultiXactId.
6874 : : *
6875 : : * "flags" is an output value; it's used to tell caller what to do on return.
6876 : : * "pagefrz" is an input/output value, used to manage page level freezing.
6877 : : *
6878 : : * Possible values that we can set in "flags":
6879 : : * FRM_NOOP
6880 : : * don't do anything -- keep existing Xmax
6881 : : * FRM_INVALIDATE_XMAX
6882 : : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6883 : : * FRM_RETURN_IS_XID
6884 : : * The Xid return value is a single update Xid to set as xmax.
6885 : : * FRM_MARK_COMMITTED
6886 : : * Xmax can be marked as HEAP_XMAX_COMMITTED
6887 : : * FRM_RETURN_IS_MULTI
6888 : : * The return value is a new MultiXactId to set as new Xmax.
6889 : : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6890 : : *
6891 : : * Caller delegates control of page freezing to us. In practice we always
6892 : : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6893 : : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6894 : : * can never be left behind. We freely choose when and how to process each
6895 : : * Multi, without ever violating the cutoff postconditions for freezing.
6896 : : *
6897 : : * It's useful to remove Multis on a proactive timeline (relative to freezing
6898 : : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6899 : : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6900 : : * misses through eager processing.
6901 : : *
6902 : : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6903 : : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6904 : : * This can usually be put off, which is usually enough to avoid it altogether.
6905 : : * Allocating new multis during VACUUM should be avoided on general principle;
6906 : : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6907 : : * its own special risks.
6908 : : *
6909 : : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6910 : : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6911 : : *
6912 : : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6913 : : * have already forced page-level freezing, since that might incur the same
6914 : : * SLRU buffer misses that we specifically intended to avoid by freezing.
6915 : : */
6916 : : static TransactionId
6917 : 6 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6918 : : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6919 : : HeapPageFreeze *pagefrz)
6920 : : {
6921 : : TransactionId newxmax;
6922 : : MultiXactMember *members;
6923 : : int nmembers;
6924 : : bool need_replace;
6925 : : int nnewmembers;
6926 : : MultiXactMember *newmembers;
6927 : : bool has_lockers;
6928 : : TransactionId update_xid;
6929 : : bool update_committed;
6930 : : TransactionId FreezePageRelfrozenXid;
6931 : :
6932 : 6 : *flags = 0;
6933 : :
6934 : : /* We should only be called in Multis */
6935 : : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6936 : :
6937 [ + - - + ]: 12 : if (!MultiXactIdIsValid(multi) ||
6938 : 6 : HEAP_LOCKED_UPGRADED(t_infomask))
6939 : : {
6940 : 0 : *flags |= FRM_INVALIDATE_XMAX;
6941 : 0 : pagefrz->freeze_required = true;
6942 : 0 : return InvalidTransactionId;
6943 : : }
6944 [ - + ]: 6 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6945 [ # # ]: 0 : ereport(ERROR,
6946 : : (errcode(ERRCODE_DATA_CORRUPTED),
6947 : : errmsg_internal("found multixact %u from before relminmxid %u",
6948 : : multi, cutoffs->relminmxid)));
6949 [ + + ]: 6 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6950 : : {
6951 : : TransactionId update_xact;
6952 : :
6953 : : /*
6954 : : * This old multi cannot possibly have members still running, but
6955 : : * verify just in case. If it was a locker only, it can be removed
6956 : : * without any further consideration; but if it contained an update,
6957 : : * we might need to preserve it.
6958 : : */
6959 [ - + ]: 4 : if (MultiXactIdIsRunning(multi,
6960 : 4 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6961 [ # # ]: 0 : ereport(ERROR,
6962 : : (errcode(ERRCODE_DATA_CORRUPTED),
6963 : : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6964 : : multi, cutoffs->OldestMxact)));
6965 : :
6966 [ + - ]: 4 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6967 : : {
6968 : 4 : *flags |= FRM_INVALIDATE_XMAX;
6969 : 4 : pagefrz->freeze_required = true;
6970 : 4 : return InvalidTransactionId;
6971 : : }
6972 : :
6973 : : /* replace multi with single XID for its updater? */
6974 : 0 : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6975 [ # # ]: 0 : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6976 [ # # ]: 0 : ereport(ERROR,
6977 : : (errcode(ERRCODE_DATA_CORRUPTED),
6978 : : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6979 : : multi, update_xact,
6980 : : cutoffs->relfrozenxid)));
6981 [ # # ]: 0 : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6982 : : {
6983 : : /*
6984 : : * Updater XID has to have aborted (otherwise the tuple would have
6985 : : * been pruned away instead, since updater XID is < OldestXmin).
6986 : : * Just remove xmax.
6987 : : */
6988 [ # # ]: 0 : if (TransactionIdDidCommit(update_xact))
6989 [ # # ]: 0 : ereport(ERROR,
6990 : : (errcode(ERRCODE_DATA_CORRUPTED),
6991 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6992 : : multi, update_xact,
6993 : : cutoffs->OldestXmin)));
6994 : 0 : *flags |= FRM_INVALIDATE_XMAX;
6995 : 0 : pagefrz->freeze_required = true;
6996 : 0 : return InvalidTransactionId;
6997 : : }
6998 : :
6999 : : /* Have to keep updater XID as new xmax */
7000 : 0 : *flags |= FRM_RETURN_IS_XID;
7001 : 0 : pagefrz->freeze_required = true;
7002 : 0 : return update_xact;
7003 : : }
7004 : :
7005 : : /*
7006 : : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
7007 : : * need to walk the whole members array to figure out what to do, if
7008 : : * anything.
7009 : : */
7010 : : nmembers =
7011 : 2 : GetMultiXactIdMembers(multi, &members, false,
7012 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
7013 [ - + ]: 2 : if (nmembers <= 0)
7014 : : {
7015 : : /* Nothing worth keeping */
7016 : 0 : *flags |= FRM_INVALIDATE_XMAX;
7017 : 0 : pagefrz->freeze_required = true;
7018 : 0 : return InvalidTransactionId;
7019 : : }
7020 : :
7021 : : /*
7022 : : * The FRM_NOOP case is the only case where we might need to ratchet back
7023 : : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
7024 : : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
7025 : : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
7026 : : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
7027 : : * trackers managed by VACUUM being ratcheting back by xmax to the degree
7028 : : * required to make it safe to leave xmax undisturbed, independent of
7029 : : * whether or not page freezing is triggered somewhere else.
7030 : : *
7031 : : * Our policy is to force freezing in every case other than FRM_NOOP,
7032 : : * which obviates the need to maintain either set of trackers, anywhere.
7033 : : * Every other case will reliably execute a freeze plan for xmax that
7034 : : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
7035 : : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
7036 : : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
7037 : : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
7038 : : */
7039 : 2 : need_replace = false;
7040 : 2 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
7041 [ + + ]: 4 : for (int i = 0; i < nmembers; i++)
7042 : : {
7043 : 3 : TransactionId xid = members[i].xid;
7044 : :
7045 : : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7046 : :
7047 [ + + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7048 : : {
7049 : : /* Can't violate the FreezeLimit postcondition */
7050 : 1 : need_replace = true;
7051 : 1 : break;
7052 : : }
7053 [ - + ]: 2 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
7054 : 0 : FreezePageRelfrozenXid = xid;
7055 : : }
7056 : :
7057 : : /* Can't violate the MultiXactCutoff postcondition, either */
7058 [ + + ]: 2 : if (!need_replace)
7059 : 1 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
7060 : :
7061 [ + + ]: 2 : if (!need_replace)
7062 : : {
7063 : : /*
7064 : : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
7065 : : * both together to make it safe to retain this particular multi after
7066 : : * freezing its page
7067 : : */
7068 : 1 : *flags |= FRM_NOOP;
7069 : 1 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
7070 [ - + ]: 1 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
7071 : 0 : pagefrz->FreezePageRelminMxid = multi;
7072 : 1 : pfree(members);
7073 : 1 : return multi;
7074 : : }
7075 : :
7076 : : /*
7077 : : * Do a more thorough second pass over the multi to figure out which
7078 : : * member XIDs actually need to be kept. Checking the precise status of
7079 : : * individual members might even show that we don't need to keep anything.
7080 : : * That is quite possible even though the Multi must be >= OldestMxact,
7081 : : * since our second pass only keeps member XIDs when it's truly necessary;
7082 : : * even member XIDs >= OldestXmin often won't be kept by second pass.
7083 : : */
7084 : 1 : nnewmembers = 0;
7085 : 1 : newmembers = palloc_array(MultiXactMember, nmembers);
7086 : 1 : has_lockers = false;
7087 : 1 : update_xid = InvalidTransactionId;
7088 : 1 : update_committed = false;
7089 : :
7090 : : /*
7091 : : * Determine whether to keep each member xid, or to ignore it instead
7092 : : */
7093 [ + + ]: 3 : for (int i = 0; i < nmembers; i++)
7094 : : {
7095 : 2 : TransactionId xid = members[i].xid;
7096 : 2 : MultiXactStatus mstatus = members[i].status;
7097 : :
7098 : : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7099 : :
7100 [ + - ]: 2 : if (!ISUPDATE_from_mxstatus(mstatus))
7101 : : {
7102 : : /*
7103 : : * Locker XID (not updater XID). We only keep lockers that are
7104 : : * still running.
7105 : : */
7106 [ + - + + ]: 4 : if (TransactionIdIsCurrentTransactionId(xid) ||
7107 : 2 : TransactionIdIsInProgress(xid))
7108 : : {
7109 [ - + ]: 1 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
7110 [ # # ]: 0 : ereport(ERROR,
7111 : : (errcode(ERRCODE_DATA_CORRUPTED),
7112 : : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
7113 : : multi, xid,
7114 : : cutoffs->OldestXmin)));
7115 : 1 : newmembers[nnewmembers++] = members[i];
7116 : 1 : has_lockers = true;
7117 : : }
7118 : :
7119 : 2 : continue;
7120 : : }
7121 : :
7122 : : /*
7123 : : * Updater XID (not locker XID). Should we keep it?
7124 : : *
7125 : : * Since the tuple wasn't totally removed when vacuum pruned, the
7126 : : * update Xid cannot possibly be older than OldestXmin cutoff unless
7127 : : * the updater XID aborted. If the updater transaction is known
7128 : : * aborted or crashed then it's okay to ignore it, otherwise not.
7129 : : *
7130 : : * In any case the Multi should never contain two updaters, whatever
7131 : : * their individual commit status. Check for that first, in passing.
7132 : : */
7133 [ # # ]: 0 : if (TransactionIdIsValid(update_xid))
7134 [ # # ]: 0 : ereport(ERROR,
7135 : : (errcode(ERRCODE_DATA_CORRUPTED),
7136 : : errmsg_internal("multixact %u has two or more updating members",
7137 : : multi),
7138 : : errdetail_internal("First updater XID=%u second updater XID=%u.",
7139 : : update_xid, xid)));
7140 : :
7141 : : /*
7142 : : * As with all tuple visibility routines, it's critical to test
7143 : : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
7144 : : * race conditions explained in detail in heapam_visibility.c.
7145 : : */
7146 [ # # # # ]: 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
7147 : 0 : TransactionIdIsInProgress(xid))
7148 : 0 : update_xid = xid;
7149 [ # # ]: 0 : else if (TransactionIdDidCommit(xid))
7150 : : {
7151 : : /*
7152 : : * The transaction committed, so we can tell caller to set
7153 : : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
7154 : : * transaction is not running.)
7155 : : */
7156 : 0 : update_committed = true;
7157 : 0 : update_xid = xid;
7158 : : }
7159 : : else
7160 : : {
7161 : : /*
7162 : : * Not in progress, not committed -- must be aborted or crashed;
7163 : : * we can ignore it.
7164 : : */
7165 : 0 : continue;
7166 : : }
7167 : :
7168 : : /*
7169 : : * We determined that updater must be kept -- add it to pending new
7170 : : * members list
7171 : : */
7172 [ # # ]: 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
7173 [ # # ]: 0 : ereport(ERROR,
7174 : : (errcode(ERRCODE_DATA_CORRUPTED),
7175 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
7176 : : multi, xid, cutoffs->OldestXmin)));
7177 : 0 : newmembers[nnewmembers++] = members[i];
7178 : : }
7179 : :
7180 : 1 : pfree(members);
7181 : :
7182 : : /*
7183 : : * Determine what to do with caller's multi based on information gathered
7184 : : * during our second pass
7185 : : */
7186 [ - + ]: 1 : if (nnewmembers == 0)
7187 : : {
7188 : : /* Nothing worth keeping */
7189 : 0 : *flags |= FRM_INVALIDATE_XMAX;
7190 : 0 : newxmax = InvalidTransactionId;
7191 : : }
7192 [ - + - - ]: 1 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
7193 : : {
7194 : : /*
7195 : : * If there's a single member and it's an update, pass it back alone
7196 : : * without creating a new Multi. (XXX we could do this when there's a
7197 : : * single remaining locker, too, but that would complicate the API too
7198 : : * much; moreover, the case with the single updater is more
7199 : : * interesting, because those are longer-lived.)
7200 : : */
7201 : : Assert(nnewmembers == 1);
7202 : 0 : *flags |= FRM_RETURN_IS_XID;
7203 [ # # ]: 0 : if (update_committed)
7204 : 0 : *flags |= FRM_MARK_COMMITTED;
7205 : 0 : newxmax = update_xid;
7206 : : }
7207 : : else
7208 : : {
7209 : : /*
7210 : : * Create a new multixact with the surviving members of the previous
7211 : : * one, to set as new Xmax in the tuple
7212 : : */
7213 : 1 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
7214 : 1 : *flags |= FRM_RETURN_IS_MULTI;
7215 : : }
7216 : :
7217 : 1 : pfree(newmembers);
7218 : :
7219 : 1 : pagefrz->freeze_required = true;
7220 : 1 : return newxmax;
7221 : : }
7222 : :
7223 : : /*
7224 : : * heap_prepare_freeze_tuple
7225 : : *
7226 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7227 : : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
7228 : : * setup enough state (in the *frz output argument) to enable caller to
7229 : : * process this tuple as part of freezing its page, and return true. Return
7230 : : * false if nothing can be changed about the tuple right now.
7231 : : *
7232 : : * FreezePageConflictXid is advanced only for xmin/xvac freezing, not for xmax
7233 : : * changes. We only remove xmax state here when it is lock-only, or when the
7234 : : * updater XID (including an updater member of a MultiXact) must be aborted;
7235 : : * otherwise, the tuple would already be removable. Neither case affects
7236 : : * visibility on a standby.
7237 : : *
7238 : : * Also sets *totally_frozen to true if the tuple will be totally frozen once
7239 : : * caller executes returned freeze plan (or if the tuple was already totally
7240 : : * frozen by an earlier VACUUM). This indicates that there are no remaining
7241 : : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
7242 : : *
7243 : : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
7244 : : * tuple that we returned true for, and then execute freezing. Caller must
7245 : : * initialize pagefrz fields for page as a whole before first call here for
7246 : : * each heap page.
7247 : : *
7248 : : * VACUUM caller decides on whether or not to freeze the page as a whole.
7249 : : * We'll often prepare freeze plans for a page that caller just discards.
7250 : : * However, VACUUM doesn't always get to make a choice; it must freeze when
7251 : : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7252 : : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7253 : : * that VACUUM always follows that rule.
7254 : : *
7255 : : * We sometimes force freezing of xmax MultiXactId values long before it is
7256 : : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7257 : : * It's worth processing MultiXactIds proactively when it is cheap to do so,
7258 : : * and it's convenient to make that happen by piggy-backing it on the "force
7259 : : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7260 : : * because it is expensive right now (though only when it's still possible to
7261 : : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7262 : : *
7263 : : * It is assumed that the caller has checked the tuple with
7264 : : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7265 : : * (else we should be removing the tuple, not freezing it).
7266 : : *
7267 : : * NB: This function has side effects: it might allocate a new MultiXactId.
7268 : : * It will be set as tuple's new xmax when our *frz output is processed within
7269 : : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7270 : : * then caller had better have an exclusive lock on it already.
7271 : : */
7272 : : bool
7273 : 13523892 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
7274 : : const struct VacuumCutoffs *cutoffs,
7275 : : HeapPageFreeze *pagefrz,
7276 : : HeapTupleFreeze *frz, bool *totally_frozen)
7277 : : {
7278 : 13523892 : bool xmin_already_frozen = false,
7279 : 13523892 : xmax_already_frozen = false;
7280 : 13523892 : bool freeze_xmin = false,
7281 : 13523892 : replace_xvac = false,
7282 : 13523892 : replace_xmax = false,
7283 : 13523892 : freeze_xmax = false;
7284 : : TransactionId xid;
7285 : :
7286 : 13523892 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
7287 : 13523892 : frz->t_infomask2 = tuple->t_infomask2;
7288 : 13523892 : frz->t_infomask = tuple->t_infomask;
7289 : 13523892 : frz->frzflags = 0;
7290 : 13523892 : frz->checkflags = 0;
7291 : :
7292 : : /*
7293 : : * Process xmin, while keeping track of whether it's already frozen, or
7294 : : * will become frozen iff our freeze plan is executed by caller (could be
7295 : : * neither).
7296 : : */
7297 : 13523892 : xid = HeapTupleHeaderGetXmin(tuple);
7298 [ + + ]: 13523892 : if (!TransactionIdIsNormal(xid))
7299 : 9038193 : xmin_already_frozen = true;
7300 : : else
7301 : : {
7302 [ - + ]: 4485699 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7303 [ # # ]: 0 : ereport(ERROR,
7304 : : (errcode(ERRCODE_DATA_CORRUPTED),
7305 : : errmsg_internal("found xmin %u from before relfrozenxid %u",
7306 : : xid, cutoffs->relfrozenxid)));
7307 : :
7308 : : /* Will set freeze_xmin flags in freeze plan below */
7309 : 4485699 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7310 : :
7311 : : /* Verify that xmin committed if and when freeze plan is executed */
7312 [ + + ]: 4485699 : if (freeze_xmin)
7313 : : {
7314 : 3757295 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
7315 [ + + ]: 3757295 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7316 : 522979 : pagefrz->FreezePageConflictXid = xid;
7317 : : }
7318 : : }
7319 : :
7320 : : /*
7321 : : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7322 : : * as we support having MOVED_OFF/MOVED_IN tuples in the database
7323 : : */
7324 : 13523892 : xid = HeapTupleHeaderGetXvac(tuple);
7325 [ - + ]: 13523892 : if (TransactionIdIsNormal(xid))
7326 : : {
7327 : : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7328 : : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7329 : :
7330 : : /*
7331 : : * For Xvac, we always freeze proactively. This allows totally_frozen
7332 : : * tracking to ignore xvac.
7333 : : */
7334 : 0 : replace_xvac = pagefrz->freeze_required = true;
7335 : :
7336 [ # # ]: 0 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7337 : 0 : pagefrz->FreezePageConflictXid = xid;
7338 : :
7339 : : /* Will set replace_xvac flags in freeze plan below */
7340 : : }
7341 : :
7342 : : /* Now process xmax */
7343 : 13523892 : xid = frz->xmax;
7344 [ + + ]: 13523892 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7345 : : {
7346 : : /* Raw xmax is a MultiXactId */
7347 : : TransactionId newxmax;
7348 : : uint16 flags;
7349 : :
7350 : : /*
7351 : : * We will either remove xmax completely (in the "freeze_xmax" path),
7352 : : * process xmax by replacing it (in the "replace_xmax" path), or
7353 : : * perform no-op xmax processing. The only constraint is that the
7354 : : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7355 : : */
7356 : 6 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7357 : : &flags, pagefrz);
7358 : :
7359 [ + + ]: 6 : if (flags & FRM_NOOP)
7360 : : {
7361 : : /*
7362 : : * xmax is a MultiXactId, and nothing about it changes for now.
7363 : : * This is the only case where 'freeze_required' won't have been
7364 : : * set for us by FreezeMultiXactId, as well as the only case where
7365 : : * neither freeze_xmax nor replace_xmax are set (given a multi).
7366 : : *
7367 : : * This is a no-op, but the call to FreezeMultiXactId might have
7368 : : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7369 : : * for us (the "freeze page" variants, specifically). That'll
7370 : : * make it safe for our caller to freeze the page later on, while
7371 : : * leaving this particular xmax undisturbed.
7372 : : *
7373 : : * FreezeMultiXactId is _not_ responsible for the "no freeze"
7374 : : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7375 : : * job. A call to heap_tuple_should_freeze for this same tuple
7376 : : * will take place below if 'freeze_required' isn't set already.
7377 : : * (This repeats work from FreezeMultiXactId, but allows "no
7378 : : * freeze" tracker maintenance to happen in only one place.)
7379 : : */
7380 : : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7381 : : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7382 : : }
7383 [ - + ]: 5 : else if (flags & FRM_RETURN_IS_XID)
7384 : : {
7385 : : /*
7386 : : * xmax will become an updater Xid (original MultiXact's updater
7387 : : * member Xid will be carried forward as a simple Xid in Xmax).
7388 : : */
7389 : : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7390 : :
7391 : : /*
7392 : : * NB -- some of these transformations are only valid because we
7393 : : * know the return Xid is a tuple updater (i.e. not merely a
7394 : : * locker.) Also note that the only reason we don't explicitly
7395 : : * worry about HEAP_KEYS_UPDATED is because it lives in
7396 : : * t_infomask2 rather than t_infomask.
7397 : : */
7398 : 0 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7399 : 0 : frz->xmax = newxmax;
7400 [ # # ]: 0 : if (flags & FRM_MARK_COMMITTED)
7401 : 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
7402 : 0 : replace_xmax = true;
7403 : : }
7404 [ + + ]: 5 : else if (flags & FRM_RETURN_IS_MULTI)
7405 : : {
7406 : : uint16 newbits;
7407 : : uint16 newbits2;
7408 : :
7409 : : /*
7410 : : * xmax is an old MultiXactId that we have to replace with a new
7411 : : * MultiXactId, to carry forward two or more original member XIDs.
7412 : : */
7413 : : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7414 : :
7415 : : /*
7416 : : * We can't use GetMultiXactIdHintBits directly on the new multi
7417 : : * here; that routine initializes the masks to all zeroes, which
7418 : : * would lose other bits we need. Doing it this way ensures all
7419 : : * unrelated bits remain untouched.
7420 : : */
7421 : 1 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7422 : 1 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7423 : 1 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7424 : 1 : frz->t_infomask |= newbits;
7425 : 1 : frz->t_infomask2 |= newbits2;
7426 : 1 : frz->xmax = newxmax;
7427 : 1 : replace_xmax = true;
7428 : : }
7429 : : else
7430 : : {
7431 : : /*
7432 : : * Freeze plan for tuple "freezes xmax" in the strictest sense:
7433 : : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7434 : : */
7435 : : Assert(flags & FRM_INVALIDATE_XMAX);
7436 : : Assert(!TransactionIdIsValid(newxmax));
7437 : :
7438 : : /* Will set freeze_xmax flags in freeze plan below */
7439 : 4 : freeze_xmax = true;
7440 : : }
7441 : :
7442 : : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
7443 : : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
7444 : : }
7445 [ + + ]: 13523886 : else if (TransactionIdIsNormal(xid))
7446 : : {
7447 : : /* Raw xmax is normal XID */
7448 [ - + ]: 6215095 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7449 [ # # ]: 0 : ereport(ERROR,
7450 : : (errcode(ERRCODE_DATA_CORRUPTED),
7451 : : errmsg_internal("found xmax %u from before relfrozenxid %u",
7452 : : xid, cutoffs->relfrozenxid)));
7453 : :
7454 : : /* Will set freeze_xmax flags in freeze plan below */
7455 : 6215095 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7456 : :
7457 : : /*
7458 : : * Verify that xmax aborted if and when freeze plan is executed,
7459 : : * provided it's from an update. (A lock-only xmax can be removed
7460 : : * independent of this, since the lock is released at xact end.)
7461 : : */
7462 [ + + + + ]: 6215095 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7463 : 2410 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7464 : : }
7465 [ + - ]: 7308791 : else if (!TransactionIdIsValid(xid))
7466 : : {
7467 : : /* Raw xmax is InvalidTransactionId XID */
7468 : : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
7469 : 7308791 : xmax_already_frozen = true;
7470 : : }
7471 : : else
7472 [ # # ]: 0 : ereport(ERROR,
7473 : : (errcode(ERRCODE_DATA_CORRUPTED),
7474 : : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7475 : : xid, tuple->t_infomask)));
7476 : :
7477 [ + + ]: 13523892 : if (freeze_xmin)
7478 : : {
7479 : : Assert(!xmin_already_frozen);
7480 : :
7481 : 3757295 : frz->t_infomask |= HEAP_XMIN_FROZEN;
7482 : : }
7483 [ - + ]: 13523892 : if (replace_xvac)
7484 : : {
7485 : : /*
7486 : : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7487 : : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7488 : : * transaction succeeded.
7489 : : */
7490 : : Assert(pagefrz->freeze_required);
7491 [ # # ]: 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
7492 : 0 : frz->frzflags |= XLH_INVALID_XVAC;
7493 : : else
7494 : 0 : frz->frzflags |= XLH_FREEZE_XVAC;
7495 : : }
7496 : : if (replace_xmax)
7497 : : {
7498 : : Assert(!xmax_already_frozen && !freeze_xmax);
7499 : : Assert(pagefrz->freeze_required);
7500 : :
7501 : : /* Already set replace_xmax flags in freeze plan earlier */
7502 : : }
7503 [ + + ]: 13523892 : if (freeze_xmax)
7504 : : {
7505 : : Assert(!xmax_already_frozen && !replace_xmax);
7506 : :
7507 : 3410 : frz->xmax = InvalidTransactionId;
7508 : :
7509 : : /*
7510 : : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7511 : : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7512 : : * Also get rid of the HEAP_KEYS_UPDATED bit.
7513 : : */
7514 : 3410 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7515 : 3410 : frz->t_infomask |= HEAP_XMAX_INVALID;
7516 : 3410 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7517 : 3410 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7518 : : }
7519 : :
7520 : : /*
7521 : : * Determine if this tuple is already totally frozen, or will become
7522 : : * totally frozen (provided caller executes freeze plans for the page)
7523 : : */
7524 [ + + + + : 26315970 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
+ + ]
7525 [ + + ]: 12792078 : (freeze_xmax || xmax_already_frozen));
7526 : :
7527 [ + + + + : 13523892 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
+ + ]
7528 : : xmax_already_frozen))
7529 : : {
7530 : : /*
7531 : : * So far no previous tuple from the page made freezing mandatory.
7532 : : * Does this tuple force caller to freeze the entire page?
7533 : : */
7534 : 8877644 : pagefrz->freeze_required =
7535 : 8877644 : heap_tuple_should_freeze(tuple, cutoffs,
7536 : : &pagefrz->NoFreezePageRelfrozenXid,
7537 : : &pagefrz->NoFreezePageRelminMxid);
7538 : : }
7539 : :
7540 : : /* Tell caller if this tuple has a usable freeze plan set in *frz */
7541 [ + + + - : 13523892 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
+ - + + ]
7542 : : }
7543 : :
7544 : : /*
7545 : : * Perform xmin/xmax XID status sanity checks before actually executing freeze
7546 : : * plans.
7547 : : *
7548 : : * heap_prepare_freeze_tuple doesn't perform these checks directly because
7549 : : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7550 : : * successive VACUUMs that each decide against freezing the same page.
7551 : : */
7552 : : void
7553 : 27584 : heap_pre_freeze_checks(Buffer buffer,
7554 : : HeapTupleFreeze *tuples, int ntuples)
7555 : : {
7556 : 27584 : Page page = BufferGetPage(buffer);
7557 : :
7558 [ + + ]: 1406099 : for (int i = 0; i < ntuples; i++)
7559 : : {
7560 : 1378515 : HeapTupleFreeze *frz = tuples + i;
7561 : 1378515 : ItemId itemid = PageGetItemId(page, frz->offset);
7562 : : HeapTupleHeader htup;
7563 : :
7564 : 1378515 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7565 : :
7566 : : /* Deliberately avoid relying on tuple hint bits here */
7567 [ + + ]: 1378515 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7568 : : {
7569 : 1378514 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
7570 : :
7571 : : Assert(!HeapTupleHeaderXminFrozen(htup));
7572 [ - + ]: 1378514 : if (unlikely(!TransactionIdDidCommit(xmin)))
7573 [ # # ]: 0 : ereport(ERROR,
7574 : : (errcode(ERRCODE_DATA_CORRUPTED),
7575 : : errmsg_internal("uncommitted xmin %u needs to be frozen",
7576 : : xmin)));
7577 : : }
7578 : :
7579 : : /*
7580 : : * TransactionIdDidAbort won't work reliably in the presence of XIDs
7581 : : * left behind by transactions that were in progress during a crash,
7582 : : * so we can only check that xmax didn't commit
7583 : : */
7584 [ + + ]: 1378515 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7585 : : {
7586 : 466 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
7587 : :
7588 : : Assert(TransactionIdIsNormal(xmax));
7589 [ - + ]: 466 : if (unlikely(TransactionIdDidCommit(xmax)))
7590 [ # # ]: 0 : ereport(ERROR,
7591 : : (errcode(ERRCODE_DATA_CORRUPTED),
7592 : : errmsg_internal("cannot freeze committed xmax %u",
7593 : : xmax)));
7594 : : }
7595 : : }
7596 : 27584 : }
7597 : :
7598 : : /*
7599 : : * Helper which executes freezing of one or more heap tuples on a page on
7600 : : * behalf of caller. Caller passes an array of tuple plans from
7601 : : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7602 : : * Must be called in a critical section that also marks the buffer dirty and,
7603 : : * if needed, emits WAL.
7604 : : */
7605 : : void
7606 : 27584 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
7607 : : {
7608 : 27584 : Page page = BufferGetPage(buffer);
7609 : :
7610 [ + + ]: 1406099 : for (int i = 0; i < ntuples; i++)
7611 : : {
7612 : 1378515 : HeapTupleFreeze *frz = tuples + i;
7613 : 1378515 : ItemId itemid = PageGetItemId(page, frz->offset);
7614 : : HeapTupleHeader htup;
7615 : :
7616 : 1378515 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7617 : 1378515 : heap_execute_freeze_tuple(htup, frz);
7618 : : }
7619 : 27584 : }
7620 : :
7621 : : /*
7622 : : * heap_freeze_tuple
7623 : : * Freeze tuple in place, without WAL logging.
7624 : : *
7625 : : * Useful for callers like CLUSTER that perform their own WAL logging.
7626 : : */
7627 : : bool
7628 : 447308 : heap_freeze_tuple(HeapTupleHeader tuple,
7629 : : TransactionId relfrozenxid, TransactionId relminmxid,
7630 : : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7631 : : {
7632 : : HeapTupleFreeze frz;
7633 : : bool do_freeze;
7634 : : bool totally_frozen;
7635 : : struct VacuumCutoffs cutoffs;
7636 : : HeapPageFreeze pagefrz;
7637 : :
7638 : 447308 : cutoffs.relfrozenxid = relfrozenxid;
7639 : 447308 : cutoffs.relminmxid = relminmxid;
7640 : 447308 : cutoffs.OldestXmin = FreezeLimit;
7641 : 447308 : cutoffs.OldestMxact = MultiXactCutoff;
7642 : 447308 : cutoffs.FreezeLimit = FreezeLimit;
7643 : 447308 : cutoffs.MultiXactCutoff = MultiXactCutoff;
7644 : :
7645 : 447308 : pagefrz.freeze_required = true;
7646 : 447308 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7647 : 447308 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
7648 : 447308 : pagefrz.FreezePageConflictXid = InvalidTransactionId;
7649 : 447308 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7650 : 447308 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7651 : :
7652 : 447308 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7653 : : &pagefrz, &frz, &totally_frozen);
7654 : :
7655 : : /*
7656 : : * Note that because this is not a WAL-logged operation, we don't need to
7657 : : * fill in the offset in the freeze record.
7658 : : */
7659 : :
7660 [ + + ]: 447308 : if (do_freeze)
7661 : 371905 : heap_execute_freeze_tuple(tuple, &frz);
7662 : 447308 : return do_freeze;
7663 : : }
7664 : :
7665 : : /*
7666 : : * For a given MultiXactId, return the hint bits that should be set in the
7667 : : * tuple's infomask.
7668 : : *
7669 : : * Normally this should be called for a multixact that was just created, and
7670 : : * so is on our local cache, so the GetMembers call is fast.
7671 : : */
7672 : : static void
7673 : 76803 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
7674 : : uint16 *new_infomask2)
7675 : : {
7676 : : int nmembers;
7677 : : MultiXactMember *members;
7678 : : int i;
7679 : 76803 : uint16 bits = HEAP_XMAX_IS_MULTI;
7680 : 76803 : uint16 bits2 = 0;
7681 : 76803 : bool has_update = false;
7682 : 76803 : LockTupleMode strongest = LockTupleKeyShare;
7683 : :
7684 : : /*
7685 : : * We only use this in multis we just created, so they cannot be values
7686 : : * pre-pg_upgrade.
7687 : : */
7688 : 76803 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7689 : :
7690 [ + + ]: 1472611 : for (i = 0; i < nmembers; i++)
7691 : : {
7692 : : LockTupleMode mode;
7693 : :
7694 : : /*
7695 : : * Remember the strongest lock mode held by any member of the
7696 : : * multixact.
7697 : : */
7698 : 1395808 : mode = TUPLOCK_from_mxstatus(members[i].status);
7699 [ + + ]: 1395808 : if (mode > strongest)
7700 : 2902 : strongest = mode;
7701 : :
7702 : : /* See what other bits we need */
7703 [ + + + + : 1395808 : switch (members[i].status)
- ]
7704 : : {
7705 : 1393384 : case MultiXactStatusForKeyShare:
7706 : : case MultiXactStatusForShare:
7707 : : case MultiXactStatusForNoKeyUpdate:
7708 : 1393384 : break;
7709 : :
7710 : 53 : case MultiXactStatusForUpdate:
7711 : 53 : bits2 |= HEAP_KEYS_UPDATED;
7712 : 53 : break;
7713 : :
7714 : 2361 : case MultiXactStatusNoKeyUpdate:
7715 : 2361 : has_update = true;
7716 : 2361 : break;
7717 : :
7718 : 10 : case MultiXactStatusUpdate:
7719 : 10 : bits2 |= HEAP_KEYS_UPDATED;
7720 : 10 : has_update = true;
7721 : 10 : break;
7722 : : }
7723 : : }
7724 : :
7725 [ + + + + ]: 76803 : if (strongest == LockTupleExclusive ||
7726 : : strongest == LockTupleNoKeyExclusive)
7727 : 2452 : bits |= HEAP_XMAX_EXCL_LOCK;
7728 [ + + ]: 74351 : else if (strongest == LockTupleShare)
7729 : 447 : bits |= HEAP_XMAX_SHR_LOCK;
7730 [ + - ]: 73904 : else if (strongest == LockTupleKeyShare)
7731 : 73904 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7732 : :
7733 [ + + ]: 76803 : if (!has_update)
7734 : 74432 : bits |= HEAP_XMAX_LOCK_ONLY;
7735 : :
7736 [ + - ]: 76803 : if (nmembers > 0)
7737 : 76803 : pfree(members);
7738 : :
7739 : 76803 : *new_infomask = bits;
7740 : 76803 : *new_infomask2 = bits2;
7741 : 76803 : }
7742 : :
7743 : : /*
7744 : : * MultiXactIdGetUpdateXid
7745 : : *
7746 : : * Given a multixact Xmax and corresponding infomask, which does not have the
7747 : : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7748 : : * transaction.
7749 : : *
7750 : : * Caller is expected to check the status of the updating transaction, if
7751 : : * necessary.
7752 : : */
7753 : : static TransactionId
7754 : 162055 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7755 : : {
7756 : 162055 : TransactionId update_xact = InvalidTransactionId;
7757 : : MultiXactMember *members;
7758 : : int nmembers;
7759 : :
7760 : : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7761 : : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7762 : :
7763 : : /*
7764 : : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7765 : : * pre-pg_upgrade.
7766 : : */
7767 : 162055 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7768 : :
7769 [ + - ]: 162055 : if (nmembers > 0)
7770 : : {
7771 : : int i;
7772 : :
7773 [ + - ]: 245875 : for (i = 0; i < nmembers; i++)
7774 : : {
7775 : : /* Ignore lockers */
7776 [ + + ]: 245875 : if (!ISUPDATE_from_mxstatus(members[i].status))
7777 : 83820 : continue;
7778 : :
7779 : : /* there can be at most one updater */
7780 : : Assert(update_xact == InvalidTransactionId);
7781 : 162055 : update_xact = members[i].xid;
7782 : : #ifndef USE_ASSERT_CHECKING
7783 : :
7784 : : /*
7785 : : * in an assert-enabled build, walk the whole array to ensure
7786 : : * there's no other updater.
7787 : : */
7788 : 162055 : break;
7789 : : #endif
7790 : : }
7791 : :
7792 : 162055 : pfree(members);
7793 : : }
7794 : :
7795 : 162055 : return update_xact;
7796 : : }
7797 : :
7798 : : /*
7799 : : * HeapTupleGetUpdateXid
7800 : : * As above, but use a HeapTupleHeader
7801 : : *
7802 : : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7803 : : * checking the hint bits.
7804 : : */
7805 : : TransactionId
7806 : 159914 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
7807 : : {
7808 : 159914 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
7809 : 159914 : tup->t_infomask);
7810 : : }
7811 : :
7812 : : /*
7813 : : * Does the given multixact conflict with the current transaction grabbing a
7814 : : * tuple lock of the given strength?
7815 : : *
7816 : : * The passed infomask pairs up with the given multixact in the tuple header.
7817 : : *
7818 : : * If current_is_member is not NULL, it is set to 'true' if the current
7819 : : * transaction is a member of the given multixact.
7820 : : */
7821 : : static bool
7822 : 218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7823 : : LockTupleMode lockmode, bool *current_is_member)
7824 : : {
7825 : : int nmembers;
7826 : : MultiXactMember *members;
7827 : 218 : bool result = false;
7828 : 218 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7829 : :
7830 [ - + ]: 218 : if (HEAP_LOCKED_UPGRADED(infomask))
7831 : 0 : return false;
7832 : :
7833 : 218 : nmembers = GetMultiXactIdMembers(multi, &members, false,
7834 : 218 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7835 [ + - ]: 218 : if (nmembers >= 0)
7836 : : {
7837 : : int i;
7838 : :
7839 [ + + ]: 2682 : for (i = 0; i < nmembers; i++)
7840 : : {
7841 : : TransactionId memxid;
7842 : : LOCKMODE memlockmode;
7843 : :
7844 [ + + + + : 2471 : if (result && (current_is_member == NULL || *current_is_member))
+ - ]
7845 : : break;
7846 : :
7847 : 2464 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7848 : :
7849 : : /* ignore members from current xact (but track their presence) */
7850 : 2464 : memxid = members[i].xid;
7851 [ + + ]: 2464 : if (TransactionIdIsCurrentTransactionId(memxid))
7852 : : {
7853 [ + + ]: 92 : if (current_is_member != NULL)
7854 : 78 : *current_is_member = true;
7855 : 92 : continue;
7856 : : }
7857 [ + + ]: 2372 : else if (result)
7858 : 8 : continue;
7859 : :
7860 : : /* ignore members that don't conflict with the lock we want */
7861 [ + + ]: 2364 : if (!DoLockModesConflict(memlockmode, wanted))
7862 : 2325 : continue;
7863 : :
7864 [ + + ]: 39 : if (ISUPDATE_from_mxstatus(members[i].status))
7865 : : {
7866 : : /* ignore aborted updaters */
7867 [ + + ]: 17 : if (TransactionIdDidAbort(memxid))
7868 : 1 : continue;
7869 : : }
7870 : : else
7871 : : {
7872 : : /* ignore lockers-only that are no longer in progress */
7873 [ + + ]: 22 : if (!TransactionIdIsInProgress(memxid))
7874 : 7 : continue;
7875 : : }
7876 : :
7877 : : /*
7878 : : * Whatever remains are either live lockers that conflict with our
7879 : : * wanted lock, and updaters that are not aborted. Those conflict
7880 : : * with what we want. Set up to return true, but keep going to
7881 : : * look for the current transaction among the multixact members,
7882 : : * if needed.
7883 : : */
7884 : 31 : result = true;
7885 : : }
7886 : 218 : pfree(members);
7887 : : }
7888 : :
7889 : 218 : return result;
7890 : : }
7891 : :
7892 : : /*
7893 : : * Do_MultiXactIdWait
7894 : : * Actual implementation for the two functions below.
7895 : : *
7896 : : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7897 : : * needed to ensure we only sleep on conflicting members, and the infomask is
7898 : : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7899 : : * indicates whether to use conditional lock acquisition, to allow callers to
7900 : : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7901 : : * context information for error messages. 'remaining', if not NULL, receives
7902 : : * the number of members that are still running, including any (non-aborted)
7903 : : * subtransactions of our own transaction. 'logLockFailure' indicates whether
7904 : : * to log details when a lock acquisition fails with 'nowait' enabled.
7905 : : *
7906 : : * We do this by sleeping on each member using XactLockTableWait. Any
7907 : : * members that belong to the current backend are *not* waited for, however;
7908 : : * this would not merely be useless but would lead to Assert failure inside
7909 : : * XactLockTableWait. By the time this returns, it is certain that all
7910 : : * transactions *of other backends* that were members of the MultiXactId
7911 : : * that conflict with the requested status are dead (and no new ones can have
7912 : : * been added, since it is not legal to add members to an existing
7913 : : * MultiXactId).
7914 : : *
7915 : : * But by the time we finish sleeping, someone else may have changed the Xmax
7916 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7917 : : *
7918 : : * Note that in case we return false, the number of remaining members is
7919 : : * not to be trusted.
7920 : : */
7921 : : static bool
7922 : 61 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7923 : : uint16 infomask, bool nowait,
7924 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7925 : : int *remaining, bool logLockFailure)
7926 : : {
7927 : 61 : bool result = true;
7928 : : MultiXactMember *members;
7929 : : int nmembers;
7930 : 61 : int remain = 0;
7931 : :
7932 : : /* for pre-pg_upgrade tuples, no need to sleep at all */
7933 [ + - ]: 61 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7934 : 61 : GetMultiXactIdMembers(multi, &members, false,
7935 : 61 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7936 : :
7937 [ + - ]: 61 : if (nmembers >= 0)
7938 : : {
7939 : : int i;
7940 : :
7941 [ + + ]: 191 : for (i = 0; i < nmembers; i++)
7942 : : {
7943 : 136 : TransactionId memxid = members[i].xid;
7944 : 136 : MultiXactStatus memstatus = members[i].status;
7945 : :
7946 [ + + ]: 136 : if (TransactionIdIsCurrentTransactionId(memxid))
7947 : : {
7948 : 25 : remain++;
7949 : 25 : continue;
7950 : : }
7951 : :
7952 [ + + ]: 111 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7953 : 111 : LOCKMODE_from_mxstatus(status)))
7954 : : {
7955 [ + + + - ]: 22 : if (remaining && TransactionIdIsInProgress(memxid))
7956 : 8 : remain++;
7957 : 22 : continue;
7958 : : }
7959 : :
7960 : : /*
7961 : : * This member conflicts with our multi, so we have to sleep (or
7962 : : * return failure, if asked to avoid waiting.)
7963 : : *
7964 : : * Note that we don't set up an error context callback ourselves,
7965 : : * but instead we pass the info down to XactLockTableWait. This
7966 : : * might seem a bit wasteful because the context is set up and
7967 : : * tore down for each member of the multixact, but in reality it
7968 : : * should be barely noticeable, and it avoids duplicate code.
7969 : : */
7970 [ + + ]: 89 : if (nowait)
7971 : : {
7972 : 6 : result = ConditionalXactLockTableWait(memxid, logLockFailure);
7973 [ + - ]: 6 : if (!result)
7974 : 6 : break;
7975 : : }
7976 : : else
7977 : 83 : XactLockTableWait(memxid, rel, ctid, oper);
7978 : : }
7979 : :
7980 : 61 : pfree(members);
7981 : : }
7982 : :
7983 [ + + ]: 61 : if (remaining)
7984 : 10 : *remaining = remain;
7985 : :
7986 : 61 : return result;
7987 : : }
7988 : :
7989 : : /*
7990 : : * MultiXactIdWait
7991 : : * Sleep on a MultiXactId.
7992 : : *
7993 : : * By the time we finish sleeping, someone else may have changed the Xmax
7994 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7995 : : *
7996 : : * We return (in *remaining, if not NULL) the number of members that are still
7997 : : * running, including any (non-aborted) subtransactions of our own transaction.
7998 : : */
7999 : : static void
8000 : 55 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
8001 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
8002 : : int *remaining)
8003 : : {
8004 : 55 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
8005 : : rel, ctid, oper, remaining, false);
8006 : 55 : }
8007 : :
8008 : : /*
8009 : : * ConditionalMultiXactIdWait
8010 : : * As above, but only lock if we can get the lock without blocking.
8011 : : *
8012 : : * By the time we finish sleeping, someone else may have changed the Xmax
8013 : : * of the containing tuple, so the caller needs to iterate on us somehow.
8014 : : *
8015 : : * If the multixact is now all gone, return true. Returns false if some
8016 : : * transactions might still be running.
8017 : : *
8018 : : * We return (in *remaining, if not NULL) the number of members that are still
8019 : : * running, including any (non-aborted) subtransactions of our own transaction.
8020 : : */
8021 : : static bool
8022 : 6 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
8023 : : uint16 infomask, Relation rel, int *remaining,
8024 : : bool logLockFailure)
8025 : : {
8026 : 6 : return Do_MultiXactIdWait(multi, status, infomask, true,
8027 : : rel, NULL, XLTW_None, remaining, logLockFailure);
8028 : : }
8029 : :
8030 : : /*
8031 : : * heap_tuple_needs_eventual_freeze
8032 : : *
8033 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
8034 : : * will eventually require freezing (if tuple isn't removed by pruning first).
8035 : : */
8036 : : bool
8037 : 143463 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
8038 : : {
8039 : : TransactionId xid;
8040 : :
8041 : : /*
8042 : : * If xmin is a normal transaction ID, this tuple is definitely not
8043 : : * frozen.
8044 : : */
8045 : 143463 : xid = HeapTupleHeaderGetXmin(tuple);
8046 [ + + ]: 143463 : if (TransactionIdIsNormal(xid))
8047 : 4358 : return true;
8048 : :
8049 : : /*
8050 : : * If xmax is a valid xact or multixact, this tuple is also not frozen.
8051 : : */
8052 [ - + ]: 139105 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
8053 : : {
8054 : : MultiXactId multi;
8055 : :
8056 : 0 : multi = HeapTupleHeaderGetRawXmax(tuple);
8057 [ # # ]: 0 : if (MultiXactIdIsValid(multi))
8058 : 0 : return true;
8059 : : }
8060 : : else
8061 : : {
8062 : 139105 : xid = HeapTupleHeaderGetRawXmax(tuple);
8063 [ + + ]: 139105 : if (TransactionIdIsNormal(xid))
8064 : 8 : return true;
8065 : : }
8066 : :
8067 [ - + ]: 139097 : if (tuple->t_infomask & HEAP_MOVED)
8068 : : {
8069 : 0 : xid = HeapTupleHeaderGetXvac(tuple);
8070 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8071 : 0 : return true;
8072 : : }
8073 : :
8074 : 139097 : return false;
8075 : : }
8076 : :
8077 : : /*
8078 : : * heap_tuple_should_freeze
8079 : : *
8080 : : * Return value indicates if heap_prepare_freeze_tuple sibling function would
8081 : : * (or should) force freezing of the heap page that contains caller's tuple.
8082 : : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
8083 : : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
8084 : : *
8085 : : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
8086 : : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
8087 : : * Our working assumption is that caller won't decide to freeze this tuple.
8088 : : * It's up to caller to only ratchet back its own top-level trackers after the
8089 : : * point that it fully commits to not freezing the tuple/page in question.
8090 : : */
8091 : : bool
8092 : 8880137 : heap_tuple_should_freeze(HeapTupleHeader tuple,
8093 : : const struct VacuumCutoffs *cutoffs,
8094 : : TransactionId *NoFreezePageRelfrozenXid,
8095 : : MultiXactId *NoFreezePageRelminMxid)
8096 : : {
8097 : : TransactionId xid;
8098 : : MultiXactId multi;
8099 : 8880137 : bool freeze = false;
8100 : :
8101 : : /* First deal with xmin */
8102 : 8880137 : xid = HeapTupleHeaderGetXmin(tuple);
8103 [ + + ]: 8880137 : if (TransactionIdIsNormal(xid))
8104 : : {
8105 : : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8106 [ + + ]: 3058241 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8107 : 26672 : *NoFreezePageRelfrozenXid = xid;
8108 [ + + ]: 3058241 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8109 : 23629 : freeze = true;
8110 : : }
8111 : :
8112 : : /* Now deal with xmax */
8113 : 8880137 : xid = InvalidTransactionId;
8114 : 8880137 : multi = InvalidMultiXactId;
8115 [ + + ]: 8880137 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
8116 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8117 : : else
8118 : 8880135 : xid = HeapTupleHeaderGetRawXmax(tuple);
8119 : :
8120 [ + + ]: 8880137 : if (TransactionIdIsNormal(xid))
8121 : : {
8122 : : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8123 : : /* xmax is a non-permanent XID */
8124 [ + + ]: 6157172 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8125 : 5 : *NoFreezePageRelfrozenXid = xid;
8126 [ + + ]: 6157172 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8127 : 20 : freeze = true;
8128 : : }
8129 [ + + ]: 2722965 : else if (!MultiXactIdIsValid(multi))
8130 : : {
8131 : : /* xmax is a permanent XID or invalid MultiXactId/XID */
8132 : : }
8133 [ - + ]: 2 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
8134 : : {
8135 : : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
8136 [ # # ]: 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8137 : 0 : *NoFreezePageRelminMxid = multi;
8138 : : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
8139 : 0 : freeze = true;
8140 : : }
8141 : : else
8142 : : {
8143 : : /* xmax is a MultiXactId that may have an updater XID */
8144 : : MultiXactMember *members;
8145 : : int nmembers;
8146 : :
8147 : : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
8148 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8149 : 2 : *NoFreezePageRelminMxid = multi;
8150 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
8151 : 2 : freeze = true;
8152 : :
8153 : : /* need to check whether any member of the mxact is old */
8154 : 2 : nmembers = GetMultiXactIdMembers(multi, &members, false,
8155 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
8156 : :
8157 [ + + ]: 5 : for (int i = 0; i < nmembers; i++)
8158 : : {
8159 : 3 : xid = members[i].xid;
8160 : : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8161 [ - + ]: 3 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8162 : 0 : *NoFreezePageRelfrozenXid = xid;
8163 [ - + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8164 : 0 : freeze = true;
8165 : : }
8166 [ + + ]: 2 : if (nmembers > 0)
8167 : 1 : pfree(members);
8168 : : }
8169 : :
8170 [ - + ]: 8880137 : if (tuple->t_infomask & HEAP_MOVED)
8171 : : {
8172 : 0 : xid = HeapTupleHeaderGetXvac(tuple);
8173 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8174 : : {
8175 : : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8176 [ # # ]: 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8177 : 0 : *NoFreezePageRelfrozenXid = xid;
8178 : : /* heap_prepare_freeze_tuple forces xvac freezing */
8179 : 0 : freeze = true;
8180 : : }
8181 : : }
8182 : :
8183 : 8880137 : return freeze;
8184 : : }
8185 : :
8186 : : /*
8187 : : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
8188 : : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
8189 : : * that caller is in the process of physically removing, e.g. via HOT pruning
8190 : : * or index deletion.
8191 : : *
8192 : : * Caller must initialize its value to InvalidTransactionId, which is
8193 : : * generally interpreted as "definitely no need for a recovery conflict".
8194 : : * Final value must reflect all heap tuples that caller will physically remove
8195 : : * (or remove TID references to) via its ongoing pruning/deletion operation.
8196 : : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
8197 : : * caller's WAL record) by REDO routine when it replays caller's operation.
8198 : : */
8199 : : void
8200 : 4105791 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
8201 : : TransactionId *snapshotConflictHorizon)
8202 : : {
8203 : 4105791 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
8204 : 4105791 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
8205 : 4105791 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
8206 : :
8207 [ - + ]: 4105791 : if (tuple->t_infomask & HEAP_MOVED)
8208 : : {
8209 [ # # ]: 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
8210 : 0 : *snapshotConflictHorizon = xvac;
8211 : : }
8212 : :
8213 : : /*
8214 : : * Ignore tuples inserted by an aborted transaction or if the tuple was
8215 : : * updated/deleted by the inserting transaction.
8216 : : *
8217 : : * Look for a committed hint bit, or if no xmin bit is set, check clog.
8218 : : */
8219 [ + + ]: 4105791 : if (HeapTupleHeaderXminCommitted(tuple) ||
8220 [ + + + - ]: 141513 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
8221 : : {
8222 [ + + + + ]: 7781504 : if (xmax != xmin &&
8223 : 3799368 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
8224 : 132642 : *snapshotConflictHorizon = xmax;
8225 : : }
8226 : 4105791 : }
8227 : :
8228 : : #ifdef USE_PREFETCH
8229 : : /*
8230 : : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
8231 : : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
8232 : : * we can prefetch, and which have already been prefetched; each call to this
8233 : : * function picks up where the previous call left off.
8234 : : *
8235 : : * Note: we expect the deltids array to be sorted in an order that groups TIDs
8236 : : * by heap block, with all TIDs for each block appearing together in exactly
8237 : : * one group.
8238 : : */
8239 : : static void
8240 : 25720 : index_delete_prefetch_buffer(Relation rel,
8241 : : IndexDeletePrefetchState *prefetch_state,
8242 : : int prefetch_count)
8243 : : {
8244 : 25720 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
8245 : 25720 : int count = 0;
8246 : : int i;
8247 : 25720 : int ndeltids = prefetch_state->ndeltids;
8248 : 25720 : TM_IndexDelete *deltids = prefetch_state->deltids;
8249 : :
8250 : 25720 : for (i = prefetch_state->next_item;
8251 [ + + + + ]: 916881 : i < ndeltids && count < prefetch_count;
8252 : 891161 : i++)
8253 : : {
8254 : 891161 : ItemPointer htid = &deltids[i].tid;
8255 : :
8256 [ + + + + ]: 1774369 : if (cur_hblkno == InvalidBlockNumber ||
8257 : 883208 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
8258 : : {
8259 : 23584 : cur_hblkno = ItemPointerGetBlockNumber(htid);
8260 : 23584 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
8261 : 23584 : count++;
8262 : : }
8263 : : }
8264 : :
8265 : : /*
8266 : : * Save the prefetch position so that next time we can continue from that
8267 : : * position.
8268 : : */
8269 : 25720 : prefetch_state->next_item = i;
8270 : 25720 : prefetch_state->cur_hblkno = cur_hblkno;
8271 : 25720 : }
8272 : : #endif
8273 : :
8274 : : /*
8275 : : * Helper function for heap_index_delete_tuples. Checks for index corruption
8276 : : * involving an invalid TID in index AM caller's index page.
8277 : : *
8278 : : * This is an ideal place for these checks. The index AM must hold a buffer
8279 : : * lock on the index page containing the TIDs we examine here, so we don't
8280 : : * have to worry about concurrent VACUUMs at all. We can be sure that the
8281 : : * index is corrupt when htid points directly to an LP_UNUSED item or
8282 : : * heap-only tuple, which is not the case during standard index scans.
8283 : : */
8284 : : static inline void
8285 : 736427 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
8286 : : Page page, OffsetNumber maxoff,
8287 : : const ItemPointerData *htid, TM_IndexStatus *istatus)
8288 : : {
8289 : 736427 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8290 : : ItemId iid;
8291 : :
8292 : : Assert(OffsetNumberIsValid(istatus->idxoffnum));
8293 : :
8294 [ - + ]: 736427 : if (unlikely(indexpagehoffnum > maxoff))
8295 [ # # ]: 0 : ereport(ERROR,
8296 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8297 : : 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\"",
8298 : : ItemPointerGetBlockNumber(htid),
8299 : : indexpagehoffnum,
8300 : : istatus->idxoffnum, delstate->iblknum,
8301 : : RelationGetRelationName(delstate->irel))));
8302 : :
8303 : 736427 : iid = PageGetItemId(page, indexpagehoffnum);
8304 [ - + ]: 736427 : if (unlikely(!ItemIdIsUsed(iid)))
8305 [ # # ]: 0 : ereport(ERROR,
8306 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8307 : : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8308 : : ItemPointerGetBlockNumber(htid),
8309 : : indexpagehoffnum,
8310 : : istatus->idxoffnum, delstate->iblknum,
8311 : : RelationGetRelationName(delstate->irel))));
8312 : :
8313 [ + + ]: 736427 : if (ItemIdHasStorage(iid))
8314 : : {
8315 : : HeapTupleHeader htup;
8316 : :
8317 : : Assert(ItemIdIsNormal(iid));
8318 : 464743 : htup = (HeapTupleHeader) PageGetItem(page, iid);
8319 : :
8320 [ - + ]: 464743 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
8321 [ # # ]: 0 : ereport(ERROR,
8322 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8323 : : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8324 : : ItemPointerGetBlockNumber(htid),
8325 : : indexpagehoffnum,
8326 : : istatus->idxoffnum, delstate->iblknum,
8327 : : RelationGetRelationName(delstate->irel))));
8328 : : }
8329 : 736427 : }
8330 : :
8331 : : /*
8332 : : * heapam implementation of tableam's index_delete_tuples interface.
8333 : : *
8334 : : * This helper function is called by index AMs during index tuple deletion.
8335 : : * See tableam header comments for an explanation of the interface implemented
8336 : : * here and a general theory of operation. Note that each call here is either
8337 : : * a simple index deletion call, or a bottom-up index deletion call.
8338 : : *
8339 : : * It's possible for this to generate a fair amount of I/O, since we may be
8340 : : * deleting hundreds of tuples from a single index block. To amortize that
8341 : : * cost to some degree, this uses prefetching and combines repeat accesses to
8342 : : * the same heap block.
8343 : : */
8344 : : TransactionId
8345 : 7953 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
8346 : : {
8347 : : /* Initial assumption is that earlier pruning took care of conflict */
8348 : 7953 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
8349 : 7953 : BlockNumber blkno = InvalidBlockNumber;
8350 : 7953 : Buffer buf = InvalidBuffer;
8351 : 7953 : Page page = NULL;
8352 : 7953 : OffsetNumber maxoff = InvalidOffsetNumber;
8353 : : TransactionId priorXmax;
8354 : : #ifdef USE_PREFETCH
8355 : : IndexDeletePrefetchState prefetch_state;
8356 : : int prefetch_distance;
8357 : : #endif
8358 : : SnapshotData SnapshotNonVacuumable;
8359 : 7953 : int finalndeltids = 0,
8360 : 7953 : nblocksaccessed = 0;
8361 : :
8362 : : /* State that's only used in bottom-up index deletion case */
8363 : 7953 : int nblocksfavorable = 0;
8364 : 7953 : int curtargetfreespace = delstate->bottomupfreespace,
8365 : 7953 : lastfreespace = 0,
8366 : 7953 : actualfreespace = 0;
8367 : 7953 : bool bottomup_final_block = false;
8368 : :
8369 : 7953 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8370 : :
8371 : : /* Sort caller's deltids array by TID for further processing */
8372 : 7953 : index_delete_sort(delstate);
8373 : :
8374 : : /*
8375 : : * Bottom-up case: resort deltids array in an order attuned to where the
8376 : : * greatest number of promising TIDs are to be found, and determine how
8377 : : * many blocks from the start of sorted array should be considered
8378 : : * favorable. This will also shrink the deltids array in order to
8379 : : * eliminate completely unfavorable blocks up front.
8380 : : */
8381 [ + + ]: 7953 : if (delstate->bottomup)
8382 : 2989 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
8383 : :
8384 : : #ifdef USE_PREFETCH
8385 : : /* Initialize prefetch state. */
8386 : 7953 : prefetch_state.cur_hblkno = InvalidBlockNumber;
8387 : 7953 : prefetch_state.next_item = 0;
8388 : 7953 : prefetch_state.ndeltids = delstate->ndeltids;
8389 : 7953 : prefetch_state.deltids = delstate->deltids;
8390 : :
8391 : : /*
8392 : : * Determine the prefetch distance that we will attempt to maintain.
8393 : : *
8394 : : * Since the caller holds a buffer lock somewhere in rel, we'd better make
8395 : : * sure that isn't a catalog relation before we call code that does
8396 : : * syscache lookups, to avoid risk of deadlock.
8397 : : */
8398 [ + + ]: 7953 : if (IsCatalogRelation(rel))
8399 : 5702 : prefetch_distance = maintenance_io_concurrency;
8400 : : else
8401 : : prefetch_distance =
8402 : 2251 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
8403 : :
8404 : : /* Cap initial prefetch distance for bottom-up deletion caller */
8405 [ + + ]: 7953 : if (delstate->bottomup)
8406 : : {
8407 : : Assert(nblocksfavorable >= 1);
8408 : : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8409 : 2989 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8410 : : }
8411 : :
8412 : : /* Start prefetching. */
8413 : 7953 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8414 : : #endif
8415 : :
8416 : : /* Iterate over deltids, determine which to delete, check their horizon */
8417 : : Assert(delstate->ndeltids > 0);
8418 [ + + ]: 744380 : for (int i = 0; i < delstate->ndeltids; i++)
8419 : : {
8420 : 739416 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8421 : 739416 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8422 : 739416 : ItemPointer htid = &ideltid->tid;
8423 : : OffsetNumber offnum;
8424 : :
8425 : : /*
8426 : : * Read buffer, and perform required extra steps each time a new block
8427 : : * is encountered. Avoid refetching if it's the same block as the one
8428 : : * from the last htid.
8429 : : */
8430 [ + + + + ]: 1470879 : if (blkno == InvalidBlockNumber ||
8431 : 731463 : ItemPointerGetBlockNumber(htid) != blkno)
8432 : : {
8433 : : /*
8434 : : * Consider giving up early for bottom-up index deletion caller
8435 : : * first. (Only prefetch next-next block afterwards, when it
8436 : : * becomes clear that we're at least going to access the next
8437 : : * block in line.)
8438 : : *
8439 : : * Sometimes the first block frees so much space for bottom-up
8440 : : * caller that the deletion process can end without accessing any
8441 : : * more blocks. It is usually necessary to access 2 or 3 blocks
8442 : : * per bottom-up deletion operation, though.
8443 : : */
8444 [ + + ]: 20756 : if (delstate->bottomup)
8445 : : {
8446 : : /*
8447 : : * We often allow caller to delete a few additional items
8448 : : * whose entries we reached after the point that space target
8449 : : * from caller was satisfied. The cost of accessing the page
8450 : : * was already paid at that point, so it made sense to finish
8451 : : * it off. When that happened, we finalize everything here
8452 : : * (by finishing off the whole bottom-up deletion operation
8453 : : * without needlessly paying the cost of accessing any more
8454 : : * blocks).
8455 : : */
8456 [ + + ]: 6391 : if (bottomup_final_block)
8457 : 157 : break;
8458 : :
8459 : : /*
8460 : : * Give up when we didn't enable our caller to free any
8461 : : * additional space as a result of processing the page that we
8462 : : * just finished up with. This rule is the main way in which
8463 : : * we keep the cost of bottom-up deletion under control.
8464 : : */
8465 [ + + + + ]: 6234 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8466 : 2832 : break;
8467 : 3402 : lastfreespace = actualfreespace; /* for next time */
8468 : :
8469 : : /*
8470 : : * Deletion operation (which is bottom-up) will definitely
8471 : : * access the next block in line. Prepare for that now.
8472 : : *
8473 : : * Decay target free space so that we don't hang on for too
8474 : : * long with a marginal case. (Space target is only truly
8475 : : * helpful when it allows us to recognize that we don't need
8476 : : * to access more than 1 or 2 blocks to satisfy caller due to
8477 : : * agreeable workload characteristics.)
8478 : : *
8479 : : * We are a bit more patient when we encounter contiguous
8480 : : * blocks, though: these are treated as favorable blocks. The
8481 : : * decay process is only applied when the next block in line
8482 : : * is not a favorable/contiguous block. This is not an
8483 : : * exception to the general rule; we still insist on finding
8484 : : * at least one deletable item per block accessed. See
8485 : : * bottomup_nblocksfavorable() for full details of the theory
8486 : : * behind favorable blocks and heap block locality in general.
8487 : : *
8488 : : * Note: The first block in line is always treated as a
8489 : : * favorable block, so the earliest possible point that the
8490 : : * decay can be applied is just before we access the second
8491 : : * block in line. The Assert() verifies this for us.
8492 : : */
8493 : : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8494 [ + + ]: 3402 : if (nblocksfavorable > 0)
8495 : 3192 : nblocksfavorable--;
8496 : : else
8497 : 210 : curtargetfreespace /= 2;
8498 : : }
8499 : :
8500 : : /* release old buffer */
8501 [ + + ]: 17767 : if (BufferIsValid(buf))
8502 : 9814 : UnlockReleaseBuffer(buf);
8503 : :
8504 : 17767 : blkno = ItemPointerGetBlockNumber(htid);
8505 : 17767 : buf = ReadBuffer(rel, blkno);
8506 : 17767 : nblocksaccessed++;
8507 : : Assert(!delstate->bottomup ||
8508 : : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8509 : :
8510 : : #ifdef USE_PREFETCH
8511 : :
8512 : : /*
8513 : : * To maintain the prefetch distance, prefetch one more page for
8514 : : * each page we read.
8515 : : */
8516 : 17767 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8517 : : #endif
8518 : :
8519 : 17767 : LockBuffer(buf, BUFFER_LOCK_SHARE);
8520 : :
8521 : 17767 : page = BufferGetPage(buf);
8522 : 17767 : maxoff = PageGetMaxOffsetNumber(page);
8523 : : }
8524 : :
8525 : : /*
8526 : : * In passing, detect index corruption involving an index page with a
8527 : : * TID that points to a location in the heap that couldn't possibly be
8528 : : * correct. We only do this with actual TIDs from caller's index page
8529 : : * (not items reached by traversing through a HOT chain).
8530 : : */
8531 : 736427 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8532 : :
8533 [ + + ]: 736427 : if (istatus->knowndeletable)
8534 : : Assert(!delstate->bottomup && !istatus->promising);
8535 : : else
8536 : : {
8537 : 574176 : ItemPointerData tmp = *htid;
8538 : : HeapTupleData heapTuple;
8539 : :
8540 : : /* Are any tuples from this HOT chain non-vacuumable? */
8541 [ + + ]: 574176 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8542 : : &heapTuple, NULL, true))
8543 : 349792 : continue; /* can't delete entry */
8544 : :
8545 : : /* Caller will delete, since whole HOT chain is vacuumable */
8546 : 224384 : istatus->knowndeletable = true;
8547 : :
8548 : : /* Maintain index free space info for bottom-up deletion case */
8549 [ + + ]: 224384 : if (delstate->bottomup)
8550 : : {
8551 : : Assert(istatus->freespace > 0);
8552 : 9883 : actualfreespace += istatus->freespace;
8553 [ + + ]: 9883 : if (actualfreespace >= curtargetfreespace)
8554 : 2454 : bottomup_final_block = true;
8555 : : }
8556 : : }
8557 : :
8558 : : /*
8559 : : * Maintain snapshotConflictHorizon value for deletion operation as a
8560 : : * whole by advancing current value using heap tuple headers. This is
8561 : : * loosely based on the logic for pruning a HOT chain.
8562 : : */
8563 : 386635 : offnum = ItemPointerGetOffsetNumber(htid);
8564 : 386635 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8565 : : for (;;)
8566 : 22555 : {
8567 : : ItemId lp;
8568 : : HeapTupleHeader htup;
8569 : :
8570 : : /* Sanity check (pure paranoia) */
8571 [ - + ]: 409190 : if (offnum < FirstOffsetNumber)
8572 : 0 : break;
8573 : :
8574 : : /*
8575 : : * An offset past the end of page's line pointer array is possible
8576 : : * when the array was truncated
8577 : : */
8578 [ - + ]: 409190 : if (offnum > maxoff)
8579 : 0 : break;
8580 : :
8581 : 409190 : lp = PageGetItemId(page, offnum);
8582 [ + + ]: 409190 : if (ItemIdIsRedirected(lp))
8583 : : {
8584 : 10303 : offnum = ItemIdGetRedirect(lp);
8585 : 10303 : continue;
8586 : : }
8587 : :
8588 : : /*
8589 : : * We'll often encounter LP_DEAD line pointers (especially with an
8590 : : * entry marked knowndeletable by our caller up front). No heap
8591 : : * tuple headers get examined for an htid that leads us to an
8592 : : * LP_DEAD item. This is okay because the earlier pruning
8593 : : * operation that made the line pointer LP_DEAD in the first place
8594 : : * must have considered the original tuple header as part of
8595 : : * generating its own snapshotConflictHorizon value.
8596 : : *
8597 : : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8598 : : * the same strategy that index vacuuming uses in all cases. Index
8599 : : * VACUUM WAL records don't even have a snapshotConflictHorizon
8600 : : * field of their own for this reason.
8601 : : */
8602 [ + + ]: 398887 : if (!ItemIdIsNormal(lp))
8603 : 239857 : break;
8604 : :
8605 : 159030 : htup = (HeapTupleHeader) PageGetItem(page, lp);
8606 : :
8607 : : /*
8608 : : * Check the tuple XMIN against prior XMAX, if any
8609 : : */
8610 [ + + - + ]: 171282 : if (TransactionIdIsValid(priorXmax) &&
8611 : 12252 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
8612 : 0 : break;
8613 : :
8614 : 159030 : HeapTupleHeaderAdvanceConflictHorizon(htup,
8615 : : &snapshotConflictHorizon);
8616 : :
8617 : : /*
8618 : : * If the tuple is not HOT-updated, then we are at the end of this
8619 : : * HOT-chain. No need to visit later tuples from the same update
8620 : : * chain (they get their own index entries) -- just move on to
8621 : : * next htid from index AM caller.
8622 : : */
8623 [ + + ]: 159030 : if (!HeapTupleHeaderIsHotUpdated(htup))
8624 : 146778 : break;
8625 : :
8626 : : /* Advance to next HOT chain member */
8627 : : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8628 : 12252 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8629 : 12252 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8630 : : }
8631 : :
8632 : : /* Enable further/final shrinking of deltids for caller */
8633 : 386635 : finalndeltids = i + 1;
8634 : : }
8635 : :
8636 : 7953 : UnlockReleaseBuffer(buf);
8637 : :
8638 : : /*
8639 : : * Shrink deltids array to exclude non-deletable entries at the end. This
8640 : : * is not just a minor optimization. Final deltids array size might be
8641 : : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8642 : : * ndeltids being zero in all cases with zero total deletable entries.
8643 : : */
8644 : : Assert(finalndeltids > 0 || delstate->bottomup);
8645 : 7953 : delstate->ndeltids = finalndeltids;
8646 : :
8647 : 7953 : return snapshotConflictHorizon;
8648 : : }
8649 : :
8650 : : /*
8651 : : * Specialized inlineable comparison function for index_delete_sort()
8652 : : */
8653 : : static inline int
8654 : 17876073 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
8655 : : {
8656 : 17876073 : ItemPointer tid1 = &deltid1->tid;
8657 : 17876073 : ItemPointer tid2 = &deltid2->tid;
8658 : :
8659 : : {
8660 : 17876073 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
8661 : 17876073 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
8662 : :
8663 [ + + ]: 17876073 : if (blk1 != blk2)
8664 [ + + ]: 7271456 : return (blk1 < blk2) ? -1 : 1;
8665 : : }
8666 : : {
8667 : 10604617 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
8668 : 10604617 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
8669 : :
8670 [ + - ]: 10604617 : if (pos1 != pos2)
8671 [ + + ]: 10604617 : return (pos1 < pos2) ? -1 : 1;
8672 : : }
8673 : :
8674 : : Assert(false);
8675 : :
8676 : 0 : return 0;
8677 : : }
8678 : :
8679 : : /*
8680 : : * Sort deltids array from delstate by TID. This prepares it for further
8681 : : * processing by heap_index_delete_tuples().
8682 : : *
8683 : : * This operation becomes a noticeable consumer of CPU cycles with some
8684 : : * workloads, so we go to the trouble of specialization/micro optimization.
8685 : : * We use shellsort for this because it's easy to specialize, compiles to
8686 : : * relatively few instructions, and is adaptive to presorted inputs/subsets
8687 : : * (which are typical here).
8688 : : */
8689 : : static void
8690 : 7953 : index_delete_sort(TM_IndexDeleteOp *delstate)
8691 : : {
8692 : 7953 : TM_IndexDelete *deltids = delstate->deltids;
8693 : 7953 : int ndeltids = delstate->ndeltids;
8694 : :
8695 : : /*
8696 : : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8697 : : *
8698 : : * This implementation is fast with array sizes up to ~4500. This covers
8699 : : * all supported BLCKSZ values.
8700 : : */
8701 : 7953 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8702 : :
8703 : : /* Think carefully before changing anything here -- keep swaps cheap */
8704 : : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8705 : : "element size exceeds 8 bytes");
8706 : :
8707 [ + + ]: 79530 : for (size_t g = 0; g < lengthof(gaps); g++)
8708 : : {
8709 [ + + ]: 10775969 : for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8710 : : {
8711 : 10704392 : TM_IndexDelete d = deltids[i];
8712 : 10704392 : int j = i;
8713 : :
8714 [ + + + + ]: 18382796 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8715 : : {
8716 : 7678404 : deltids[j] = deltids[j - hi];
8717 : 7678404 : j -= hi;
8718 : : }
8719 : 10704392 : deltids[j] = d;
8720 : : }
8721 : : }
8722 : 7953 : }
8723 : :
8724 : : /*
8725 : : * Returns how many blocks should be considered favorable/contiguous for a
8726 : : * bottom-up index deletion pass. This is a number of heap blocks that starts
8727 : : * from and includes the first block in line.
8728 : : *
8729 : : * There is always at least one favorable block during bottom-up index
8730 : : * deletion. In the worst case (i.e. with totally random heap blocks) the
8731 : : * first block in line (the only favorable block) can be thought of as a
8732 : : * degenerate array of contiguous blocks that consists of a single block.
8733 : : * heap_index_delete_tuples() will expect this.
8734 : : *
8735 : : * Caller passes blockgroups, a description of the final order that deltids
8736 : : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8737 : : * processing. Note that deltids need not actually be sorted just yet (caller
8738 : : * only passes deltids to us so that we can interpret blockgroups).
8739 : : *
8740 : : * You might guess that the existence of contiguous blocks cannot matter much,
8741 : : * since in general the main factor that determines which blocks we visit is
8742 : : * the number of promising TIDs, which is a fixed hint from the index AM.
8743 : : * We're not really targeting the general case, though -- the actual goal is
8744 : : * to adapt our behavior to a wide variety of naturally occurring conditions.
8745 : : * The effects of most of the heuristics we apply are only noticeable in the
8746 : : * aggregate, over time and across many _related_ bottom-up index deletion
8747 : : * passes.
8748 : : *
8749 : : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8750 : : * workloads where heap blocks visited during bottom-up index deletion can be
8751 : : * accessed contiguously, in the sense that each newly visited block is the
8752 : : * neighbor of the block that bottom-up deletion just finished processing (or
8753 : : * close enough to it). It will likely be cheaper to access more favorable
8754 : : * blocks sooner rather than later (e.g. in this pass, not across a series of
8755 : : * related bottom-up passes). Either way it is probably only a matter of time
8756 : : * (or a matter of further correlated version churn) before all blocks that
8757 : : * appear together as a single large batch of favorable blocks get accessed by
8758 : : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8759 : : * appear almost constantly or not even once (it all depends on per-index
8760 : : * workload characteristics).
8761 : : *
8762 : : * Note that the blockgroups sort order applies a power-of-two bucketing
8763 : : * scheme that creates opportunities for contiguous groups of blocks to get
8764 : : * batched together, at least with workloads that are naturally amenable to
8765 : : * being driven by heap block locality. This doesn't just enhance the spatial
8766 : : * locality of bottom-up heap block processing in the obvious way. It also
8767 : : * enables temporal locality of access, since sorting by heap block number
8768 : : * naturally tends to make the bottom-up processing order deterministic.
8769 : : *
8770 : : * Consider the following example to get a sense of how temporal locality
8771 : : * might matter: There is a heap relation with several indexes, each of which
8772 : : * is low to medium cardinality. It is subject to constant non-HOT updates.
8773 : : * The updates are skewed (in one part of the primary key, perhaps). None of
8774 : : * the indexes are logically modified by the UPDATE statements (if they were
8775 : : * then bottom-up index deletion would not be triggered in the first place).
8776 : : * Naturally, each new round of index tuples (for each heap tuple that gets a
8777 : : * heap_update() call) will have the same heap TID in each and every index.
8778 : : * Since these indexes are low cardinality and never get logically modified,
8779 : : * heapam processing during bottom-up deletion passes will access heap blocks
8780 : : * in approximately sequential order. Temporal locality of access occurs due
8781 : : * to bottom-up deletion passes behaving very similarly across each of the
8782 : : * indexes at any given moment. This keeps the number of buffer misses needed
8783 : : * to visit heap blocks to a minimum.
8784 : : */
8785 : : static int
8786 : 2989 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8787 : : TM_IndexDelete *deltids)
8788 : : {
8789 : 2989 : int64 lastblock = -1;
8790 : 2989 : int nblocksfavorable = 0;
8791 : :
8792 : : Assert(nblockgroups >= 1);
8793 : : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8794 : :
8795 : : /*
8796 : : * We tolerate heap blocks that will be accessed only slightly out of
8797 : : * physical order. Small blips occur when a pair of almost-contiguous
8798 : : * blocks happen to fall into different buckets (perhaps due only to a
8799 : : * small difference in npromisingtids that the bucketing scheme didn't
8800 : : * quite manage to ignore). We effectively ignore these blips by applying
8801 : : * a small tolerance. The precise tolerance we use is a little arbitrary,
8802 : : * but it works well enough in practice.
8803 : : */
8804 [ + + ]: 9206 : for (int b = 0; b < nblockgroups; b++)
8805 : : {
8806 : 8875 : IndexDeleteCounts *group = blockgroups + b;
8807 : 8875 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8808 : 8875 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8809 : :
8810 [ + + ]: 8875 : if (lastblock != -1 &&
8811 [ + + ]: 5886 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8812 [ + + ]: 5174 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8813 : : break;
8814 : :
8815 : 6217 : nblocksfavorable++;
8816 : 6217 : lastblock = block;
8817 : : }
8818 : :
8819 : : /* Always indicate that there is at least 1 favorable block */
8820 : : Assert(nblocksfavorable >= 1);
8821 : :
8822 : 2989 : return nblocksfavorable;
8823 : : }
8824 : :
8825 : : /*
8826 : : * qsort comparison function for bottomup_sort_and_shrink()
8827 : : */
8828 : : static int
8829 : 267834 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8830 : : {
8831 : 267834 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8832 : 267834 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8833 : :
8834 : : /*
8835 : : * Most significant field is npromisingtids (which we invert the order of
8836 : : * so as to sort in desc order).
8837 : : *
8838 : : * Caller should have already normalized npromisingtids fields into
8839 : : * power-of-two values (buckets).
8840 : : */
8841 [ + + ]: 267834 : if (group1->npromisingtids > group2->npromisingtids)
8842 : 11855 : return -1;
8843 [ + + ]: 255979 : if (group1->npromisingtids < group2->npromisingtids)
8844 : 15400 : return 1;
8845 : :
8846 : : /*
8847 : : * Tiebreak: desc ntids sort order.
8848 : : *
8849 : : * We cannot expect power-of-two values for ntids fields. We should
8850 : : * behave as if they were already rounded up for us instead.
8851 : : */
8852 [ + + ]: 240579 : if (group1->ntids != group2->ntids)
8853 : : {
8854 : 176090 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8855 : 176090 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8856 : :
8857 [ + + ]: 176090 : if (ntids1 > ntids2)
8858 : 26304 : return -1;
8859 [ + + ]: 149786 : if (ntids1 < ntids2)
8860 : 34570 : return 1;
8861 : : }
8862 : :
8863 : : /*
8864 : : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8865 : : * block in deltids array) order.
8866 : : *
8867 : : * This is equivalent to sorting in ascending heap block number order
8868 : : * (among otherwise equal subsets of the array). This approach allows us
8869 : : * to avoid accessing the out-of-line TID. (We rely on the assumption
8870 : : * that the deltids array was sorted in ascending heap TID order when
8871 : : * these offsets to the first TID from each heap block group were formed.)
8872 : : */
8873 [ + + ]: 179705 : if (group1->ifirsttid > group2->ifirsttid)
8874 : 88135 : return 1;
8875 [ + - ]: 91570 : if (group1->ifirsttid < group2->ifirsttid)
8876 : 91570 : return -1;
8877 : :
8878 : 0 : pg_unreachable();
8879 : :
8880 : : return 0;
8881 : : }
8882 : :
8883 : : /*
8884 : : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8885 : : *
8886 : : * Sorts deltids array in the order needed for useful processing by bottom-up
8887 : : * deletion. The array should already be sorted in TID order when we're
8888 : : * called. The sort process groups heap TIDs from deltids into heap block
8889 : : * groupings. Earlier/more-promising groups/blocks are usually those that are
8890 : : * known to have the most "promising" TIDs.
8891 : : *
8892 : : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8893 : : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8894 : : * return. This often means that deltids will be shrunk to a small fraction
8895 : : * of its original size (we eliminate many heap blocks from consideration for
8896 : : * caller up front).
8897 : : *
8898 : : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8899 : : * for a definition and full details.
8900 : : */
8901 : : static int
8902 : 2989 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8903 : : {
8904 : : IndexDeleteCounts *blockgroups;
8905 : : TM_IndexDelete *reordereddeltids;
8906 : 2989 : BlockNumber curblock = InvalidBlockNumber;
8907 : 2989 : int nblockgroups = 0;
8908 : 2989 : int ncopied = 0;
8909 : 2989 : int nblocksfavorable = 0;
8910 : :
8911 : : Assert(delstate->bottomup);
8912 : : Assert(delstate->ndeltids > 0);
8913 : :
8914 : : /* Calculate per-heap-block count of TIDs */
8915 : 2989 : blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
8916 [ + + ]: 1389247 : for (int i = 0; i < delstate->ndeltids; i++)
8917 : : {
8918 : 1386258 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8919 : 1386258 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8920 : 1386258 : ItemPointer htid = &ideltid->tid;
8921 : 1386258 : bool promising = istatus->promising;
8922 : :
8923 [ + + ]: 1386258 : if (curblock != ItemPointerGetBlockNumber(htid))
8924 : : {
8925 : : /* New block group */
8926 : 53193 : nblockgroups++;
8927 : :
8928 : : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8929 : : !BlockNumberIsValid(curblock));
8930 : :
8931 : 53193 : curblock = ItemPointerGetBlockNumber(htid);
8932 : 53193 : blockgroups[nblockgroups - 1].ifirsttid = i;
8933 : 53193 : blockgroups[nblockgroups - 1].ntids = 1;
8934 : 53193 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8935 : : }
8936 : : else
8937 : : {
8938 : 1333065 : blockgroups[nblockgroups - 1].ntids++;
8939 : : }
8940 : :
8941 [ + + ]: 1386258 : if (promising)
8942 : 258197 : blockgroups[nblockgroups - 1].npromisingtids++;
8943 : : }
8944 : :
8945 : : /*
8946 : : * We're about ready to sort block groups to determine the optimal order
8947 : : * for visiting heap blocks. But before we do, round the number of
8948 : : * promising tuples for each block group up to the next power-of-two,
8949 : : * unless it is very low (less than 4), in which case we round up to 4.
8950 : : * npromisingtids is far too noisy to trust when choosing between a pair
8951 : : * of block groups that both have very low values.
8952 : : *
8953 : : * This scheme divides heap blocks/block groups into buckets. Each bucket
8954 : : * contains blocks that have _approximately_ the same number of promising
8955 : : * TIDs as each other. The goal is to ignore relatively small differences
8956 : : * in the total number of promising entries, so that the whole process can
8957 : : * give a little weight to heapam factors (like heap block locality)
8958 : : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8959 : : * would be foolish to interpret small differences in npromisingtids
8960 : : * values as anything more than noise.
8961 : : *
8962 : : * We tiebreak on nhtids when sorting block group subsets that have the
8963 : : * same npromisingtids, but this has the same issues as npromisingtids,
8964 : : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8965 : : * only reason that we don't fix nhtids in the same way here too is that
8966 : : * we'll need accurate nhtids values after the sort. We handle nhtids
8967 : : * bucketization dynamically instead (in the sort comparator).
8968 : : *
8969 : : * See bottomup_nblocksfavorable() for a full explanation of when and how
8970 : : * heap locality/favorable blocks can significantly influence when and how
8971 : : * heap blocks are accessed.
8972 : : */
8973 [ + + ]: 56182 : for (int b = 0; b < nblockgroups; b++)
8974 : : {
8975 : 53193 : IndexDeleteCounts *group = blockgroups + b;
8976 : :
8977 : : /* Better off falling back on nhtids with low npromisingtids */
8978 [ + + ]: 53193 : if (group->npromisingtids <= 4)
8979 : 44496 : group->npromisingtids = 4;
8980 : : else
8981 : 8697 : group->npromisingtids =
8982 : 8697 : pg_nextpower2_32((uint32) group->npromisingtids);
8983 : : }
8984 : :
8985 : : /* Sort groups and rearrange caller's deltids array */
8986 : 2989 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8987 : : bottomup_sort_and_shrink_cmp);
8988 : 2989 : reordereddeltids = palloc_array(TM_IndexDelete, delstate->ndeltids);
8989 : :
8990 : 2989 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8991 : : /* Determine number of favorable blocks at the start of final deltids */
8992 : 2989 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8993 : : delstate->deltids);
8994 : :
8995 [ + + ]: 19421 : for (int b = 0; b < nblockgroups; b++)
8996 : : {
8997 : 16432 : IndexDeleteCounts *group = blockgroups + b;
8998 : 16432 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8999 : :
9000 : 16432 : memcpy(reordereddeltids + ncopied, firstdtid,
9001 : 16432 : sizeof(TM_IndexDelete) * group->ntids);
9002 : 16432 : ncopied += group->ntids;
9003 : : }
9004 : :
9005 : : /* Copy final grouped and sorted TIDs back into start of caller's array */
9006 : 2989 : memcpy(delstate->deltids, reordereddeltids,
9007 : : sizeof(TM_IndexDelete) * ncopied);
9008 : 2989 : delstate->ndeltids = ncopied;
9009 : :
9010 : 2989 : pfree(reordereddeltids);
9011 : 2989 : pfree(blockgroups);
9012 : :
9013 : 2989 : return nblocksfavorable;
9014 : : }
9015 : :
9016 : : /*
9017 : : * Perform XLogInsert for a heap-update operation. Caller must already
9018 : : * have modified the buffer(s) and marked them dirty.
9019 : : */
9020 : : static XLogRecPtr
9021 : 2381936 : log_heap_update(Relation reln, Buffer oldbuf, Buffer vmbuffer_old,
9022 : : Buffer newbuf, Buffer vmbuffer_new,
9023 : : HeapTuple oldtup, HeapTuple newtup,
9024 : : HeapTuple old_key_tuple,
9025 : : bool all_visible_cleared, bool new_all_visible_cleared,
9026 : : bool walLogical)
9027 : : {
9028 : : xl_heap_update xlrec;
9029 : : xl_heap_header xlhdr;
9030 : : xl_heap_header xlhdr_idx;
9031 : : uint8 info;
9032 : : uint16 prefix_suffix[2];
9033 : 2381936 : uint16 prefixlen = 0,
9034 : 2381936 : suffixlen = 0;
9035 : : XLogRecPtr recptr;
9036 : 2381936 : Page page = BufferGetPage(newbuf);
9037 [ + + + + : 2381936 : bool need_tuple_data = walLogical && RelationIsLogicallyLogged(reln);
+ + + - -
+ - - - -
+ - + + ]
9038 : : bool init;
9039 : : int bufflags;
9040 : :
9041 : : /* Caller should not call me on a non-WAL-logged relation */
9042 : : Assert(RelationNeedsWAL(reln));
9043 : :
9044 : 2381936 : XLogBeginInsert();
9045 : :
9046 [ + + ]: 2381936 : if (HeapTupleIsHeapOnly(newtup))
9047 : 166256 : info = XLOG_HEAP_HOT_UPDATE;
9048 : : else
9049 : 2215680 : info = XLOG_HEAP_UPDATE;
9050 : :
9051 : : /*
9052 : : * If the old and new tuple are on the same page, we only need to log the
9053 : : * parts of the new tuple that were changed. That saves on the amount of
9054 : : * WAL we need to write. Currently, we just count any unchanged bytes in
9055 : : * the beginning and end of the tuple. That's quick to check, and
9056 : : * perfectly covers the common case that only one field is updated.
9057 : : *
9058 : : * We could do this even if the old and new tuple are on different pages,
9059 : : * but only if we don't make a full-page image of the old page, which is
9060 : : * difficult to know in advance. Also, if the old tuple is corrupt for
9061 : : * some reason, it would allow the corruption to propagate the new page,
9062 : : * so it seems best to avoid. Under the general assumption that most
9063 : : * updates tend to create the new tuple version on the same page, there
9064 : : * isn't much to be gained by doing this across pages anyway.
9065 : : *
9066 : : * Skip this if we're taking a full-page image of the new page, as we
9067 : : * don't include the new tuple in the WAL record in that case. Also
9068 : : * disable if effective_wal_level='logical', as logical decoding needs to
9069 : : * be able to read the new tuple in whole from the WAL record alone.
9070 : : */
9071 [ + + + + ]: 2381936 : if (oldbuf == newbuf && !need_tuple_data &&
9072 [ + + ]: 170525 : !XLogCheckBufferNeedsBackup(newbuf))
9073 : : {
9074 : 169985 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
9075 : 169985 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
9076 : 169985 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
9077 : 169985 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
9078 : :
9079 : : /* Check for common prefix between old and new tuple */
9080 [ + + ]: 14061238 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
9081 : : {
9082 [ + + ]: 14032134 : if (newp[prefixlen] != oldp[prefixlen])
9083 : 140881 : break;
9084 : : }
9085 : :
9086 : : /*
9087 : : * Storing the length of the prefix takes 2 bytes, so we need to save
9088 : : * at least 3 bytes or there's no point.
9089 : : */
9090 [ + + ]: 169985 : if (prefixlen < 3)
9091 : 23818 : prefixlen = 0;
9092 : :
9093 : : /* Same for suffix */
9094 [ + + ]: 6051555 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
9095 : : {
9096 [ + + ]: 6022102 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
9097 : 140532 : break;
9098 : : }
9099 [ + + ]: 169985 : if (suffixlen < 3)
9100 : 42774 : suffixlen = 0;
9101 : : }
9102 : :
9103 : : /* Prepare main WAL data chain */
9104 : 2381936 : xlrec.flags = 0;
9105 [ + + ]: 2381936 : if (all_visible_cleared)
9106 : 2483 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
9107 [ + + ]: 2381936 : if (new_all_visible_cleared)
9108 : 1231 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
9109 [ + + ]: 2381936 : if (prefixlen > 0)
9110 : 146167 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
9111 [ + + ]: 2381936 : if (suffixlen > 0)
9112 : 127211 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
9113 [ + + ]: 2381936 : if (need_tuple_data)
9114 : : {
9115 : 47055 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
9116 [ + + ]: 47055 : if (old_key_tuple)
9117 : : {
9118 [ + + ]: 156 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
9119 : 66 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
9120 : : else
9121 : 90 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
9122 : : }
9123 : : }
9124 : :
9125 : : /* If new tuple is the single and first tuple on page... */
9126 [ + + + + ]: 2395026 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
9127 : 13090 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
9128 : : {
9129 : 12760 : info |= XLOG_HEAP_INIT_PAGE;
9130 : 12760 : init = true;
9131 : : }
9132 : : else
9133 : 2369176 : init = false;
9134 : :
9135 : : /* Prepare WAL data for the old page */
9136 : 2381936 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
9137 : 2381936 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
9138 : 4763872 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
9139 : 2381936 : oldtup->t_data->t_infomask2);
9140 : :
9141 : : /* Prepare WAL data for the new page */
9142 : 2381936 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
9143 : 2381936 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
9144 : :
9145 : 2381936 : bufflags = REGBUF_STANDARD;
9146 [ + + ]: 2381936 : if (init)
9147 : 12760 : bufflags |= REGBUF_WILL_INIT;
9148 [ + + ]: 2381936 : if (need_tuple_data)
9149 : 47055 : bufflags |= REGBUF_KEEP_DATA;
9150 : :
9151 : 2381936 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_NEW, newbuf, bufflags);
9152 [ + + ]: 2381936 : if (oldbuf != newbuf)
9153 : 2199436 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_OLD, oldbuf, REGBUF_STANDARD);
9154 : :
9155 : 2381936 : XLogRegisterData(&xlrec, SizeOfHeapUpdate);
9156 : :
9157 : : /*
9158 : : * Prepare WAL data for the new tuple.
9159 : : */
9160 [ + + + + ]: 2381936 : if (prefixlen > 0 || suffixlen > 0)
9161 : : {
9162 [ + + + + ]: 168673 : if (prefixlen > 0 && suffixlen > 0)
9163 : : {
9164 : 104705 : prefix_suffix[0] = prefixlen;
9165 : 104705 : prefix_suffix[1] = suffixlen;
9166 : 104705 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefix_suffix,
9167 : : sizeof(uint16) * 2);
9168 : : }
9169 [ + + ]: 63968 : else if (prefixlen > 0)
9170 : : {
9171 : 41462 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefixlen,
9172 : : sizeof(uint16));
9173 : : }
9174 : : else
9175 : : {
9176 : 22506 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &suffixlen,
9177 : : sizeof(uint16));
9178 : : }
9179 : : }
9180 : :
9181 : 2381936 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
9182 : 2381936 : xlhdr.t_infomask = newtup->t_data->t_infomask;
9183 : 2381936 : xlhdr.t_hoff = newtup->t_data->t_hoff;
9184 : : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
9185 : :
9186 : : /*
9187 : : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9188 : : *
9189 : : * The 'data' doesn't include the common prefix or suffix.
9190 : : */
9191 : 2381936 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &xlhdr, SizeOfHeapHeader);
9192 [ + + ]: 2381936 : if (prefixlen == 0)
9193 : : {
9194 : 2235769 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
9195 : 2235769 : (char *) newtup->t_data + SizeofHeapTupleHeader,
9196 : 2235769 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
9197 : : }
9198 : : else
9199 : : {
9200 : : /*
9201 : : * Have to write the null bitmap and data after the common prefix as
9202 : : * two separate rdata entries.
9203 : : */
9204 : : /* bitmap [+ padding] [+ oid] */
9205 [ + - ]: 146167 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9206 : : {
9207 : 146167 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
9208 : 146167 : (char *) newtup->t_data + SizeofHeapTupleHeader,
9209 : 146167 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
9210 : : }
9211 : :
9212 : : /* data after common prefix */
9213 : 146167 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
9214 : 146167 : (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
9215 : 146167 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9216 : : }
9217 : :
9218 : : /* We need to log a tuple identity */
9219 [ + + + + ]: 2381936 : if (need_tuple_data && old_key_tuple)
9220 : : {
9221 : : /* don't really need this, but its more comfy to decode */
9222 : 156 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9223 : 156 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9224 : 156 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9225 : :
9226 : 156 : XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
9227 : :
9228 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
9229 : 156 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
9230 : 156 : old_key_tuple->t_len - SizeofHeapTupleHeader);
9231 : : }
9232 : :
9233 : : /*
9234 : : * Register VM buffers. If the old and new heap pages' VM bits are on the
9235 : : * same VM page and both their VM bits were cleared, the caller passes
9236 : : * only vmbuffer_new (mirroring the heap page convention where block 0 =
9237 : : * new is always registered).
9238 : : */
9239 : : Assert((BufferIsInvalid(vmbuffer_old) && BufferIsInvalid(vmbuffer_new)) ||
9240 : : (vmbuffer_old != vmbuffer_new));
9241 : :
9242 [ + + ]: 2381936 : if (BufferIsValid(vmbuffer_new))
9243 : 1231 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_NEW, vmbuffer_new, 0);
9244 : :
9245 [ + + ]: 2381936 : if (BufferIsValid(vmbuffer_old))
9246 : 2338 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_OLD, vmbuffer_old, 0);
9247 : :
9248 : : /* filtering by origin on a row level is much more efficient */
9249 : 2381936 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
9250 : :
9251 : 2381936 : recptr = XLogInsert(RM_HEAP_ID, info);
9252 : :
9253 : 2381936 : return recptr;
9254 : : }
9255 : :
9256 : : /*
9257 : : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
9258 : : *
9259 : : * This is only used when effective_wal_level is logical, and only for
9260 : : * catalog tuples.
9261 : : */
9262 : : static XLogRecPtr
9263 : 27524 : log_heap_new_cid(Relation relation, HeapTuple tup)
9264 : : {
9265 : : xl_heap_new_cid xlrec;
9266 : :
9267 : : XLogRecPtr recptr;
9268 : 27524 : HeapTupleHeader hdr = tup->t_data;
9269 : :
9270 : : Assert(ItemPointerIsValid(&tup->t_self));
9271 : : Assert(tup->t_tableOid != InvalidOid);
9272 : :
9273 : 27524 : xlrec.top_xid = GetTopTransactionId();
9274 : 27524 : xlrec.target_locator = relation->rd_locator;
9275 : 27524 : xlrec.target_tid = tup->t_self;
9276 : :
9277 : : /*
9278 : : * If the tuple got inserted & deleted in the same TX we definitely have a
9279 : : * combo CID, set cmin and cmax.
9280 : : */
9281 [ + + ]: 27524 : if (hdr->t_infomask & HEAP_COMBOCID)
9282 : : {
9283 : : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
9284 : : Assert(!HeapTupleHeaderXminInvalid(hdr));
9285 : 2345 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9286 : 2345 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9287 : 2345 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9288 : : }
9289 : : /* No combo CID, so only cmin or cmax can be set by this TX */
9290 : : else
9291 : : {
9292 : : /*
9293 : : * Tuple inserted.
9294 : : *
9295 : : * We need to check for LOCK ONLY because multixacts might be
9296 : : * transferred to the new tuple in case of FOR KEY SHARE updates in
9297 : : * which case there will be an xmax, although the tuple just got
9298 : : * inserted.
9299 : : */
9300 [ + + + + ]: 32958 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9301 : 7779 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
9302 : : {
9303 : 17401 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
9304 : 17401 : xlrec.cmax = InvalidCommandId;
9305 : : }
9306 : : /* Tuple from a different tx updated or deleted. */
9307 : : else
9308 : : {
9309 : 7778 : xlrec.cmin = InvalidCommandId;
9310 : 7778 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
9311 : : }
9312 : 25179 : xlrec.combocid = InvalidCommandId;
9313 : : }
9314 : :
9315 : : /*
9316 : : * Note that we don't need to register the buffer here, because this
9317 : : * operation does not modify the page. The insert/update/delete that
9318 : : * called us certainly did, but that's WAL-logged separately.
9319 : : */
9320 : 27524 : XLogBeginInsert();
9321 : 27524 : XLogRegisterData(&xlrec, SizeOfHeapNewCid);
9322 : :
9323 : : /* will be looked at irrespective of origin */
9324 : :
9325 : 27524 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9326 : :
9327 : 27524 : return recptr;
9328 : : }
9329 : :
9330 : : /*
9331 : : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9332 : : * the old tuple in an UPDATE or DELETE.
9333 : : *
9334 : : * Returns NULL if there's no need to log an identity or if there's no suitable
9335 : : * key defined.
9336 : : *
9337 : : * Pass key_required true if any replica identity columns changed value, or if
9338 : : * any of them have any external data. Delete must always pass true.
9339 : : *
9340 : : * *copy is set to true if the returned tuple is a modified copy rather than
9341 : : * the same tuple that was passed in.
9342 : : */
9343 : : static HeapTuple
9344 : 4300837 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
9345 : : bool *copy)
9346 : : {
9347 : 4300837 : TupleDesc desc = RelationGetDescr(relation);
9348 : 4300837 : char replident = relation->rd_rel->relreplident;
9349 : : Bitmapset *idattrs;
9350 : : HeapTuple key_tuple;
9351 : : bool nulls[MaxHeapAttributeNumber];
9352 : : Datum values[MaxHeapAttributeNumber];
9353 : :
9354 : 4300837 : *copy = false;
9355 : :
9356 [ + + + + : 4300837 : if (!RelationIsLogicallyLogged(relation))
+ + - + -
- - - + -
+ + ]
9357 : 4200375 : return NULL;
9358 : :
9359 [ + + ]: 100462 : if (replident == REPLICA_IDENTITY_NOTHING)
9360 : 335 : return NULL;
9361 : :
9362 [ + + ]: 100127 : if (replident == REPLICA_IDENTITY_FULL)
9363 : : {
9364 : : /*
9365 : : * When logging the entire old tuple, it very well could contain
9366 : : * toasted columns. If so, force them to be inlined.
9367 : : */
9368 [ + + ]: 198 : if (HeapTupleHasExternal(tp))
9369 : : {
9370 : 4 : *copy = true;
9371 : 4 : tp = toast_flatten_tuple(tp, desc);
9372 : : }
9373 : 198 : return tp;
9374 : : }
9375 : :
9376 : : /* if the key isn't required and we're only logging the key, we're done */
9377 [ + + ]: 99929 : if (!key_required)
9378 : 46923 : return NULL;
9379 : :
9380 : : /* find out the replica identity columns */
9381 : 53006 : idattrs = RelationGetIndexAttrBitmap(relation,
9382 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
9383 : :
9384 : : /*
9385 : : * If there's no defined replica identity columns, treat as !key_required.
9386 : : * (This case should not be reachable from heap_update, since that should
9387 : : * calculate key_required accurately. But heap_delete just passes
9388 : : * constant true for key_required, so we can hit this case in deletes.)
9389 : : */
9390 [ + + ]: 53006 : if (bms_is_empty(idattrs))
9391 : 6021 : return NULL;
9392 : :
9393 : : /*
9394 : : * Construct a new tuple containing only the replica identity columns,
9395 : : * with nulls elsewhere. While we're at it, assert that the replica
9396 : : * identity columns aren't null.
9397 : : */
9398 : 46985 : heap_deform_tuple(tp, desc, values, nulls);
9399 : :
9400 [ + + ]: 150966 : for (int i = 0; i < desc->natts; i++)
9401 : : {
9402 [ + + ]: 103981 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
9403 : : idattrs))
9404 : : Assert(!nulls[i]);
9405 : : else
9406 : 56984 : nulls[i] = true;
9407 : : }
9408 : :
9409 : 46985 : key_tuple = heap_form_tuple(desc, values, nulls);
9410 : 46985 : *copy = true;
9411 : :
9412 : 46985 : bms_free(idattrs);
9413 : :
9414 : : /*
9415 : : * If the tuple, which by here only contains indexed columns, still has
9416 : : * toasted columns, force them to be inlined. This is somewhat unlikely
9417 : : * since there's limits on the size of indexed columns, so we don't
9418 : : * duplicate toast_flatten_tuple()s functionality in the above loop over
9419 : : * the indexed columns, even if it would be more efficient.
9420 : : */
9421 [ + + ]: 46985 : if (HeapTupleHasExternal(key_tuple))
9422 : : {
9423 : 4 : HeapTuple oldtup = key_tuple;
9424 : :
9425 : 4 : key_tuple = toast_flatten_tuple(oldtup, desc);
9426 : 4 : heap_freetuple(oldtup);
9427 : : }
9428 : :
9429 : 46985 : return key_tuple;
9430 : : }
9431 : :
9432 : : /*
9433 : : * HeapCheckForSerializableConflictOut
9434 : : * We are reading a tuple. If it's not visible, there may be a
9435 : : * rw-conflict out with the inserter. Otherwise, if it is visible to us
9436 : : * but has been deleted, there may be a rw-conflict out with the deleter.
9437 : : *
9438 : : * We will determine the top level xid of the writing transaction with which
9439 : : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9440 : : * for overlap with our own transaction.
9441 : : *
9442 : : * This function should be called just about anywhere in heapam.c where a
9443 : : * tuple has been read. The caller must hold at least a shared lock on the
9444 : : * buffer, because this function might set hint bits on the tuple. There is
9445 : : * currently no known reason to call this function from an index AM.
9446 : : */
9447 : : void
9448 : 41743843 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
9449 : : HeapTuple tuple, Buffer buffer,
9450 : : Snapshot snapshot)
9451 : : {
9452 : : TransactionId xid;
9453 : : HTSV_Result htsvResult;
9454 : :
9455 [ + + ]: 41743843 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9456 : 41735865 : return;
9457 : :
9458 : : /*
9459 : : * Check to see whether the tuple has been written to by a concurrent
9460 : : * transaction, either to create it not visible to us, or to delete it
9461 : : * while it is visible to us. The "visible" bool indicates whether the
9462 : : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9463 : : * is going on with it.
9464 : : *
9465 : : * In the event of a concurrently inserted tuple that also happens to have
9466 : : * been concurrently updated (by a separate transaction), the xmin of the
9467 : : * tuple will be used -- not the updater's xid.
9468 : : */
9469 : 7978 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9470 [ + + + + : 7978 : switch (htsvResult)
- ]
9471 : : {
9472 : 7151 : case HEAPTUPLE_LIVE:
9473 [ + + ]: 7151 : if (visible)
9474 : 7129 : return;
9475 : 22 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9476 : 22 : break;
9477 : 364 : case HEAPTUPLE_RECENTLY_DEAD:
9478 : : case HEAPTUPLE_DELETE_IN_PROGRESS:
9479 [ + + ]: 364 : if (visible)
9480 : 289 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9481 : : else
9482 : 75 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9483 : :
9484 [ + + ]: 364 : if (TransactionIdPrecedes(xid, TransactionXmin))
9485 : : {
9486 : : /* This is like the HEAPTUPLE_DEAD case */
9487 : : Assert(!visible);
9488 : 68 : return;
9489 : : }
9490 : 296 : break;
9491 : 345 : case HEAPTUPLE_INSERT_IN_PROGRESS:
9492 : 345 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9493 : 345 : break;
9494 : 118 : case HEAPTUPLE_DEAD:
9495 : : Assert(!visible);
9496 : 118 : return;
9497 : 0 : default:
9498 : :
9499 : : /*
9500 : : * The only way to get to this default clause is if a new value is
9501 : : * added to the enum type without adding it to this switch
9502 : : * statement. That's a bug, so elog.
9503 : : */
9504 [ # # ]: 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9505 : :
9506 : : /*
9507 : : * In spite of having all enum values covered and calling elog on
9508 : : * this default, some compilers think this is a code path which
9509 : : * allows xid to be used below without initialization. Silence
9510 : : * that warning.
9511 : : */
9512 : : xid = InvalidTransactionId;
9513 : : }
9514 : :
9515 : : Assert(TransactionIdIsValid(xid));
9516 : : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
9517 : :
9518 : : /*
9519 : : * Find top level xid. Bail out if xid is too early to be a conflict, or
9520 : : * if it's our own xid.
9521 : : */
9522 [ + + ]: 663 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
9523 : 82 : return;
9524 : 581 : xid = SubTransGetTopmostTransaction(xid);
9525 [ - + ]: 581 : if (TransactionIdPrecedes(xid, TransactionXmin))
9526 : 0 : return;
9527 : :
9528 : 581 : CheckForSerializableConflictOut(relation, xid, snapshot);
9529 : : }
|