Age Owner Branch data TLA 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
478 nathan@postgresql.or 228 :CBC 16599993 : AssertHasSnapshotForToast(Relation rel)
229 : : {
230 : : #ifdef USE_ASSERT_CHECKING
231 : :
232 : : /* bootstrap mode in particular breaks this rule */
233 [ + + ]: 16599993 : if (!IsNormalProcessingMode())
234 : 681442 : return;
235 : :
236 : : /* if the relation doesn't have a TOAST table, we are good */
237 [ + + ]: 15918551 : if (!OidIsValid(rel->rd_rel->reltoastrelid))
238 : 10267397 : return;
239 : :
240 [ - + ]: 5651154 : Assert(HaveRegisteredOrActiveSnapshot());
241 : :
242 : : #endif /* USE_ASSERT_CHECKING */
243 : : }
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
895 tmunro@postgresql.or 255 : 146293 : heap_scan_stream_read_next_parallel(ReadStream *stream,
256 : : void *callback_private_data,
257 : : void *per_buffer_data)
258 : : {
259 : 146293 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
260 : :
261 [ - + ]: 146293 : Assert(ScanDirectionIsForward(scan->rs_dir));
262 [ - + ]: 146293 : Assert(scan->rs_base.rs_parallel);
263 : :
264 [ + + ]: 146293 : if (unlikely(!scan->rs_inited))
265 : : {
266 : : /* parallel scan */
267 : 2833 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
268 : 2833 : scan->rs_parallelworkerdata,
297 drowley@postgresql.o 269 : 2833 : (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 */
895 tmunro@postgresql.or 274 : 5666 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
275 : 2833 : scan->rs_parallelworkerdata,
276 : 2833 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
277 : 2833 : scan->rs_inited = true;
278 : : }
279 : : else
280 : : {
281 : 143460 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
282 : 143460 : scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
283 : 143460 : scan->rs_base.rs_parallel);
284 : : }
285 : :
286 : 146293 : 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 : 3963530 : heap_scan_stream_read_next_serial(ReadStream *stream,
296 : : void *callback_private_data,
297 : : void *per_buffer_data)
298 : : {
299 : 3963530 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
300 : :
301 [ + + ]: 3963530 : if (unlikely(!scan->rs_inited))
302 : : {
303 : 1072690 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
304 : 1072690 : scan->rs_inited = true;
305 : : }
306 : : else
307 : 2890840 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
308 : : scan->rs_prefetch_block,
309 : : scan->rs_dir);
310 : :
311 : 3963530 : 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
554 melanieplageman@gmai 320 : 258197 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
321 : : void *per_buffer_data)
322 : : {
323 : 258197 : TBMIterateResult *tbmres = per_buffer_data;
324 : 258197 : BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
325 : 258197 : HeapScanDesc hscan = (HeapScanDesc) bscan;
326 : 258197 : TableScanDesc sscan = &hscan->rs_base;
327 : :
328 : : for (;;)
329 : : {
330 [ - + ]: 258197 : CHECK_FOR_INTERRUPTS();
331 : :
332 : : /* no more entries in the bitmap */
333 [ + + ]: 258197 : if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
334 : 14459 : 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 [ + + ]: 243738 : if (!IsolationIsSerializable() &&
345 [ - + ]: 243629 : tbmres->blockno >= hscan->rs_nblocks)
554 melanieplageman@gmai 346 :UBC 0 : continue;
347 : :
554 melanieplageman@gmai 348 :CBC 243738 : 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
4075 tgl@sss.pgh.pa.us 360 : 1111481 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
361 : : {
2750 andres@anarazel.de 362 : 1111481 : 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 [ + + ]: 1111481 : if (scan->rs_base.rs_parallel != NULL)
378 : : {
379 : 4632 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
380 : 4632 : scan->rs_nblocks = bpscan->phs_nblocks;
381 : : }
382 : : else
383 : 1106849 : 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 [ + + ]: 1111479 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
7043 tgl@sss.pgh.pa.us 398 [ + + ]: 1093724 : scan->rs_nblocks > NBuffers / 4)
399 : : {
2681 andres@anarazel.de 400 : 15103 : allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
401 : 15103 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
402 : : }
403 : : else
6824 tgl@sss.pgh.pa.us 404 : 1096376 : allow_strat = allow_sync = false;
405 : :
406 [ + + ]: 1111479 : if (allow_strat)
407 : : {
408 : : /* During a rescan, keep the previous strategy object. */
7053 409 [ + + ]: 13758 : if (scan->rs_strategy == NULL)
410 : 13553 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
411 : : }
412 : : else
413 : : {
414 [ - + ]: 1097721 : if (scan->rs_strategy != NULL)
7053 tgl@sss.pgh.pa.us 415 :UBC 0 : FreeAccessStrategy(scan->rs_strategy);
7053 tgl@sss.pgh.pa.us 416 :CBC 1097721 : scan->rs_strategy = NULL;
417 : : }
418 : :
2750 andres@anarazel.de 419 [ + + ]: 1111479 : if (scan->rs_base.rs_parallel != NULL)
420 : : {
421 : : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
2681 422 [ + + ]: 4632 : if (scan->rs_base.rs_parallel->phs_syncscan)
423 : 5 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
424 : : else
425 : 4627 : 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 : : */
296 drowley@postgresql.o 434 [ + + ]: 4632 : if (!keep_startblock)
435 : 4480 : scan->rs_startblock = InvalidBlockNumber;
436 : : }
437 : : else
438 : : {
439 [ + + ]: 1106847 : 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 [ + + + + ]: 653648 : if (allow_sync && synchronize_seqscans)
447 : 60 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
448 : : else
449 : 653588 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
450 : : }
451 [ + + + + ]: 453199 : else if (allow_sync && synchronize_seqscans)
452 : : {
453 : 115 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
454 : 115 : scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
455 : : }
456 : : else
457 : : {
458 : 453084 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
459 : 453084 : scan->rs_startblock = 0;
460 : : }
461 : : }
462 : :
4335 alvherre@alvh.no-ip. 463 : 1111479 : scan->rs_numblocks = InvalidBlockNumber;
7603 tgl@sss.pgh.pa.us 464 : 1111479 : scan->rs_inited = false;
9234 465 : 1111479 : scan->rs_ctup.t_data = NULL;
7603 466 : 1111479 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
9234 467 : 1111479 : scan->rs_cbuf = InvalidBuffer;
7603 468 : 1111479 : scan->rs_cblock = InvalidBlockNumber;
641 melanieplageman@gmai 469 : 1111479 : scan->rs_ntuples = 0;
470 : 1111479 : 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 : : */
895 tmunro@postgresql.or 476 : 1111479 : scan->rs_dir = ForwardScanDirection;
477 : 1111479 : 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 : : */
1662 tgl@sss.pgh.pa.us 484 [ + + + + ]: 1111479 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
2750 andres@anarazel.de 485 : 256851 : 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 : : */
2681 492 [ + + ]: 1111479 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
2750 493 [ + + + + : 1076012 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
+ + - + ]
11030 scrappy@hub.org 494 : 1111479 : }
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
2750 andres@anarazel.de 503 : 3291 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
504 : : {
505 : 3291 : HeapScanDesc scan = (HeapScanDesc) sscan;
506 : :
4079 tgl@sss.pgh.pa.us 507 [ - + ]: 3291 : Assert(!scan->rs_inited); /* else too late to change */
508 : : /* else rs_startblock is significant */
2681 andres@anarazel.de 509 [ - + ]: 3291 : Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
510 : :
511 : : /* Check startBlk is valid (but allow case of zero blocks...) */
4079 tgl@sss.pgh.pa.us 512 [ + + - + ]: 3291 : Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
513 : :
4335 alvherre@alvh.no-ip. 514 : 3291 : scan->rs_startblock = startBlk;
515 : 3291 : scan->rs_numblocks = numBlks;
516 : 3291 : }
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
896 andres@anarazel.de 525 : 2904015 : 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 : : {
251 530 : 2904015 : Oid relid = RelationGetRelid(scan->rs_base.rs_rd);
897 531 : 2904015 : int ntup = 0;
251 532 : 2904015 : int nvis = 0;
533 : : BatchMVCCState batchmvcc;
534 : :
535 : : /* page at a time should have been disabled otherwise */
536 [ - + ]: 2904015 : Assert(IsMVCCSnapshot(snapshot));
537 : :
538 : : /* first find all tuples on the page */
539 [ + + ]: 156296179 : for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
540 : : {
897 541 : 153392164 : ItemId lpp = PageGetItemId(page, lineoff);
542 : : HeapTuple tup;
543 : :
251 544 [ + + ]: 153392164 : if (unlikely(!ItemIdIsNormal(lpp)))
897 545 : 25334616 : 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 : : */
251 553 [ + + - + ]: 128057548 : if (!all_visible || check_serializable)
554 : : {
555 : 70104347 : tup = &batchmvcc.tuples[ntup];
556 : :
557 : 70104347 : tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
558 : 70104347 : tup->t_len = ItemIdGetLength(lpp);
559 : 70104347 : tup->t_tableOid = relid;
560 : 70104347 : 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 [ + + ]: 128057548 : if (all_visible)
568 : : {
569 [ - + ]: 57953201 : if (check_serializable)
570 : : {
251 andres@anarazel.de 571 :UBC 0 : batchmvcc.visible[ntup] = true;
572 : : }
897 andres@anarazel.de 573 :CBC 57953201 : scan->rs_vistuples[ntup] = lineoff;
574 : : }
575 : :
251 576 : 128057548 : ntup++;
577 : : }
578 : :
897 579 [ - + ]: 2904015 : 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 : : */
251 586 [ + + ]: 2904015 : if (all_visible)
587 : 1236887 : nvis = ntup;
588 : : else
589 : 1667128 : nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
590 : : ntup,
591 : : &batchmvcc,
592 : 1667128 : 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 [ + + ]: 2904015 : 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 : 2904007 : 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
899 drowley@postgresql.o 619 : 2904015 : heap_prepare_pagescan(TableScanDesc sscan)
620 : : {
2750 andres@anarazel.de 621 : 2904015 : HeapScanDesc scan = (HeapScanDesc) sscan;
899 drowley@postgresql.o 622 : 2904015 : Buffer buffer = scan->rs_cbuf;
623 : 2904015 : BlockNumber block = scan->rs_cblock;
624 : : Snapshot snapshot;
625 : : Page page;
626 : : int lines;
627 : : bool all_visible;
628 : : bool check_serializable;
629 : :
630 [ - + ]: 2904015 : Assert(BufferGetBlockNumber(buffer) == block);
631 : :
632 : : /* ensure we're not accidentally being used when not in pagemode */
633 [ - + ]: 2904015 : Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
2750 andres@anarazel.de 634 : 2904015 : snapshot = scan->rs_base.rs_snapshot;
635 : :
636 : : /*
637 : : * Prune and repair fragmentation for the whole page, if possible.
638 : : */
174 melanieplageman@gmai 639 : 2904015 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer, &scan->rs_vmbuffer,
640 : 2904015 : 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 : : */
7603 tgl@sss.pgh.pa.us 647 : 2904015 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
648 : :
1404 peter@eisentraut.org 649 : 2904015 : page = BufferGetPage(buffer);
650 : 2904015 : 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 [ + + + + ]: 2904015 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
673 : : check_serializable =
897 andres@anarazel.de 674 : 2904015 : 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 [ + + ]: 2904015 : if (likely(all_visible))
683 : : {
684 [ + - ]: 1236887 : if (likely(!check_serializable))
896 685 : 1236887 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
686 : : block, lines, true, false);
687 : : else
896 andres@anarazel.de 688 :UBC 0 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
689 : : block, lines, true, true);
690 : : }
691 : : else
692 : : {
897 andres@anarazel.de 693 [ + + ]:CBC 1667128 : if (likely(!check_serializable))
896 694 : 1666505 : 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 : :
7603 tgl@sss.pgh.pa.us 701 : 2904007 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
702 : 2904007 : }
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
899 drowley@postgresql.o 711 : 3904249 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
712 : : {
895 tmunro@postgresql.or 713 [ - + ]: 3904249 : Assert(scan->rs_read_stream);
714 : :
715 : : /* release previous scan buffer, if any */
899 drowley@postgresql.o 716 [ + + ]: 3904249 : if (BufferIsValid(scan->rs_cbuf))
717 : : {
718 : 2828725 : ReleaseBuffer(scan->rs_cbuf);
719 : 2828725 : 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 [ + + ]: 3904249 : 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 : : */
895 tmunro@postgresql.or 735 [ + + ]: 3904246 : if (unlikely(scan->rs_dir != dir))
736 : : {
737 : 101 : scan->rs_prefetch_block = scan->rs_cblock;
738 : 101 : read_stream_reset(scan->rs_read_stream);
739 : : }
740 : :
741 : 3904246 : scan->rs_dir = dir;
742 : :
743 : 3904246 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
744 [ + + ]: 3904218 : if (BufferIsValid(scan->rs_cbuf))
745 : 3015452 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
899 drowley@postgresql.o 746 : 3904218 : }
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
1326 756 : 1072690 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
757 : : {
758 [ - + ]: 1072690 : Assert(!scan->rs_inited);
895 tmunro@postgresql.or 759 [ - + ]: 1072690 : Assert(scan->rs_base.rs_parallel == NULL);
760 : :
761 : : /* When there are no pages to scan, return InvalidBlockNumber */
1326 drowley@postgresql.o 762 [ + + + + ]: 1072690 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
763 : 528725 : return InvalidBlockNumber;
764 : :
765 [ + + ]: 543965 : if (ScanDirectionIsForward(dir))
766 : : {
895 tmunro@postgresql.or 767 : 543924 : 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 : : */
1326 drowley@postgresql.o 777 : 41 : 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 [ + + ]: 41 : if (scan->rs_numblocks != InvalidBlockNumber)
784 : 4 : return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
785 : :
786 [ - + ]: 37 : if (scan->rs_startblock > 0)
1326 drowley@postgresql.o 787 :UBC 0 : return scan->rs_startblock - 1;
788 : :
1326 drowley@postgresql.o 789 :CBC 37 : 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
1325 803 : 117123 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
804 : : OffsetNumber *lineoff)
805 : : {
806 : : Page page;
807 : :
808 [ - + ]: 117123 : Assert(scan->rs_inited);
809 [ - + ]: 117123 : Assert(BufferIsValid(scan->rs_cbuf));
810 : :
811 : : /* Caller is responsible for ensuring buffer is locked if needed */
812 : 117123 : page = BufferGetPage(scan->rs_cbuf);
813 : :
1321 814 : 117123 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
815 : :
1325 816 [ + - ]: 117123 : if (ScanDirectionIsForward(dir))
817 : 117123 : *lineoff = FirstOffsetNumber;
818 : : else
1325 drowley@postgresql.o 819 :UBC 0 : *lineoff = (OffsetNumber) (*linesleft);
820 : :
821 : : /* lineoff now references the physically previous or next tid */
1325 drowley@postgresql.o 822 :CBC 117123 : 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 : 9469805 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
835 : : OffsetNumber *lineoff)
836 : : {
837 : : Page page;
838 : :
839 [ - + ]: 9469805 : Assert(scan->rs_inited);
840 [ - + ]: 9469805 : Assert(BufferIsValid(scan->rs_cbuf));
841 : :
842 : : /* Caller is responsible for ensuring buffer is locked if needed */
843 : 9469805 : page = BufferGetPage(scan->rs_cbuf);
844 : :
845 [ + - ]: 9469805 : if (ScanDirectionIsForward(dir))
846 : : {
847 : 9469805 : *lineoff = OffsetNumberNext(scan->rs_coffset);
848 : 9469805 : *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 : : */
1325 drowley@postgresql.o 857 [ # # ]:UBC 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 */
1325 drowley@postgresql.o 862 :CBC 9469805 : 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 : 2890840 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
881 : : {
895 tmunro@postgresql.or 882 [ - + ]: 2890840 : Assert(scan->rs_base.rs_parallel == NULL);
883 : :
884 [ + + ]: 2890840 : if (likely(ScanDirectionIsForward(dir)))
885 : : {
886 : 2890763 : block++;
887 : :
888 : : /* wrap back to the start of the heap */
889 [ + + ]: 2890763 : if (block >= scan->rs_nblocks)
890 : 428223 : 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 [ + + ]: 2890763 : if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
905 : 40852 : ss_report_location(scan->rs_base.rs_rd, block);
906 : :
907 : : /* we're done if we're back at where we started */
908 [ + + ]: 2890763 : if (block == scan->rs_startblock)
909 : 428173 : return InvalidBlockNumber;
910 : :
911 : : /* check if the limit imposed by heap_setscanlimits() is met */
912 [ + + ]: 2462590 : if (scan->rs_numblocks != InvalidBlockNumber)
913 : : {
914 [ + + ]: 2820 : if (--scan->rs_numblocks == 0)
915 : 1596 : return InvalidBlockNumber;
916 : : }
917 : :
918 : 2460994 : return block;
919 : : }
920 : : else
921 : : {
922 : : /* we're done if the last block is the start position */
1325 drowley@postgresql.o 923 [ + - ]: 77 : if (block == scan->rs_startblock)
924 : 77 : return InvalidBlockNumber;
925 : :
926 : : /* check if the limit imposed by heap_setscanlimits() is met */
1325 drowley@postgresql.o 927 [ # # ]:UBC 0 : if (scan->rs_numblocks != InvalidBlockNumber)
928 : : {
929 [ # # ]: 0 : if (--scan->rs_numblocks == 0)
930 : 0 : return InvalidBlockNumber;
931 : : }
932 : :
933 : : /* wrap to the end of the heap when the last page was page 0 */
934 [ # # ]: 0 : if (block == 0)
935 : 0 : block = scan->rs_nblocks;
936 : :
937 : 0 : block--;
938 : :
939 : 0 : return block;
940 : : }
941 : : }
942 : :
943 : : /* ----------------
944 : : * heapgettup - fetch next heap tuple
945 : : *
946 : : * Initialize the scan if not already done; then advance to the next
947 : : * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
948 : : * or set scan->rs_ctup.t_data = NULL if no more tuples.
949 : : *
950 : : * Note: the reason nkeys/key are passed separately, even though they are
951 : : * kept in the scan descriptor, is that the caller may not want us to check
952 : : * the scankeys.
953 : : *
954 : : * Note: when we fall off the end of the scan in either direction, we
955 : : * reset rs_inited. This means that a further request with the same
956 : : * scan direction will restart the scan, which is a bit odd, but a
957 : : * request with the opposite scan direction will start a fresh scan
958 : : * in the proper direction. The latter is required behavior for cursors,
959 : : * while the former case is generally undefined behavior in Postgres
960 : : * so we don't care too much.
961 : : * ----------------
962 : : */
963 : : static void
7603 tgl@sss.pgh.pa.us 964 :CBC 9496241 : heapgettup(HeapScanDesc scan,
965 : : ScanDirection dir,
966 : : int nkeys,
967 : : ScanKey key)
968 : : {
969 : 9496241 : HeapTuple tuple = &(scan->rs_ctup);
970 : : Page page;
971 : : OffsetNumber lineoff;
972 : : int linesleft;
973 : :
899 drowley@postgresql.o 974 [ + + ]: 9496241 : if (likely(scan->rs_inited))
975 : : {
976 : : /* continue from previously returned page/tuple */
1325 977 : 9469805 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
978 : 9469805 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
1321 979 : 9469805 : goto continue_page;
980 : : }
981 : :
982 : : /*
983 : : * advance the scan until we find a qualifying tuple or run out of stuff
984 : : * to scan
985 : : */
986 : : while (true)
987 : : {
899 988 : 142682 : heap_fetch_next_buffer(scan, dir);
989 : :
990 : : /* did we run out of blocks to scan? */
991 [ + + ]: 142682 : if (!BufferIsValid(scan->rs_cbuf))
992 : 25559 : break;
993 : :
994 [ - + ]: 117123 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
995 : :
1321 996 : 117123 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
997 : 117123 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
998 : 9586928 : continue_page:
999 : :
1000 : : /*
1001 : : * Only continue scanning the page while we have lines left.
1002 : : *
1003 : : * Note that this protects us from accessing line pointers past
1004 : : * PageGetMaxOffsetNumber(); both for forward scans when we resume the
1005 : : * table scan, and for when we start scanning a new page.
1006 : : */
1007 [ + + ]: 9643162 : for (; linesleft > 0; linesleft--, lineoff += dir)
1008 : : {
1009 : : bool visible;
1010 : 9526916 : ItemId lpp = PageGetItemId(page, lineoff);
1011 : :
1012 [ + + ]: 9526916 : if (!ItemIdIsNormal(lpp))
1013 : 35815 : continue;
1014 : :
1015 : 9491101 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1016 : 9491101 : tuple->t_len = ItemIdGetLength(lpp);
899 1017 : 9491101 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1018 : :
1321 1019 : 9491101 : visible = HeapTupleSatisfiesVisibility(tuple,
1020 : : scan->rs_base.rs_snapshot,
1021 : : scan->rs_cbuf);
1022 : :
1023 : 9491101 : HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
1024 : : tuple, scan->rs_cbuf,
1025 : : scan->rs_base.rs_snapshot);
1026 : :
1027 : : /* skip tuples not visible to this snapshot */
1028 [ + + ]: 9491101 : if (!visible)
1029 : 6820 : continue;
1030 : :
1031 : : /* skip any tuples that don't match the scan key */
1032 [ + + ]: 9484281 : if (key != NULL &&
1033 [ + + ]: 14324 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1034 : : nkeys, key))
1035 : 13599 : continue;
1036 : :
1037 : 9470682 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1038 : 9470682 : scan->rs_coffset = lineoff;
1039 : 9470682 : return;
1040 : : }
1041 : :
1042 : : /*
1043 : : * if we get here, it means we've exhausted the items on this page and
1044 : : * it's time to move to the next.
1045 : : */
7603 tgl@sss.pgh.pa.us 1046 : 116246 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1047 : : }
1048 : :
1049 : : /* end of scan */
1321 drowley@postgresql.o 1050 [ - + ]: 25559 : if (BufferIsValid(scan->rs_cbuf))
1321 drowley@postgresql.o 1051 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1052 : :
1321 drowley@postgresql.o 1053 :CBC 25559 : scan->rs_cbuf = InvalidBuffer;
1054 : 25559 : scan->rs_cblock = InvalidBlockNumber;
895 tmunro@postgresql.or 1055 : 25559 : scan->rs_prefetch_block = InvalidBlockNumber;
1321 drowley@postgresql.o 1056 : 25559 : tuple->t_data = NULL;
1057 : 25559 : scan->rs_inited = false;
1058 : : }
1059 : :
1060 : : /* ----------------
1061 : : * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
1062 : : *
1063 : : * Same API as heapgettup, but used in page-at-a-time mode
1064 : : *
1065 : : * The internal logic is much the same as heapgettup's too, but there are some
1066 : : * differences: we do not take the buffer content lock (that only needs to
1067 : : * happen inside heap_prepare_pagescan), and we iterate through just the
1068 : : * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
1069 : : * that lineindex is 0-based, where the corresponding loop variable lineoff in
1070 : : * heapgettup is 1-based.
1071 : : * ----------------
1072 : : */
1073 : : static void
7603 tgl@sss.pgh.pa.us 1074 : 62504276 : heapgettup_pagemode(HeapScanDesc scan,
1075 : : ScanDirection dir,
1076 : : int nkeys,
1077 : : ScanKey key)
1078 : : {
1079 : 62504276 : HeapTuple tuple = &(scan->rs_ctup);
1080 : : Page page;
1081 : : uint32 lineindex;
1082 : : uint32 linesleft;
1083 : :
899 drowley@postgresql.o 1084 [ + + ]: 62504276 : if (likely(scan->rs_inited))
1085 : : {
1086 : : /* continue from previously returned page/tuple */
1325 1087 : 61455188 : page = BufferGetPage(scan->rs_cbuf);
1088 : :
1089 : 61455188 : lineindex = scan->rs_cindex + dir;
1090 [ + + ]: 61455188 : if (ScanDirectionIsForward(dir))
1091 : 61454751 : linesleft = scan->rs_ntuples - lineindex;
1092 : : else
1093 : 437 : linesleft = scan->rs_cindex;
1094 : : /* lineindex now references the next or previous visible tid */
1095 : :
1321 1096 : 61455188 : goto continue_page;
1097 : : }
1098 : :
1099 : : /*
1100 : : * advance the scan until we find a qualifying tuple or run out of stuff
1101 : : * to scan
1102 : : */
1103 : : while (true)
1104 : : {
899 1105 : 3761567 : heap_fetch_next_buffer(scan, dir);
1106 : :
1107 : : /* did we run out of blocks to scan? */
1108 [ + + ]: 3761536 : if (!BufferIsValid(scan->rs_cbuf))
1109 : 863207 : break;
1110 : :
1111 [ - + ]: 2898329 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1112 : :
1113 : : /* prune the page and determine visible tuple offsets */
1114 : 2898329 : heap_prepare_pagescan((TableScanDesc) scan);
1321 1115 : 2898321 : page = BufferGetPage(scan->rs_cbuf);
1116 : 2898321 : linesleft = scan->rs_ntuples;
1117 [ + + ]: 2898321 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1118 : :
1119 : : /* block is the same for all tuples, set it once outside the loop */
537 heikki.linnakangas@i 1120 : 2898321 : ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1121 : :
1122 : : /* lineindex now references the next or previous visible tid */
1321 drowley@postgresql.o 1123 : 64353509 : continue_page:
1124 : :
1125 [ + + ]: 120007241 : for (; linesleft > 0; linesleft--, lineindex += dir)
1126 : : {
1127 : : ItemId lpp;
1128 : : OffsetNumber lineoff;
1129 : :
258 heikki.linnakangas@i 1130 [ - + ]: 117294762 : Assert(lineindex < scan->rs_ntuples);
7603 tgl@sss.pgh.pa.us 1131 : 117294762 : lineoff = scan->rs_vistuples[lineindex];
1404 peter@eisentraut.org 1132 : 117294762 : lpp = PageGetItemId(page, lineoff);
6948 tgl@sss.pgh.pa.us 1133 [ - + ]: 117294762 : Assert(ItemIdIsNormal(lpp));
1134 : :
1404 peter@eisentraut.org 1135 : 117294762 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
7603 tgl@sss.pgh.pa.us 1136 : 117294762 : tuple->t_len = ItemIdGetLength(lpp);
537 heikki.linnakangas@i 1137 : 117294762 : ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1138 : :
1139 : : /* skip any tuples that don't match the scan key */
1321 drowley@postgresql.o 1140 [ + + ]: 117294762 : if (key != NULL &&
1141 [ + + ]: 56032331 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1142 : : nkeys, key))
1143 : 55653732 : continue;
1144 : :
1145 : 61641030 : scan->rs_cindex = lineindex;
1146 : 61641030 : return;
1147 : : }
1148 : : }
1149 : :
1150 : : /* end of scan */
1151 [ - + ]: 863207 : if (BufferIsValid(scan->rs_cbuf))
1321 drowley@postgresql.o 1152 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1321 drowley@postgresql.o 1153 :CBC 863207 : scan->rs_cbuf = InvalidBuffer;
1154 : 863207 : scan->rs_cblock = InvalidBlockNumber;
895 tmunro@postgresql.or 1155 : 863207 : scan->rs_prefetch_block = InvalidBlockNumber;
1321 drowley@postgresql.o 1156 : 863207 : tuple->t_data = NULL;
1157 : 863207 : scan->rs_inited = false;
1158 : : }
1159 : :
1160 : :
1161 : : /* ----------------------------------------------------------------
1162 : : * heap access method interface
1163 : : * ----------------------------------------------------------------
1164 : : */
1165 : :
1166 : :
1167 : : TableScanDesc
8889 tgl@sss.pgh.pa.us 1168 : 457681 : heap_beginscan(Relation relation, Snapshot snapshot,
1169 : : int nkeys, ScanKey key,
1170 : : ParallelTableScanDesc parallel_scan,
1171 : : uint32 flags)
1172 : : {
1173 : : HeapScanDesc scan;
1174 : :
1175 : : /*
1176 : : * increment relation ref count while scanning relation
1177 : : *
1178 : : * This is just to make really sure the relcache entry won't go away while
1179 : : * the scan has a pointer to it. Caller should be holding the rel open
1180 : : * anyway, so this is redundant in all normal scenarios...
1181 : : */
9447 1182 : 457681 : RelationIncrementReferenceCount(relation);
1183 : :
1184 : : /*
1185 : : * allocate and initialize scan descriptor
1186 : : */
612 melanieplageman@gmai 1187 [ + + ]: 457681 : if (flags & SO_TYPE_BITMAPSCAN)
1188 : : {
284 michael@paquier.xyz 1189 : 12306 : BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
1190 : :
1191 : : /*
1192 : : * Bitmap Heap scans do not have any fields that a normal Heap Scan
1193 : : * does not have, so no special initializations required here.
1194 : : */
612 melanieplageman@gmai 1195 : 12306 : scan = (HeapScanDesc) bscan;
1196 : : }
1197 : : else
284 michael@paquier.xyz 1198 : 445375 : scan = (HeapScanDesc) palloc_object(HeapScanDescData);
1199 : :
2750 andres@anarazel.de 1200 : 457681 : scan->rs_base.rs_rd = relation;
1201 : 457681 : scan->rs_base.rs_snapshot = snapshot;
1202 : 457681 : scan->rs_base.rs_nkeys = nkeys;
2681 1203 : 457681 : scan->rs_base.rs_flags = flags;
2750 1204 : 457681 : scan->rs_base.rs_parallel = parallel_scan;
166 tomas.vondra@postgre 1205 : 457681 : scan->rs_base.rs_instrument = NULL;
2681 andres@anarazel.de 1206 : 457681 : scan->rs_strategy = NULL; /* set in initscan */
554 melanieplageman@gmai 1207 : 457681 : scan->rs_cbuf = InvalidBuffer;
1208 : :
1209 : : /*
1210 : : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1211 : : */
2681 andres@anarazel.de 1212 [ + + + + ]: 457681 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
1213 : 37708 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1214 : :
1215 : : /* Check that a historic snapshot is not used for non-catalog tables */
394 heikki.linnakangas@i 1216 [ + + ]: 457681 : if (snapshot &&
1217 [ + + ]: 446409 : IsHistoricMVCCSnapshot(snapshot) &&
1218 [ + + + - : 725 : !RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - - +
- - - - -
- - - -
- ]
1219 : : {
394 heikki.linnakangas@i 1220 [ # # ]:UBC 0 : ereport(ERROR,
1221 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1222 : : errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1223 : : RelationGetRelationName(relation))));
1224 : : }
1225 : :
1226 : : /*
1227 : : * For seqscan and sample scans in a serializable transaction, acquire a
1228 : : * predicate lock on the entire relation. This is required not only to
1229 : : * lock all the matching tuples, but also to conflict with new insertions
1230 : : * into the table. In an indexscan, we take page locks on the index pages
1231 : : * covering the range specified in the scan qual, but in a heap scan there
1232 : : * is nothing more fine-grained to lock. A bitmap scan is a different
1233 : : * story, there we have already scanned the index and locked the index
1234 : : * pages covering the predicate. But in that case we still have to lock
1235 : : * any matching heap tuples. For sample scan we could optimize the locking
1236 : : * to be at least page-level granularity, but we'd need to add per-tuple
1237 : : * locking for that.
1238 : : */
2681 andres@anarazel.de 1239 [ + + ]:CBC 457681 : if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
1240 : : {
1241 : : /*
1242 : : * Ensure a missing snapshot is noticed reliably, even if the
1243 : : * isolation mode means predicate locking isn't performed (and
1244 : : * therefore the snapshot isn't used here).
1245 : : */
1246 [ - + ]: 432307 : Assert(snapshot);
5562 heikki.linnakangas@i 1247 : 432307 : PredicateLockRelation(relation, snapshot);
1248 : : }
1249 : :
1250 : : /* we only need to set this up once */
7603 tgl@sss.pgh.pa.us 1251 : 457681 : scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1252 : :
1253 : : /*
1254 : : * Allocate memory to keep track of page allocation for parallel workers
1255 : : * when doing a parallel scan.
1256 : : */
2000 drowley@postgresql.o 1257 [ + + ]: 457681 : if (parallel_scan != NULL)
284 michael@paquier.xyz 1258 : 4480 : scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
1259 : : else
2000 drowley@postgresql.o 1260 : 453201 : scan->rs_parallelworkerdata = NULL;
1261 : :
1262 : : /*
1263 : : * we do this here instead of in initscan() because heap_rescan also calls
1264 : : * initscan() and we don't want to allocate memory again
1265 : : */
8889 tgl@sss.pgh.pa.us 1266 [ + + ]: 457681 : if (nkeys > 0)
284 michael@paquier.xyz 1267 : 256851 : scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
1268 : : else
2750 andres@anarazel.de 1269 : 200830 : scan->rs_base.rs_key = NULL;
1270 : :
6311 tgl@sss.pgh.pa.us 1271 : 457681 : initscan(scan, key, false);
1272 : :
895 tmunro@postgresql.or 1273 : 457679 : scan->rs_read_stream = NULL;
1274 : :
1275 : : /*
1276 : : * Set up a read stream for sequential scans and TID range scans. This
1277 : : * should be done after initscan() because initscan() allocates the
1278 : : * BufferAccessStrategy object passed to the read stream API.
1279 : : */
1280 [ + + ]: 457679 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1281 [ + + ]: 25469 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
1282 : 433515 : {
1283 : : ReadStreamBlockNumberCB cb;
1284 : :
1285 [ + + ]: 433520 : if (scan->rs_base.rs_parallel)
1286 : 4480 : cb = heap_scan_stream_read_next_parallel;
1287 : : else
1288 : 429040 : cb = heap_scan_stream_read_next_serial;
1289 : :
1290 : : /* ---
1291 : : * It is safe to use batchmode as the only locks taken by `cb`
1292 : : * are never taken while waiting for IO:
1293 : : * - SyncScanLock is used in the non-parallel case
1294 : : * - in the parallel case, only spinlocks and atomics are used
1295 : : * ---
1296 : : */
539 andres@anarazel.de 1297 : 433520 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
1298 : : READ_STREAM_USE_BATCHING,
1299 : : scan->rs_strategy,
1300 : : scan->rs_base.rs_rd,
1301 : : MAIN_FORKNUM,
1302 : : cb,
1303 : : scan,
1304 : : 0);
1305 : : }
554 melanieplageman@gmai 1306 [ + + ]: 24159 : else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1307 : : {
535 1308 : 12306 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
1309 : : READ_STREAM_USE_BATCHING,
1310 : : scan->rs_strategy,
1311 : : scan->rs_base.rs_rd,
1312 : : MAIN_FORKNUM,
1313 : : bitmapheap_stream_read_next,
1314 : : scan,
1315 : : sizeof(TBMIterateResult));
1316 : : }
1317 : :
1318 : : /* enable read stream instrumentation */
166 tomas.vondra@postgre 1319 [ + + + - ]: 457674 : if ((flags & SO_SCAN_INSTRUMENT) && (scan->rs_read_stream != NULL))
1320 : : {
1321 : 8 : scan->rs_base.rs_instrument = palloc0_object(TableScanInstrumentation);
1322 : 8 : read_stream_enable_stats(scan->rs_read_stream,
1323 : 8 : &scan->rs_base.rs_instrument->io);
1324 : : }
1325 : :
189 melanieplageman@gmai 1326 : 457674 : scan->rs_vmbuffer = InvalidBuffer;
1327 : :
2750 andres@anarazel.de 1328 : 457674 : return (TableScanDesc) scan;
1329 : : }
1330 : :
1331 : : void
1332 : 653800 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1333 : : bool allow_strat, bool allow_sync, bool allow_pagemode)
1334 : : {
1335 : 653800 : HeapScanDesc scan = (HeapScanDesc) sscan;
1336 : :
1337 [ + + ]: 653800 : if (set_params)
1338 : : {
2681 1339 [ + - ]: 19 : if (allow_strat)
1340 : 19 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1341 : : else
2681 andres@anarazel.de 1342 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1343 : :
2681 andres@anarazel.de 1344 [ + + ]:CBC 19 : if (allow_sync)
1345 : 8 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1346 : : else
1347 : 11 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1348 : :
1349 [ + - + - ]: 19 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1350 [ + - ]: 19 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1351 : 19 : scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
1352 : : else
2681 andres@anarazel.de 1353 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1354 : : }
1355 : :
1356 : : /*
1357 : : * unpin scan buffers
1358 : : */
9234 tgl@sss.pgh.pa.us 1359 [ + + ]:CBC 653800 : if (BufferIsValid(scan->rs_cbuf))
1360 : : {
1361 : 2084 : ReleaseBuffer(scan->rs_cbuf);
554 melanieplageman@gmai 1362 : 2084 : scan->rs_cbuf = InvalidBuffer;
1363 : : }
1364 : :
189 1365 [ + + ]: 653800 : if (BufferIsValid(scan->rs_vmbuffer))
1366 : : {
1367 : 18 : ReleaseBuffer(scan->rs_vmbuffer);
1368 : 18 : scan->rs_vmbuffer = InvalidBuffer;
1369 : : }
1370 : :
1371 : : /*
1372 : : * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1373 : : * additional data vs a normal HeapScan
1374 : : */
1375 : :
1376 : : /*
1377 : : * The read stream is reset on rescan. This must be done before
1378 : : * initscan(), as some state referred to by read_stream_reset() is reset
1379 : : * in initscan().
1380 : : */
895 tmunro@postgresql.or 1381 [ + + ]: 653800 : if (scan->rs_read_stream)
1382 : 646114 : read_stream_reset(scan->rs_read_stream);
1383 : :
1384 : : /*
1385 : : * reinitialize scan descriptor
1386 : : */
6311 tgl@sss.pgh.pa.us 1387 : 653800 : initscan(scan, key, true);
11030 scrappy@hub.org 1388 : 653800 : }
1389 : :
1390 : : void
2750 andres@anarazel.de 1391 : 454421 : heap_endscan(TableScanDesc sscan)
1392 : : {
1393 : 454421 : HeapScanDesc scan = (HeapScanDesc) sscan;
1394 : :
1395 : : /* Note: no locking manipulations needed */
1396 : :
1397 : : /*
1398 : : * unpin scan buffers
1399 : : */
9234 tgl@sss.pgh.pa.us 1400 [ + + ]: 454421 : if (BufferIsValid(scan->rs_cbuf))
1401 : 182368 : ReleaseBuffer(scan->rs_cbuf);
1402 : :
189 melanieplageman@gmai 1403 [ + + ]: 454421 : if (BufferIsValid(scan->rs_vmbuffer))
1404 : 2740 : ReleaseBuffer(scan->rs_vmbuffer);
1405 : :
1406 : : /*
1407 : : * Must free the read stream before freeing the BufferAccessStrategy.
1408 : : */
895 tmunro@postgresql.or 1409 [ + + ]: 454421 : if (scan->rs_read_stream)
1410 : 442635 : read_stream_end(scan->rs_read_stream);
1411 : :
1412 : : /*
1413 : : * decrement relation reference count and free scan descriptor storage
1414 : : */
2750 andres@anarazel.de 1415 : 454421 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1416 : :
1417 [ + + ]: 454421 : if (scan->rs_base.rs_key)
1418 : 256815 : pfree(scan->rs_base.rs_key);
1419 : :
7053 tgl@sss.pgh.pa.us 1420 [ + + ]: 454421 : if (scan->rs_strategy != NULL)
1421 : 13544 : FreeAccessStrategy(scan->rs_strategy);
1422 : :
2000 drowley@postgresql.o 1423 [ + + ]: 454421 : if (scan->rs_parallelworkerdata != NULL)
1424 : 4480 : pfree(scan->rs_parallelworkerdata);
1425 : :
2681 andres@anarazel.de 1426 [ + + ]: 454421 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
2750 1427 : 44812 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1428 : :
166 tomas.vondra@postgre 1429 [ + + ]: 454421 : if (scan->rs_base.rs_instrument)
1430 : 8 : pfree(scan->rs_base.rs_instrument);
1431 : :
9864 tgl@sss.pgh.pa.us 1432 : 454421 : pfree(scan);
11030 scrappy@hub.org 1433 : 454421 : }
1434 : :
1435 : : HeapTuple
2750 andres@anarazel.de 1436 : 11933377 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1437 : : {
1438 : 11933377 : HeapScanDesc scan = (HeapScanDesc) sscan;
1439 : :
1440 : : /*
1441 : : * This is still widely used directly, without going through table AM, so
1442 : : * add a safety check. It's possible we should, at a later point,
1443 : : * downgrade this to an assert. The reason for checking the AM routine,
1444 : : * rather than the AM oid, is that this allows to write regression tests
1445 : : * that create another AM reusing the heap handler.
1446 : : */
1447 [ - + ]: 11933377 : if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
2750 andres@anarazel.de 1448 [ # # ]:UBC 0 : ereport(ERROR,
1449 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1450 : : errmsg_internal("only heap AM is supported")));
1451 : :
1452 : : /* Note: no locking manipulations needed */
1453 : :
2681 andres@anarazel.de 1454 [ + + ]:CBC 11933377 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
7516 neilc@samurai.com 1455 : 3027719 : heapgettup_pagemode(scan, direction,
2750 andres@anarazel.de 1456 : 3027719 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1457 : : else
1458 : 8905658 : heapgettup(scan, direction,
1459 : 8905658 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1460 : :
7603 tgl@sss.pgh.pa.us 1461 [ + + ]: 11933377 : if (scan->rs_ctup.t_data == NULL)
8889 1462 : 75093 : return NULL;
1463 : :
1464 : : /*
1465 : : * if we get here it means we have a new current scan tuple, so point to
1466 : : * the proper return buffer and return the tuple.
1467 : : */
1468 : :
2750 andres@anarazel.de 1469 [ - + - - : 11858284 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - - + ]
1470 : :
1471 : 11858284 : return &scan->rs_ctup;
1472 : : }
1473 : :
1474 : : bool
1475 : 60060508 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1476 : : {
1477 : 60060508 : HeapScanDesc scan = (HeapScanDesc) sscan;
1478 : :
1479 : : /* Note: no locking manipulations needed */
1480 : :
2681 1481 [ + + ]: 60060508 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1482 : 59469925 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1483 : : else
1484 : 590583 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1485 : :
2750 1486 [ + + ]: 60060479 : if (scan->rs_ctup.t_data == NULL)
1487 : : {
1488 : 813535 : ExecClearTuple(slot);
1489 : 813535 : return false;
1490 : : }
1491 : :
1492 : : /*
1493 : : * if we get here it means we have a new current scan tuple, so point to
1494 : : * the proper return buffer and return the tuple.
1495 : : */
1496 : :
1497 [ + + - + : 59246944 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ + - + ]
1498 : :
1499 : 59246944 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1500 : : scan->rs_cbuf);
1501 : 59246944 : return true;
1502 : : }
1503 : :
1504 : : void
2031 drowley@postgresql.o 1505 : 1370 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
1506 : : ItemPointer maxtid)
1507 : : {
1508 : 1370 : HeapScanDesc scan = (HeapScanDesc) sscan;
1509 : : BlockNumber startBlk;
1510 : : BlockNumber numBlks;
1511 : : ItemPointerData highestItem;
1512 : : ItemPointerData lowestItem;
1513 : :
1514 : : /*
1515 : : * For relations without any pages, we can simply leave the TID range
1516 : : * unset. There will be no tuples to scan, therefore no tuples outside
1517 : : * the given TID range.
1518 : : */
1519 [ + + ]: 1370 : if (scan->rs_nblocks == 0)
1520 : 32 : return;
1521 : :
1522 : : /*
1523 : : * Set up some ItemPointers which point to the first and last possible
1524 : : * tuples in the heap.
1525 : : */
1526 : 1362 : ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1527 : 1362 : ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1528 : :
1529 : : /*
1530 : : * If the given maximum TID is below the highest possible TID in the
1531 : : * relation, then restrict the range to that, otherwise we scan to the end
1532 : : * of the relation.
1533 : : */
1534 [ + + ]: 1362 : if (ItemPointerCompare(maxtid, &highestItem) < 0)
1535 : 172 : ItemPointerCopy(maxtid, &highestItem);
1536 : :
1537 : : /*
1538 : : * If the given minimum TID is above the lowest possible TID in the
1539 : : * relation, then restrict the range to only scan for TIDs above that.
1540 : : */
1541 [ + + ]: 1362 : if (ItemPointerCompare(mintid, &lowestItem) > 0)
1542 : 1206 : ItemPointerCopy(mintid, &lowestItem);
1543 : :
1544 : : /*
1545 : : * Check for an empty range and protect from would be negative results
1546 : : * from the numBlks calculation below.
1547 : : */
1548 [ + + ]: 1362 : if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1549 : : {
1550 : : /* Set an empty range of blocks to scan */
1551 : 24 : heap_setscanlimits(sscan, 0, 0);
1552 : 24 : return;
1553 : : }
1554 : :
1555 : : /*
1556 : : * Calculate the first block and the number of blocks we must scan. We
1557 : : * could be more aggressive here and perform some more validation to try
1558 : : * and further narrow the scope of blocks to scan by checking if the
1559 : : * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1560 : : * advance startBlk by one. Likewise, if highestItem has an offset of 0
1561 : : * we could scan one fewer blocks. However, such an optimization does not
1562 : : * seem worth troubling over, currently.
1563 : : */
1564 : 1338 : startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1565 : :
1566 : 1338 : numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1567 : 1338 : ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1568 : :
1569 : : /* Set the start block and number of blocks to scan */
1570 : 1338 : heap_setscanlimits(sscan, startBlk, numBlks);
1571 : :
1572 : : /* Finally, set the TID range in sscan */
695 melanieplageman@gmai 1573 : 1338 : ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1574 : 1338 : ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1575 : : }
1576 : :
1577 : : bool
2031 drowley@postgresql.o 1578 : 6508 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1579 : : TupleTableSlot *slot)
1580 : : {
1581 : 6508 : HeapScanDesc scan = (HeapScanDesc) sscan;
695 melanieplageman@gmai 1582 : 6508 : ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
1583 : 6508 : ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
1584 : :
1585 : : /* Note: no locking manipulations needed */
1586 : : for (;;)
1587 : : {
2031 drowley@postgresql.o 1588 [ + - ]: 6632 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1589 : 6632 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1590 : : else
2031 drowley@postgresql.o 1591 :UBC 0 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1592 : :
2031 drowley@postgresql.o 1593 [ + + ]:CBC 6622 : if (scan->rs_ctup.t_data == NULL)
1594 : : {
1595 : 138 : ExecClearTuple(slot);
1596 : 138 : return false;
1597 : : }
1598 : :
1599 : : /*
1600 : : * heap_set_tidrange will have used heap_setscanlimits to limit the
1601 : : * range of pages we scan to only ones that can contain the TID range
1602 : : * we're scanning for. Here we must filter out any tuples from these
1603 : : * pages that are outside of that range.
1604 : : */
1605 [ + + ]: 6484 : if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1606 : : {
1607 : 124 : ExecClearTuple(slot);
1608 : :
1609 : : /*
1610 : : * When scanning backwards, the TIDs will be in descending order.
1611 : : * Future tuples in this direction will be lower still, so we can
1612 : : * just return false to indicate there will be no more tuples.
1613 : : */
1614 [ - + ]: 124 : if (ScanDirectionIsBackward(direction))
2031 drowley@postgresql.o 1615 :UBC 0 : return false;
1616 : :
2031 drowley@postgresql.o 1617 :CBC 124 : continue;
1618 : : }
1619 : :
1620 : : /*
1621 : : * Likewise for the final page, we must filter out TIDs greater than
1622 : : * maxtid.
1623 : : */
1624 [ + + ]: 6360 : if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1625 : : {
1626 : 74 : ExecClearTuple(slot);
1627 : :
1628 : : /*
1629 : : * When scanning forward, the TIDs will be in ascending order.
1630 : : * Future tuples in this direction will be higher still, so we can
1631 : : * just return false to indicate there will be no more tuples.
1632 : : */
1633 [ + - ]: 74 : if (ScanDirectionIsForward(direction))
1634 : 74 : return false;
2031 drowley@postgresql.o 1635 :UBC 0 : continue;
1636 : : }
1637 : :
2031 drowley@postgresql.o 1638 :CBC 6286 : break;
1639 : : }
1640 : :
1641 : : /*
1642 : : * if we get here it means we have a new current scan tuple, so point to
1643 : : * the proper return buffer and return the tuple.
1644 : : */
1645 [ - + - - : 6286 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - - + ]
1646 : :
1647 : 6286 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1648 : 6286 : return true;
1649 : : }
1650 : :
1651 : : /*
1652 : : * heap_fetch - retrieve tuple with given tid
1653 : : *
1654 : : * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1655 : : * the tuple, fill in the remaining fields of *tuple, and check the tuple
1656 : : * against the specified snapshot.
1657 : : *
1658 : : * If successful (tuple found and passes snapshot time qual), then *userbuf
1659 : : * is set to the buffer holding the tuple and true is returned. The caller
1660 : : * must unpin the buffer when done with the tuple.
1661 : : *
1662 : : * If the tuple is not found (ie, item number references a deleted slot),
1663 : : * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1664 : : * and false is returned.
1665 : : *
1666 : : * If the tuple is found but fails the time qual check, then the behavior
1667 : : * depends on the keep_buf parameter. If keep_buf is false, the results
1668 : : * are the same as for the tuple-not-found case. If keep_buf is true,
1669 : : * then tuple->t_data and *userbuf are returned as for the success case,
1670 : : * and again the caller must unpin the buffer; but false is returned.
1671 : : *
1672 : : * heap_fetch does not follow HOT chains: only the exact TID requested will
1673 : : * be fetched.
1674 : : *
1675 : : * It is somewhat inconsistent that we ereport() on invalid block number but
1676 : : * return false on invalid item number. There are a couple of reasons though.
1677 : : * One is that the caller can relatively easily check the block number for
1678 : : * validity, but cannot check the item number without reading the page
1679 : : * himself. Another is that when we are following a t_ctid link, we can be
1680 : : * reasonably confident that the page number is valid (since VACUUM shouldn't
1681 : : * truncate off the destination page without having killed the referencing
1682 : : * tuple first), but the item number might well not be good.
1683 : : */
1684 : : bool
11030 scrappy@hub.org 1685 : 2862352 : heap_fetch(Relation relation,
1686 : : Snapshot snapshot,
1687 : : HeapTuple tuple,
1688 : : Buffer *userbuf,
1689 : : bool keep_buf)
1690 : : {
8885 tgl@sss.pgh.pa.us 1691 : 2862352 : ItemPointer tid = &(tuple->t_self);
1692 : : ItemId lp;
1693 : : Buffer buffer;
1694 : : Page page;
1695 : : OffsetNumber offnum;
1696 : : bool valid;
1697 : :
1698 : : /*
1699 : : * Fetch and pin the appropriate page of the relation.
1700 : : */
6744 1701 : 2862352 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1702 : :
1703 : : /*
1704 : : * Need share lock on buffer to examine tuple commit status.
1705 : : */
10141 vadim4o@yahoo.com 1706 : 2862344 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3805 kgrittn@postgresql.o 1707 : 2862344 : page = BufferGetPage(buffer);
1708 : :
1709 : : /*
1710 : : * We'd better check for out-of-range offnum in case of VACUUM since the
1711 : : * TID was obtained.
1712 : : */
10605 bruce@momjian.us 1713 : 2862344 : offnum = ItemPointerGetOffsetNumber(tid);
6643 tgl@sss.pgh.pa.us 1714 [ + - + + ]: 2862344 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1715 : : {
177 andres@anarazel.de 1716 : 4 : UnlockReleaseBuffer(buffer);
2738 1717 : 4 : *userbuf = InvalidBuffer;
7847 tgl@sss.pgh.pa.us 1718 : 4 : tuple->t_data = NULL;
1719 : 4 : return false;
1720 : : }
1721 : :
1722 : : /*
1723 : : * get the item line pointer corresponding to the requested tid
1724 : : */
6643 1725 : 2862340 : lp = PageGetItemId(page, offnum);
1726 : :
1727 : : /*
1728 : : * Must check for deleted tuple.
1729 : : */
6948 1730 [ + + ]: 2862340 : if (!ItemIdIsNormal(lp))
1731 : : {
177 andres@anarazel.de 1732 : 332 : UnlockReleaseBuffer(buffer);
2738 1733 : 332 : *userbuf = InvalidBuffer;
8885 tgl@sss.pgh.pa.us 1734 : 332 : tuple->t_data = NULL;
1735 : 332 : return false;
1736 : : }
1737 : :
1738 : : /*
1739 : : * fill in *tuple fields
1740 : : */
6643 1741 : 2862008 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10159 vadim4o@yahoo.com 1742 : 2862008 : tuple->t_len = ItemIdGetLength(lp);
7701 tgl@sss.pgh.pa.us 1743 : 2862008 : tuple->t_tableOid = RelationGetRelid(relation);
1744 : :
1745 : : /*
1746 : : * check tuple visibility, then release lock
1747 : : */
7603 1748 : 2862008 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1749 : :
5704 heikki.linnakangas@i 1750 [ + + ]: 2862008 : if (valid)
2427 tmunro@postgresql.or 1751 : 2861922 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1752 : 2861922 : HeapTupleHeaderGetXmin(tuple->t_data));
1753 : :
1754 : 2862008 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1755 : :
5679 heikki.linnakangas@i 1756 : 2862008 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1757 : :
8885 tgl@sss.pgh.pa.us 1758 [ + + ]: 2862008 : if (valid)
1759 : : {
1760 : : /*
1761 : : * All checks passed, so return the tuple as valid. Caller is now
1762 : : * responsible for releasing the buffer.
1763 : : */
9858 1764 : 2861922 : *userbuf = buffer;
1765 : :
8885 1766 : 2861922 : return true;
1767 : : }
1768 : :
1769 : : /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1621 1770 [ + + ]: 86 : if (keep_buf)
1771 : 40 : *userbuf = buffer;
1772 : : else
1773 : : {
1774 : 46 : ReleaseBuffer(buffer);
1775 : 46 : *userbuf = InvalidBuffer;
1776 : 46 : tuple->t_data = NULL;
1777 : : }
1778 : :
8885 1779 : 86 : return false;
1780 : : }
1781 : :
1782 : : /*
1783 : : * heap_get_latest_tid - get the latest tid of a specified tuple
1784 : : *
1785 : : * Actually, this gets the latest version that is visible according to the
1786 : : * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1787 : : * possibly uncommitted version.
1788 : : *
1789 : : * *tid is both an input and an output parameter: it is updated to
1790 : : * show the latest version of the row. Note that it will not be changed
1791 : : * if no version of the row passes the snapshot test.
1792 : : */
1793 : : void
2683 andres@anarazel.de 1794 : 207 : heap_get_latest_tid(TableScanDesc sscan,
1795 : : ItemPointer tid)
1796 : : {
2678 tgl@sss.pgh.pa.us 1797 : 207 : Relation relation = sscan->rs_rd;
1798 : 207 : Snapshot snapshot = sscan->rs_snapshot;
1799 : : ItemPointerData ctid;
1800 : : TransactionId priorXmax;
1801 : :
1802 : : /*
1803 : : * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1804 : : * Assume that t_ctid links are valid however - there shouldn't be invalid
1805 : : * ones in the table.
1806 : : */
2683 andres@anarazel.de 1807 [ - + ]: 207 : Assert(ItemPointerIsValid(tid));
1808 : :
1809 : : /*
1810 : : * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1811 : : * need to examine, and *tid is the TID we will return if ctid turns out
1812 : : * to be bogus.
1813 : : *
1814 : : * Note that we will loop until we reach the end of the t_ctid chain.
1815 : : * Depending on the snapshot passed, there might be at most one visible
1816 : : * version of the row, but we don't try to optimize for that.
1817 : : */
7701 tgl@sss.pgh.pa.us 1818 : 207 : ctid = *tid;
1819 : 207 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1820 : : for (;;)
1821 : 64 : {
1822 : : Buffer buffer;
1823 : : Page page;
1824 : : OffsetNumber offnum;
1825 : : ItemId lp;
1826 : : HeapTupleData tp;
1827 : : bool valid;
1828 : :
1829 : : /*
1830 : : * Read, pin, and lock the page.
1831 : : */
1832 : 271 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1833 : 271 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3805 kgrittn@postgresql.o 1834 : 271 : page = BufferGetPage(buffer);
1835 : :
1836 : : /*
1837 : : * Check for bogus item number. This is not treated as an error
1838 : : * condition because it can happen while following a t_ctid link. We
1839 : : * just assume that the prior tid is OK and return it unchanged.
1840 : : */
7701 tgl@sss.pgh.pa.us 1841 : 271 : offnum = ItemPointerGetOffsetNumber(&ctid);
6643 1842 [ + - - + ]: 271 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1843 : : {
7478 tgl@sss.pgh.pa.us 1844 :UBC 0 : UnlockReleaseBuffer(buffer);
7701 1845 : 0 : break;
1846 : : }
6643 tgl@sss.pgh.pa.us 1847 :CBC 271 : lp = PageGetItemId(page, offnum);
6948 1848 [ - + ]: 271 : if (!ItemIdIsNormal(lp))
1849 : : {
7478 tgl@sss.pgh.pa.us 1850 :UBC 0 : UnlockReleaseBuffer(buffer);
7701 1851 : 0 : break;
1852 : : }
1853 : :
1854 : : /* OK to access the tuple */
7701 tgl@sss.pgh.pa.us 1855 :CBC 271 : tp.t_self = ctid;
6643 1856 : 271 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
7701 1857 : 271 : tp.t_len = ItemIdGetLength(lp);
4808 rhaas@postgresql.org 1858 : 271 : tp.t_tableOid = RelationGetRelid(relation);
1859 : :
1860 : : /*
1861 : : * After following a t_ctid link, we might arrive at an unrelated
1862 : : * tuple. Check for XMIN match.
1863 : : */
7701 tgl@sss.pgh.pa.us 1864 [ + + - + ]: 335 : if (TransactionIdIsValid(priorXmax) &&
3244 alvherre@alvh.no-ip. 1865 : 64 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1866 : : {
7478 tgl@sss.pgh.pa.us 1867 :UBC 0 : UnlockReleaseBuffer(buffer);
7701 1868 : 0 : break;
1869 : : }
1870 : :
1871 : : /*
1872 : : * Check tuple visibility; if visible, set it as the new result
1873 : : * candidate.
1874 : : */
7603 tgl@sss.pgh.pa.us 1875 :CBC 271 : valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2427 tmunro@postgresql.or 1876 : 271 : HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
7701 tgl@sss.pgh.pa.us 1877 [ + + ]: 271 : if (valid)
1878 : 191 : *tid = ctid;
1879 : :
1880 : : /*
1881 : : * If there's a valid t_ctid link, follow it, else we're done.
1882 : : */
4988 alvherre@alvh.no-ip. 1883 [ + + + + ]: 391 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1884 [ + - ]: 200 : HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
3088 andres@anarazel.de 1885 [ + + ]: 160 : HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
7701 tgl@sss.pgh.pa.us 1886 : 80 : ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1887 : : {
7478 1888 : 207 : UnlockReleaseBuffer(buffer);
7701 1889 : 207 : break;
1890 : : }
1891 : :
1892 : 64 : ctid = tp.t_data->t_ctid;
4988 alvherre@alvh.no-ip. 1893 : 64 : priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
7478 tgl@sss.pgh.pa.us 1894 : 64 : UnlockReleaseBuffer(buffer);
1895 : : } /* end of loop */
9841 inoue@tpf.co.jp 1896 : 207 : }
1897 : :
1898 : :
1899 : : /*
1900 : : * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1901 : : *
1902 : : * This is called after we have waited for the XMAX transaction to terminate.
1903 : : * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1904 : : * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1905 : : * hint bit if possible --- but beware that that may not yet be possible,
1906 : : * if the transaction committed asynchronously.
1907 : : *
1908 : : * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1909 : : * even if it commits.
1910 : : *
1911 : : * Hence callers should look only at XMAX_INVALID.
1912 : : *
1913 : : * Note this is not allowed for tuples whose xmax is a multixact.
1914 : : */
1915 : : static void
6977 tgl@sss.pgh.pa.us 1916 : 239 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1917 : : {
4988 alvherre@alvh.no-ip. 1918 [ - + ]: 239 : Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1919 [ - + ]: 239 : Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1920 : :
6977 tgl@sss.pgh.pa.us 1921 [ + + ]: 239 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1922 : : {
4988 alvherre@alvh.no-ip. 1923 [ + + + + ]: 425 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1924 : 187 : TransactionIdDidCommit(xid))
6977 tgl@sss.pgh.pa.us 1925 : 160 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1926 : : xid);
1927 : : else
1928 : 78 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1929 : : InvalidTransactionId);
1930 : : }
1931 : 239 : }
1932 : :
1933 : :
1934 : : /*
1935 : : * GetBulkInsertState - prepare status object for a bulk insert
1936 : : */
1937 : : BulkInsertState
6527 1938 : 3143 : GetBulkInsertState(void)
1939 : : {
1940 : : BulkInsertState bistate;
1941 : :
284 michael@paquier.xyz 1942 : 3143 : bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
6527 tgl@sss.pgh.pa.us 1943 : 3143 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1944 : 3143 : bistate->current_buf = InvalidBuffer;
1263 andres@anarazel.de 1945 : 3143 : bistate->next_free = InvalidBlockNumber;
1946 : 3143 : bistate->last_free = InvalidBlockNumber;
1133 1947 : 3143 : bistate->already_extended_by = 0;
6527 tgl@sss.pgh.pa.us 1948 : 3143 : return bistate;
1949 : : }
1950 : :
1951 : : /*
1952 : : * FreeBulkInsertState - clean up after finishing a bulk insert
1953 : : */
1954 : : void
1955 : 2907 : FreeBulkInsertState(BulkInsertState bistate)
1956 : : {
1957 [ + + ]: 2907 : if (bistate->current_buf != InvalidBuffer)
6310 bruce@momjian.us 1958 : 2373 : ReleaseBuffer(bistate->current_buf);
6527 tgl@sss.pgh.pa.us 1959 : 2907 : FreeAccessStrategy(bistate->strategy);
1960 : 2907 : pfree(bistate);
1961 : 2907 : }
1962 : :
1963 : : /*
1964 : : * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
1965 : : */
1966 : : void
3526 rhaas@postgresql.org 1967 : 90779 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
1968 : : {
1969 [ + + ]: 90779 : if (bistate->current_buf != InvalidBuffer)
1970 : 40028 : ReleaseBuffer(bistate->current_buf);
1971 : 90779 : bistate->current_buf = InvalidBuffer;
1972 : :
1973 : : /*
1974 : : * Despite the name, we also reset bulk relation extension state.
1975 : : * Otherwise we can end up erroring out due to looking for free space in
1976 : : * ->next_free of one partition, even though ->next_free was set when
1977 : : * extending another partition. It could obviously also be bad for
1978 : : * efficiency to look at existing blocks at offsets from another
1979 : : * partition, even if we don't error out.
1980 : : */
1073 andres@anarazel.de 1981 : 90779 : bistate->next_free = InvalidBlockNumber;
1982 : 90779 : bistate->last_free = InvalidBlockNumber;
3526 rhaas@postgresql.org 1983 : 90779 : }
1984 : :
1985 : :
1986 : : /*
1987 : : * heap_insert - insert tuple into a heap
1988 : : *
1989 : : * The new tuple is stamped with current transaction ID and the specified
1990 : : * command ID.
1991 : : *
1992 : : * See table_tuple_insert for comments about most of the input flags, except
1993 : : * that this routine directly takes a tuple rather than a slot.
1994 : : *
1995 : : * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
1996 : : * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
1997 : : * implement table_tuple_insert_speculative().
1998 : : *
1999 : : * On return the header fields of *tup are updated to match the stored tuple;
2000 : : * in particular tup->t_self receives the actual TID where the tuple was
2001 : : * stored. But note that any toasting of fields within the tuple data is NOT
2002 : : * reflected into *tup.
2003 : : */
2004 : : void
7762 tgl@sss.pgh.pa.us 2005 : 11899437 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2006 : : uint32 options, BulkInsertState bistate)
2007 : : {
8039 2008 : 11899437 : TransactionId xid = GetCurrentTransactionId();
2009 : : HeapTuple heaptup;
2010 : : Buffer buffer;
2011 : : Page page;
5570 rhaas@postgresql.org 2012 : 11899437 : Buffer vmbuffer = InvalidBuffer;
67 melanieplageman@gmai 2013 : 11899437 : bool clear_all_visible = false;
2014 : 11899437 : bool vmbuffer_modified = false;
2015 : :
2016 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1959 tgl@sss.pgh.pa.us 2017 [ - + ]: 11899437 : Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
2018 : : RelationGetNumberOfAttributes(relation));
2019 : :
478 nathan@postgresql.or 2020 : 11899437 : AssertHasSnapshotForToast(relation);
2021 : :
2022 : : /*
2023 : : * Fill in tuple header fields and toast the tuple if necessary.
2024 : : *
2025 : : * Note: below this point, heaptup is the data we actually intend to store
2026 : : * into the relation; tup is the caller's original untoasted data.
2027 : : */
5429 heikki.linnakangas@i 2028 : 11899437 : heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2029 : :
2030 : : /*
2031 : : * Find buffer to insert this tuple into. If the page is all visible,
2032 : : * this will also pin the requisite visibility map page.
2033 : : */
3977 kgrittn@postgresql.o 2034 : 11899437 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2035 : : InvalidBuffer, options, bistate,
2036 : : &vmbuffer, NULL,
2037 : : 0);
2038 : :
174 melanieplageman@gmai 2039 : 11899435 : page = BufferGetPage(buffer);
2040 : :
2041 : : /*
2042 : : * We're about to do the actual insert -- but check for conflict first, to
2043 : : * avoid possibly having to roll back work we've just done.
2044 : : *
2045 : : * This is safe without a recheck as long as there is no possibility of
2046 : : * another process scanning the page between this check and the insert
2047 : : * being visible to the scan (i.e., an exclusive buffer content lock is
2048 : : * continuously held from this point until the tuple insert is visible).
2049 : : *
2050 : : * For a heap insert, we only need to check for table-level SSI locks. Our
2051 : : * new tuple can't possibly conflict with existing tuple locks, and heap
2052 : : * page locks are only consolidated versions of tuple locks; they do not
2053 : : * lock "gaps" as index page locks do. So we don't need to specify a
2054 : : * buffer when making the call, which makes for a faster check.
2055 : : */
2427 tmunro@postgresql.or 2056 : 11899435 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2057 : :
2058 : : /* Lock the vmbuffer before the critical section */
67 melanieplageman@gmai 2059 [ + + ]: 11899418 : if (PageIsAllVisible(page))
2060 : : {
2061 : 9693 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2062 : 9693 : clear_all_visible = true;
2063 : : }
2064 : :
2065 : : /* NO EREPORT(ERROR) from here till changes are logged */
9382 tgl@sss.pgh.pa.us 2066 : 11899418 : START_CRIT_SECTION();
2067 : :
4153 andres@anarazel.de 2068 : 11899418 : RelationPutHeapTuple(relation, buffer, heaptup,
2069 : 11899418 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2070 : :
67 melanieplageman@gmai 2071 [ + + ]: 11899418 : if (clear_all_visible)
2072 : : {
2073 : : /* It's possible the VM bits were already clear */
67 melanieplageman@gmai 2074 [ + + ]:GNC 9693 : if (visibilitymap_clear(relation->rd_locator,
67 melanieplageman@gmai 2075 :CBC 9693 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2076 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
2077 : 9690 : vmbuffer_modified = true;
2078 : :
174 2079 : 9693 : PageClearAllVisible(page);
2080 : : }
2081 : :
2082 : : /*
2083 : : * Set pd_prune_xid to trigger heap_page_prune_and_freeze() once the page
2084 : : * is full so that we can set the page all-visible in the VM on the next
2085 : : * page access.
2086 : : *
2087 : : * Setting pd_prune_xid is also handy if the inserting transaction
2088 : : * eventually aborts making this tuple DEAD and hence available for
2089 : : * pruning. If no other tuple in this page is UPDATEd/DELETEd, the aborted
2090 : : * tuple would never otherwise be pruned until next vacuum is triggered.
2091 : : *
2092 : : * Don't set it if we are in bootstrap mode or we are inserting a frozen
2093 : : * tuple, as there is no further pruning/freezing needed in those cases.
2094 : : */
2095 [ + + + + ]: 11899418 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
2096 [ - + + + : 11235643 : PageSetPrunable(page, xid);
+ + ]
2097 : :
7478 tgl@sss.pgh.pa.us 2098 : 11899418 : MarkBufferDirty(buffer);
2099 : :
2100 : : /* XLOG stuff */
2360 noah@leadboat.com 2101 [ + + + + : 11899418 : if (RelationNeedsWAL(relation))
+ + + + ]
2102 : : {
2103 : : xl_heap_insert xlrec;
2104 : : xl_heap_header xlhdr;
2105 : : XLogRecPtr recptr;
9313 bruce@momjian.us 2106 : 10681304 : uint8 info = XLOG_HEAP_INSERT;
4322 heikki.linnakangas@i 2107 : 10681304 : int bufflags = 0;
2108 : :
2109 : : /*
2110 : : * If this is a catalog, we need to transmit combo CIDs to properly
2111 : : * decode, so log that as well.
2112 : : */
4667 rhaas@postgresql.org 2113 [ + + + + : 10681304 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
2114 : 3825 : log_heap_new_cid(relation, heaptup);
2115 : :
2116 : : /*
2117 : : * If this is the single and first tuple on page, we can reinit the
2118 : : * page instead of restoring the whole thing. Set flag, and hide
2119 : : * buffer references from XLogInsert.
2120 : : */
4322 heikki.linnakangas@i 2121 [ + + + + ]: 10803764 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2122 : 122460 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2123 : : {
2124 : 120794 : info |= XLOG_HEAP_INIT_PAGE;
2125 : 120794 : bufflags |= REGBUF_WILL_INIT;
2126 : : }
2127 : :
2128 : 10681304 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
4153 andres@anarazel.de 2129 : 10681304 : xlrec.flags = 0;
67 melanieplageman@gmai 2130 [ + + ]: 10681304 : if (clear_all_visible)
4153 andres@anarazel.de 2131 : 9614 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2132 [ + + ]: 10681304 : if (options & HEAP_INSERT_SPECULATIVE)
2133 : 2255 : xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
4322 heikki.linnakangas@i 2134 [ - + ]: 10681304 : Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2135 : :
2136 : : /*
2137 : : * For logical decoding, we need the tuple even if we're doing a full
2138 : : * page write, so make sure it's included even if we take a full-page
2139 : : * image. (XXX We could alternatively store a pointer into the FPW).
2140 : : */
2902 andres@anarazel.de 2141 [ + + + + : 10681304 : if (RelationIsLogicallyLogged(relation) &&
+ - - + -
- - - + -
+ + ]
2142 [ + + ]: 278479 : !(options & HEAP_INSERT_NO_LOGICAL))
2143 : : {
4153 2144 : 278332 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
4322 heikki.linnakangas@i 2145 : 278332 : bufflags |= REGBUF_KEEP_DATA;
2146 : :
2234 akapila@postgresql.o 2147 [ + + ]: 278332 : if (IsToastRelation(relation))
2148 : 1907 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2149 : : }
2150 : :
4322 heikki.linnakangas@i 2151 : 10681304 : XLogBeginInsert();
586 peter@eisentraut.org 2152 : 10681304 : XLogRegisterData(&xlrec, SizeOfHeapInsert);
2153 : :
4322 heikki.linnakangas@i 2154 : 10681304 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2155 : 10681304 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2156 : 10681304 : xlhdr.t_hoff = heaptup->t_data->t_hoff;
2157 : :
2158 : : /*
2159 : : * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2160 : : * write the whole page to the xlog, we don't need to store
2161 : : * xl_heap_header in the xlog.
2162 : : */
67 melanieplageman@gmai 2163 : 10681304 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_HEAP, buffer,
2164 : 10681304 : REGBUF_STANDARD | bufflags);
2165 : 10681304 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP, &xlhdr,
2166 : : SizeOfHeapHeader);
2167 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2168 : 10681304 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP,
4229 tgl@sss.pgh.pa.us 2169 : 10681304 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2170 : 10681304 : heaptup->t_len - SizeofHeapTupleHeader);
2171 : :
2172 : : /* filtering by origin on a row level is much more efficient */
3559 andres@anarazel.de 2173 : 10681304 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2174 : :
67 melanieplageman@gmai 2175 [ + + ]: 10681304 : if (vmbuffer_modified)
2176 : 9611 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_VM, vmbuffer, 0);
2177 : :
4322 heikki.linnakangas@i 2178 : 10681304 : recptr = XLogInsert(RM_HEAP_ID, info);
2179 : :
9397 vadim4o@yahoo.com 2180 : 10681304 : PageSetLSN(page, recptr);
2181 : :
67 melanieplageman@gmai 2182 [ + + ]: 10681304 : if (vmbuffer_modified)
2183 : 9611 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2184 : : }
2185 : :
9382 tgl@sss.pgh.pa.us 2186 [ - + ]: 11899418 : END_CRIT_SECTION();
2187 : :
7478 2188 : 11899418 : UnlockReleaseBuffer(buffer);
2189 : :
2190 : : /*
2191 : : * We locked vmbuffer if clear_all_visible was true regardless of whether
2192 : : * or not we ended up modifying the vmbuffer.
2193 : : */
67 melanieplageman@gmai 2194 [ + + ]: 11899418 : if (clear_all_visible)
2195 : 9693 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2196 [ + + ]: 11899418 : if (BufferIsValid(vmbuffer))
5570 rhaas@postgresql.org 2197 : 10048 : ReleaseBuffer(vmbuffer);
2198 : :
2199 : : /*
2200 : : * If tuple is cacheable, mark it for invalidation from the caches in case
2201 : : * we abort. Note it is OK to do this after releasing the buffer, because
2202 : : * the heaptup data structure is all in local memory, not in the shared
2203 : : * buffer.
2204 : : */
5514 tgl@sss.pgh.pa.us 2205 : 11899418 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2206 : :
2207 : : /* Note: speculative insertions are counted too, even if aborted later */
5429 heikki.linnakangas@i 2208 : 11899418 : pgstat_count_heap_insert(relation, 1);
2209 : :
2210 : : /*
2211 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
2212 : : * back to the caller's image, too.
2213 : : */
7609 tgl@sss.pgh.pa.us 2214 [ + + ]: 11899418 : if (heaptup != tup)
2215 : : {
2216 : 22251 : tup->t_self = heaptup->t_self;
2217 : 22251 : heap_freetuple(heaptup);
2218 : : }
11030 scrappy@hub.org 2219 : 11899418 : }
2220 : :
2221 : : /*
2222 : : * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2223 : : * tuple header fields and toasts the tuple if necessary. Returns a toasted
2224 : : * version of the tuple if it was toasted, or the original tuple if not. Note
2225 : : * that in any case, the header fields are also set in the original tuple.
2226 : : */
2227 : : static HeapTuple
5429 heikki.linnakangas@i 2228 : 13687912 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2229 : : CommandId cid, uint32 options)
2230 : : {
2231 : : /*
2232 : : * To allow parallel inserts, we need to ensure that they are safe to be
2233 : : * performed in workers. We have the infrastructure to allow parallel
2234 : : * inserts in general except for the cases where inserts generate a new
2235 : : * CommandId (eg. inserts into a table having a foreign key column).
2236 : : */
3272 rhaas@postgresql.org 2237 [ - + ]: 13687912 : if (IsParallelWorker())
4161 rhaas@postgresql.org 2238 [ # # ]:UBC 0 : ereport(ERROR,
2239 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2240 : : errmsg("cannot insert tuples in a parallel worker")));
2241 : :
5429 heikki.linnakangas@i 2242 :CBC 13687912 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2243 : 13687912 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2244 : 13687912 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
4655 rhaas@postgresql.org 2245 : 13687912 : HeapTupleHeaderSetXmin(tup->t_data, xid);
5040 simon@2ndQuadrant.co 2246 [ + + ]: 13687912 : if (options & HEAP_INSERT_FROZEN)
4655 rhaas@postgresql.org 2247 : 102652 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2248 : :
5429 heikki.linnakangas@i 2249 : 13687912 : HeapTupleHeaderSetCmin(tup->t_data, cid);
3378 tgl@sss.pgh.pa.us 2250 : 13687912 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
5429 heikki.linnakangas@i 2251 : 13687912 : tup->t_tableOid = RelationGetRelid(relation);
2252 : :
2253 : : /*
2254 : : * If the new tuple is too big for storage or contains already toasted
2255 : : * out-of-line attributes from some other relation, invoke the toaster.
2256 : : */
4949 kgrittn@postgresql.o 2257 [ + + ]: 13687912 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2258 [ + + ]: 40996 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2259 : : {
2260 : : /* toast table entries should never be recursively toasted */
5429 heikki.linnakangas@i 2261 [ - + ]: 40935 : Assert(!HeapTupleHasExternal(tup));
2262 : 40935 : return tup;
2263 : : }
2264 [ + + + + ]: 13646977 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2543 rhaas@postgresql.org 2265 : 22326 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2266 : : else
5429 heikki.linnakangas@i 2267 : 13624651 : return tup;
2268 : : }
2269 : :
2270 : : /*
2271 : : * Helper for heap_multi_insert() that computes the number of entire pages
2272 : : * that inserting the remaining heaptuples requires. Used to determine how
2273 : : * much the relation needs to be extended by.
2274 : : */
2275 : : static int
1263 andres@anarazel.de 2276 : 465245 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2277 : : {
2278 : 465245 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2279 : 465245 : int npages = 1;
2280 : :
2281 [ + + ]: 2937606 : for (int i = done; i < ntuples; i++)
2282 : : {
2283 : 2472361 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2284 : :
2285 [ + + ]: 2472361 : if (page_avail < tup_sz)
2286 : : {
2287 : 17601 : npages++;
2288 : 17601 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2289 : : }
2290 : 2472361 : page_avail -= tup_sz;
2291 : : }
2292 : :
2293 : 465245 : return npages;
2294 : : }
2295 : :
2296 : : /*
2297 : : * heap_multi_insert - insert multiple tuples into a heap
2298 : : *
2299 : : * This is like heap_insert(), but inserts multiple tuples in one operation.
2300 : : * That's faster than calling heap_insert() in a loop, because when multiple
2301 : : * tuples can be inserted on a single page, we can write just a single WAL
2302 : : * record covering all of them, and only need to lock/unlock the page once.
2303 : : *
2304 : : * Note: this leaks memory into the current memory context. You can create a
2305 : : * temporary context before calling this, if that's a problem.
2306 : : */
2307 : : void
2726 2308 : 457108 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2309 : : CommandId cid, uint32 options, BulkInsertState bistate)
2310 : : {
5429 heikki.linnakangas@i 2311 : 457108 : TransactionId xid = GetCurrentTransactionId();
2312 : : HeapTuple *heaptuples;
2313 : : int i;
2314 : : int ndone;
2315 : : PGAlignedBlock scratch;
2316 : : Page page;
2072 tomas.vondra@postgre 2317 : 457108 : Buffer vmbuffer = InvalidBuffer;
2318 : : bool needwal;
2319 : : Size saveFreeSpace;
4667 rhaas@postgresql.org 2320 [ + + + + : 457108 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
+ - - + -
- - - + -
+ + ]
2321 [ + + + + : 457108 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
+ - - + -
- - - + +
- + - - -
- - - ]
1263 andres@anarazel.de 2322 : 457108 : bool starting_with_empty_page = false;
2323 : 457108 : int npages = 0;
2324 : 457108 : int npages_used = 0;
2325 : :
2326 : : /* currently not needed (thus unsupported) for heap_multi_insert() */
1423 peter@eisentraut.org 2327 [ - + ]: 457108 : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2328 : :
478 nathan@postgresql.or 2329 : 457108 : AssertHasSnapshotForToast(relation);
2330 : :
2360 noah@leadboat.com 2331 [ + + + + : 457108 : needwal = RelationNeedsWAL(relation);
+ - + + ]
892 akorotkov@postgresql 2332 [ + + ]: 457108 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2333 : : HEAP_DEFAULT_FILLFACTOR);
2334 : :
2335 : : /* Toast and set header data in all the slots */
34 michael@paquier.xyz 2336 :GNC 457108 : heaptuples = palloc_array(HeapTuple, ntuples);
5429 heikki.linnakangas@i 2337 [ + + ]:CBC 2245583 : for (i = 0; i < ntuples; i++)
2338 : : {
2339 : : HeapTuple tuple;
2340 : :
2726 andres@anarazel.de 2341 : 1788475 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2342 : 1788475 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2343 : 1788475 : tuple->t_tableOid = slots[i]->tts_tableOid;
2344 : 1788475 : heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2345 : : options);
2346 : : }
2347 : :
2348 : : /*
2349 : : * We're about to do the actual inserts -- but check for conflict first,
2350 : : * to minimize the possibility of having to roll back work we've just
2351 : : * done.
2352 : : *
2353 : : * A check here does not definitively prevent a serialization anomaly;
2354 : : * that check MUST be done at least past the point of acquiring an
2355 : : * exclusive buffer content lock on every buffer that will be affected,
2356 : : * and MAY be done after all inserts are reflected in the buffers and
2357 : : * those locks are released; otherwise there is a race condition. Since
2358 : : * multiple buffers can be locked and unlocked in the loop below, and it
2359 : : * would not be feasible to identify and lock all of those buffers before
2360 : : * the loop, we must do a final check at the end.
2361 : : *
2362 : : * The check here could be omitted with no loss of correctness; it is
2363 : : * present strictly as an optimization.
2364 : : *
2365 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2366 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2367 : : * page locks are only consolidated versions of tuple locks; they do not
2368 : : * lock "gaps" as index page locks do. So we don't need to specify a
2369 : : * buffer when making the call, which makes for a faster check.
2370 : : */
2427 tmunro@postgresql.or 2371 : 457108 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2372 : :
5429 heikki.linnakangas@i 2373 : 457108 : ndone = 0;
2374 [ + + ]: 931597 : while (ndone < ntuples)
2375 : : {
2376 : : Buffer buffer;
67 melanieplageman@gmai 2377 : 474489 : bool clear_all_visible = false;
2072 tomas.vondra@postgre 2378 : 474489 : bool all_frozen_set = false;
67 melanieplageman@gmai 2379 : 474489 : bool vmbuffer_modified = false;
2380 : : int nthispage;
2381 : :
4472 rhaas@postgresql.org 2382 [ + + ]: 474489 : CHECK_FOR_INTERRUPTS();
2383 : :
2384 : : /*
2385 : : * Compute number of pages needed to fit the to-be-inserted tuples in
2386 : : * the worst case. This will be used to determine how much to extend
2387 : : * the relation by in RelationGetBufferForTuple(), if needed. If we
2388 : : * filled a prior page from scratch, we can just update our last
2389 : : * computation, but if we started with a partially filled page,
2390 : : * recompute from scratch, the number of potentially required pages
2391 : : * can vary due to tuples needing to fit onto the page, page headers
2392 : : * etc.
2393 : : */
1263 andres@anarazel.de 2394 [ + + + + ]: 474489 : if (ndone == 0 || !starting_with_empty_page)
2395 : : {
2396 : 465245 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2397 : : saveFreeSpace);
2398 : 465245 : npages_used = 0;
2399 : : }
2400 : : else
2401 : 9244 : npages_used++;
2402 : :
2403 : : /*
2404 : : * Find buffer where at least the next tuple will fit. If the page is
2405 : : * all-visible, this will also pin the requisite visibility map page.
2406 : : *
2407 : : * Also pin visibility map page if COPY FREEZE inserts tuples into an
2408 : : * empty page. See all_frozen_set below.
2409 : : */
5429 heikki.linnakangas@i 2410 : 474489 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2411 : : InvalidBuffer, options, bistate,
2412 : : &vmbuffer, NULL,
2413 : : npages - npages_used);
3805 kgrittn@postgresql.o 2414 : 474489 : page = BufferGetPage(buffer);
2415 : :
2072 tomas.vondra@postgre 2416 : 474489 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2417 : :
2418 [ + + + + ]: 474489 : if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2419 : : {
2420 : 1665 : all_frozen_set = true;
2421 : : /* Lock the vmbuffer before entering the critical section */
346 melanieplageman@gmai 2422 : 1665 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2423 : : }
67 2424 [ + + + + ]: 472824 : else if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2425 : : {
2426 : 6783 : clear_all_visible = true;
2427 : : /* Lock the vmbuffer before entering the critical section */
2428 : 6783 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2429 : : }
2430 : :
2431 : : /* NO EREPORT(ERROR) from here till changes are logged */
5429 heikki.linnakangas@i 2432 : 474489 : START_CRIT_SECTION();
2433 : :
2434 : : /*
2435 : : * RelationGetBufferForTuple has ensured that the first tuple fits.
2436 : : * Put that on the page, and then as many other tuples as fit.
2437 : : */
4153 andres@anarazel.de 2438 : 474489 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2439 : :
2440 : : /*
2441 : : * For logical decoding we need combo CIDs to properly decode the
2442 : : * catalog.
2443 : : */
2399 michael@paquier.xyz 2444 [ + + + + ]: 474489 : if (needwal && need_cids)
2445 : 5583 : log_heap_new_cid(relation, heaptuples[ndone]);
2446 : :
5030 heikki.linnakangas@i 2447 [ + + ]: 1788475 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2448 : : {
5429 2449 : 1331367 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2450 : :
5240 2451 [ + + ]: 1331367 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
5429 2452 : 17381 : break;
2453 : :
4153 andres@anarazel.de 2454 : 1313986 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2455 : :
2456 : : /*
2457 : : * For logical decoding we need combo CIDs to properly decode the
2458 : : * catalog.
2459 : : */
4322 heikki.linnakangas@i 2460 [ + + + + ]: 1313986 : if (needwal && need_cids)
2461 : 5181 : log_heap_new_cid(relation, heaptup);
2462 : : }
2463 : :
2464 : : /*
2465 : : * If the page is all visible, need to clear that, unless we're only
2466 : : * going to add further frozen rows to it.
2467 : : *
2468 : : * If we're only adding already frozen rows to a previously empty
2469 : : * page, mark it as all-frozen and update the visibility map. We're
2470 : : * already holding a pin on the vmbuffer.
2471 : : */
67 melanieplageman@gmai 2472 [ + + ]: 474489 : if (clear_all_visible)
2473 : : {
2474 [ - + ]: 6783 : Assert(!(options & HEAP_INSERT_FROZEN));
2475 : : /* It's possible the VM bits were already clear */
67 melanieplageman@gmai 2476 [ + + ]:GNC 6783 : if (visibilitymap_clear(relation->rd_locator,
2477 : : BufferGetBlockNumber(buffer),
2478 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
67 melanieplageman@gmai 2479 :CBC 6782 : vmbuffer_modified = true;
2480 : :
5218 rhaas@postgresql.org 2481 : 6783 : PageClearAllVisible(page);
2482 : : }
2072 tomas.vondra@postgre 2483 [ + + ]: 467706 : else if (all_frozen_set)
2484 : : {
2485 : 1665 : PageSetAllVisible(page);
202 melanieplageman@gmai 2486 : 1665 : PageClearPrunable(page);
6 2487 : 1665 : (void) visibilitymap_set(BufferGetBlockNumber(buffer),
2488 : : vmbuffer,
2489 : : VISIBILITYMAP_ALL_VISIBLE |
2490 : : VISIBILITYMAP_ALL_FROZEN,
2491 : : relation->rd_locator);
2492 : : }
2493 : :
2494 : : /*
2495 : : * Set pd_prune_xid. See heap_insert() for more on why we do this when
2496 : : * inserting tuples. This only makes sense if the tuples aren't frozen
2497 : : * and we're not in bootstrap mode.
2498 : : */
2499 [ + + + + ]: 474489 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
174 2500 [ - + + + : 451496 : PageSetPrunable(page, xid);
+ + ]
2501 : :
5429 heikki.linnakangas@i 2502 : 474489 : MarkBufferDirty(buffer);
2503 : :
2504 : : /* XLOG stuff */
2505 [ + + ]: 474489 : if (needwal)
2506 : : {
2507 : : XLogRecPtr recptr;
2508 : : xl_heap_multi_insert *xlrec;
2509 : 470590 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2510 : : char *tupledata;
2511 : : int totaldatalen;
2941 tgl@sss.pgh.pa.us 2512 : 470590 : char *scratchptr = scratch.data;
2513 : : bool init;
4322 heikki.linnakangas@i 2514 : 470590 : int bufflags = 0;
2515 : :
2516 : : /*
2517 : : * If the page was previously empty, we can reinit the page
2518 : : * instead of restoring the whole thing.
2519 : : */
2072 tomas.vondra@postgre 2520 : 470590 : init = starting_with_empty_page;
2521 : :
2522 : : /* allocate xl_heap_multi_insert struct from the scratch area */
5429 heikki.linnakangas@i 2523 : 470590 : xlrec = (xl_heap_multi_insert *) scratchptr;
2524 : 470590 : scratchptr += SizeOfHeapMultiInsert;
2525 : :
2526 : : /*
2527 : : * Allocate offsets array. Unless we're reinitializing the page,
2528 : : * in that case the tuples are stored in order starting at
2529 : : * FirstOffsetNumber and we don't need to store the offsets
2530 : : * explicitly.
2531 : : */
2532 [ + + ]: 470590 : if (!init)
2533 : 456329 : scratchptr += nthispage * sizeof(OffsetNumber);
2534 : :
2535 : : /* the rest of the scratch space is used for tuple data */
2536 : 470590 : tupledata = scratchptr;
2537 : :
2538 : : /* check that the mutually exclusive flags are not both set */
67 melanieplageman@gmai 2539 [ + + - + ]: 470590 : Assert(!(clear_all_visible && all_frozen_set));
2540 : :
2072 tomas.vondra@postgre 2541 : 470590 : xlrec->flags = 0;
67 melanieplageman@gmai 2542 [ + + ]: 470590 : if (clear_all_visible)
2072 tomas.vondra@postgre 2543 : 6783 : xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
2544 : :
2545 : : /*
2546 : : * We don't have to worry about including a conflict xid in the
2547 : : * WAL record, as HEAP_INSERT_FROZEN intentionally violates
2548 : : * visibility rules.
2549 : : */
2550 [ + + ]: 470590 : if (all_frozen_set)
2551 : 21 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2552 : :
5429 heikki.linnakangas@i 2553 : 470590 : xlrec->ntuples = nthispage;
2554 : :
2555 : : /*
2556 : : * Write out an xl_multi_insert_tuple and the tuple data itself
2557 : : * for each tuple.
2558 : : */
2559 [ + + ]: 2051890 : for (i = 0; i < nthispage; i++)
2560 : : {
2561 : 1581300 : HeapTuple heaptup = heaptuples[ndone + i];
2562 : : xl_multi_insert_tuple *tuphdr;
2563 : : int datalen;
2564 : :
2565 [ + + ]: 1581300 : if (!init)
2566 : 952805 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2567 : : /* xl_multi_insert_tuple needs two-byte alignment. */
2568 : 1581300 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2569 : 1581300 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2570 : :
2571 : 1581300 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2572 : 1581300 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2573 : 1581300 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2574 : :
2575 : : /* write bitmap [+ padding] [+ oid] + data */
4229 tgl@sss.pgh.pa.us 2576 : 1581300 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
5429 heikki.linnakangas@i 2577 : 1581300 : memcpy(scratchptr,
4229 tgl@sss.pgh.pa.us 2578 : 1581300 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2579 : : datalen);
5429 heikki.linnakangas@i 2580 : 1581300 : tuphdr->datalen = datalen;
2581 : 1581300 : scratchptr += datalen;
2582 : : }
2583 : 470590 : totaldatalen = scratchptr - tupledata;
2941 tgl@sss.pgh.pa.us 2584 [ - + ]: 470590 : Assert((scratchptr - scratch.data) < BLCKSZ);
2585 : :
4667 rhaas@postgresql.org 2586 [ + + ]: 470590 : if (need_tuple_data)
4153 andres@anarazel.de 2587 : 75 : xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2588 : :
2589 : : /*
2590 : : * Signal that this is the last xl_heap_multi_insert record
2591 : : * emitted by this call to heap_multi_insert(). Needed for logical
2592 : : * decoding so it knows when to cleanup temporary data.
2593 : : */
4322 heikki.linnakangas@i 2594 [ + + ]: 470590 : if (ndone + nthispage == ntuples)
4153 andres@anarazel.de 2595 : 456654 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2596 : :
5429 heikki.linnakangas@i 2597 [ + + ]: 470590 : if (init)
2598 : : {
2599 : 14261 : info |= XLOG_HEAP_INIT_PAGE;
4322 2600 : 14261 : bufflags |= REGBUF_WILL_INIT;
2601 : : }
2602 : :
2603 : : /*
2604 : : * If we're doing logical decoding, include the new tuple data
2605 : : * even if we take a full-page image of the page.
2606 : : */
2607 [ + + ]: 470590 : if (need_tuple_data)
2608 : 75 : bufflags |= REGBUF_KEEP_DATA;
2609 : :
2610 : 470590 : XLogBeginInsert();
586 peter@eisentraut.org 2611 : 470590 : XLogRegisterData(xlrec, tupledata - scratch.data);
67 melanieplageman@gmai 2612 : 470590 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_HEAP, buffer,
2613 : 470590 : REGBUF_STANDARD | bufflags);
2614 [ + + + + ]: 470590 : if (all_frozen_set || vmbuffer_modified)
2615 : 6803 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_VM, vmbuffer, 0);
2616 : :
2617 : 470590 : XLogRegisterBufData(HEAP_MULTI_INSERT_BLKREF_HEAP, tupledata,
2618 : : totaldatalen);
2619 : :
2620 : : /* filtering by origin on a row level is much more efficient */
3559 andres@anarazel.de 2621 : 470590 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2622 : :
4322 heikki.linnakangas@i 2623 : 470590 : recptr = XLogInsert(RM_HEAP2_ID, info);
2624 : :
5429 2625 : 470590 : PageSetLSN(page, recptr);
67 melanieplageman@gmai 2626 [ + + + + ]: 470590 : if (all_frozen_set || vmbuffer_modified)
2627 : : {
346 2628 [ - + ]: 6803 : Assert(BufferIsDirty(vmbuffer));
2629 : 6803 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2630 : : }
2631 : : }
2632 : :
5429 heikki.linnakangas@i 2633 [ - + ]: 474489 : END_CRIT_SECTION();
2634 : :
2635 : : /*
2636 : : * We locked vmbuffer if clear_all_visible was true regardless of
2637 : : * whether or not we ended up modifying the vmbuffer.
2638 : : */
67 melanieplageman@gmai 2639 [ + + + + ]: 474489 : if (all_frozen_set || clear_all_visible)
346 2640 : 8448 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2641 : :
2072 tomas.vondra@postgre 2642 : 474489 : UnlockReleaseBuffer(buffer);
5429 heikki.linnakangas@i 2643 : 474489 : ndone += nthispage;
2644 : :
2645 : : /*
2646 : : * NB: Only release vmbuffer after inserting all tuples - it's fairly
2647 : : * likely that we'll insert into subsequent heap pages that are likely
2648 : : * to use the same vm page.
2649 : : */
2650 : : }
2651 : :
2652 : : /* We're done with inserting all tuples, so release the last vmbuffer. */
2072 tomas.vondra@postgre 2653 [ + + ]: 457108 : if (vmbuffer != InvalidBuffer)
2654 : 6798 : ReleaseBuffer(vmbuffer);
2655 : :
2656 : : /*
2657 : : * We're done with the actual inserts. Check for conflicts again, to
2658 : : * ensure that all rw-conflicts in to these inserts are detected. Without
2659 : : * this final check, a sequential scan of the heap may have locked the
2660 : : * table after the "before" check, missing one opportunity to detect the
2661 : : * conflict, and then scanned the table before the new tuples were there,
2662 : : * missing the other chance to detect the conflict.
2663 : : *
2664 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2665 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2666 : : * page locks are only consolidated versions of tuple locks; they do not
2667 : : * lock "gaps" as index page locks do. So we don't need to specify a
2668 : : * buffer when making the call.
2669 : : */
2427 tmunro@postgresql.or 2670 : 457108 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2671 : :
2672 : : /*
2673 : : * If tuples are cacheable, mark them for invalidation from the caches in
2674 : : * case we abort. Note it is OK to do this after releasing the buffer,
2675 : : * because the heaptuples data structure is all in local memory, not in
2676 : : * the shared buffer.
2677 : : */
4679 rhaas@postgresql.org 2678 [ + + ]: 457108 : if (IsCatalogRelation(relation))
2679 : : {
5429 heikki.linnakangas@i 2680 [ + + ]: 1530719 : for (i = 0; i < ntuples; i++)
2681 : 1075090 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2682 : : }
2683 : :
2684 : : /* copy t_self fields back to the caller's slots */
5333 2685 [ + + ]: 2245583 : for (i = 0; i < ntuples; i++)
2726 andres@anarazel.de 2686 : 1788475 : slots[i]->tts_tid = heaptuples[i]->t_self;
2687 : :
5429 heikki.linnakangas@i 2688 : 457108 : pgstat_count_heap_insert(relation, ntuples);
2689 : 457108 : }
2690 : :
2691 : : /*
2692 : : * simple_heap_insert - insert a tuple
2693 : : *
2694 : : * Currently, this routine differs from heap_insert only in supplying
2695 : : * a default command ID and not allowing access to the speedup options.
2696 : : *
2697 : : * This should be used rather than using heap_insert directly in most places
2698 : : * where we are modifying system catalogs.
2699 : : */
2700 : : void
8888 tgl@sss.pgh.pa.us 2701 : 1085109 : simple_heap_insert(Relation relation, HeapTuple tup)
2702 : : {
2861 andres@anarazel.de 2703 : 1085109 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
8888 tgl@sss.pgh.pa.us 2704 : 1085109 : }
2705 : :
2706 : : /*
2707 : : * Given infomask/infomask2, compute the bits that must be saved in the
2708 : : * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2709 : : * xl_heap_lock_updated WAL records.
2710 : : *
2711 : : * See fix_infomask_from_infobits.
2712 : : */
2713 : : static uint8
4988 alvherre@alvh.no-ip. 2714 : 6488401 : compute_infobits(uint16 infomask, uint16 infomask2)
2715 : : {
2716 : : return
2717 : 6488401 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2718 : 6488401 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2719 : 6488401 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2720 : : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2721 : 12976802 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2722 : : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2723 : 6488401 : XLHL_KEYS_UPDATED : 0);
2724 : : }
2725 : :
2726 : : /*
2727 : : * Given two versions of the same t_infomask for a tuple, compare them and
2728 : : * return whether the relevant status for a tuple Xmax has changed. This is
2729 : : * used after a buffer lock has been released and reacquired: we want to ensure
2730 : : * that the tuple state continues to be the same it was when we previously
2731 : : * examined it.
2732 : : *
2733 : : * Note the Xmax field itself must be compared separately.
2734 : : */
2735 : : static inline bool
4532 2736 : 5410 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2737 : : {
4520 bruce@momjian.us 2738 : 5410 : const uint16 interesting =
2739 : : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2740 : :
4532 alvherre@alvh.no-ip. 2741 [ + + ]: 5410 : if ((new_infomask & interesting) != (old_infomask & interesting))
2742 : 15 : return true;
2743 : :
2744 : 5395 : return false;
2745 : : }
2746 : :
2747 : : /*
2748 : : * heap_delete - delete a tuple
2749 : : *
2750 : : * See table_tuple_delete() for an explanation of the parameters, except that
2751 : : * this routine directly takes a tuple rather than a slot.
2752 : : *
2753 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2754 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2755 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2756 : : * generated by another transaction).
2757 : : */
2758 : : TM_Result
325 peter@eisentraut.org 2759 : 1848054 : heap_delete(Relation relation, const ItemPointerData *tid,
2760 : : CommandId cid, uint32 options, Snapshot crosscheck,
2761 : : bool wait, TM_FailureData *tmfd)
2762 : : {
2763 : : TM_Result result;
8039 tgl@sss.pgh.pa.us 2764 : 1848054 : TransactionId xid = GetCurrentTransactionId();
2765 : : ItemId lp;
2766 : : HeapTupleData tp;
2767 : : Page page;
2768 : : BlockNumber block;
2769 : : Buffer buffer;
5570 rhaas@postgresql.org 2770 : 1848054 : Buffer vmbuffer = InvalidBuffer;
67 melanieplageman@gmai 2771 : 1848054 : bool vmbuffer_modified = false;
2772 : : TransactionId new_xmax;
2773 : : uint16 new_infomask,
2774 : : new_infomask2;
172 alvherre@kurilemu.de 2775 : 1848054 : bool changingPart = (options & TABLE_DELETE_CHANGING_PARTITION) != 0;
167 2776 : 1848054 : bool walLogical = (options & TABLE_DELETE_NO_LOGICAL) == 0;
7813 tgl@sss.pgh.pa.us 2777 : 1848054 : bool have_tuple_lock = false;
2778 : : bool iscombo;
67 melanieplageman@gmai 2779 : 1848054 : bool clear_all_visible = false;
4520 bruce@momjian.us 2780 : 1848054 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
4667 rhaas@postgresql.org 2781 : 1848054 : bool old_key_copied = false;
2782 : :
10605 bruce@momjian.us 2783 [ - + ]: 1848054 : Assert(ItemPointerIsValid(tid));
2784 : :
478 nathan@postgresql.or 2785 : 1848054 : AssertHasSnapshotForToast(relation);
2786 : :
2787 : : /*
2788 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
2789 : : * Other workers might need that combo CID for visibility checks, and we
2790 : : * have no provision for broadcasting it to them.
2791 : : */
4161 rhaas@postgresql.org 2792 [ - + ]: 1848054 : if (IsInParallelMode())
4161 rhaas@postgresql.org 2793 [ # # ]:UBC 0 : ereport(ERROR,
2794 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2795 : : errmsg("cannot delete tuples during a parallel operation")));
2796 : :
5570 rhaas@postgresql.org 2797 :CBC 1848054 : block = ItemPointerGetBlockNumber(tid);
2798 : 1848054 : buffer = ReadBuffer(relation, block);
3805 kgrittn@postgresql.o 2799 : 1848054 : page = BufferGetPage(buffer);
2800 : :
2801 : : /*
2802 : : * Before locking the buffer, pin the visibility map page if it appears to
2803 : : * be necessary. Since we haven't got the lock yet, someone else might be
2804 : : * in the middle of changing this, so we'll need to recheck after we have
2805 : : * the lock.
2806 : : */
5570 rhaas@postgresql.org 2807 [ + + ]: 1848054 : if (PageIsAllVisible(page))
2808 : 2096 : visibilitymap_pin(relation, block, &vmbuffer);
2809 : :
10141 vadim4o@yahoo.com 2810 : 1848054 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2811 : :
1459 jdavis@postgresql.or 2812 : 1848054 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2813 [ - + ]: 1848054 : Assert(ItemIdIsNormal(lp));
2814 : :
2815 : 1848054 : tp.t_tableOid = RelationGetRelid(relation);
2816 : 1848054 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2817 : 1848054 : tp.t_len = ItemIdGetLength(lp);
2818 : 1848054 : tp.t_self = *tid;
2819 : :
2820 : 1 : l1:
2821 : :
2822 : : /*
2823 : : * If we didn't pin the visibility map page and the page has become all
2824 : : * visible while we were busy locking the buffer, we'll have to unlock and
2825 : : * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2826 : : * unfortunate, but hopefully shouldn't happen often.
2827 : : */
5570 rhaas@postgresql.org 2828 [ + + - + ]: 1848055 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2829 : : {
5570 rhaas@postgresql.org 2830 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2831 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
2832 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2833 : : }
2834 : :
4808 rhaas@postgresql.org 2835 :CBC 1848055 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2836 : :
2738 andres@anarazel.de 2837 [ - + ]: 1848055 : if (result == TM_Invisible)
2838 : : {
7478 tgl@sss.pgh.pa.us 2839 :UBC 0 : UnlockReleaseBuffer(buffer);
4067 2840 [ # # ]: 0 : ereport(ERROR,
2841 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2842 : : errmsg("attempted to delete invisible tuple")));
2843 : : }
892 akorotkov@postgresql 2844 [ + + + - ]:CBC 1848055 : else if (result == TM_BeingModified && wait)
2845 : : {
2846 : : TransactionId xwait;
2847 : : uint16 infomask;
2848 : :
2849 : : /* must copy state data before unlocking buffer */
4988 alvherre@alvh.no-ip. 2850 : 40602 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
7813 tgl@sss.pgh.pa.us 2851 : 40602 : infomask = tp.t_data->t_infomask;
2852 : :
2853 : : /*
2854 : : * Sleep until concurrent transaction ends -- except when there's a
2855 : : * single locker and it's our own transaction. Note we don't care
2856 : : * which lock mode the locker has, because we need the strongest one.
2857 : : *
2858 : : * Before sleeping, we need to acquire tuple lock to establish our
2859 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
2860 : : * release us when we are next-in-line for the tuple.
2861 : : *
2862 : : * If we are forced to "start over" below, we keep the tuple lock;
2863 : : * this arranges that we stay at the head of the line while rechecking
2864 : : * tuple state.
2865 : : */
7815 2866 [ + + ]: 40602 : if (infomask & HEAP_XMAX_IS_MULTI)
2867 : : {
2651 alvherre@alvh.no-ip. 2868 : 8 : bool current_is_member = false;
2869 : :
4181 2870 [ + - ]: 8 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2871 : : LockTupleExclusive, ¤t_is_member))
2872 : : {
2873 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2874 : :
2875 : : /*
2876 : : * Acquire the lock, if necessary (but skip it when we're
2877 : : * requesting a lock and already have one; avoids deadlock).
2878 : : */
2651 2879 [ + + ]: 8 : if (!current_is_member)
2880 : 6 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2881 : : LockWaitBlock, &have_tuple_lock);
2882 : :
2883 : : /* wait for multixact */
4181 2884 : 8 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2885 : : relation, &(tp.t_self), XLTW_Delete,
2886 : : NULL);
2887 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2888 : :
2889 : : /*
2890 : : * If xwait had just locked the tuple then some other xact
2891 : : * could update this tuple before we get to this point. Check
2892 : : * for xmax change, and start over if so.
2893 : : *
2894 : : * We also must start over if we didn't pin the VM page, and
2895 : : * the page has become all visible.
2896 : : */
1459 jdavis@postgresql.or 2897 [ + - + - : 16 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ - ]
2898 [ - + ]: 16 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4181 alvherre@alvh.no-ip. 2899 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2900 : : xwait))
4181 alvherre@alvh.no-ip. 2901 :UBC 0 : goto l1;
2902 : : }
2903 : :
2904 : : /*
2905 : : * You might think the multixact is necessarily done here, but not
2906 : : * so: it could have surviving members, namely our own xact or
2907 : : * other subxacts of this backend. It is legal for us to delete
2908 : : * the tuple in either case, however (the latter case is
2909 : : * essentially a situation of upgrading our former shared lock to
2910 : : * exclusive). We don't bother changing the on-disk hint bits
2911 : : * since we are about to overwrite the xmax altogether.
2912 : : */
2913 : : }
4181 alvherre@alvh.no-ip. 2914 [ + + ]:CBC 40594 : else if (!TransactionIdIsCurrentTransactionId(xwait))
2915 : : {
2916 : : /*
2917 : : * Wait for regular transaction to end; but first, acquire tuple
2918 : : * lock.
2919 : : */
2920 : 53 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2921 : 53 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2922 : : LockWaitBlock, &have_tuple_lock);
4246 heikki.linnakangas@i 2923 : 53 : XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
7815 tgl@sss.pgh.pa.us 2924 : 49 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2925 : :
2926 : : /*
2927 : : * xwait is done, but if xwait had just locked the tuple then some
2928 : : * other xact could update this tuple before we get to this point.
2929 : : * Check for xmax change, and start over if so.
2930 : : *
2931 : : * We also must start over if we didn't pin the VM page, and the
2932 : : * page has become all visible.
2933 : : */
1459 jdavis@postgresql.or 2934 [ + - + - : 98 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ + ]
2935 [ - + ]: 97 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4988 alvherre@alvh.no-ip. 2936 : 48 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2937 : : xwait))
7815 tgl@sss.pgh.pa.us 2938 : 1 : goto l1;
2939 : :
2940 : : /* Otherwise check if it committed or aborted */
6977 2941 : 48 : UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2942 : : }
2943 : :
2944 : : /*
2945 : : * We may overwrite if previous xmax aborted, or if it committed but
2946 : : * only locked the tuple without updating it.
2947 : : */
4988 alvherre@alvh.no-ip. 2948 [ + + + + ]: 81174 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2949 [ + + ]: 40609 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2950 : 32 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2738 andres@anarazel.de 2951 : 40569 : result = TM_Ok;
2036 alvherre@alvh.no-ip. 2952 [ + + ]: 28 : else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2738 andres@anarazel.de 2953 : 24 : result = TM_Updated;
2954 : : else
2955 : 4 : result = TM_Deleted;
2956 : : }
2957 : :
2958 : : /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2959 [ + + ]: 1848050 : if (result != TM_Ok)
2960 : : {
2961 [ + + + + : 69 : Assert(result == TM_SelfModified ||
- + - - ]
2962 : : result == TM_Updated ||
2963 : : result == TM_Deleted ||
2964 : : result == TM_BeingModified);
7701 tgl@sss.pgh.pa.us 2965 [ - + ]: 69 : Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2738 andres@anarazel.de 2966 [ + + - + ]: 69 : Assert(result != TM_Updated ||
2967 : : !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2968 : : }
2969 : :
1027 heikki.linnakangas@i 2970 [ + + + - ]: 1848050 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
2971 : : {
2972 : : /* Perform additional check for transaction-snapshot mode RI updates */
2973 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2974 : 1 : result = TM_Updated;
2975 : : }
2976 : :
2977 [ + + ]: 1848050 : if (result != TM_Ok)
2978 : : {
2738 andres@anarazel.de 2979 : 70 : tmfd->ctid = tp.t_data->t_ctid;
2980 : 70 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2981 [ + + ]: 70 : if (result == TM_SelfModified)
2982 : 28 : tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2983 : : else
2984 : 42 : tmfd->cmax = InvalidCommandId;
892 akorotkov@postgresql 2985 : 70 : UnlockReleaseBuffer(buffer);
7813 tgl@sss.pgh.pa.us 2986 [ + + ]: 70 : if (have_tuple_lock)
4988 alvherre@alvh.no-ip. 2987 : 28 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
5570 rhaas@postgresql.org 2988 [ - + ]: 70 : if (vmbuffer != InvalidBuffer)
5570 rhaas@postgresql.org 2989 :UBC 0 : ReleaseBuffer(vmbuffer);
10141 vadim4o@yahoo.com 2990 :CBC 70 : return result;
2991 : : }
2992 : :
2993 : : /*
2994 : : * We're about to do the actual delete -- check for conflict first, to
2995 : : * avoid possibly having to roll back work we've just done.
2996 : : *
2997 : : * This is safe without a recheck as long as there is no possibility of
2998 : : * another process scanning the page between this check and the delete
2999 : : * being visible to the scan (i.e., an exclusive buffer content lock is
3000 : : * continuously held from this point until the tuple delete is visible).
3001 : : */
2427 tmunro@postgresql.or 3002 : 1847980 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
3003 : :
3004 : : /* replace cid with a combo CID if necessary */
7163 tgl@sss.pgh.pa.us 3005 : 1847966 : HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
3006 : :
3007 : : /*
3008 : : * Compute replica identity tuple before entering the critical section so
3009 : : * we don't PANIC upon a memory allocation failure.
3010 : : */
167 alvherre@kurilemu.de 3011 : 1847966 : old_key_tuple = walLogical ?
3012 [ + + ]: 1847966 : ExtractReplicaIdentity(relation, &tp, true, &old_key_copied) : NULL;
3013 : :
3014 : : /*
3015 : : * If this is the first possibly-multixact-able operation in the current
3016 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
3017 : : * certain that the transaction will never become a member of any older
3018 : : * MultiXactIds than that. (We have to do this even if we end up just
3019 : : * using our own TransactionId below, since some other backend could
3020 : : * incorporate our XID into a MultiXact immediately afterwards.)
3021 : : */
4552 heikki.linnakangas@i 3022 : 1847966 : MultiXactIdSetOldestMember();
3023 : :
3024 : 1847966 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
3025 : 1847966 : tp.t_data->t_infomask, tp.t_data->t_infomask2,
3026 : : xid, LockTupleExclusive, true,
3027 : : &new_xmax, &new_infomask, &new_infomask2);
3028 : :
3029 : : /* Lock the VM before entering the critical section */
67 melanieplageman@gmai 3030 [ + + ]: 1847966 : if (PageIsAllVisible(page))
3031 : : {
3032 : 2096 : clear_all_visible = true;
3033 : 2096 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3034 : : }
3035 : :
9382 tgl@sss.pgh.pa.us 3036 : 1847966 : START_CRIT_SECTION();
3037 : :
3038 : : /*
3039 : : * If this transaction commits, the tuple will become DEAD sooner or
3040 : : * later. Set flag that this page is a candidate for pruning once our xid
3041 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
3042 : : * the subsequent page pruning will be a no-op and the hint will be
3043 : : * cleared.
3044 : : */
6643 3045 [ - + + + : 1847966 : PageSetPrunable(page, xid);
+ + ]
3046 : :
67 melanieplageman@gmai 3047 [ + + ]: 1847966 : if (clear_all_visible)
3048 : : {
3049 : : /* It's possible the VM bits were already clear */
67 melanieplageman@gmai 3050 [ + - ]:GNC 2096 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(buffer),
3051 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
67 melanieplageman@gmai 3052 :CBC 2096 : vmbuffer_modified = true;
3053 : :
6500 heikki.linnakangas@i 3054 : 2096 : PageClearAllVisible(page);
3055 : : }
3056 : :
3057 : : /* store transaction information of xact deleting the tuple */
4988 alvherre@alvh.no-ip. 3058 : 1847966 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3059 : 1847966 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3060 : 1847966 : tp.t_data->t_infomask |= new_infomask;
3061 : 1847966 : tp.t_data->t_infomask2 |= new_infomask2;
6940 tgl@sss.pgh.pa.us 3062 : 1847966 : HeapTupleHeaderClearHotUpdated(tp.t_data);
4988 alvherre@alvh.no-ip. 3063 : 1847966 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
7163 tgl@sss.pgh.pa.us 3064 : 1847966 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3065 : : /* Make sure there is no forward chain link in t_ctid */
8804 3066 : 1847966 : tp.t_data->t_ctid = tp.t_self;
3067 : :
3068 : : /* Signal that this is actually a move into another partition */
3088 andres@anarazel.de 3069 [ + + ]: 1847966 : if (changingPart)
3070 : 635 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
3071 : :
7478 tgl@sss.pgh.pa.us 3072 : 1847966 : MarkBufferDirty(buffer);
3073 : :
3074 : : /*
3075 : : * XLOG stuff
3076 : : *
3077 : : * NB: heap_abort_speculative() uses the same xlog record and replay
3078 : : * routines.
3079 : : */
5760 rhaas@postgresql.org 3080 [ + + + + : 1847966 : if (RelationNeedsWAL(relation))
+ - + + ]
3081 : : {
3082 : : xl_heap_delete xlrec;
3083 : : xl_heap_header xlhdr;
3084 : : XLogRecPtr recptr;
3085 : :
3086 : : /*
3087 : : * For logical decode we need combo CIDs to properly decode the
3088 : : * catalog
3089 : : */
4667 3090 [ + + + + : 1739555 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- - + ]
3091 : 7366 : log_heap_new_cid(relation, &tp);
3092 : :
3088 andres@anarazel.de 3093 : 1739555 : xlrec.flags = 0;
67 melanieplageman@gmai 3094 [ + + ]: 1739555 : if (clear_all_visible)
3088 andres@anarazel.de 3095 : 2038 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3096 [ + + ]: 1739555 : if (changingPart)
3097 : 635 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
4988 alvherre@alvh.no-ip. 3098 : 3479110 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3099 : 1739555 : tp.t_data->t_infomask2);
4322 heikki.linnakangas@i 3100 : 1739555 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
4988 alvherre@alvh.no-ip. 3101 : 1739555 : xlrec.xmax = new_xmax;
3102 : :
4322 heikki.linnakangas@i 3103 [ + + ]: 1739555 : if (old_key_tuple != NULL)
3104 : : {
3105 [ + + ]: 47025 : if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4153 andres@anarazel.de 3106 : 132 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
3107 : : else
3108 : 46893 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
3109 : : }
3110 : :
3111 : : /*
3112 : : * Mark the change as not-for-logical-decoding if caller requested so.
3113 : : *
3114 : : * (This is used for changes that affect relations not visible to
3115 : : * other transactions, such as the transient table during concurrent
3116 : : * repack.)
3117 : : */
167 alvherre@kurilemu.de 3118 [ + + ]: 1739555 : if (!walLogical)
3119 : 3 : xlrec.flags |= XLH_DELETE_NO_LOGICAL;
3120 : :
4322 heikki.linnakangas@i 3121 : 1739555 : XLogBeginInsert();
586 peter@eisentraut.org 3122 : 1739555 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3123 : :
67 melanieplageman@gmai 3124 : 1739555 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3125 : :
3126 : : /*
3127 : : * Log replica identity of the deleted tuple if there is one
3128 : : */
4667 rhaas@postgresql.org 3129 [ + + ]: 1739555 : if (old_key_tuple != NULL)
3130 : : {
3131 : 47025 : xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3132 : 47025 : xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3133 : 47025 : xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3134 : :
586 peter@eisentraut.org 3135 : 47025 : XLogRegisterData(&xlhdr, SizeOfHeapHeader);
4322 heikki.linnakangas@i 3136 : 47025 : XLogRegisterData((char *) old_key_tuple->t_data
3137 : : + SizeofHeapTupleHeader,
3138 : 47025 : old_key_tuple->t_len
3139 : : - SizeofHeapTupleHeader);
3140 : : }
3141 : :
3142 : : /* filtering by origin on a row level is much more efficient */
3559 andres@anarazel.de 3143 : 1739555 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3144 : :
67 melanieplageman@gmai 3145 [ + + ]: 1739555 : if (vmbuffer_modified)
3146 : 2038 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_VM, vmbuffer, 0);
3147 : :
4322 heikki.linnakangas@i 3148 : 1739555 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3149 : :
6643 tgl@sss.pgh.pa.us 3150 : 1739555 : PageSetLSN(page, recptr);
3151 : :
67 melanieplageman@gmai 3152 [ + + ]: 1739555 : if (vmbuffer_modified)
3153 : 2038 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3154 : : }
3155 : :
9382 tgl@sss.pgh.pa.us 3156 [ - + ]: 1847966 : END_CRIT_SECTION();
3157 : :
3158 : : /*
3159 : : * Release VM lock first, since it covers many heap blocks. We locked
3160 : : * vmbuffer if clear_all_visible was true regardless of whether or not we
3161 : : * ended up modifying the vmbuffer.
3162 : : */
67 melanieplageman@gmai 3163 [ + + ]: 1847966 : if (clear_all_visible)
3164 : 2096 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3165 : :
9379 tgl@sss.pgh.pa.us 3166 : 1847966 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3167 : :
5570 rhaas@postgresql.org 3168 [ + + ]: 1847966 : if (vmbuffer != InvalidBuffer)
3169 : 2096 : ReleaseBuffer(vmbuffer);
3170 : :
3171 : : /*
3172 : : * If the tuple has toasted out-of-line attributes, we need to delete
3173 : : * those items too. We have to do this before releasing the buffer
3174 : : * because we need to look at the contents of the tuple, but it's OK to
3175 : : * release the content lock on the buffer first.
3176 : : */
4949 kgrittn@postgresql.o 3177 [ + + ]: 1847966 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3178 [ + + ]: 4484 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3179 : : {
3180 : : /* toast table entries should never be recursively toasted */
7110 tgl@sss.pgh.pa.us 3181 [ - + ]: 4471 : Assert(!HeapTupleHasExternal(&tp));
3182 : : }
3183 [ + + ]: 1843495 : else if (HeapTupleHasExternal(&tp))
2543 rhaas@postgresql.org 3184 : 523 : heap_toast_delete(relation, &tp, false);
3185 : :
3186 : : /*
3187 : : * Mark tuple for invalidation from system caches at next command
3188 : : * boundary. We have to do this before releasing the buffer because we
3189 : : * need to look at the contents of the tuple.
3190 : : */
5514 tgl@sss.pgh.pa.us 3191 : 1847966 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3192 : :
3193 : : /* Now we can release the buffer */
892 akorotkov@postgresql 3194 : 1847966 : ReleaseBuffer(buffer);
3195 : :
3196 : : /*
3197 : : * Release the lmgr tuple lock, if we had it.
3198 : : */
7813 tgl@sss.pgh.pa.us 3199 [ + + ]: 1847966 : if (have_tuple_lock)
4988 alvherre@alvh.no-ip. 3200 : 26 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3201 : :
7056 tgl@sss.pgh.pa.us 3202 : 1847966 : pgstat_count_heap_delete(relation);
3203 : :
4667 rhaas@postgresql.org 3204 [ + + + + ]: 1847966 : if (old_key_tuple != NULL && old_key_copied)
3205 : 46894 : heap_freetuple(old_key_tuple);
3206 : :
2738 andres@anarazel.de 3207 : 1847966 : return TM_Ok;
3208 : : }
3209 : :
3210 : : /*
3211 : : * simple_heap_delete - delete a tuple
3212 : : *
3213 : : * This routine may be used to delete a tuple when concurrent updates of
3214 : : * the target tuple are not expected (for example, because we have a lock
3215 : : * on the relation associated with the tuple). Any failure is reported
3216 : : * via ereport().
3217 : : */
3218 : : void
325 peter@eisentraut.org 3219 : 795613 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
3220 : : {
3221 : : TM_Result result;
3222 : : TM_FailureData tmfd;
3223 : :
8406 tgl@sss.pgh.pa.us 3224 : 795613 : result = heap_delete(relation, tid,
3225 : : GetCurrentCommandId(true),
3226 : : 0,
3227 : : InvalidSnapshot,
3228 : : true /* wait for commit */ ,
3229 : : &tmfd);
9371 3230 [ - + - - : 795613 : switch (result)
- ]
3231 : : {
2738 andres@anarazel.de 3232 :UBC 0 : case TM_SelfModified:
3233 : : /* Tuple was already updated in current command? */
8462 tgl@sss.pgh.pa.us 3234 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
3235 : : break;
3236 : :
2738 andres@anarazel.de 3237 :CBC 795613 : case TM_Ok:
3238 : : /* done successfully */
9371 tgl@sss.pgh.pa.us 3239 : 795613 : break;
3240 : :
2738 andres@anarazel.de 3241 :UBC 0 : case TM_Updated:
8462 tgl@sss.pgh.pa.us 3242 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
3243 : : break;
3244 : :
2738 andres@anarazel.de 3245 : 0 : case TM_Deleted:
3246 [ # # ]: 0 : elog(ERROR, "tuple concurrently deleted");
3247 : : break;
3248 : :
9371 tgl@sss.pgh.pa.us 3249 : 0 : default:
8462 3250 [ # # ]: 0 : elog(ERROR, "unrecognized heap_delete status: %u", result);
3251 : : break;
3252 : : }
9371 tgl@sss.pgh.pa.us 3253 :CBC 795613 : }
3254 : :
3255 : : /*
3256 : : * heap_update - replace a tuple
3257 : : *
3258 : : * See table_tuple_update() for an explanation of the parameters, except that
3259 : : * this routine directly takes a tuple rather than a slot.
3260 : : *
3261 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3262 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3263 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3264 : : * generated by another transaction).
3265 : : */
3266 : : TM_Result
325 peter@eisentraut.org 3267 : 2395394 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
3268 : : CommandId cid, uint32 options, Snapshot crosscheck, bool wait,
3269 : : TM_FailureData *tmfd, LockTupleMode *lockmode,
3270 : : TU_UpdateIndexes *update_indexes)
3271 : : {
3272 : : TM_Result result;
8039 tgl@sss.pgh.pa.us 3273 : 2395394 : TransactionId xid = GetCurrentTransactionId();
3274 : : Bitmapset *hot_attrs;
3275 : : Bitmapset *sum_attrs;
3276 : : Bitmapset *key_attrs;
3277 : : Bitmapset *id_attrs;
3278 : : Bitmapset *interesting_attrs;
3279 : : Bitmapset *modified_attrs;
3280 : : ItemId lp;
3281 : : HeapTupleData oldtup;
3282 : : HeapTuple heaptup;
4667 rhaas@postgresql.org 3283 : 2395394 : HeapTuple old_key_tuple = NULL;
3284 : 2395394 : bool old_key_copied = false;
167 alvherre@kurilemu.de 3285 : 2395394 : bool walLogical = (options & TABLE_UPDATE_NO_LOGICAL) == 0;
3286 : : Page page,
3287 : : newpage;
3288 : : BlockNumber block;
3289 : : MultiXactStatus mxact_status;
3290 : : Buffer buffer,
3291 : : newbuf,
5570 rhaas@postgresql.org 3292 : 2395394 : vmbuffer = InvalidBuffer,
3293 : 2395394 : vmbuffer_new = InvalidBuffer;
67 melanieplageman@gmai 3294 : 2395394 : bool unlock_vmbuffer = false;
3295 : 2395394 : bool unlock_vmbuffer_new = false;
3296 : : bool need_toast;
3297 : : Size newtupsize,
3298 : : pagefree;
7813 tgl@sss.pgh.pa.us 3299 : 2395394 : bool have_tuple_lock = false;
3300 : : bool iscombo;
6940 3301 : 2395394 : bool use_hot_update = false;
1280 tomas.vondra@postgre 3302 : 2395394 : bool summarized_update = false;
3303 : : bool key_intact;
67 melanieplageman@gmai 3304 : 2395394 : bool clear_all_visible = false;
3305 : 2395394 : bool clear_all_visible_new = false;
3306 : 2395394 : bool vmbuffer_modified = false;
3307 : 2395394 : bool vmbuffer_new_modified = false;
3308 : : bool checked_lockers;
3309 : : bool locker_remains;
1679 akapila@postgresql.o 3310 : 2395394 : bool id_has_external = false;
3311 : : TransactionId xmax_new_tuple,
3312 : : xmax_old_tuple;
3313 : : uint16 infomask_old_tuple,
3314 : : infomask2_old_tuple,
3315 : : infomask_new_tuple,
3316 : : infomask2_new_tuple;
3317 : :
10605 bruce@momjian.us 3318 [ - + ]: 2395394 : Assert(ItemPointerIsValid(otid));
3319 : :
3320 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1959 tgl@sss.pgh.pa.us 3321 [ - + ]: 2395394 : Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
3322 : : RelationGetNumberOfAttributes(relation));
3323 : :
478 nathan@postgresql.or 3324 : 2395394 : AssertHasSnapshotForToast(relation);
3325 : :
3326 : : /*
3327 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
3328 : : * Other workers might need that combo CID for visibility checks, and we
3329 : : * have no provision for broadcasting it to them.
3330 : : */
4161 rhaas@postgresql.org 3331 [ - + ]: 2395394 : if (IsInParallelMode())
4161 rhaas@postgresql.org 3332 [ # # ]:UBC 0 : ereport(ERROR,
3333 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3334 : : errmsg("cannot update tuples during a parallel operation")));
3335 : :
3336 : : #ifdef USE_ASSERT_CHECKING
726 noah@leadboat.com 3337 :CBC 2395394 : check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3338 : : #endif
3339 : :
3340 : : /*
3341 : : * Fetch the list of attributes to be checked for various operations.
3342 : : *
3343 : : * For HOT considerations, this is wasted effort if we fail to update or
3344 : : * have to put the new tuple on a different page. But we must compute the
3345 : : * list before obtaining buffer lock --- in the worst case, if we are
3346 : : * doing an update on one of the relevant system catalogs, we could
3347 : : * deadlock if we try to fetch the list later. In any case, the relcache
3348 : : * caches the data so this is usually pretty cheap.
3349 : : *
3350 : : * We also need columns used by the replica identity and columns that are
3351 : : * considered the "key" of rows in the table.
3352 : : *
3353 : : * Note that we get copies of each bitmap, so we need not worry about
3354 : : * relcache flush happening midway through.
3355 : : */
1280 tomas.vondra@postgre 3356 : 2395394 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3357 : : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3358 : 2395394 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3359 : : INDEX_ATTR_BITMAP_SUMMARIZED);
4667 rhaas@postgresql.org 3360 : 2395394 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3361 : 2395394 : id_attrs = RelationGetIndexAttrBitmap(relation,
3362 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
1759 pg@bowt.ie 3363 : 2395394 : interesting_attrs = NULL;
3364 : 2395394 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
1280 tomas.vondra@postgre 3365 : 2395394 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
1759 pg@bowt.ie 3366 : 2395394 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3367 : 2395394 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3368 : :
5570 rhaas@postgresql.org 3369 : 2395394 : block = ItemPointerGetBlockNumber(otid);
498 michael@paquier.xyz 3370 : 2395394 : INJECTION_POINT("heap_update-before-pin", NULL);
5570 rhaas@postgresql.org 3371 : 2395394 : buffer = ReadBuffer(relation, block);
3805 kgrittn@postgresql.o 3372 : 2395394 : page = BufferGetPage(buffer);
3373 : :
3374 : : /*
3375 : : * Before locking the buffer, pin the visibility map page if it appears to
3376 : : * be necessary. Since we haven't got the lock yet, someone else might be
3377 : : * in the middle of changing this, so we'll need to recheck after we have
3378 : : * the lock.
3379 : : */
5570 rhaas@postgresql.org 3380 [ + + ]: 2395394 : if (PageIsAllVisible(page))
3381 : 2494 : visibilitymap_pin(relation, block, &vmbuffer);
3382 : :
10141 vadim4o@yahoo.com 3383 : 2395394 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3384 : :
6643 tgl@sss.pgh.pa.us 3385 : 2395394 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3386 : :
3387 : : /*
3388 : : * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3389 : : * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3390 : : * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3391 : : * of which indicates concurrent pruning.
3392 : : *
3393 : : * Failing with TM_Updated would be most accurate. However, unlike other
3394 : : * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3395 : : * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3396 : : * does matter to SQL statements UPDATE and MERGE, those SQL statements
3397 : : * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3398 : : * TM_Updated and TM_Deleted affects only the wording of error messages.
3399 : : * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3400 : : * the specification of when tmfd->ctid is valid. Second, it creates
3401 : : * error log evidence that we took this branch.
3402 : : *
3403 : : * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3404 : : * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3405 : : * unrelated row, we'll fail with "duplicate key value violates unique".
3406 : : * XXX if otid is the live, newer version of the newtup row, we'll discard
3407 : : * changes originating in versions of this catalog row after the version
3408 : : * the caller got from syscache. See syscache-update-pruned.spec.
3409 : : */
603 noah@leadboat.com 3410 [ + + ]: 2395394 : if (!ItemIdIsNormal(lp))
3411 : : {
3412 [ - + ]: 1 : Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
3413 : :
3414 : 1 : UnlockReleaseBuffer(buffer);
3415 [ - + ]: 1 : Assert(!have_tuple_lock);
3416 [ + - ]: 1 : if (vmbuffer != InvalidBuffer)
3417 : 1 : ReleaseBuffer(vmbuffer);
3418 : 1 : tmfd->ctid = *otid;
3419 : 1 : tmfd->xmax = InvalidTransactionId;
3420 : 1 : tmfd->cmax = InvalidCommandId;
3421 : 1 : *update_indexes = TU_None;
3422 : :
3423 : 1 : bms_free(hot_attrs);
3424 : 1 : bms_free(sum_attrs);
3425 : 1 : bms_free(key_attrs);
3426 : 1 : bms_free(id_attrs);
3427 : : /* modified_attrs not yet initialized */
3428 : 1 : bms_free(interesting_attrs);
3429 : 1 : return TM_Deleted;
3430 : : }
3431 : :
3432 : : /*
3433 : : * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3434 : : * properly.
3435 : : */
4979 alvherre@alvh.no-ip. 3436 : 2395393 : oldtup.t_tableOid = RelationGetRelid(relation);
6643 tgl@sss.pgh.pa.us 3437 : 2395393 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
10159 vadim4o@yahoo.com 3438 : 2395393 : oldtup.t_len = ItemIdGetLength(lp);
3439 : 2395393 : oldtup.t_self = *otid;
3440 : :
3441 : : /* the new tuple is ready, except for this: */
4979 alvherre@alvh.no-ip. 3442 : 2395393 : newtup->t_tableOid = RelationGetRelid(relation);
3443 : :
3444 : : /*
3445 : : * Determine columns modified by the update. Additionally, identify
3446 : : * whether any of the unmodified replica identity key attributes in the
3447 : : * old tuple is externally stored or not. This is required because for
3448 : : * such attributes the flattened value won't be WAL logged as part of the
3449 : : * new tuple so we must include it as part of the old_key_tuple. See
3450 : : * ExtractReplicaIdentity.
3451 : : */
1679 akapila@postgresql.o 3452 : 2395393 : modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3453 : : id_attrs, &oldtup,
3454 : : newtup, &id_has_external);
3455 : :
3456 : : /*
3457 : : * If we're not updating any "key" column, we can grab a weaker lock type.
3458 : : * This allows for more concurrency when we are running simultaneously
3459 : : * with foreign key checks.
3460 : : *
3461 : : * Note that if a column gets detoasted while executing the update, but
3462 : : * the value ends up being the same, this test will fail and we will use
3463 : : * the stronger lock. This is acceptable; the important case to optimize
3464 : : * is updates that don't manipulate key columns, not those that
3465 : : * serendipitously arrive at the same key values.
3466 : : */
3462 alvherre@alvh.no-ip. 3467 [ + + ]: 2395393 : if (!bms_overlap(modified_attrs, key_attrs))
3468 : : {
3083 simon@2ndQuadrant.co 3469 : 2389950 : *lockmode = LockTupleNoKeyExclusive;
4988 alvherre@alvh.no-ip. 3470 : 2389950 : mxact_status = MultiXactStatusNoKeyUpdate;
3471 : 2389950 : key_intact = true;
3472 : :
3473 : : /*
3474 : : * If this is the first possibly-multixact-able operation in the
3475 : : * current transaction, set my per-backend OldestMemberMXactId
3476 : : * setting. We can be certain that the transaction will never become a
3477 : : * member of any older MultiXactIds than that. (We have to do this
3478 : : * even if we end up just using our own TransactionId below, since
3479 : : * some other backend could incorporate our XID into a MultiXact
3480 : : * immediately afterwards.)
3481 : : */
3482 : 2389950 : MultiXactIdSetOldestMember();
3483 : : }
3484 : : else
3485 : : {
3083 simon@2ndQuadrant.co 3486 : 5443 : *lockmode = LockTupleExclusive;
4988 alvherre@alvh.no-ip. 3487 : 5443 : mxact_status = MultiXactStatusUpdate;
3488 : 5443 : key_intact = false;
3489 : : }
3490 : :
3491 : : /*
3492 : : * Note: beyond this point, use oldtup not otid to refer to old tuple.
3493 : : * otid may very well point at newtup->t_self, which we will overwrite
3494 : : * with the new tuple's location, so there's great risk of confusion if we
3495 : : * use otid anymore.
3496 : : */
3497 : :
10141 vadim4o@yahoo.com 3498 : 1 : l2:
4988 alvherre@alvh.no-ip. 3499 : 2395394 : checked_lockers = false;
3500 : 2395394 : locker_remains = false;
4808 rhaas@postgresql.org 3501 : 2395394 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3502 : :
3503 : : /* see below about the "no wait" case */
892 akorotkov@postgresql 3504 [ + + - + ]: 2395394 : Assert(result != TM_BeingModified || wait);
3505 : :
2738 andres@anarazel.de 3506 [ - + ]: 2395394 : if (result == TM_Invisible)
3507 : : {
7478 tgl@sss.pgh.pa.us 3508 :UBC 0 : UnlockReleaseBuffer(buffer);
4067 3509 [ # # ]: 0 : ereport(ERROR,
3510 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3511 : : errmsg("attempted to update invisible tuple")));
3512 : : }
892 akorotkov@postgresql 3513 [ + + + - ]:CBC 2395394 : else if (result == TM_BeingModified && wait)
3514 : : {
3515 : : TransactionId xwait;
3516 : : uint16 infomask;
4988 alvherre@alvh.no-ip. 3517 : 36486 : bool can_continue = false;
3518 : :
3519 : : /*
3520 : : * XXX note that we don't consider the "no wait" case here. This
3521 : : * isn't a problem currently because no caller uses that case, but it
3522 : : * should be fixed if such a caller is introduced. It wasn't a
3523 : : * problem previously because this code would always wait, but now
3524 : : * that some tuple locks do not conflict with one of the lock modes we
3525 : : * use, it is possible that this case is interesting to handle
3526 : : * specially.
3527 : : *
3528 : : * This may cause failures with third-party code that calls
3529 : : * heap_update directly.
3530 : : */
3531 : :
3532 : : /* must copy state data before unlocking buffer */
3533 : 36486 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
7813 tgl@sss.pgh.pa.us 3534 : 36486 : infomask = oldtup.t_data->t_infomask;
3535 : :
3536 : : /*
3537 : : * Now we have to do something about the existing locker. If it's a
3538 : : * multi, sleep on it; we might be awakened before it is completely
3539 : : * gone (or even not sleep at all in some cases); we need to preserve
3540 : : * it as locker, unless it is gone completely.
3541 : : *
3542 : : * If it's not a multi, we need to check for sleeping conditions
3543 : : * before actually going to sleep. If the update doesn't conflict
3544 : : * with the locks, we just continue without sleeping (but making sure
3545 : : * it is preserved).
3546 : : *
3547 : : * Before sleeping, we need to acquire tuple lock to establish our
3548 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
3549 : : * release us when we are next-in-line for the tuple. Note we must
3550 : : * not acquire the tuple lock until we're sure we're going to sleep;
3551 : : * otherwise we're open for race conditions with other transactions
3552 : : * holding the tuple lock which sleep on us.
3553 : : *
3554 : : * If we are forced to "start over" below, we keep the tuple lock;
3555 : : * this arranges that we stay at the head of the line while rechecking
3556 : : * tuple state.
3557 : : */
7815 3558 [ + + ]: 36486 : if (infomask & HEAP_XMAX_IS_MULTI)
3559 : : {
3560 : : TransactionId update_xact;
3561 : : int remain;
2651 alvherre@alvh.no-ip. 3562 : 179 : bool current_is_member = false;
3563 : :
4181 3564 [ + + ]: 179 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3565 : : *lockmode, ¤t_is_member))
3566 : : {
3567 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3568 : :
3569 : : /*
3570 : : * Acquire the lock, if necessary (but skip it when we're
3571 : : * requesting a lock and already have one; avoids deadlock).
3572 : : */
2651 3573 [ - + ]: 8 : if (!current_is_member)
2651 alvherre@alvh.no-ip. 3574 :UBC 0 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3575 : : LockWaitBlock, &have_tuple_lock);
3576 : :
3577 : : /* wait for multixact */
4181 alvherre@alvh.no-ip. 3578 :CBC 8 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3579 : : relation, &oldtup.t_self, XLTW_Update,
3580 : : &remain);
3581 : 8 : checked_lockers = true;
3582 : 8 : locker_remains = remain != 0;
3583 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3584 : :
3585 : : /*
3586 : : * If xwait had just locked the tuple then some other xact
3587 : : * could update this tuple before we get to this point. Check
3588 : : * for xmax change, and start over if so.
3589 : : */
3590 [ + - ]: 8 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3591 [ - + ]: 8 : infomask) ||
3378 tgl@sss.pgh.pa.us 3592 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3593 : : xwait))
4181 alvherre@alvh.no-ip. 3594 :UBC 0 : goto l2;
3595 : : }
3596 : :
3597 : : /*
3598 : : * Note that the multixact may not be done by now. It could have
3599 : : * surviving members; our own xact or other subxacts of this
3600 : : * backend, and also any other concurrent transaction that locked
3601 : : * the tuple with LockTupleKeyShare if we only got
3602 : : * LockTupleNoKeyExclusive. If this is the case, we have to be
3603 : : * careful to mark the updated tuple with the surviving members in
3604 : : * Xmax.
3605 : : *
3606 : : * Note that there could have been another update in the
3607 : : * MultiXact. In that case, we need to check whether it committed
3608 : : * or aborted. If it aborted we are safe to update it again;
3609 : : * otherwise there is an update conflict, and we have to return
3610 : : * TableTuple{Deleted, Updated} below.
3611 : : *
3612 : : * In the LockTupleExclusive case, we still need to preserve the
3613 : : * surviving members: those would include the tuple locks we had
3614 : : * before this one, which are important to keep in case this
3615 : : * subxact aborts.
3616 : : */
4988 alvherre@alvh.no-ip. 3617 [ + + ]:CBC 179 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3618 : 8 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3619 : : else
4181 3620 : 171 : update_xact = InvalidTransactionId;
3621 : :
3622 : : /*
3623 : : * There was no UPDATE in the MultiXact; or it aborted. No
3624 : : * TransactionIdIsInProgress() call needed here, since we called
3625 : : * MultiXactIdWait() above.
3626 : : */
4988 3627 [ + + + + ]: 187 : if (!TransactionIdIsValid(update_xact) ||
3628 : 8 : TransactionIdDidAbort(update_xact))
3629 : 172 : can_continue = true;
3630 : : }
4181 3631 [ + + ]: 36307 : else if (TransactionIdIsCurrentTransactionId(xwait))
3632 : : {
3633 : : /*
3634 : : * The only locker is ourselves; we can avoid grabbing the tuple
3635 : : * lock here, but must preserve our locking information.
3636 : : */
3637 : 36193 : checked_lockers = true;
3638 : 36193 : locker_remains = true;
3639 : 36193 : can_continue = true;
3640 : : }
3641 [ + + + + ]: 114 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3642 : : {
3643 : : /*
3644 : : * If it's just a key-share locker, and we're not changing the key
3645 : : * columns, we don't need to wait for it to end; but we need to
3646 : : * preserve it as locker.
3647 : : */
3648 : 30 : checked_lockers = true;
3649 : 30 : locker_remains = true;
3650 : 30 : can_continue = true;
3651 : : }
3652 : : else
3653 : : {
3654 : : /*
3655 : : * Wait for regular transaction to end; but first, acquire tuple
3656 : : * lock.
3657 : : */
3658 : 84 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3083 simon@2ndQuadrant.co 3659 : 84 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3660 : : LockWaitBlock, &have_tuple_lock);
4181 alvherre@alvh.no-ip. 3661 : 84 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3662 : : XLTW_Update);
3663 : 84 : checked_lockers = true;
3664 : 84 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3665 : :
3666 : : /*
3667 : : * xwait is done, but if xwait had just locked the tuple then some
3668 : : * other xact could update this tuple before we get to this point.
3669 : : * Check for xmax change, and start over if so.
3670 : : */
3671 [ + + - + ]: 167 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3672 : 83 : !TransactionIdEquals(xwait,
3673 : : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3674 : 1 : goto l2;
3675 : :
3676 : : /* Otherwise check if it committed or aborted */
3677 : 83 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3678 [ + + ]: 83 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
4988 3679 : 23 : can_continue = true;
3680 : : }
3681 : :
2738 andres@anarazel.de 3682 [ + + ]: 36485 : if (can_continue)
3683 : 36418 : result = TM_Ok;
2036 alvherre@alvh.no-ip. 3684 [ + + ]: 67 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
2738 andres@anarazel.de 3685 : 62 : result = TM_Updated;
3686 : : else
3687 : 5 : result = TM_Deleted;
3688 : : }
3689 : :
3690 : : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3691 [ + + ]: 2395393 : if (result != TM_Ok)
3692 : : {
3693 [ + + + + : 181 : Assert(result == TM_SelfModified ||
- + - - ]
3694 : : result == TM_Updated ||
3695 : : result == TM_Deleted ||
3696 : : result == TM_BeingModified);
7701 tgl@sss.pgh.pa.us 3697 [ - + ]: 181 : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
2738 andres@anarazel.de 3698 [ + + - + ]: 181 : Assert(result != TM_Updated ||
3699 : : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3700 : : }
3701 : :
1027 heikki.linnakangas@i 3702 [ + + + - ]: 2395393 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3703 : : {
3704 : : /* Perform additional check for transaction-snapshot mode RI updates */
3705 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3706 : 1 : result = TM_Updated;
3707 : : }
3708 : :
3709 [ + + ]: 2395393 : if (result != TM_Ok)
3710 : : {
2738 andres@anarazel.de 3711 : 182 : tmfd->ctid = oldtup.t_data->t_ctid;
3712 : 182 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3713 [ + + ]: 182 : if (result == TM_SelfModified)
3714 : 69 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3715 : : else
3716 : 113 : tmfd->cmax = InvalidCommandId;
892 akorotkov@postgresql 3717 : 182 : UnlockReleaseBuffer(buffer);
7813 tgl@sss.pgh.pa.us 3718 [ + + ]: 182 : if (have_tuple_lock)
3083 simon@2ndQuadrant.co 3719 : 60 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
5570 rhaas@postgresql.org 3720 [ - + ]: 182 : if (vmbuffer != InvalidBuffer)
5570 rhaas@postgresql.org 3721 :UBC 0 : ReleaseBuffer(vmbuffer);
1280 tomas.vondra@postgre 3722 :CBC 182 : *update_indexes = TU_None;
3723 : :
6940 tgl@sss.pgh.pa.us 3724 : 182 : bms_free(hot_attrs);
1280 tomas.vondra@postgre 3725 : 182 : bms_free(sum_attrs);
4988 alvherre@alvh.no-ip. 3726 : 182 : bms_free(key_attrs);
3679 tgl@sss.pgh.pa.us 3727 : 182 : bms_free(id_attrs);
3462 alvherre@alvh.no-ip. 3728 : 182 : bms_free(modified_attrs);
3729 : 182 : bms_free(interesting_attrs);
10141 vadim4o@yahoo.com 3730 : 182 : return result;
3731 : : }
3732 : :
3733 : : /*
3734 : : * If we didn't pin the visibility map page and the page has become all
3735 : : * visible while we were busy locking the buffer, or during some
3736 : : * subsequent window during which we had it unlocked, we'll have to unlock
3737 : : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3738 : : * bit unfortunate, especially since we'll now have to recheck whether the
3739 : : * tuple has been locked or updated under us, but hopefully it won't
3740 : : * happen very often.
3741 : : */
5564 rhaas@postgresql.org 3742 [ + + - + ]: 2395211 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3743 : : {
5564 rhaas@postgresql.org 3744 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3745 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
3746 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5472 3747 : 0 : goto l2;
3748 : : }
3749 : :
3750 : : /* Fill in transaction status data */
3751 : :
3752 : : /*
3753 : : * If the tuple we're updating is locked, we need to preserve the locking
3754 : : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3755 : : */
4988 alvherre@alvh.no-ip. 3756 :CBC 2395211 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3757 : 2395211 : oldtup.t_data->t_infomask,
3758 : 2395211 : oldtup.t_data->t_infomask2,
3759 : : xid, *lockmode, true,
3760 : : &xmax_old_tuple, &infomask_old_tuple,
3761 : : &infomask2_old_tuple);
3762 : :
3763 : : /*
3764 : : * And also prepare an Xmax value for the new copy of the tuple. If there
3765 : : * was no xmax previously, or there was one but all lockers are now gone,
3766 : : * then use InvalidTransactionId; otherwise, get the xmax from the old
3767 : : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3768 : : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3769 : : */
3770 [ + + + - ]: 2431606 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3740 3771 [ + + ]: 72790 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
4988 3772 [ - + ]: 36224 : (checked_lockers && !locker_remains))
3773 : 2358816 : xmax_new_tuple = InvalidTransactionId;
3774 : : else
3775 : 36395 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3776 : :
3777 [ + + ]: 2395211 : if (!TransactionIdIsValid(xmax_new_tuple))
3778 : : {
3779 : 2358816 : infomask_new_tuple = HEAP_XMAX_INVALID;
3780 : 2358816 : infomask2_new_tuple = 0;
3781 : : }
3782 : : else
3783 : : {
3784 : : /*
3785 : : * If we found a valid Xmax for the new tuple, then the infomask bits
3786 : : * to use on the new tuple depend on what was there on the old one.
3787 : : * Note that since we're doing an update, the only possibility is that
3788 : : * the lockers had FOR KEY SHARE lock.
3789 : : */
3790 [ + + ]: 36395 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3791 : : {
3792 : 172 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3793 : : &infomask2_new_tuple);
3794 : : }
3795 : : else
3796 : : {
3797 : 36223 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3798 : 36223 : infomask2_new_tuple = 0;
3799 : : }
3800 : : }
3801 : :
3802 : : /*
3803 : : * Prepare the new tuple with the appropriate initial values of Xmin and
3804 : : * Xmax, as well as initial infomask bits as computed above.
3805 : : */
10159 vadim4o@yahoo.com 3806 : 2395211 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
6940 tgl@sss.pgh.pa.us 3807 : 2395211 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
8039 3808 : 2395211 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
8863 bruce@momjian.us 3809 : 2395211 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
4988 alvherre@alvh.no-ip. 3810 : 2395211 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3811 : 2395211 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3812 : 2395211 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3813 : :
3814 : : /*
3815 : : * Replace cid with a combo CID if necessary. Note that we already put
3816 : : * the plain cid into the new tuple.
3817 : : */
7163 tgl@sss.pgh.pa.us 3818 : 2395211 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3819 : :
3820 : : /*
3821 : : * If the toaster needs to be activated, OR if the new tuple will not fit
3822 : : * on the same page as the old, then we need to release the content lock
3823 : : * (but not the pin!) on the old tuple's buffer while we are off doing
3824 : : * TOAST and/or table-file-extension work. We must mark the old tuple to
3825 : : * show that it's locked, else other processes may try to update it
3826 : : * themselves.
3827 : : *
3828 : : * We need to invoke the toaster if there are already any out-of-line
3829 : : * toasted values present, or if the new tuple is over-threshold.
3830 : : */
4949 kgrittn@postgresql.o 3831 [ - + ]: 2395211 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
4949 kgrittn@postgresql.o 3832 [ # # ]:UBC 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3833 : : {
3834 : : /* toast table entries should never be recursively toasted */
7110 tgl@sss.pgh.pa.us 3835 [ # # ]: 0 : Assert(!HeapTupleHasExternal(&oldtup));
3836 [ # # ]: 0 : Assert(!HeapTupleHasExternal(newtup));
3837 : 0 : need_toast = false;
3838 : : }
3839 : : else
7110 tgl@sss.pgh.pa.us 3840 [ + + ]:CBC 7184979 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3841 [ + + ]: 4789768 : HeapTupleHasExternal(newtup) ||
3842 [ + + ]: 2394525 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3843 : :
6643 3844 : 2395211 : pagefree = PageGetHeapFreeSpace(page);
3845 : :
7168 3846 : 2395211 : newtupsize = MAXALIGN(newtup->t_len);
3847 : :
9258 3848 [ + + + + ]: 2395211 : if (need_toast || newtupsize > pagefree)
9509 vadim4o@yahoo.com 3849 : 2213090 : {
3850 : : TransactionId xmax_lock_old_tuple;
3851 : : uint16 infomask_lock_old_tuple,
3852 : : infomask2_lock_old_tuple;
3716 andres@anarazel.de 3853 : 2213090 : bool cleared_all_frozen = false;
3854 : :
3855 : : /*
3856 : : * To prevent concurrent sessions from updating the tuple, we have to
3857 : : * temporarily mark it locked, while we release the page-level lock.
3858 : : *
3859 : : * To satisfy the rule that any xid potentially appearing in a buffer
3860 : : * written out to disk, we unfortunately have to WAL log this
3861 : : * temporary modification. We can reuse xl_heap_lock for this
3862 : : * purpose. If we crash/error before following through with the
3863 : : * actual update, xmax will be of an aborted transaction, allowing
3864 : : * other sessions to proceed.
3865 : : */
3866 : :
3867 : : /*
3868 : : * Compute xmax / infomask appropriate for locking the tuple. This has
3869 : : * to be done separately from the combo that's going to be used for
3870 : : * updating, because the potentially created multixact would otherwise
3871 : : * be wrong.
3872 : : */
3719 3873 : 2213090 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3874 : 2213090 : oldtup.t_data->t_infomask,
3875 : 2213090 : oldtup.t_data->t_infomask2,
3876 : : xid, *lockmode, false,
3877 : : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3878 : : &infomask2_lock_old_tuple);
3879 : :
3880 [ - + ]: 2213090 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3881 : :
67 melanieplageman@gmai 3882 [ + + ]: 2213090 : if (PageIsAllVisible(page))
3883 : : {
3884 : 1468 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3885 : 1468 : unlock_vmbuffer = true;
3886 : : }
3887 : :
3719 andres@anarazel.de 3888 : 2213090 : START_CRIT_SECTION();
3889 : :
3890 : : /* Clear obsolete visibility flags ... */
4988 alvherre@alvh.no-ip. 3891 : 2213090 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3892 : 2213090 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6940 tgl@sss.pgh.pa.us 3893 : 2213090 : HeapTupleClearHotUpdated(&oldtup);
3894 : : /* ... and store info about transaction updating this tuple */
3719 andres@anarazel.de 3895 [ - + ]: 2213090 : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3896 : 2213090 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3897 : 2213090 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3898 : 2213090 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
7163 tgl@sss.pgh.pa.us 3899 : 2213090 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3900 : :
3901 : : /* temporarily make it look not-updated, but locked */
7609 3902 : 2213090 : oldtup.t_data->t_ctid = oldtup.t_self;
3903 : :
3904 : : /*
3905 : : * Clear all-frozen bit on visibility map if needed. We could
3906 : : * immediately reset ALL_VISIBLE, but given that the WAL logging
3907 : : * overhead would be unchanged, that doesn't seem necessarily
3908 : : * worthwhile.
3909 : : */
67 melanieplageman@gmai 3910 [ + + ]: 2213090 : if (PageIsAllVisible(page))
3911 : : {
3912 : : /* It's possible all-frozen was already clear */
67 melanieplageman@gmai 3913 [ + + ]:GNC 1468 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
3914 : : VISIBILITYMAP_ALL_FROZEN))
67 melanieplageman@gmai 3915 :CBC 792 : cleared_all_frozen = true;
3916 : : }
3917 : :
3719 andres@anarazel.de 3918 : 2213090 : MarkBufferDirty(buffer);
3919 : :
3920 [ + + + + : 2213090 : if (RelationNeedsWAL(relation))
+ - + + ]
3921 : : {
3922 : : xl_heap_lock xlrec;
3923 : : XLogRecPtr recptr;
3924 : :
3925 : 2202958 : XLogBeginInsert();
67 melanieplageman@gmai 3926 : 2202958 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3927 : :
3719 andres@anarazel.de 3928 : 2202958 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
1258 pg@bowt.ie 3929 : 2202958 : xlrec.xmax = xmax_lock_old_tuple;
3719 andres@anarazel.de 3930 : 4405916 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3931 : 2202958 : oldtup.t_data->t_infomask2);
3716 3932 : 2202958 : xlrec.flags =
3933 : 2202958 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
586 peter@eisentraut.org 3934 : 2202958 : XLogRegisterData(&xlrec, SizeOfHeapLock);
3935 : :
67 melanieplageman@gmai 3936 [ + + ]: 2202958 : if (cleared_all_frozen)
3937 : 792 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
3938 : :
3719 andres@anarazel.de 3939 : 2202958 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3940 : 2202958 : PageSetLSN(page, recptr);
3941 : :
67 melanieplageman@gmai 3942 [ + + ]: 2202958 : if (cleared_all_frozen)
3943 : 792 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3944 : : }
3945 : :
3719 andres@anarazel.de 3946 [ - + ]: 2213090 : END_CRIT_SECTION();
3947 : :
3948 : : /* release VM lock first, since it covers many heap blocks */
67 melanieplageman@gmai 3949 [ + + ]: 2213090 : if (unlock_vmbuffer)
3950 : 1468 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3951 : 2213090 : unlock_vmbuffer = false;
3952 : :
9509 vadim4o@yahoo.com 3953 : 2213090 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3954 : :
3955 : : /*
3956 : : * Let the toaster do its thing, if needed.
3957 : : *
3958 : : * Note: below this point, heaptup is the data we actually intend to
3959 : : * store into the relation; newtup is the caller's original untoasted
3960 : : * data.
3961 : : */
9379 tgl@sss.pgh.pa.us 3962 [ + + ]: 2213090 : if (need_toast)
3963 : : {
3964 : : /*
3965 : : * If logical decoding is not needed, suppress it for the TOAST
3966 : : * tuples too. We never skip the FSM here.
3967 : : */
9 msawada@postgresql.o 3968 [ + + ]: 2249 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
3969 : : walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
7609 tgl@sss.pgh.pa.us 3970 : 2249 : newtupsize = MAXALIGN(heaptup->t_len);
3971 : : }
3972 : : else
3973 : 2210841 : heaptup = newtup;
3974 : :
3975 : : /*
3976 : : * Now, do we need a new page for the tuple, or not? This is a bit
3977 : : * tricky since someone else could have added tuples to the page while
3978 : : * we weren't looking. We have to recheck the available space after
3979 : : * reacquiring the buffer lock. But don't bother to do that if the
3980 : : * former amount of free space is still not enough; it's unlikely
3981 : : * there's more free now than before.
3982 : : *
3983 : : * What's more, if we need to get a new page, we will need to acquire
3984 : : * buffer locks on both old and new pages. To avoid deadlock against
3985 : : * some other backend trying to get the same two locks in the other
3986 : : * order, we must be consistent about the order we get the locks in.
3987 : : * We use the rule "lock the lower-numbered page of the relation
3988 : : * first". To implement this, we must do RelationGetBufferForTuple
3989 : : * while not holding the lock on the old page, and we must rely on it
3990 : : * to get the locks on both pages in the correct order.
3991 : : *
3992 : : * Another consideration is that we need visibility map page pin(s) if
3993 : : * we will have to clear the all-visible flag on either page. If we
3994 : : * call RelationGetBufferForTuple, we rely on it to acquire any such
3995 : : * pins; but if we don't, we have to handle that here. Hence we need
3996 : : * a loop.
3997 : : */
3998 : : for (;;)
3999 : : {
1986 4000 [ + + ]: 2213090 : if (newtupsize > pagefree)
4001 : : {
4002 : : /* It doesn't fit, must use RelationGetBufferForTuple. */
4003 : 2212249 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
4004 : : buffer, 0, NULL,
4005 : : &vmbuffer_new, &vmbuffer,
4006 : : 0);
4007 : : /* We're all done. */
4008 : 2212249 : break;
4009 : : }
4010 : : /* Acquire VM page pin if needed and we don't have it. */
4011 [ + + - + ]: 841 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
1986 tgl@sss.pgh.pa.us 4012 :UBC 0 : visibilitymap_pin(relation, block, &vmbuffer);
4013 : : /* Re-acquire the lock on the old tuple's page. */
9258 tgl@sss.pgh.pa.us 4014 :CBC 841 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4015 : : /* Re-check using the up-to-date free space */
6643 4016 : 841 : pagefree = PageGetHeapFreeSpace(page);
1986 4017 [ + - ]: 841 : if (newtupsize > pagefree ||
4018 [ + + - + ]: 841 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
4019 : : {
4020 : : /*
4021 : : * Rats, it doesn't fit anymore, or somebody just now set the
4022 : : * all-visible flag. We must now unlock and loop to avoid
4023 : : * deadlock. Fortunately, this path should seldom be taken.
4024 : : */
9258 tgl@sss.pgh.pa.us 4025 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4026 : : }
4027 : : else
4028 : : {
4029 : : /* We're all done. */
9258 tgl@sss.pgh.pa.us 4030 :CBC 841 : newbuf = buffer;
1986 4031 : 841 : break;
4032 : : }
4033 : : }
4034 : : }
4035 : : else
4036 : : {
4037 : : /* No TOAST work needed, and it'll fit on same page */
9379 4038 : 182121 : newbuf = buffer;
7609 4039 : 182121 : heaptup = newtup;
4040 : : }
4041 : :
189 melanieplageman@gmai 4042 : 2395211 : newpage = BufferGetPage(newbuf);
4043 : :
4044 : : /*
4045 : : * We're about to do the actual update -- check for conflict first, to
4046 : : * avoid possibly having to roll back work we've just done.
4047 : : *
4048 : : * This is safe without a recheck as long as there is no possibility of
4049 : : * another process scanning the pages between this check and the update
4050 : : * being visible to the scan (i.e., exclusive buffer content lock(s) are
4051 : : * continuously held from this point until the tuple update is visible).
4052 : : *
4053 : : * For the new tuple the only check needed is at the relation level, but
4054 : : * since both tuples are in the same relation and the check for oldtup
4055 : : * will include checking the relation level, there is no benefit to a
4056 : : * separate check for the new tuple.
4057 : : */
1986 tmunro@postgresql.or 4058 : 2395211 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
4059 : : BufferGetBlockNumber(buffer));
4060 : :
4061 : : /*
4062 : : * At this point newbuf and buffer are both pinned and locked, and newbuf
4063 : : * has enough space for the new tuple. If they are the same buffer, only
4064 : : * one pin is held.
4065 : : */
4066 : :
6940 tgl@sss.pgh.pa.us 4067 [ + + ]: 2395198 : if (newbuf == buffer)
4068 : : {
4069 : : /*
4070 : : * Since the new tuple is going into the same page, we might be able
4071 : : * to do a HOT update. Check if any of the index columns have been
4072 : : * changed.
4073 : : */
1759 pg@bowt.ie 4074 [ + + ]: 182949 : if (!bms_overlap(modified_attrs, hot_attrs))
4075 : : {
6940 tgl@sss.pgh.pa.us 4076 : 166868 : use_hot_update = true;
4077 : :
4078 : : /*
4079 : : * If none of the columns that are used in hot-blocking indexes
4080 : : * were updated, we can apply HOT, but we do still need to check
4081 : : * if we need to update the summarizing indexes, and update those
4082 : : * indexes if the columns were updated, or we may fail to detect
4083 : : * e.g. value bound changes in BRIN minmax indexes.
4084 : : */
1280 tomas.vondra@postgre 4085 [ + + ]: 166868 : if (bms_overlap(modified_attrs, sum_attrs))
4086 : 2188 : summarized_update = true;
4087 : : }
4088 : : }
4089 : : else
4090 : : {
4091 : : /* Set a hint that the old page could use prune/defrag */
6643 tgl@sss.pgh.pa.us 4092 : 2212249 : PageSetFull(page);
4093 : : }
4094 : :
4095 : : /*
4096 : : * Compute replica identity tuple before entering the critical section so
4097 : : * we don't PANIC upon a memory allocation failure.
4098 : : * ExtractReplicaIdentity() will return NULL if nothing needs to be
4099 : : * logged. Pass old key required as true only if the replica identity key
4100 : : * columns are modified or it has external data.
4101 : : */
3462 alvherre@alvh.no-ip. 4102 : 2395198 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
1679 akapila@postgresql.o 4103 [ + + + + ]: 2395198 : bms_overlap(modified_attrs, id_attrs) ||
4104 : : id_has_external,
3462 alvherre@alvh.no-ip. 4105 : 2395198 : &old_key_copied);
4106 : :
67 melanieplageman@gmai 4107 : 2395198 : clear_all_visible = PageIsAllVisible(page);
4108 [ + + + + ]: 2395198 : clear_all_visible_new = newbuf != buffer && PageIsAllVisible(newpage);
4109 : :
4110 : : /*
4111 : : * Clear PD_ALL_VISIBLE flags and reset visibility map bits for any heap
4112 : : * pages that were all-visible. If there are two heap pages, we may need
4113 : : * to clear VM bits for both.
4114 : : */
4115 [ + + + + ]: 2395198 : if (clear_all_visible && clear_all_visible_new &&
4116 [ + - ]: 174 : vmbuffer_new == vmbuffer)
4117 : : {
4118 : : /*
4119 : : * This is the more complicated case: both the new and old heap pages
4120 : : * are all-visible and both their VM bits are on the same page of the
4121 : : * VM, so we register a single VM buffer as HEAP_UPDATE_BLKREF_VM_NEW
4122 : : * in the WAL record. We must be careful to only lock and register one
4123 : : * buffer, even though we modify it twice -- once for each heap
4124 : : * block's VM bits.
4125 : : */
4126 : 174 : LockBuffer(vmbuffer_new, BUFFER_LOCK_EXCLUSIVE);
4127 : 174 : unlock_vmbuffer_new = true;
4128 : :
4129 : : /* We will not lock or attempt to modify old VM buffer */
4130 : : }
4131 : : else
4132 : : {
4133 : : /*
4134 : : * In all the remaining cases, we will clear at most one heap block's
4135 : : * VM bits per VM page.
4136 : : */
4137 : 4790048 : Buffer vmbuffers[2] = {
4138 [ + + ]: 2395024 : clear_all_visible ? vmbuffer : InvalidBuffer,
4139 [ + + ]: 2395024 : clear_all_visible_new ? vmbuffer_new : InvalidBuffer
4140 : : };
4141 : :
4142 : : /*
4143 : : * When both pages need different VM pages cleared, acquire the VM
4144 : : * buffer locks in VM block order to avoid deadlocks between backends
4145 : : * updating tuples in opposite directions across VM pages.
4146 : : */
4147 [ + + - + : 2395024 : if (clear_all_visible && clear_all_visible_new &&
- - ]
67 melanieplageman@gmai 4148 :UBC 0 : BufferGetBlockNumber(vmbuffers[0]) > BufferGetBlockNumber(vmbuffers[1]))
4149 : : {
4150 : 0 : Buffer swap = vmbuffers[0];
4151 : :
4152 : 0 : vmbuffers[0] = vmbuffers[1];
4153 : 0 : vmbuffers[1] = swap;
4154 : : }
4155 : :
67 melanieplageman@gmai 4156 [ + + + + :CBC 2395024 : Assert((!BufferIsValid(vmbuffers[0]) && !BufferIsValid(vmbuffers[1])) ||
- + ]
4157 : : vmbuffers[0] != vmbuffers[1]);
4158 : :
4159 [ + + ]: 2395024 : if (BufferIsValid(vmbuffers[0]))
4160 : 2319 : LockBuffer(vmbuffers[0], BUFFER_LOCK_EXCLUSIVE);
4161 [ + + ]: 2395024 : if (BufferIsValid(vmbuffers[1]))
4162 : 1335 : LockBuffer(vmbuffers[1], BUFFER_LOCK_EXCLUSIVE);
4163 : :
4164 [ + + ]: 2395024 : if (clear_all_visible)
4165 : 2319 : unlock_vmbuffer = true;
4166 [ + + ]: 2395024 : if (clear_all_visible_new)
4167 : 1335 : unlock_vmbuffer_new = true;
4168 : : }
4169 : :
4170 : : /* NO EREPORT(ERROR) from here till changes are logged */
9382 tgl@sss.pgh.pa.us 4171 : 2395198 : START_CRIT_SECTION();
4172 : :
4173 : : /*
4174 : : * If this transaction commits, the old tuple will become DEAD sooner or
4175 : : * later. Set flag that this page is a candidate for pruning once our xid
4176 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
4177 : : * the subsequent page pruning will be a no-op and the hint will be
4178 : : * cleared.
4179 : : *
4180 : : * We set the new page prunable as well. See heap_insert() for more on why
4181 : : * we do this when inserting tuples.
4182 : : */
6643 4183 [ - + + + : 2395198 : PageSetPrunable(page, xid);
+ + ]
174 melanieplageman@gmai 4184 [ + + ]: 2395198 : if (newbuf != buffer)
4185 [ - + + + : 2212249 : PageSetPrunable(newpage, xid);
+ + ]
4186 : :
6940 tgl@sss.pgh.pa.us 4187 [ + + ]: 2395198 : if (use_hot_update)
4188 : : {
4189 : : /* Mark the old tuple as HOT-updated */
4190 : 166868 : HeapTupleSetHotUpdated(&oldtup);
4191 : : /* And mark the new tuple as heap-only */
4192 : 166868 : HeapTupleSetHeapOnly(heaptup);
4193 : : /* Mark the caller's copy too, in case different from heaptup */
4194 : 166868 : HeapTupleSetHeapOnly(newtup);
4195 : : }
4196 : : else
4197 : : {
4198 : : /* Make sure tuples are correctly marked as not-HOT */
4199 : 2228330 : HeapTupleClearHotUpdated(&oldtup);
4200 : 2228330 : HeapTupleClearHeapOnly(heaptup);
4201 : 2228330 : HeapTupleClearHeapOnly(newtup);
4202 : : }
4203 : :
3378 4204 : 2395198 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4205 : :
4206 : :
4207 : : /* Clear obsolete visibility flags, possibly set by ourselves above... */
3719 andres@anarazel.de 4208 : 2395198 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4209 : 2395198 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4210 : : /* ... and store info about transaction updating this tuple */
4211 [ - + ]: 2395198 : Assert(TransactionIdIsValid(xmax_old_tuple));
4212 : 2395198 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4213 : 2395198 : oldtup.t_data->t_infomask |= infomask_old_tuple;
4214 : 2395198 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4215 : 2395198 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4216 : :
4217 : : /* record address of new tuple in t_ctid of old one */
7609 tgl@sss.pgh.pa.us 4218 : 2395198 : oldtup.t_data->t_ctid = heaptup->t_self;
4219 : :
4220 : : /*
4221 : : * Clear PD_ALL_VISIBLE flags and reset all visibilitymap bits. In all
4222 : : * cases, it's possible that PD_ALL_VISIBLE was set but the corresponding
4223 : : * visibility map bits were already clear.
4224 : : */
67 melanieplageman@gmai 4225 [ + + ]: 2395198 : if (clear_all_visible)
4226 : : {
67 melanieplageman@gmai 4227 [ + - ]:GNC 2493 : if (visibilitymap_clear(relation->rd_locator, block,
4228 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
4229 : : {
4230 : : /*
4231 : : * When old and new heap blocks' VM bits are on the same VM page,
4232 : : * that page is registered in the WAL record only once. If both
4233 : : * heap pages were PD_ALL_VISIBLE and either VM bit needs
4234 : : * clearing, we register the VM buffer as
4235 : : * HEAP_UPDATE_BLKREF_VM_NEW.
4236 : : */
67 melanieplageman@gmai 4237 [ + + + - ]:CBC 2493 : if (clear_all_visible_new && vmbuffer == vmbuffer_new)
4238 : 174 : vmbuffer_new_modified = true;
4239 : : else
4240 : 2319 : vmbuffer_modified = true;
4241 : : }
4242 : :
189 4243 : 2493 : PageClearAllVisible(page);
4244 : : }
67 4245 [ + + ]: 2395198 : if (clear_all_visible_new)
4246 : : {
4247 : : /*
4248 : : * If both heap blocks' VM bits are on the same VM buffer, this will
4249 : : * clear the new heap block's VM bits from the shared vmbuffer.
4250 : : */
67 melanieplageman@gmai 4251 [ + - ]:GNC 1509 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(newbuf),
4252 : : vmbuffer_new, VISIBILITYMAP_VALID_BITS))
67 melanieplageman@gmai 4253 :CBC 1509 : vmbuffer_new_modified = true;
4254 : :
189 4255 : 1509 : PageClearAllVisible(newpage);
4256 : : }
4257 : :
7478 tgl@sss.pgh.pa.us 4258 [ + + ]: 2395198 : if (newbuf != buffer)
4259 : 2212249 : MarkBufferDirty(newbuf);
4260 : 2395198 : MarkBufferDirty(buffer);
4261 : :
4262 : : /* XLOG stuff */
5760 rhaas@postgresql.org 4263 [ + + + + : 2395198 : if (RelationNeedsWAL(relation))
+ - + + ]
4264 : : {
4265 : : XLogRecPtr recptr;
4266 : :
4267 : : /*
4268 : : * For logical decoding we need combo CIDs to properly decode the
4269 : : * catalog.
4270 : : */
4667 4271 [ + + + + : 2383423 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
4272 : : {
4273 : 2724 : log_heap_new_cid(relation, &oldtup);
4274 : 2724 : log_heap_new_cid(relation, heaptup);
4275 : : }
4276 : :
4277 [ + + + + ]: 2383423 : recptr = log_heap_update(relation, buffer,
4278 : : vmbuffer_modified ? vmbuffer : InvalidBuffer,
4279 : : newbuf,
4280 : : vmbuffer_new_modified ? vmbuffer_new : InvalidBuffer,
4281 : : &oldtup, heaptup,
4282 : : old_key_tuple,
4283 : : clear_all_visible,
4284 : : clear_all_visible_new,
4285 : : walLogical);
9575 vadim4o@yahoo.com 4286 [ + + ]: 2383423 : if (newbuf != buffer)
4287 : : {
189 melanieplageman@gmai 4288 : 2202125 : PageSetLSN(newpage, recptr);
4289 : : }
4290 : 2383423 : PageSetLSN(page, recptr);
4291 : :
67 4292 [ + + ]: 2383423 : if (vmbuffer_modified)
4293 : 2318 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
4294 [ + + ]: 2383423 : if (vmbuffer_new_modified)
4295 : 1509 : PageSetLSN(BufferGetPage(vmbuffer_new), recptr);
4296 : : }
4297 : :
9382 tgl@sss.pgh.pa.us 4298 [ - + ]: 2395198 : END_CRIT_SECTION();
4299 : :
67 melanieplageman@gmai 4300 [ + + ]: 2395198 : if (unlock_vmbuffer)
4301 : 2319 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
4302 [ + + ]: 2395198 : if (unlock_vmbuffer_new)
4303 : 1509 : LockBuffer(vmbuffer_new, BUFFER_LOCK_UNLOCK);
4304 : :
9575 vadim4o@yahoo.com 4305 [ + + ]: 2395198 : if (newbuf != buffer)
4306 : 2212249 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
10141 4307 : 2395198 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4308 : :
4309 : : /*
4310 : : * Mark old tuple for invalidation from system caches at next command
4311 : : * boundary, and mark the new tuple for invalidation in case we abort. We
4312 : : * have to do this before releasing the buffer because oldtup is in the
4313 : : * buffer. (heaptup is all in local memory, but it's necessary to process
4314 : : * both tuple versions in one call to inval.c so we can avoid redundant
4315 : : * sinval messages.)
4316 : : */
5514 tgl@sss.pgh.pa.us 4317 : 2395198 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4318 : :
4319 : : /* Now we can release the buffer(s) */
9387 4320 [ + + ]: 2395198 : if (newbuf != buffer)
7478 4321 : 2212249 : ReleaseBuffer(newbuf);
892 akorotkov@postgresql 4322 : 2395198 : ReleaseBuffer(buffer);
5570 rhaas@postgresql.org 4323 [ + + ]: 2395198 : if (BufferIsValid(vmbuffer_new))
4324 : 1512 : ReleaseBuffer(vmbuffer_new);
4325 [ + + ]: 2395198 : if (BufferIsValid(vmbuffer))
4326 : 2493 : ReleaseBuffer(vmbuffer);
4327 : :
4328 : : /*
4329 : : * Release the lmgr tuple lock, if we had it.
4330 : : */
7813 tgl@sss.pgh.pa.us 4331 [ + + ]: 2395198 : if (have_tuple_lock)
3083 simon@2ndQuadrant.co 4332 : 22 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4333 : :
1277 pg@bowt.ie 4334 : 2395198 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4335 : :
4336 : : /*
4337 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
4338 : : * back to the caller's image, too.
4339 : : */
7609 tgl@sss.pgh.pa.us 4340 [ + + ]: 2395198 : if (heaptup != newtup)
4341 : : {
4342 : 2180 : newtup->t_self = heaptup->t_self;
4343 : 2180 : heap_freetuple(heaptup);
4344 : : }
4345 : :
4346 : : /*
4347 : : * If it is a HOT update, the update may still need to update summarized
4348 : : * indexes, lest we fail to update those summaries and get incorrect
4349 : : * results (for example, minmax bounds of the block may change with this
4350 : : * update).
4351 : : */
1280 tomas.vondra@postgre 4352 [ + + ]: 2395198 : if (use_hot_update)
4353 : : {
4354 [ + + ]: 166868 : if (summarized_update)
4355 : 2188 : *update_indexes = TU_Summarizing;
4356 : : else
4357 : 164680 : *update_indexes = TU_None;
4358 : : }
4359 : : else
4360 : 2228330 : *update_indexes = TU_All;
4361 : :
4667 rhaas@postgresql.org 4362 [ + + + + ]: 2395198 : if (old_key_tuple != NULL && old_key_copied)
4363 : 93 : heap_freetuple(old_key_tuple);
4364 : :
6940 tgl@sss.pgh.pa.us 4365 : 2395198 : bms_free(hot_attrs);
1280 tomas.vondra@postgre 4366 : 2395198 : bms_free(sum_attrs);
4988 alvherre@alvh.no-ip. 4367 : 2395198 : bms_free(key_attrs);
3679 tgl@sss.pgh.pa.us 4368 : 2395198 : bms_free(id_attrs);
3462 alvherre@alvh.no-ip. 4369 : 2395198 : bms_free(modified_attrs);
4370 : 2395198 : bms_free(interesting_attrs);
4371 : :
2738 andres@anarazel.de 4372 : 2395198 : return TM_Ok;
4373 : : }
4374 : :
4375 : : #ifdef USE_ASSERT_CHECKING
4376 : : /*
4377 : : * Confirm adequate lock held during heap_update(), per rules from
4378 : : * README.tuplock section "Locking to write inplace-updated tables".
4379 : : */
4380 : : static void
726 noah@leadboat.com 4381 : 2395394 : check_lock_if_inplace_updateable_rel(Relation relation,
4382 : : const ItemPointerData *otid,
4383 : : HeapTuple newtup)
4384 : : {
4385 : : /* LOCKTAG_TUPLE acceptable for any catalog */
4386 [ + + ]: 2395394 : switch (RelationGetRelid(relation))
4387 : : {
4388 : 85264 : case RelationRelationId:
4389 : : case DatabaseRelationId:
4390 : : {
4391 : : LOCKTAG tuptag;
4392 : :
4393 : 85264 : SET_LOCKTAG_TUPLE(tuptag,
4394 : : relation->rd_lockInfo.lockRelId.dbId,
4395 : : relation->rd_lockInfo.lockRelId.relId,
4396 : : ItemPointerGetBlockNumber(otid),
4397 : : ItemPointerGetOffsetNumber(otid));
4398 [ + + ]: 85264 : if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
4399 : 36359 : return;
4400 : : }
4401 : 48905 : break;
4402 : 2310130 : default:
4403 [ - + ]: 2310130 : Assert(!IsInplaceUpdateRelation(relation));
4404 : 2310130 : return;
4405 : : }
4406 : :
4407 [ + - - ]: 48905 : switch (RelationGetRelid(relation))
4408 : : {
4409 : 48905 : case RelationRelationId:
4410 : : {
4411 : : /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4412 : 48905 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
4413 : 48905 : Oid relid = classForm->oid;
4414 : : Oid dbid;
4415 : : LOCKTAG tag;
4416 : :
4417 [ + + ]: 48905 : if (IsSharedRelation(relid))
4418 : 47 : dbid = InvalidOid;
4419 : : else
4420 : 48858 : dbid = MyDatabaseId;
4421 : :
4422 [ + + ]: 48905 : if (classForm->relkind == RELKIND_INDEX)
4423 : : {
4424 : 1387 : Relation irel = index_open(relid, AccessShareLock);
4425 : :
4426 : 1387 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4427 : 1387 : index_close(irel, AccessShareLock);
4428 : : }
4429 : : else
4430 : 47518 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4431 : :
4432 [ + + ]: 48905 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4433 [ - + ]: 44421 : !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
726 noah@leadboat.com 4434 [ # # ]:UBC 0 : elog(WARNING,
4435 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4436 : : NameStr(classForm->relname),
4437 : : relid,
4438 : : classForm->relkind,
4439 : : ItemPointerGetBlockNumber(otid),
4440 : : ItemPointerGetOffsetNumber(otid));
4441 : : }
726 noah@leadboat.com 4442 :CBC 48905 : break;
726 noah@leadboat.com 4443 :UBC 0 : case DatabaseRelationId:
4444 : : {
4445 : : /* LOCKTAG_TUPLE required */
4446 : 0 : Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
4447 : :
4448 [ # # ]: 0 : elog(WARNING,
4449 : : "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4450 : : NameStr(dbForm->datname),
4451 : : dbForm->oid,
4452 : : ItemPointerGetBlockNumber(otid),
4453 : : ItemPointerGetOffsetNumber(otid));
4454 : : }
4455 : 0 : break;
4456 : : }
4457 : : }
4458 : :
4459 : : /*
4460 : : * Confirm adequate relation lock held, per rules from README.tuplock section
4461 : : * "Locking to write inplace-updated tables".
4462 : : */
4463 : : static void
726 noah@leadboat.com 4464 :CBC 112992 : check_inplace_rel_lock(HeapTuple oldtup)
4465 : : {
4466 : 112992 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
4467 : 112992 : Oid relid = classForm->oid;
4468 : : Oid dbid;
4469 : : LOCKTAG tag;
4470 : :
4471 [ + + ]: 112992 : if (IsSharedRelation(relid))
4472 : 10096 : dbid = InvalidOid;
4473 : : else
4474 : 102896 : dbid = MyDatabaseId;
4475 : :
4476 [ + + ]: 112992 : if (classForm->relkind == RELKIND_INDEX)
4477 : : {
4478 : 49584 : Relation irel = index_open(relid, AccessShareLock);
4479 : :
4480 : 49584 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4481 : 49584 : index_close(irel, AccessShareLock);
4482 : : }
4483 : : else
4484 : 63408 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4485 : :
4486 [ - + ]: 112992 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
726 noah@leadboat.com 4487 [ # # ]:UBC 0 : elog(WARNING,
4488 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4489 : : NameStr(classForm->relname),
4490 : : relid,
4491 : : classForm->relkind,
4492 : : ItemPointerGetBlockNumber(&oldtup->t_self),
4493 : : ItemPointerGetOffsetNumber(&oldtup->t_self));
726 noah@leadboat.com 4494 :CBC 112992 : }
4495 : : #endif
4496 : :
4497 : : /*
4498 : : * Check if the specified attribute's values are the same. Subroutine for
4499 : : * HeapDetermineColumnsInfo.
4500 : : */
4501 : : static bool
1679 akapila@postgresql.o 4502 : 1006826 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4503 : : bool isnull1, bool isnull2)
4504 : : {
4505 : : /*
4506 : : * If one value is NULL and other is not, then they are certainly not
4507 : : * equal
4508 : : */
6940 tgl@sss.pgh.pa.us 4509 [ + + ]: 1006826 : if (isnull1 != isnull2)
4510 : 62 : return false;
4511 : :
4512 : : /*
4513 : : * If both are NULL, they can be considered equal.
4514 : : */
4515 [ + + ]: 1006764 : if (isnull1)
4516 : 6641 : return true;
4517 : :
4518 : : /*
4519 : : * We do simple binary comparison of the two datums. This may be overly
4520 : : * strict because there can be multiple binary representations for the
4521 : : * same logical value. But we should be OK as long as there are no false
4522 : : * positives. Using a type-specific equality operator is messy because
4523 : : * there could be multiple notions of equality in different operator
4524 : : * classes; furthermore, we cannot safely invoke user-defined functions
4525 : : * while holding exclusive buffer lock.
4526 : : */
4527 [ - + ]: 1000123 : if (attrnum <= 0)
4528 : : {
4529 : : /* The only allowed system columns are OIDs, so do this */
6940 tgl@sss.pgh.pa.us 4530 :UBC 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4531 : : }
4532 : : else
4533 : : {
4534 : : CompactAttribute *att;
4535 : :
6940 tgl@sss.pgh.pa.us 4536 [ - + ]:CBC 1000123 : Assert(attrnum <= tupdesc->natts);
639 drowley@postgresql.o 4537 : 1000123 : att = TupleDescCompactAttr(tupdesc, attrnum - 1);
6940 tgl@sss.pgh.pa.us 4538 : 1000123 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4539 : : }
4540 : : }
4541 : :
4542 : : /*
4543 : : * Check which columns are being updated.
4544 : : *
4545 : : * Given an updated tuple, determine (and return into the output bitmapset),
4546 : : * from those listed as interesting, the set of columns that changed.
4547 : : *
4548 : : * has_external indicates if any of the unmodified attributes (from those
4549 : : * listed as interesting) of the old tuple is a member of external_cols and is
4550 : : * stored externally.
4551 : : */
4552 : : static Bitmapset *
1679 akapila@postgresql.o 4553 : 2395393 : HeapDetermineColumnsInfo(Relation relation,
4554 : : Bitmapset *interesting_cols,
4555 : : Bitmapset *external_cols,
4556 : : HeapTuple oldtup, HeapTuple newtup,
4557 : : bool *has_external)
4558 : : {
4559 : : int attidx;
3413 bruce@momjian.us 4560 : 2395393 : Bitmapset *modified = NULL;
1679 akapila@postgresql.o 4561 : 2395393 : TupleDesc tupdesc = RelationGetDescr(relation);
4562 : :
1298 tgl@sss.pgh.pa.us 4563 : 2395393 : attidx = -1;
4564 [ + + ]: 3402219 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4565 : : {
4566 : : /* attidx is zero-based, attrnum is the normal attribute number */
4567 : 1006826 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4568 : : Datum value1,
4569 : : value2;
4570 : : bool isnull1,
4571 : : isnull2;
4572 : :
4573 : : /*
4574 : : * If it's a whole-tuple reference, say "not equal". It's not really
4575 : : * worth supporting this case, since it could only succeed after a
4576 : : * no-op update, which is hardly a case worth optimizing for.
4577 : : */
1679 akapila@postgresql.o 4578 [ - + ]: 1006826 : if (attrnum == 0)
4579 : : {
1298 tgl@sss.pgh.pa.us 4580 :UBC 0 : modified = bms_add_member(modified, attidx);
1679 akapila@postgresql.o 4581 :CBC 974737 : continue;
4582 : : }
4583 : :
4584 : : /*
4585 : : * Likewise, automatically say "not equal" for any system attribute
4586 : : * other than tableOID; we cannot expect these to be consistent in a
4587 : : * HOT chain, or even to be set correctly yet in the new tuple.
4588 : : */
4589 [ - + ]: 1006826 : if (attrnum < 0)
4590 : : {
1679 akapila@postgresql.o 4591 [ # # ]:UBC 0 : if (attrnum != TableOidAttributeNumber)
4592 : : {
1298 tgl@sss.pgh.pa.us 4593 : 0 : modified = bms_add_member(modified, attidx);
1679 akapila@postgresql.o 4594 : 0 : continue;
4595 : : }
4596 : : }
4597 : :
4598 : : /*
4599 : : * Extract the corresponding values. XXX this is pretty inefficient
4600 : : * if there are many indexed columns. Should we do a single
4601 : : * heap_deform_tuple call on each tuple, instead? But that doesn't
4602 : : * work for system columns ...
4603 : : */
1679 akapila@postgresql.o 4604 :CBC 1006826 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4605 : 1006826 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4606 : :
4607 [ + + ]: 1006826 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4608 : : value2, isnull1, isnull2))
4609 : : {
1298 tgl@sss.pgh.pa.us 4610 : 64205 : modified = bms_add_member(modified, attidx);
1679 akapila@postgresql.o 4611 : 64205 : continue;
4612 : : }
4613 : :
4614 : : /*
4615 : : * No need to check attributes that can't be stored externally. Note
4616 : : * that system attributes can't be stored externally.
4617 : : */
4618 [ + - + + ]: 942621 : if (attrnum < 0 || isnull1 ||
639 drowley@postgresql.o 4619 [ + + ]: 935980 : TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
1679 akapila@postgresql.o 4620 : 910532 : continue;
4621 : :
4622 : : /*
4623 : : * Check if the old tuple's attribute is stored externally and is a
4624 : : * member of external_cols.
4625 : : */
221 michael@paquier.xyz 4626 [ + + + + ]: 32094 : if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
1298 tgl@sss.pgh.pa.us 4627 : 5 : bms_is_member(attidx, external_cols))
1679 akapila@postgresql.o 4628 : 2 : *has_external = true;
4629 : : }
4630 : :
3462 alvherre@alvh.no-ip. 4631 : 2395393 : return modified;
4632 : : }
4633 : :
4634 : : /*
4635 : : * simple_heap_update - replace a tuple
4636 : : *
4637 : : * This routine may be used to update a tuple when concurrent updates of
4638 : : * the target tuple are not expected (for example, because we have a lock
4639 : : * on the relation associated with the tuple). Any failure is reported
4640 : : * via ereport().
4641 : : */
4642 : : void
325 peter@eisentraut.org 4643 : 137575 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
4644 : : TU_UpdateIndexes *update_indexes)
4645 : : {
4646 : : TM_Result result;
4647 : : TM_FailureData tmfd;
4648 : : LockTupleMode lockmode;
4649 : :
8406 tgl@sss.pgh.pa.us 4650 : 137575 : result = heap_update(relation, otid, tup,
4651 : : GetCurrentCommandId(true), 0,
4652 : : InvalidSnapshot,
4653 : : true /* wait for commit */ ,
4654 : : &tmfd, &lockmode, update_indexes);
9371 4655 [ - + - + : 137575 : switch (result)
- ]
4656 : : {
2738 andres@anarazel.de 4657 :UBC 0 : case TM_SelfModified:
4658 : : /* Tuple was already updated in current command? */
8462 tgl@sss.pgh.pa.us 4659 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
4660 : : break;
4661 : :
2738 andres@anarazel.de 4662 :CBC 137574 : case TM_Ok:
4663 : : /* done successfully */
9371 tgl@sss.pgh.pa.us 4664 : 137574 : break;
4665 : :
2738 andres@anarazel.de 4666 :UBC 0 : case TM_Updated:
8462 tgl@sss.pgh.pa.us 4667 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
4668 : : break;
4669 : :
2738 andres@anarazel.de 4670 :CBC 1 : case TM_Deleted:
4671 [ + - ]: 1 : elog(ERROR, "tuple concurrently deleted");
4672 : : break;
4673 : :
9371 tgl@sss.pgh.pa.us 4674 :UBC 0 : default:
8462 4675 [ # # ]: 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4676 : : break;
4677 : : }
9371 tgl@sss.pgh.pa.us 4678 :CBC 137574 : }
4679 : :
4680 : :
4681 : : /*
4682 : : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4683 : : */
4684 : : static MultiXactStatus
4988 alvherre@alvh.no-ip. 4685 : 115450 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4686 : : {
4687 : : int retval;
4688 : :
4689 [ + + ]: 115450 : if (is_update)
4690 : 217 : retval = tupleLockExtraInfo[mode].updstatus;
4691 : : else
4692 : 115233 : retval = tupleLockExtraInfo[mode].lockstatus;
4693 : :
4694 [ - + ]: 115450 : if (retval == -1)
4988 alvherre@alvh.no-ip. 4695 [ # # # # ]:UBC 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4696 : : is_update ? "true" : "false");
4697 : :
4835 alvherre@alvh.no-ip. 4698 :CBC 115450 : return (MultiXactStatus) retval;
4699 : : }
4700 : :
4701 : : /*
4702 : : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4703 : : *
4704 : : * Note that this acquires a buffer pin, which the caller must release.
4705 : : *
4706 : : * Input parameters:
4707 : : * relation: relation containing tuple (caller must hold suitable lock)
4708 : : * cid: current command ID (used for visibility test, and stored into
4709 : : * tuple's cmax if lock is successful)
4710 : : * mode: indicates if shared or exclusive tuple lock is desired
4711 : : * wait_policy: what to do if tuple lock is not available
4712 : : * follow_updates: if true, follow the update chain to also lock descendant
4713 : : * tuples.
4714 : : *
4715 : : * Output parameters:
4716 : : * *tuple: all fields filled in
4717 : : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4718 : : * *tmfd: filled in failure cases (see below)
4719 : : *
4720 : : * Function results are the same as the ones for table_tuple_lock().
4721 : : *
4722 : : * In the failure cases other than TM_Invisible, the routine fills
4723 : : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4724 : : * if necessary), and t_cmax (the last only for TM_SelfModified,
4725 : : * since we cannot obtain cmax from a combo CID generated by another
4726 : : * transaction).
4727 : : * See comments for struct TM_FailureData for additional info.
4728 : : *
4729 : : * See README.tuplock for a thorough explanation of this mechanism.
4730 : : */
4731 : : TM_Result
892 akorotkov@postgresql 4732 : 571733 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4733 : : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4734 : : bool follow_updates,
4735 : : Buffer *buffer, TM_FailureData *tmfd)
4736 : : {
4737 : : TM_Result result;
4738 : 571733 : ItemPointer tid = &(tuple->t_self);
4739 : : ItemId lp;
4740 : : Page page;
3716 andres@anarazel.de 4741 : 571733 : Buffer vmbuffer = InvalidBuffer;
67 melanieplageman@gmai 4742 : 571733 : bool unlock_vmbuffer = false;
4743 : : BlockNumber block;
4744 : : TransactionId xid,
4745 : : xmax;
4746 : : uint16 old_infomask,
4747 : : new_infomask,
4748 : : new_infomask2;
4181 alvherre@alvh.no-ip. 4749 : 571733 : bool first_time = true;
2651 4750 : 571733 : bool skip_tuple_lock = false;
7813 tgl@sss.pgh.pa.us 4751 : 571733 : bool have_tuple_lock = false;
3716 andres@anarazel.de 4752 : 571733 : bool cleared_all_frozen = false;
4753 : :
892 akorotkov@postgresql 4754 : 571733 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3716 andres@anarazel.de 4755 : 571733 : block = ItemPointerGetBlockNumber(tid);
67 melanieplageman@gmai 4756 : 571733 : page = BufferGetPage(*buffer);
4757 : :
4758 : : /*
4759 : : * Before locking the buffer, pin the visibility map page if it appears to
4760 : : * be necessary. Since we haven't got the lock yet, someone else might be
4761 : : * in the middle of changing this, so we'll need to recheck after we have
4762 : : * the lock.
4763 : : */
4764 [ + + ]: 571733 : if (PageIsAllVisible(page))
3716 andres@anarazel.de 4765 : 413390 : visibilitymap_pin(relation, block, &vmbuffer);
4766 : :
892 akorotkov@postgresql 4767 : 571733 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4768 : :
6643 tgl@sss.pgh.pa.us 4769 : 571733 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6948 4770 [ - + ]: 571733 : Assert(ItemIdIsNormal(lp));
4771 : :
6643 4772 : 571733 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10141 vadim4o@yahoo.com 4773 : 571733 : tuple->t_len = ItemIdGetLength(lp);
7701 tgl@sss.pgh.pa.us 4774 : 571733 : tuple->t_tableOid = RelationGetRelid(relation);
4775 : :
10141 vadim4o@yahoo.com 4776 : 14 : l3:
892 akorotkov@postgresql 4777 : 571747 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4778 : :
2738 andres@anarazel.de 4779 [ + + ]: 571747 : if (result == TM_Invisible)
4780 : : {
4781 : : /*
4782 : : * This is possible, but only when locking a tuple for ON CONFLICT DO
4783 : : * SELECT/UPDATE. We return this value here rather than throwing an
4784 : : * error in order to give that case the opportunity to throw a more
4785 : : * specific error.
4786 : : */
4787 : 28 : result = TM_Invisible;
3716 4788 : 28 : goto out_locked;
4789 : : }
2738 4790 [ + + + + ]: 571719 : else if (result == TM_BeingModified ||
4791 [ + + ]: 81289 : result == TM_Updated ||
4792 : : result == TM_Deleted)
4793 : : {
4794 : : TransactionId xwait;
4795 : : uint16 infomask;
4796 : : uint16 infomask2;
4797 : : bool require_sleep;
4798 : : ItemPointerData t_ctid;
4799 : :
4800 : : /* must copy state data before unlocking buffer */
4988 alvherre@alvh.no-ip. 4801 : 490431 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
7813 tgl@sss.pgh.pa.us 4802 : 490431 : infomask = tuple->t_data->t_infomask;
4988 alvherre@alvh.no-ip. 4803 : 490431 : infomask2 = tuple->t_data->t_infomask2;
4804 : 490431 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4805 : :
892 akorotkov@postgresql 4806 : 490431 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4807 : :
4808 : : /*
4809 : : * If any subtransaction of the current top transaction already holds
4810 : : * a lock as strong as or stronger than what we're requesting, we
4811 : : * effectively hold the desired lock already. We *must* succeed
4812 : : * without trying to take the tuple lock, else we will deadlock
4813 : : * against anyone wanting to acquire a stronger lock.
4814 : : *
4815 : : * Note we only do this the first time we loop on the HTSU result;
4816 : : * there is no point in testing in subsequent passes, because
4817 : : * evidently our own transaction cannot have acquired a new lock after
4818 : : * the first time we checked.
4819 : : */
4181 alvherre@alvh.no-ip. 4820 [ + + ]: 490431 : if (first_time)
4821 : : {
4822 : 490420 : first_time = false;
4823 : :
4824 [ + + ]: 490420 : if (infomask & HEAP_XMAX_IS_MULTI)
4825 : : {
4826 : : int i;
4827 : : int nmembers;
4828 : : MultiXactMember *members;
4829 : :
4830 : : /*
4831 : : * We don't need to allow old multixacts here; if that had
4832 : : * been the case, HeapTupleSatisfiesUpdate would have returned
4833 : : * MayBeUpdated and we wouldn't be here.
4834 : : */
4835 : : nmembers =
4836 : 73288 : GetMultiXactIdMembers(xwait, &members, false,
4837 : 73288 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4838 : :
4839 [ + + ]: 1422633 : for (i = 0; i < nmembers; i++)
4840 : : {
4841 : : /* only consider members of our own transaction */
4842 [ + + ]: 1349359 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4843 : 1349309 : continue;
4844 : :
4845 [ + + ]: 50 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4846 : : {
4988 4847 : 14 : pfree(members);
2738 andres@anarazel.de 4848 : 14 : result = TM_Ok;
3716 4849 : 14 : goto out_unlocked;
4850 : : }
4851 : : else
4852 : : {
4853 : : /*
4854 : : * Disable acquisition of the heavyweight tuple lock.
4855 : : * Otherwise, when promoting a weaker lock, we might
4856 : : * deadlock with another locker that has acquired the
4857 : : * heavyweight tuple lock and is waiting for our
4858 : : * transaction to finish.
4859 : : *
4860 : : * Note that in this case we still need to wait for
4861 : : * the multixact if required, to avoid acquiring
4862 : : * conflicting locks.
4863 : : */
2651 alvherre@alvh.no-ip. 4864 : 36 : skip_tuple_lock = true;
4865 : : }
4866 : : }
4867 : :
4181 4868 [ + - ]: 73274 : if (members)
4869 : 73274 : pfree(members);
4870 : : }
4871 [ + + ]: 417132 : else if (TransactionIdIsCurrentTransactionId(xwait))
4872 : : {
4873 [ + + + + : 415779 : switch (mode)
- ]
4874 : : {
4875 : 409341 : case LockTupleKeyShare:
4876 [ - + - - : 409341 : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
- - ]
4877 : : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4878 : : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
2738 andres@anarazel.de 4879 : 409341 : result = TM_Ok;
3716 4880 : 409341 : goto out_unlocked;
4181 alvherre@alvh.no-ip. 4881 : 37 : case LockTupleShare:
4882 [ + + - + ]: 43 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4883 : 6 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4884 : : {
2738 andres@anarazel.de 4885 : 31 : result = TM_Ok;
3716 4886 : 31 : goto out_unlocked;
4887 : : }
4181 alvherre@alvh.no-ip. 4888 : 6 : break;
4889 : 85 : case LockTupleNoKeyExclusive:
4890 [ + + ]: 85 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4891 : : {
2738 andres@anarazel.de 4892 : 72 : result = TM_Ok;
3716 4893 : 72 : goto out_unlocked;
4894 : : }
4181 alvherre@alvh.no-ip. 4895 : 13 : break;
4896 : 6316 : case LockTupleExclusive:
4897 [ + + ]: 6316 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4898 [ + + ]: 1274 : infomask2 & HEAP_KEYS_UPDATED)
4899 : : {
2738 andres@anarazel.de 4900 : 1245 : result = TM_Ok;
3716 4901 : 1245 : goto out_unlocked;
4902 : : }
4181 alvherre@alvh.no-ip. 4903 : 5071 : break;
4904 : : }
4905 : : }
4906 : : }
4907 : :
4908 : : /*
4909 : : * Initially assume that we will have to wait for the locking
4910 : : * transaction(s) to finish. We check various cases below in which
4911 : : * this can be turned off.
4912 : : */
4988 4913 : 79728 : require_sleep = true;
4914 [ + + ]: 79728 : if (mode == LockTupleKeyShare)
4915 : : {
4916 : : /*
4917 : : * If we're requesting KeyShare, and there's no update present, we
4918 : : * don't need to wait. Even if there is an update, we can still
4919 : : * continue if the key hasn't been modified.
4920 : : *
4921 : : * However, if there are updates, we need to walk the update chain
4922 : : * to mark future versions of the row as locked, too. That way,
4923 : : * if somebody deletes that future version, we're protected
4924 : : * against the key going away. This locking of future versions
4925 : : * could block momentarily, if a concurrent transaction is
4926 : : * deleting a key; or it could return a value to the effect that
4927 : : * the transaction deleting the key has already committed. So we
4928 : : * do this before re-locking the buffer; otherwise this would be
4929 : : * prone to deadlocks.
4930 : : *
4931 : : * Note that the TID we're locking was grabbed before we unlocked
4932 : : * the buffer. For it to change while we're not looking, the
4933 : : * other properties we're testing for below after re-locking the
4934 : : * buffer would also change, in which case we would restart this
4935 : : * loop above.
4936 : : */
4937 [ + + ]: 73863 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4938 : : {
4939 : : bool updated;
4940 : :
4941 : 73811 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4942 : :
4943 : : /*
4944 : : * If there are updates, follow the update chain; bail out if
4945 : : * that cannot be done.
4946 : : */
271 heikki.linnakangas@i 4947 [ + + + + ]: 73811 : if (follow_updates && updated &&
4948 [ + - ]: 2171 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
4949 : : {
4950 : : TM_Result res;
4951 : :
4952 : 2171 : res = heap_lock_updated_tuple(relation,
4953 : : infomask, xwait, &t_ctid,
4954 : : GetCurrentTransactionId(),
4955 : : mode);
2738 andres@anarazel.de 4956 [ + + ]: 2171 : if (res != TM_Ok)
4957 : : {
4988 alvherre@alvh.no-ip. 4958 : 6 : result = res;
4959 : : /* recovery code expects to have buffer lock held */
892 akorotkov@postgresql 4960 : 6 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4988 alvherre@alvh.no-ip. 4961 : 204 : goto failed;
4962 : : }
4963 : : }
4964 : :
892 akorotkov@postgresql 4965 : 73805 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4966 : :
4967 : : /*
4968 : : * Make sure it's still an appropriate lock, else start over.
4969 : : * Also, if it wasn't updated before we released the lock, but
4970 : : * is updated now, we start over too; the reason is that we
4971 : : * now need to follow the update chain to lock the new
4972 : : * versions.
4973 : : */
4988 alvherre@alvh.no-ip. 4974 [ + + ]: 73805 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4975 [ + - ]: 2154 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4976 [ - + ]: 2154 : !updated))
4977 : 14 : goto l3;
4978 : :
4979 : : /* Things look okay, so we can skip sleeping */
4980 : 73805 : require_sleep = false;
4981 : :
4982 : : /*
4983 : : * Note we allow Xmax to change here; other updaters/lockers
4984 : : * could have modified it before we grabbed the buffer lock.
4985 : : * However, this is not a problem, because with the recheck we
4986 : : * just did we ensure that they still don't conflict with the
4987 : : * lock we want.
4988 : : */
4989 : : }
4990 : : }
4991 [ + + ]: 5865 : else if (mode == LockTupleShare)
4992 : : {
4993 : : /*
4994 : : * If we're requesting Share, we can similarly avoid sleeping if
4995 : : * there's no update and no exclusive lock present.
4996 : : */
4997 [ + - ]: 451 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4998 [ + + ]: 451 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4999 : : {
892 akorotkov@postgresql 5000 : 445 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5001 : :
5002 : : /*
5003 : : * Make sure it's still an appropriate lock, else start over.
5004 : : * See above about allowing xmax to change.
5005 : : */
4988 alvherre@alvh.no-ip. 5006 [ + - - + ]: 890 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5007 : 445 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
4988 alvherre@alvh.no-ip. 5008 :UBC 0 : goto l3;
4988 alvherre@alvh.no-ip. 5009 :CBC 445 : require_sleep = false;
5010 : : }
5011 : : }
5012 [ + + ]: 5414 : else if (mode == LockTupleNoKeyExclusive)
5013 : : {
5014 : : /*
5015 : : * If we're requesting NoKeyExclusive, we might also be able to
5016 : : * avoid sleeping; just ensure that there no conflicting lock
5017 : : * already acquired.
5018 : : */
5019 [ + + ]: 176 : if (infomask & HEAP_XMAX_IS_MULTI)
5020 : : {
4286 5021 [ + + ]: 26 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
5022 : : mode, NULL))
5023 : : {
5024 : : /*
5025 : : * No conflict, but if the xmax changed under us in the
5026 : : * meantime, start over.
5027 : : */
892 akorotkov@postgresql 5028 : 13 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4286 alvherre@alvh.no-ip. 5029 [ + - - + ]: 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5030 : 13 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5031 : : xwait))
4286 alvherre@alvh.no-ip. 5032 :UBC 0 : goto l3;
5033 : :
5034 : : /* otherwise, we're good */
4286 alvherre@alvh.no-ip. 5035 :CBC 13 : require_sleep = false;
5036 : : }
5037 : : }
4988 5038 [ + + ]: 150 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
5039 : : {
892 akorotkov@postgresql 5040 : 19 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5041 : :
5042 : : /* if the xmax changed in the meantime, start over */
4532 alvherre@alvh.no-ip. 5043 [ + - - + ]: 38 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
2425 5044 : 19 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5045 : : xwait))
4988 alvherre@alvh.no-ip. 5046 :UBC 0 : goto l3;
5047 : : /* otherwise, we're good */
4988 alvherre@alvh.no-ip. 5048 :CBC 19 : require_sleep = false;
5049 : : }
5050 : : }
5051 : :
5052 : : /*
5053 : : * As a check independent from those above, we can also avoid sleeping
5054 : : * if the current transaction is the sole locker of the tuple. Note
5055 : : * that the strength of the lock already held is irrelevant; this is
5056 : : * not about recording the lock in Xmax (which will be done regardless
5057 : : * of this optimization, below). Also, note that the cases where we
5058 : : * hold a lock stronger than we are requesting are already handled
5059 : : * above by not doing anything.
5060 : : *
5061 : : * Note we only deal with the non-multixact case here; MultiXactIdWait
5062 : : * is well equipped to deal with this situation on its own.
5063 : : */
4181 5064 [ + + + + : 85119 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
+ + ]
5065 : 5397 : TransactionIdIsCurrentTransactionId(xwait))
5066 : : {
5067 : : /* ... but if the xmax changed in the meantime, start over */
892 akorotkov@postgresql 5068 : 5071 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4181 alvherre@alvh.no-ip. 5069 [ + - - + ]: 10142 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5070 : 5071 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5071 : : xwait))
4181 alvherre@alvh.no-ip. 5072 :UBC 0 : goto l3;
4181 alvherre@alvh.no-ip. 5073 [ - + ]:CBC 5071 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
5074 : 5071 : require_sleep = false;
5075 : : }
5076 : :
5077 : : /*
5078 : : * Time to sleep on the other transaction/multixact, if necessary.
5079 : : *
5080 : : * If the other transaction is an update/delete that's already
5081 : : * committed, then sleeping cannot possibly do any good: if we're
5082 : : * required to sleep, get out to raise an error instead.
5083 : : *
5084 : : * By here, we either have already acquired the buffer exclusive lock,
5085 : : * or we must wait for the locking transaction or multixact; so below
5086 : : * we ensure that we grab buffer lock after the sleep.
5087 : : */
2738 andres@anarazel.de 5088 [ + + + + : 79722 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
+ + ]
5089 : : {
892 akorotkov@postgresql 5090 : 157 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3719 alvherre@alvh.no-ip. 5091 : 157 : goto failed;
5092 : : }
5093 [ + + ]: 79565 : else if (require_sleep)
5094 : : {
5095 : : /*
5096 : : * Acquire tuple lock to establish our priority for the tuple, or
5097 : : * die trying. LockTuple will release us when we are next-in-line
5098 : : * for the tuple. We must do this even if we are share-locking,
5099 : : * but not if we already have a weaker lock on the tuple.
5100 : : *
5101 : : * If we are forced to "start over" below, we keep the tuple lock;
5102 : : * this arranges that we stay at the head of the line while
5103 : : * rechecking tuple state.
5104 : : */
2651 5105 [ + + ]: 212 : if (!skip_tuple_lock &&
5106 [ + + ]: 195 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
5107 : : &have_tuple_lock))
5108 : : {
5109 : : /*
5110 : : * This can only happen if wait_policy is Skip and the lock
5111 : : * couldn't be obtained.
5112 : : */
2738 andres@anarazel.de 5113 : 1 : result = TM_WouldBlock;
5114 : : /* recovery code expects to have buffer lock held */
892 akorotkov@postgresql 5115 : 1 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4286 alvherre@alvh.no-ip. 5116 : 1 : goto failed;
5117 : : }
5118 : :
4988 5119 [ + + ]: 210 : if (infomask & HEAP_XMAX_IS_MULTI)
5120 : : {
5121 : 43 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
5122 : :
5123 : : /* We only ever lock tuples, never update them */
5124 [ - + ]: 43 : if (status >= MultiXactStatusNoKeyUpdate)
4988 alvherre@alvh.no-ip. 5125 [ # # ]:UBC 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
5126 : :
5127 : : /* wait for multixact to end, or die trying */
4366 alvherre@alvh.no-ip. 5128 [ + + + - ]:CBC 43 : switch (wait_policy)
5129 : : {
5130 : 37 : case LockWaitBlock:
5131 : 37 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
3378 tgl@sss.pgh.pa.us 5132 : 37 : relation, &tuple->t_self, XLTW_Lock, NULL);
4366 alvherre@alvh.no-ip. 5133 : 37 : break;
5134 : 2 : case LockWaitSkip:
5135 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5136 : : status, infomask, relation,
5137 : : NULL, false))
5138 : : {
2738 andres@anarazel.de 5139 : 2 : result = TM_WouldBlock;
5140 : : /* recovery code expects to have buffer lock held */
892 akorotkov@postgresql 5141 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4366 alvherre@alvh.no-ip. 5142 : 2 : goto failed;
5143 : : }
4366 alvherre@alvh.no-ip. 5144 :UBC 0 : break;
4366 alvherre@alvh.no-ip. 5145 :CBC 4 : case LockWaitError:
5146 [ + - ]: 4 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5147 : : status, infomask, relation,
5148 : : NULL, log_lock_failures))
5149 [ + - ]: 4 : ereport(ERROR,
5150 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5151 : : errmsg("could not obtain lock on row in relation \"%s\"",
5152 : : RelationGetRelationName(relation))));
5153 : :
4366 alvherre@alvh.no-ip. 5154 :UBC 0 : break;
5155 : : }
5156 : :
5157 : : /*
5158 : : * Of course, the multixact might not be done here: if we're
5159 : : * requesting a light lock mode, other transactions with light
5160 : : * locks could still be alive, as well as locks owned by our
5161 : : * own xact or other subxacts of this backend. We need to
5162 : : * preserve the surviving MultiXact members. Note that it
5163 : : * isn't absolutely necessary in the latter case, but doing so
5164 : : * is simpler.
5165 : : */
5166 : : }
5167 : : else
5168 : : {
5169 : : /* wait for regular transaction to end, or die trying */
4366 alvherre@alvh.no-ip. 5170 [ + + + - ]:CBC 167 : switch (wait_policy)
5171 : : {
5172 : 126 : case LockWaitBlock:
4246 heikki.linnakangas@i 5173 : 126 : XactLockTableWait(xwait, relation, &tuple->t_self,
5174 : : XLTW_Lock);
4366 alvherre@alvh.no-ip. 5175 : 126 : break;
5176 : 33 : case LockWaitSkip:
555 fujii@postgresql.org 5177 [ + - ]: 33 : if (!ConditionalXactLockTableWait(xwait, false))
5178 : : {
2738 andres@anarazel.de 5179 : 33 : result = TM_WouldBlock;
5180 : : /* recovery code expects to have buffer lock held */
892 akorotkov@postgresql 5181 : 33 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4366 alvherre@alvh.no-ip. 5182 : 33 : goto failed;
5183 : : }
4366 alvherre@alvh.no-ip. 5184 :UBC 0 : break;
4366 alvherre@alvh.no-ip. 5185 :CBC 8 : case LockWaitError:
474 fujii@postgresql.org 5186 [ + - ]: 8 : if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
4366 alvherre@alvh.no-ip. 5187 [ + - ]: 8 : ereport(ERROR,
5188 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5189 : : errmsg("could not obtain lock on row in relation \"%s\"",
5190 : : RelationGetRelationName(relation))));
4366 alvherre@alvh.no-ip. 5191 :UBC 0 : break;
5192 : : }
5193 : : }
5194 : :
5195 : : /* if there are updates, follow the update chain */
271 heikki.linnakangas@i 5196 [ + + + + ]:CBC 163 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5197 [ + + ]: 70 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
5198 : : {
5199 : : TM_Result res;
5200 : :
5201 : 54 : res = heap_lock_updated_tuple(relation,
5202 : : infomask, xwait, &t_ctid,
5203 : : GetCurrentTransactionId(),
5204 : : mode);
2738 andres@anarazel.de 5205 [ + + ]: 54 : if (res != TM_Ok)
5206 : : {
4181 alvherre@alvh.no-ip. 5207 : 5 : result = res;
5208 : : /* recovery code expects to have buffer lock held */
892 akorotkov@postgresql 5209 : 5 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4181 alvherre@alvh.no-ip. 5210 : 5 : goto failed;
5211 : : }
5212 : : }
5213 : :
892 akorotkov@postgresql 5214 : 158 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5215 : :
5216 : : /*
5217 : : * xwait is done, but if xwait had just locked the tuple then some
5218 : : * other xact could update this tuple before we get to this point.
5219 : : * Check for xmax change, and start over if so.
5220 : : */
4181 alvherre@alvh.no-ip. 5221 [ + + + + ]: 303 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5222 : 145 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5223 : : xwait))
5224 : 14 : goto l3;
5225 : :
5226 [ + + ]: 144 : if (!(infomask & HEAP_XMAX_IS_MULTI))
5227 : : {
5228 : : /*
5229 : : * Otherwise check if it committed or aborted. Note we cannot
5230 : : * be here if the tuple was only locked by somebody who didn't
5231 : : * conflict with us; that would have been handled above. So
5232 : : * that transaction must necessarily be gone by now. But
5233 : : * don't check for this in the multixact case, because some
5234 : : * locker transactions might still be running.
5235 : : */
892 akorotkov@postgresql 5236 : 108 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5237 : : }
5238 : : }
5239 : :
5240 : : /* By here, we're certain that we hold buffer exclusive lock again */
5241 : :
5242 : : /*
5243 : : * We may lock if previous xmax aborted, or if it committed but only
5244 : : * locked the tuple without updating it; or if we didn't have to wait
5245 : : * at all for whatever reason.
5246 : : */
4988 alvherre@alvh.no-ip. 5247 [ + + ]: 79497 : if (!require_sleep ||
5248 [ + + + + ]: 252 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5249 [ + + ]: 200 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5250 : 92 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
2738 andres@anarazel.de 5251 : 79414 : result = TM_Ok;
2036 alvherre@alvh.no-ip. 5252 [ + + ]: 83 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
2738 andres@anarazel.de 5253 : 63 : result = TM_Updated;
5254 : : else
5255 : 20 : result = TM_Deleted;
5256 : : }
5257 : :
4988 alvherre@alvh.no-ip. 5258 : 81288 : failed:
2738 andres@anarazel.de 5259 [ + + ]: 160989 : if (result != TM_Ok)
5260 : : {
5261 [ + + + + : 295 : Assert(result == TM_SelfModified || result == TM_Updated ||
+ + - + ]
5262 : : result == TM_Deleted || result == TM_WouldBlock);
5263 : :
5264 : : /*
5265 : : * When locking a tuple under LockWaitSkip semantics and we fail with
5266 : : * TM_WouldBlock above, it's possible for concurrent transactions to
5267 : : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5268 : : * this assert is slightly different from the equivalent one in
5269 : : * heap_delete and heap_update.
5270 : : */
1720 alvherre@alvh.no-ip. 5271 [ + + - + ]: 295 : Assert((result == TM_WouldBlock) ||
5272 : : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
2738 andres@anarazel.de 5273 [ + + - + ]: 295 : Assert(result != TM_Updated ||
5274 : : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5275 : 295 : tmfd->ctid = tuple->t_data->t_ctid;
5276 : 295 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5277 [ + + ]: 295 : if (result == TM_SelfModified)
5278 : 8 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5279 : : else
5280 : 287 : tmfd->cmax = InvalidCommandId;
3716 5281 : 295 : goto out_locked;
5282 : : }
5283 : :
5284 : : /*
5285 : : * If we didn't pin the visibility map page and the page has become all
5286 : : * visible while we were busy locking the buffer, or during some
5287 : : * subsequent window during which we had it unlocked, we'll have to unlock
5288 : : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5289 : : * unfortunate, especially since we'll now have to recheck whether the
5290 : : * tuple has been locked or updated under us, but hopefully it won't
5291 : : * happen very often.
5292 : : */
3699 5293 [ + + - + ]: 160694 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5294 : : {
892 akorotkov@postgresql 5295 :UBC 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3699 andres@anarazel.de 5296 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
892 akorotkov@postgresql 5297 : 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3699 andres@anarazel.de 5298 : 0 : goto l3;
5299 : : }
5300 : :
4988 alvherre@alvh.no-ip. 5301 :CBC 160694 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5302 : 160694 : old_infomask = tuple->t_data->t_infomask;
5303 : :
5304 : : /*
5305 : : * If this is the first possibly-multixact-able operation in the current
5306 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
5307 : : * certain that the transaction will never become a member of any older
5308 : : * MultiXactIds than that. (We have to do this even if we end up just
5309 : : * using our own TransactionId below, since some other backend could
5310 : : * incorporate our XID into a MultiXact immediately afterwards.)
5311 : : */
5312 : 160694 : MultiXactIdSetOldestMember();
5313 : :
5314 : : /*
5315 : : * Compute the new xmax and infomask to store into the tuple. Note we do
5316 : : * not modify the tuple just yet, because that would leave it in the wrong
5317 : : * state if multixact.c elogs.
5318 : : */
5319 : 160694 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5320 : : GetCurrentTransactionId(), mode, false,
5321 : : &xid, &new_infomask, &new_infomask2);
5322 : :
5323 : : /* Lock VM buffer before entering critical section */
67 melanieplageman@gmai 5324 [ + + ]: 160694 : if (PageIsAllVisible(page))
5325 : : {
5326 : 3493 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
5327 : 3493 : unlock_vmbuffer = true;
5328 : : }
5329 : :
7815 tgl@sss.pgh.pa.us 5330 : 160694 : START_CRIT_SECTION();
5331 : :
5332 : : /*
5333 : : * Store transaction information of xact locking the tuple.
5334 : : *
5335 : : * Note: Cmax is meaningless in this context, so don't set it; this avoids
5336 : : * possibly generating a useless combo CID. Moreover, if we're locking a
5337 : : * previously updated tuple, it's important to preserve the Cmax.
5338 : : *
5339 : : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5340 : : * we would break the HOT chain.
5341 : : */
4988 alvherre@alvh.no-ip. 5342 : 160694 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5343 : 160694 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5344 : 160694 : tuple->t_data->t_infomask |= new_infomask;
5345 : 160694 : tuple->t_data->t_infomask2 |= new_infomask2;
5346 [ + + ]: 160694 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5347 : 158544 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
8039 tgl@sss.pgh.pa.us 5348 : 160694 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
5349 : :
5350 : : /*
5351 : : * Make sure there is no forward chain link in t_ctid. Note that in the
5352 : : * cases where the tuple has been updated, we must not overwrite t_ctid,
5353 : : * because it was set by the updater. Moreover, if the tuple has been
5354 : : * updated, we need to follow the update chain to lock the new versions of
5355 : : * the tuple as well.
5356 : : */
4988 alvherre@alvh.no-ip. 5357 [ + + ]: 160694 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5358 : 158544 : tuple->t_data->t_ctid = *tid;
5359 : :
5360 : : /* Clear only the all-frozen bit on visibility map if needed */
67 melanieplageman@gmai 5361 [ + + ]: 160694 : if (PageIsAllVisible(page))
5362 : : {
67 melanieplageman@gmai 5363 [ + + ]:GNC 3493 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
5364 : : VISIBILITYMAP_ALL_FROZEN))
67 melanieplageman@gmai 5365 :CBC 16 : cleared_all_frozen = true;
5366 : : }
5367 : :
5368 : :
892 akorotkov@postgresql 5369 : 160694 : MarkBufferDirty(*buffer);
5370 : :
5371 : : /*
5372 : : * XLOG stuff. You might think that we don't need an XLOG record because
5373 : : * there is no state change worth restoring after a crash. You would be
5374 : : * wrong however: we have just written either a TransactionId or a
5375 : : * MultiXactId that may never have been seen on disk before, and we need
5376 : : * to make sure that there are XLOG entries covering those ID numbers.
5377 : : * Else the same IDs might be re-used after a crash, which would be
5378 : : * disastrous if this page made it to disk before the crash. Essentially
5379 : : * we have to enforce the WAL log-before-data rule even in this case.
5380 : : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5381 : : * entries for everything anyway.)
5382 : : */
5760 rhaas@postgresql.org 5383 [ + + + + : 160694 : if (RelationNeedsWAL(relation))
+ - + - ]
5384 : : {
5385 : : xl_heap_lock xlrec;
5386 : : XLogRecPtr recptr;
5387 : :
4322 heikki.linnakangas@i 5388 : 160265 : XLogBeginInsert();
67 melanieplageman@gmai 5389 : 160265 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, *buffer, REGBUF_STANDARD);
5390 : :
4322 heikki.linnakangas@i 5391 : 160265 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
1258 pg@bowt.ie 5392 : 160265 : xlrec.xmax = xid;
4988 alvherre@alvh.no-ip. 5393 : 320530 : xlrec.infobits_set = compute_infobits(new_infomask,
5394 : 160265 : tuple->t_data->t_infomask2);
3716 andres@anarazel.de 5395 : 160265 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
586 peter@eisentraut.org 5396 : 160265 : XLogRegisterData(&xlrec, SizeOfHeapLock);
5397 : :
67 melanieplageman@gmai 5398 [ + + ]: 160265 : if (cleared_all_frozen)
5399 : 16 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
5400 : :
5401 : : /* we don't decode row locks atm, so no need to log the origin */
5402 : :
4322 heikki.linnakangas@i 5403 : 160265 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5404 : :
6643 tgl@sss.pgh.pa.us 5405 : 160265 : PageSetLSN(page, recptr);
5406 : :
67 melanieplageman@gmai 5407 [ + + ]: 160265 : if (cleared_all_frozen)
5408 : 16 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
5409 : : }
5410 : :
7815 tgl@sss.pgh.pa.us 5411 [ - + ]: 160694 : END_CRIT_SECTION();
5412 : :
5413 : : /* release VM lock first, since it covers many heap blocks */
67 melanieplageman@gmai 5414 [ + + ]: 160694 : if (unlock_vmbuffer)
5415 : : {
5416 : 3493 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
5417 : 3493 : unlock_vmbuffer = false;
5418 : : }
5419 : :
2738 andres@anarazel.de 5420 : 160694 : result = TM_Ok;
5421 : :
3716 5422 : 161017 : out_locked:
892 akorotkov@postgresql 5423 : 161017 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
67 melanieplageman@gmai 5424 [ - + ]: 161017 : Assert(!unlock_vmbuffer);
5425 : :
3716 andres@anarazel.de 5426 : 161017 : out_unlocked:
5427 [ + + ]: 571720 : if (BufferIsValid(vmbuffer))
5428 : 413390 : ReleaseBuffer(vmbuffer);
5429 : :
5430 : : /*
5431 : : * Don't update the visibility map here. Locking a tuple doesn't change
5432 : : * visibility info.
5433 : : */
5434 : :
5435 : : /*
5436 : : * Now that we have successfully marked the tuple as locked, we can
5437 : : * release the lmgr tuple lock, if we had it.
5438 : : */
7813 tgl@sss.pgh.pa.us 5439 [ + + ]: 571720 : if (have_tuple_lock)
4988 alvherre@alvh.no-ip. 5440 : 176 : UnlockTupleTuplock(relation, tid, mode);
5441 : :
3716 andres@anarazel.de 5442 : 571720 : return result;
5443 : : }
5444 : :
5445 : : /*
5446 : : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5447 : : * its normal, Xmax-based tuple lock.
5448 : : *
5449 : : * have_tuple_lock is an input and output parameter: on input, it indicates
5450 : : * whether the lock has previously been acquired (and this function does
5451 : : * nothing in that case). If this function returns success, have_tuple_lock
5452 : : * has been flipped to true.
5453 : : *
5454 : : * Returns false if it was unable to obtain the lock; this can only happen if
5455 : : * wait_policy is Skip.
5456 : : */
5457 : : static bool
325 peter@eisentraut.org 5458 : 338 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
5459 : : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5460 : : {
4286 alvherre@alvh.no-ip. 5461 [ + + ]: 338 : if (*have_tuple_lock)
5462 : 9 : return true;
5463 : :
5464 [ + + + - ]: 329 : switch (wait_policy)
5465 : : {
5466 : 284 : case LockWaitBlock:
5467 : 284 : LockTupleTuplock(relation, tid, mode);
5468 : 284 : break;
5469 : :
5470 : 34 : case LockWaitSkip:
555 fujii@postgresql.org 5471 [ + + ]: 34 : if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
4286 alvherre@alvh.no-ip. 5472 : 1 : return false;
5473 : 33 : break;
5474 : :
5475 : 11 : case LockWaitError:
474 fujii@postgresql.org 5476 [ + + ]: 11 : if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
4286 alvherre@alvh.no-ip. 5477 [ + - ]: 1 : ereport(ERROR,
5478 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5479 : : errmsg("could not obtain lock on row in relation \"%s\"",
5480 : : RelationGetRelationName(relation))));
5481 : 10 : break;
5482 : : }
5483 : 327 : *have_tuple_lock = true;
5484 : :
5485 : 327 : return true;
5486 : : }
5487 : :
5488 : : /*
5489 : : * Given an original set of Xmax and infomask, and a transaction (identified by
5490 : : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5491 : : * corresponding infomasks to use on the tuple.
5492 : : *
5493 : : * Note that this might have side effects such as creating a new MultiXactId.
5494 : : *
5495 : : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5496 : : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5497 : : * but it was not running anymore. There is a race condition, which is that the
5498 : : * MultiXactId may have finished since then, but that uncommon case is handled
5499 : : * either here, or within MultiXactIdExpand.
5500 : : *
5501 : : * There is a similar race condition possible when the old xmax was a regular
5502 : : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5503 : : * window, but it's still possible to end up creating an unnecessary
5504 : : * MultiXactId. Fortunately this is harmless.
5505 : : */
5506 : : static void
4988 5507 : 6619149 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5508 : : uint16 old_infomask2, TransactionId add_to_xmax,
5509 : : LockTupleMode mode, bool is_update,
5510 : : TransactionId *result_xmax, uint16 *result_infomask,
5511 : : uint16 *result_infomask2)
5512 : : {
5513 : : TransactionId new_xmax;
5514 : : uint16 new_infomask,
5515 : : new_infomask2;
5516 : :
4658 5517 [ + - ]: 6619149 : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5518 : :
4988 5519 : 6723625 : l5:
5520 : 6723625 : new_infomask = 0;
5521 : 6723625 : new_infomask2 = 0;
5522 [ + + ]: 6723625 : if (old_infomask & HEAP_XMAX_INVALID)
5523 : : {
5524 : : /*
5525 : : * No previous locker; we just insert our own TransactionId.
5526 : : *
5527 : : * Note that it's critical that this case be the first one checked,
5528 : : * because there are several blocks below that come back to this one
5529 : : * to implement certain optimizations; old_infomask might contain
5530 : : * other dirty bits in those cases, but we don't really care.
5531 : : */
5532 [ + + ]: 6542519 : if (is_update)
5533 : : {
5534 : 4242960 : new_xmax = add_to_xmax;
5535 [ + + ]: 4242960 : if (mode == LockTupleExclusive)
5536 : 1885492 : new_infomask2 |= HEAP_KEYS_UPDATED;
5537 : : }
5538 : : else
5539 : : {
5540 : 2299559 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5541 [ + + + + : 2299559 : switch (mode)
- ]
5542 : : {
5543 : 6176 : case LockTupleKeyShare:
5544 : 6176 : new_xmax = add_to_xmax;
5545 : 6176 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5546 : 6176 : break;
5547 : 785 : case LockTupleShare:
5548 : 785 : new_xmax = add_to_xmax;
5549 : 785 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5550 : 785 : break;
5551 : 2196619 : case LockTupleNoKeyExclusive:
5552 : 2196619 : new_xmax = add_to_xmax;
5553 : 2196619 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5554 : 2196619 : break;
5555 : 95979 : case LockTupleExclusive:
5556 : 95979 : new_xmax = add_to_xmax;
5557 : 95979 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5558 : 95979 : new_infomask2 |= HEAP_KEYS_UPDATED;
5559 : 95979 : break;
4988 alvherre@alvh.no-ip. 5560 :UBC 0 : default:
5561 : 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5562 [ # # ]: 0 : elog(ERROR, "invalid lock mode");
5563 : : }
5564 : : }
5565 : : }
4988 alvherre@alvh.no-ip. 5566 [ + + ]:CBC 181106 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5567 : : {
5568 : : MultiXactStatus new_status;
5569 : :
5570 : : /*
5571 : : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5572 : : * cross-check.
5573 : : */
5574 [ - + ]: 75552 : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5575 : :
5576 : : /*
5577 : : * A multixact together with LOCK_ONLY set but neither lock bit set
5578 : : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5579 : : * anymore. This check is critical for databases upgraded by
5580 : : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5581 : : * that such multis are never passed.
5582 : : */
3740 5583 [ - + ]: 75552 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5584 : : {
4988 alvherre@alvh.no-ip. 5585 :UBC 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5586 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5587 : 0 : goto l5;
5588 : : }
5589 : :
5590 : : /*
5591 : : * If the XMAX is already a MultiXactId, then we need to expand it to
5592 : : * include add_to_xmax; but if all the members were lockers and are
5593 : : * all gone, we can do away with the IS_MULTI bit and just set
5594 : : * add_to_xmax as the only locker/updater. If all lockers are gone
5595 : : * and we have an updater that aborted, we can also do without a
5596 : : * multi.
5597 : : *
5598 : : * The cost of doing GetMultiXactIdMembers would be paid by
5599 : : * MultiXactIdExpand if we weren't to do this, so this check is not
5600 : : * incurring extra work anyhow.
5601 : : */
4436 alvherre@alvh.no-ip. 5602 [ + + ]:CBC 75552 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5603 : : {
4988 5604 [ + + ]: 26 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4181 5605 [ + - ]: 10 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5606 : : old_infomask)))
5607 : : {
5608 : : /*
5609 : : * Reset these bits and restart; otherwise fall through to
5610 : : * create a new multi below.
5611 : : */
4988 5612 : 26 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5613 : 26 : old_infomask |= HEAP_XMAX_INVALID;
5614 : 26 : goto l5;
5615 : : }
5616 : : }
5617 : :
5618 : 75526 : new_status = get_mxact_status_for_lock(mode, is_update);
5619 : :
5620 : 75526 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5621 : : new_status);
5622 : 75526 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5623 : : }
5624 [ + + ]: 105554 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5625 : : {
5626 : : /*
5627 : : * It's a committed update, so we need to preserve him as updater of
5628 : : * the tuple.
5629 : : */
5630 : : MultiXactStatus status;
5631 : : MultiXactStatus new_status;
5632 : :
5633 [ - + ]: 14 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4988 alvherre@alvh.no-ip. 5634 :UBC 0 : status = MultiXactStatusUpdate;
5635 : : else
4988 alvherre@alvh.no-ip. 5636 :CBC 14 : status = MultiXactStatusNoKeyUpdate;
5637 : :
5638 : 14 : new_status = get_mxact_status_for_lock(mode, is_update);
5639 : :
5640 : : /*
5641 : : * since it's not running, it's obviously impossible for the old
5642 : : * updater to be identical to the current one, so we need not check
5643 : : * for that case as we do in the block above.
5644 : : */
5645 : 14 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5646 : 14 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5647 : : }
5648 [ + + ]: 105540 : else if (TransactionIdIsInProgress(xmax))
5649 : : {
5650 : : /*
5651 : : * If the XMAX is a valid, in-progress TransactionId, then we need to
5652 : : * create a new MultiXactId that includes both the old locker or
5653 : : * updater and our own TransactionId.
5654 : : */
5655 : : MultiXactStatus new_status;
5656 : : MultiXactStatus old_status;
5657 : : LockTupleMode old_mode;
5658 : :
5659 [ + + ]: 105531 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5660 : : {
5661 [ + + ]: 105503 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4658 5662 : 5694 : old_status = MultiXactStatusForKeyShare;
4988 5663 [ + + ]: 99809 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4658 5664 : 442 : old_status = MultiXactStatusForShare;
4988 5665 [ + - ]: 99367 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5666 : : {
5667 [ + + ]: 99367 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4658 5668 : 92838 : old_status = MultiXactStatusForUpdate;
5669 : : else
5670 : 6529 : old_status = MultiXactStatusForNoKeyUpdate;
5671 : : }
5672 : : else
5673 : : {
5674 : : /*
5675 : : * LOCK_ONLY can be present alone only when a page has been
5676 : : * upgraded by pg_upgrade. But in that case,
5677 : : * TransactionIdIsInProgress() should have returned false. We
5678 : : * assume it's no longer locked in this case.
5679 : : */
4988 alvherre@alvh.no-ip. 5680 [ # # ]:UBC 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5681 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5682 : 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5683 : 0 : goto l5;
5684 : : }
5685 : : }
5686 : : else
5687 : : {
5688 : : /* it's an update, but which kind? */
4988 alvherre@alvh.no-ip. 5689 [ - + ]:CBC 28 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4658 alvherre@alvh.no-ip. 5690 :UBC 0 : old_status = MultiXactStatusUpdate;
5691 : : else
4658 alvherre@alvh.no-ip. 5692 :CBC 28 : old_status = MultiXactStatusNoKeyUpdate;
5693 : : }
5694 : :
5695 : 105531 : old_mode = TUPLOCK_from_mxstatus(old_status);
5696 : :
5697 : : /*
5698 : : * If the lock to be acquired is for the same TransactionId as the
5699 : : * existing lock, there's an optimization possible: consider only the
5700 : : * strongest of both locks as the only one present, and restart.
5701 : : */
4988 5702 [ + + ]: 105531 : if (xmax == add_to_xmax)
5703 : : {
5704 : : /*
5705 : : * Note that it's not possible for the original tuple to be
5706 : : * updated: we wouldn't be here because the tuple would have been
5707 : : * invisible and we wouldn't try to update it. As a subtlety,
5708 : : * this code can also run when traversing an update chain to lock
5709 : : * future versions of a tuple. But we wouldn't be here either,
5710 : : * because the add_to_xmax would be different from the original
5711 : : * updater.
5712 : : */
4658 5713 [ - + ]: 104442 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5714 : :
5715 : : /* acquire the strongest of both */
5716 [ + + ]: 104442 : if (mode < old_mode)
5717 : 52235 : mode = old_mode;
5718 : : /* mustn't touch is_update */
5719 : :
5720 : 104442 : old_infomask |= HEAP_XMAX_INVALID;
5721 : 104442 : goto l5;
5722 : : }
5723 : :
5724 : : /* otherwise, just fall back to creating a new multixact */
5725 : 1089 : new_status = get_mxact_status_for_lock(mode, is_update);
5726 : 1089 : new_xmax = MultiXactIdCreate(xmax, old_status,
5727 : : add_to_xmax, new_status);
4988 5728 : 1089 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5729 : : }
5730 [ + + + + ]: 14 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5731 : 5 : TransactionIdDidCommit(xmax))
5732 : 1 : {
5733 : : /*
5734 : : * It's a committed update, so we gotta preserve him as updater of the
5735 : : * tuple.
5736 : : */
5737 : : MultiXactStatus status;
5738 : : MultiXactStatus new_status;
5739 : :
5740 [ - + ]: 1 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4988 alvherre@alvh.no-ip. 5741 :UBC 0 : status = MultiXactStatusUpdate;
5742 : : else
4988 alvherre@alvh.no-ip. 5743 :CBC 1 : status = MultiXactStatusNoKeyUpdate;
5744 : :
5745 : 1 : new_status = get_mxact_status_for_lock(mode, is_update);
5746 : :
5747 : : /*
5748 : : * since it's not running, it's obviously impossible for the old
5749 : : * updater to be identical to the current one, so we need not check
5750 : : * for that case as we do in the block above.
5751 : : */
5752 : 1 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5753 : 1 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5754 : : }
5755 : : else
5756 : : {
5757 : : /*
5758 : : * Can get here iff the locking/updating transaction was running when
5759 : : * the infomask was extracted from the tuple, but finished before
5760 : : * TransactionIdIsInProgress got to run. Deal with it as if there was
5761 : : * no locker at all in the first place.
5762 : : */
5763 : 8 : old_infomask |= HEAP_XMAX_INVALID;
5764 : 8 : goto l5;
5765 : : }
5766 : :
5767 : 6619149 : *result_infomask = new_infomask;
5768 : 6619149 : *result_infomask2 = new_infomask2;
5769 : 6619149 : *result_xmax = new_xmax;
5770 : 6619149 : }
5771 : :
5772 : : /*
5773 : : * Subroutine for heap_lock_updated_tuple_rec.
5774 : : *
5775 : : * Given a hypothetical multixact status held by the transaction identified
5776 : : * with the given xid, does the current transaction need to wait, fail, or can
5777 : : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5778 : : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5779 : : * returned. If the lock is already held by the current transaction, return
5780 : : * TM_SelfModified. In case of a conflict with another transaction, a
5781 : : * different HeapTupleSatisfiesUpdate return code is returned.
5782 : : *
5783 : : * The held status is said to be hypothetical because it might correspond to a
5784 : : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5785 : : * way for simplicity of API.
5786 : : */
5787 : : static TM_Result
4680 5788 : 38777 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5789 : : LockTupleMode mode, HeapTuple tup,
5790 : : bool *needwait)
5791 : : {
5792 : : MultiXactStatus wantedstatus;
5793 : :
5794 : 38777 : *needwait = false;
5795 : 38777 : wantedstatus = get_mxact_status_for_lock(mode, false);
5796 : :
5797 : : /*
5798 : : * Note: we *must* check TransactionIdIsInProgress before
5799 : : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5800 : : * for an explanation.
5801 : : */
5802 [ - + ]: 38777 : if (TransactionIdIsCurrentTransactionId(xid))
5803 : : {
5804 : : /*
5805 : : * The tuple has already been locked by our own transaction. This is
5806 : : * very rare but can happen if multiple transactions are trying to
5807 : : * lock an ancient version of the same tuple.
5808 : : */
2738 andres@anarazel.de 5809 :UBC 0 : return TM_SelfModified;
5810 : : }
4680 alvherre@alvh.no-ip. 5811 [ + + ]:CBC 38777 : else if (TransactionIdIsInProgress(xid))
5812 : : {
5813 : : /*
5814 : : * If the locking transaction is running, what we do depends on
5815 : : * whether the lock modes conflict: if they do, then we must wait for
5816 : : * it to finish; otherwise we can fall through to lock this tuple
5817 : : * version without waiting.
5818 : : */
5819 [ + + ]: 36539 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5820 : 36539 : LOCKMODE_from_mxstatus(wantedstatus)))
5821 : : {
5822 : 8 : *needwait = true;
5823 : : }
5824 : :
5825 : : /*
5826 : : * If we set needwait above, then this value doesn't matter;
5827 : : * otherwise, this value signals to caller that it's okay to proceed.
5828 : : */
2738 andres@anarazel.de 5829 : 36539 : return TM_Ok;
5830 : : }
4680 alvherre@alvh.no-ip. 5831 [ + + ]: 2238 : else if (TransactionIdDidAbort(xid))
2738 andres@anarazel.de 5832 : 206 : return TM_Ok;
4680 alvherre@alvh.no-ip. 5833 [ + - ]: 2032 : else if (TransactionIdDidCommit(xid))
5834 : : {
5835 : : /*
5836 : : * The other transaction committed. If it was only a locker, then the
5837 : : * lock is completely gone now and we can return success; but if it
5838 : : * was an update, then what we do depends on whether the two lock
5839 : : * modes conflict. If they conflict, then we must report error to
5840 : : * caller. But if they don't, we can fall through to allow the current
5841 : : * transaction to lock the tuple.
5842 : : *
5843 : : * Note: the reason we worry about ISUPDATE here is because as soon as
5844 : : * a transaction ends, all its locks are gone and meaningless, and
5845 : : * thus we can ignore them; whereas its updates persist. In the
5846 : : * TransactionIdIsInProgress case, above, we don't need to check
5847 : : * because we know the lock is still "alive" and thus a conflict needs
5848 : : * always be checked.
5849 : : */
4672 5850 [ + + ]: 2032 : if (!ISUPDATE_from_mxstatus(status))
2738 andres@anarazel.de 5851 : 2020 : return TM_Ok;
5852 : :
4680 alvherre@alvh.no-ip. 5853 [ + + ]: 12 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5854 : 12 : LOCKMODE_from_mxstatus(wantedstatus)))
5855 : : {
5856 : : /* bummer */
2036 5857 [ + + ]: 11 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
2738 andres@anarazel.de 5858 : 9 : return TM_Updated;
5859 : : else
5860 : 2 : return TM_Deleted;
5861 : : }
5862 : :
5863 : 1 : return TM_Ok;
5864 : : }
5865 : :
5866 : : /* Not in progress, not aborted, not committed -- must have crashed */
2738 andres@anarazel.de 5867 :UBC 0 : return TM_Ok;
5868 : : }
5869 : :
5870 : :
5871 : : /*
5872 : : * Recursive part of heap_lock_updated_tuple
5873 : : *
5874 : : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5875 : : * xid with the given mode; if this tuple is updated, recurse to lock the new
5876 : : * version as well.
5877 : : */
5878 : : static TM_Result
271 heikki.linnakangas@i 5879 :CBC 2223 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
5880 : : const ItemPointerData *tid, TransactionId xid,
5881 : : LockTupleMode mode)
5882 : : {
5883 : : TM_Result result;
5884 : : ItemPointerData tupid;
5885 : : HeapTupleData mytup;
5886 : : Buffer buf;
5887 : : Page page;
5888 : : uint16 new_infomask,
5889 : : new_infomask2,
5890 : : old_infomask,
5891 : : old_infomask2;
5892 : : TransactionId xmax,
5893 : : new_xmax;
3716 andres@anarazel.de 5894 : 2223 : bool cleared_all_frozen = false;
5895 : : bool pinned_desired_page;
5896 : 2223 : Buffer vmbuffer = InvalidBuffer;
67 melanieplageman@gmai 5897 : 2223 : bool unlock_vmbuffer = false;
5898 : : BlockNumber block;
5899 : :
4988 alvherre@alvh.no-ip. 5900 : 2223 : ItemPointerCopy(tid, &tupid);
5901 : :
5902 : : for (;;)
5903 : : {
5904 : 2226 : new_infomask = 0;
5905 : 2226 : new_xmax = InvalidTransactionId;
67 melanieplageman@gmai 5906 : 2226 : cleared_all_frozen = false;
3716 andres@anarazel.de 5907 : 2226 : block = ItemPointerGetBlockNumber(&tupid);
4988 alvherre@alvh.no-ip. 5908 : 2226 : ItemPointerCopy(&tupid, &(mytup.t_self));
5909 : :
1621 tgl@sss.pgh.pa.us 5910 [ + - ]: 2226 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5911 : : {
5912 : : /*
5913 : : * if we fail to find the updated version of the tuple, it's
5914 : : * because it was vacuumed/pruned away after its creator
5915 : : * transaction aborted. So behave as if we got to the end of the
5916 : : * chain, and there's no further tuple to lock: return success to
5917 : : * caller.
5918 : : */
2738 andres@anarazel.de 5919 :UBC 0 : result = TM_Ok;
3124 tgl@sss.pgh.pa.us 5920 : 0 : goto out_unlocked;
5921 : : }
5922 : :
4988 alvherre@alvh.no-ip. 5923 :CBC 2226 : l4:
5924 [ - + ]: 2234 : CHECK_FOR_INTERRUPTS();
5925 : :
67 melanieplageman@gmai 5926 : 2234 : page = BufferGetPage(buf);
5927 : :
5928 : : /*
5929 : : * Before locking the buffer, pin the visibility map page if it
5930 : : * appears to be necessary. Since we haven't got the lock yet,
5931 : : * someone else might be in the middle of changing this, so we'll need
5932 : : * to recheck after we have the lock.
5933 : : */
5934 [ - + ]: 2234 : if (PageIsAllVisible(page))
5935 : : {
3716 andres@anarazel.de 5936 :UBC 0 : visibilitymap_pin(rel, block, &vmbuffer);
3124 tgl@sss.pgh.pa.us 5937 : 0 : pinned_desired_page = true;
5938 : : }
5939 : : else
3124 tgl@sss.pgh.pa.us 5940 :CBC 2234 : pinned_desired_page = false;
5941 : :
4988 alvherre@alvh.no-ip. 5942 : 2234 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5943 : :
5944 : : /*
5945 : : * If we didn't pin the visibility map page and the page has become
5946 : : * all visible while we were busy locking the buffer, we'll have to
5947 : : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5948 : : * That's a bit unfortunate, but hopefully shouldn't happen often.
5949 : : *
5950 : : * Note: in some paths through this function, we will reach here
5951 : : * holding a pin on a vm page that may or may not be the one matching
5952 : : * this page. If this page isn't all-visible, we won't use the vm
5953 : : * page, but we hold onto such a pin till the end of the function.
5954 : : */
67 melanieplageman@gmai 5955 [ + - - + ]: 2234 : if (!pinned_desired_page && PageIsAllVisible(page))
5956 : : {
3699 andres@anarazel.de 5957 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5958 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5959 : 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5960 : : }
5961 : :
5962 : : /*
5963 : : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5964 : : * end of the chain, we're done, so return success.
5965 : : */
4680 alvherre@alvh.no-ip. 5966 [ + - + + ]:CBC 4468 : if (TransactionIdIsValid(priorXmax) &&
3244 5967 : 2234 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5968 : : priorXmax))
5969 : : {
2738 andres@anarazel.de 5970 : 2 : result = TM_Ok;
3716 5971 : 2 : goto out_locked;
5972 : : }
5973 : :
5974 : : /*
5975 : : * Also check Xmin: if this tuple was created by an aborted
5976 : : * (sub)transaction, then we already locked the last live one in the
5977 : : * chain, thus we're done, so return success.
5978 : : */
3663 alvherre@alvh.no-ip. 5979 [ + + ]: 2232 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
5980 : : {
2738 andres@anarazel.de 5981 : 25 : result = TM_Ok;
3124 tgl@sss.pgh.pa.us 5982 : 25 : goto out_locked;
5983 : : }
5984 : :
4988 alvherre@alvh.no-ip. 5985 : 2207 : old_infomask = mytup.t_data->t_infomask;
4680 5986 : 2207 : old_infomask2 = mytup.t_data->t_infomask2;
4988 5987 : 2207 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5988 : :
5989 : : /*
5990 : : * If this tuple version has been updated or locked by some concurrent
5991 : : * transaction(s), what we do depends on whether our lock mode
5992 : : * conflicts with what those other transactions hold, and also on the
5993 : : * status of them.
5994 : : */
4680 5995 [ + + ]: 2207 : if (!(old_infomask & HEAP_XMAX_INVALID))
5996 : : {
5997 : : TransactionId rawxmax;
5998 : : bool needwait;
5999 : :
6000 : 2141 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
6001 [ + + ]: 2141 : if (old_infomask & HEAP_XMAX_IS_MULTI)
6002 : : {
6003 : : int nmembers;
6004 : : int i;
6005 : : MultiXactMember *members;
6006 : :
6007 : : /*
6008 : : * We don't need a test for pg_upgrade'd tuples: this is only
6009 : : * applied to tuples after the first in an update chain. Said
6010 : : * first tuple in the chain may well be locked-in-9.2-and-
6011 : : * pg_upgraded, but that one was already locked by our caller,
6012 : : * not us; and any subsequent ones cannot be because our
6013 : : * caller must necessarily have obtained a snapshot later than
6014 : : * the pg_upgrade itself.
6015 : : */
3740 6016 [ - + ]: 2109 : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
6017 : :
4436 6018 : 2109 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
3378 tgl@sss.pgh.pa.us 6019 : 2109 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4680 alvherre@alvh.no-ip. 6020 [ + + ]: 40854 : for (i = 0; i < nmembers; i++)
6021 : : {
3716 andres@anarazel.de 6022 : 38745 : result = test_lockmode_for_conflict(members[i].status,
6023 : 38745 : members[i].xid,
6024 : : mode,
6025 : : &mytup,
6026 : : &needwait);
6027 : :
6028 : : /*
6029 : : * If the tuple was already locked by ourselves in a
6030 : : * previous iteration of this (say heap_lock_tuple was
6031 : : * forced to restart the locking loop because of a change
6032 : : * in xmax), then we hold the lock already on this tuple
6033 : : * version and we don't need to do anything; and this is
6034 : : * not an error condition either. We just need to skip
6035 : : * this tuple and continue locking the next version in the
6036 : : * update chain.
6037 : : */
2738 6038 [ - + ]: 38745 : if (result == TM_SelfModified)
6039 : : {
3343 alvherre@alvh.no-ip. 6040 :UBC 0 : pfree(members);
6041 : 0 : goto next;
6042 : : }
6043 : :
4680 alvherre@alvh.no-ip. 6044 [ - + ]:CBC 38745 : if (needwait)
6045 : : {
4680 alvherre@alvh.no-ip. 6046 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4568 6047 : 0 : XactLockTableWait(members[i].xid, rel,
6048 : : &mytup.t_self,
6049 : : XLTW_LockUpdated);
4680 6050 : 0 : pfree(members);
6051 : 0 : goto l4;
6052 : : }
2738 andres@anarazel.de 6053 [ - + ]:CBC 38745 : if (result != TM_Ok)
6054 : : {
4680 alvherre@alvh.no-ip. 6055 :UBC 0 : pfree(members);
3716 andres@anarazel.de 6056 : 0 : goto out_locked;
6057 : : }
6058 : : }
4680 alvherre@alvh.no-ip. 6059 [ + - ]:CBC 2109 : if (members)
6060 : 2109 : pfree(members);
6061 : : }
6062 : : else
6063 : : {
6064 : : MultiXactStatus status;
6065 : :
6066 : : /*
6067 : : * For a non-multi Xmax, we first need to compute the
6068 : : * corresponding MultiXactStatus by using the infomask bits.
6069 : : */
6070 [ + + ]: 32 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
6071 : : {
6072 [ + - ]: 10 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
6073 : 10 : status = MultiXactStatusForKeyShare;
4680 alvherre@alvh.no-ip. 6074 [ # # ]:UBC 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
6075 : 0 : status = MultiXactStatusForShare;
6076 [ # # ]: 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
6077 : : {
6078 [ # # ]: 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6079 : 0 : status = MultiXactStatusForUpdate;
6080 : : else
6081 : 0 : status = MultiXactStatusForNoKeyUpdate;
6082 : : }
6083 : : else
6084 : : {
6085 : : /*
6086 : : * LOCK_ONLY present alone (a pg_upgraded tuple marked
6087 : : * as share-locked in the old cluster) shouldn't be
6088 : : * seen in the middle of an update chain.
6089 : : */
6090 [ # # ]: 0 : elog(ERROR, "invalid lock status in tuple");
6091 : : }
6092 : : }
6093 : : else
6094 : : {
6095 : : /* it's an update, but which kind? */
4680 alvherre@alvh.no-ip. 6096 [ + + ]:CBC 22 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6097 : 17 : status = MultiXactStatusUpdate;
6098 : : else
6099 : 5 : status = MultiXactStatusNoKeyUpdate;
6100 : : }
6101 : :
3716 andres@anarazel.de 6102 : 32 : result = test_lockmode_for_conflict(status, rawxmax, mode,
6103 : : &mytup, &needwait);
6104 : :
6105 : : /*
6106 : : * If the tuple was already locked by ourselves in a previous
6107 : : * iteration of this (say heap_lock_tuple was forced to
6108 : : * restart the locking loop because of a change in xmax), then
6109 : : * we hold the lock already on this tuple version and we don't
6110 : : * need to do anything; and this is not an error condition
6111 : : * either. We just need to skip this tuple and continue
6112 : : * locking the next version in the update chain.
6113 : : */
2738 6114 [ - + ]: 32 : if (result == TM_SelfModified)
3343 alvherre@alvh.no-ip. 6115 :UBC 0 : goto next;
6116 : :
4680 alvherre@alvh.no-ip. 6117 [ + + ]:CBC 32 : if (needwait)
6118 : : {
6119 : 8 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4246 heikki.linnakangas@i 6120 : 8 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
6121 : : XLTW_LockUpdated);
4680 alvherre@alvh.no-ip. 6122 : 8 : goto l4;
6123 : : }
2738 andres@anarazel.de 6124 [ + + ]: 24 : if (result != TM_Ok)
6125 : : {
3716 6126 : 11 : goto out_locked;
6127 : : }
6128 : : }
6129 : : }
6130 : :
6131 : : /* compute the new Xmax and infomask values for the tuple ... */
4988 alvherre@alvh.no-ip. 6132 : 2188 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
6133 : : xid, mode, false,
6134 : : &new_xmax, &new_infomask, &new_infomask2);
6135 : :
67 melanieplageman@gmai 6136 [ - + ]: 2188 : if (PageIsAllVisible(page))
6137 : : {
67 melanieplageman@gmai 6138 :UBC 0 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
6139 : 0 : unlock_vmbuffer = true;
6140 : : }
6141 : :
4988 alvherre@alvh.no-ip. 6142 :CBC 2188 : START_CRIT_SECTION();
6143 : :
6144 : : /* ... and set them */
6145 : 2188 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
6146 : 2188 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
6147 : 2188 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6148 : 2188 : mytup.t_data->t_infomask |= new_infomask;
6149 : 2188 : mytup.t_data->t_infomask2 |= new_infomask2;
6150 : :
6151 : 2188 : MarkBufferDirty(buf);
6152 : :
67 melanieplageman@gmai 6153 [ - + ]: 2188 : if (PageIsAllVisible(page))
6154 : : {
6155 : : /* It's possible all-frozen was already clear */
67 melanieplageman@gmai 6156 [ # # ]:UNC 0 : if (visibilitymap_clear(rel->rd_locator, block, vmbuffer,
6157 : : VISIBILITYMAP_ALL_FROZEN))
67 melanieplageman@gmai 6158 :UBC 0 : cleared_all_frozen = true;
6159 : : }
6160 : :
6161 : : /* XLOG stuff */
4988 alvherre@alvh.no-ip. 6162 [ + - + + :CBC 2188 : if (RelationNeedsWAL(rel))
+ - + - ]
6163 : : {
6164 : : xl_heap_lock_updated xlrec;
6165 : : XLogRecPtr recptr;
6166 : :
4322 heikki.linnakangas@i 6167 : 2188 : XLogBeginInsert();
67 melanieplageman@gmai 6168 : 2188 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buf, REGBUF_STANDARD);
6169 : :
4322 heikki.linnakangas@i 6170 : 2188 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
4988 alvherre@alvh.no-ip. 6171 : 2188 : xlrec.xmax = new_xmax;
6172 : 2188 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
3716 andres@anarazel.de 6173 : 2188 : xlrec.flags =
6174 : 2188 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
6175 : :
586 peter@eisentraut.org 6176 : 2188 : XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
6177 : :
67 melanieplageman@gmai 6178 [ - + ]: 2188 : if (cleared_all_frozen)
67 melanieplageman@gmai 6179 :UBC 0 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
6180 : :
4322 heikki.linnakangas@i 6181 :CBC 2188 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
6182 : :
4988 alvherre@alvh.no-ip. 6183 : 2188 : PageSetLSN(page, recptr);
6184 : :
67 melanieplageman@gmai 6185 [ - + ]: 2188 : if (cleared_all_frozen)
67 melanieplageman@gmai 6186 :UBC 0 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
6187 : : }
6188 : :
4988 alvherre@alvh.no-ip. 6189 [ - + ]:CBC 2188 : END_CRIT_SECTION();
6190 : :
6191 : : /* release VM lock first, since it covers many heap blocks */
67 melanieplageman@gmai 6192 [ + - ]: 2188 : if (unlock_vmbuffer)
6193 : : {
67 melanieplageman@gmai 6194 :UBC 0 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
6195 : 0 : unlock_vmbuffer = false;
6196 : : }
6197 : :
3343 alvherre@alvh.no-ip. 6198 :CBC 2188 : next:
6199 : : /* if we find the end of update chain, we're done. */
4988 6200 [ + - + - ]: 4376 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
3088 andres@anarazel.de 6201 [ + + ]: 4376 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
4862 bruce@momjian.us 6202 [ + + ]: 2192 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
4988 alvherre@alvh.no-ip. 6203 : 4 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
6204 : : {
2738 andres@anarazel.de 6205 : 2185 : result = TM_Ok;
3716 6206 : 2185 : goto out_locked;
6207 : : }
6208 : :
6209 : : /* tail recursion */
4680 alvherre@alvh.no-ip. 6210 : 3 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
4988 6211 : 3 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6212 : 3 : UnlockReleaseBuffer(buf);
6213 : : }
6214 : :
6215 : : result = TM_Ok;
6216 : :
3716 andres@anarazel.de 6217 : 2223 : out_locked:
6218 : 2223 : UnlockReleaseBuffer(buf);
6219 : :
3124 tgl@sss.pgh.pa.us 6220 : 2223 : out_unlocked:
3716 andres@anarazel.de 6221 [ - + ]: 2223 : if (vmbuffer != InvalidBuffer)
3716 andres@anarazel.de 6222 :UBC 0 : ReleaseBuffer(vmbuffer);
67 melanieplageman@gmai 6223 [ - + ]:CBC 2223 : Assert(!unlock_vmbuffer);
6224 : :
3716 andres@anarazel.de 6225 : 2223 : return result;
6226 : : }
6227 : :
6228 : : /*
6229 : : * heap_lock_updated_tuple
6230 : : * Follow update chain when locking an updated tuple, acquiring locks (row
6231 : : * marks) on the updated versions.
6232 : : *
6233 : : * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
6234 : : * fields from the initial tuple. We will lock the tuples starting from the
6235 : : * one that 'prior_ctid' points to. Note: This function does not lock the
6236 : : * initial tuple itself.
6237 : : *
6238 : : * This function doesn't check visibility, it just unconditionally marks the
6239 : : * tuple(s) as locked. If any tuple in the updated chain is being deleted
6240 : : * concurrently (or updated with the key being modified), sleep until the
6241 : : * transaction doing it is finished.
6242 : : *
6243 : : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6244 : : * when we have to wait for other transactions to release them, as opposed to
6245 : : * what heap_lock_tuple does. The reason is that having more than one
6246 : : * transaction walking the chain is probably uncommon enough that risk of
6247 : : * starvation is not likely: one of the preconditions for being here is that
6248 : : * the snapshot in use predates the update that created this tuple (because we
6249 : : * started at an earlier version of the tuple), but at the same time such a
6250 : : * transaction cannot be using repeatable read or serializable isolation
6251 : : * levels, because that would lead to a serializability failure.
6252 : : */
6253 : : static TM_Result
271 heikki.linnakangas@i 6254 : 2225 : heap_lock_updated_tuple(Relation rel,
6255 : : uint16 prior_infomask,
6256 : : TransactionId prior_raw_xmax,
6257 : : const ItemPointerData *prior_ctid,
6258 : : TransactionId xid, LockTupleMode mode)
6259 : : {
6260 : 2225 : INJECTION_POINT("heap_lock_updated_tuple", NULL);
6261 : :
6262 : : /*
6263 : : * If the tuple has moved into another partition (effectively a delete)
6264 : : * stop here.
6265 : : */
6266 [ + + ]: 2225 : if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
6267 : : {
6268 : : TransactionId prior_xmax;
6269 : :
6270 : : /*
6271 : : * If this is the first possibly-multixact-able operation in the
6272 : : * current transaction, set my per-backend OldestMemberMXactId
6273 : : * setting. We can be certain that the transaction will never become a
6274 : : * member of any older MultiXactIds than that. (We have to do this
6275 : : * even if we end up just using our own TransactionId below, since
6276 : : * some other backend could incorporate our XID into a MultiXact
6277 : : * immediately afterwards.)
6278 : : */
4988 alvherre@alvh.no-ip. 6279 : 2223 : MultiXactIdSetOldestMember();
6280 : :
271 heikki.linnakangas@i 6281 : 4446 : prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
6282 [ + + ]: 2223 : MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
6283 : 2223 : return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
6284 : : }
6285 : :
6286 : : /* nothing to lock */
2738 andres@anarazel.de 6287 : 2 : return TM_Ok;
6288 : : }
6289 : :
6290 : : /*
6291 : : * heap_finish_speculative - mark speculative insertion as successful
6292 : : *
6293 : : * To successfully finish a speculative insertion we have to clear speculative
6294 : : * token from tuple. To do so the t_ctid field, which will contain a
6295 : : * speculative token value, is modified in place to point to the tuple itself,
6296 : : * which is characteristic of a newly inserted ordinary tuple.
6297 : : *
6298 : : * NB: It is not ok to commit without either finishing or aborting a
6299 : : * speculative insertion. We could treat speculative tuples of committed
6300 : : * transactions implicitly as completed, but then we would have to be prepared
6301 : : * to deal with speculative tokens on committed tuples. That wouldn't be
6302 : : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6303 : : * but clearing the token at completion isn't very expensive either.
6304 : : * An explicit confirmation WAL record also makes logical decoding simpler.
6305 : : */
6306 : : void
325 peter@eisentraut.org 6307 : 2236 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
6308 : : {
6309 : : Buffer buffer;
6310 : : Page page;
6311 : : OffsetNumber offnum;
6312 : : ItemId lp;
6313 : : HeapTupleHeader htup;
6314 : :
2738 andres@anarazel.de 6315 : 2236 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4153 6316 : 2236 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
387 peter@eisentraut.org 6317 : 2236 : page = BufferGetPage(buffer);
6318 : :
2738 andres@anarazel.de 6319 : 2236 : offnum = ItemPointerGetOffsetNumber(tid);
279 tgl@sss.pgh.pa.us 6320 [ + - - + ]: 2236 : if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
279 tgl@sss.pgh.pa.us 6321 [ # # ]:UBC 0 : elog(ERROR, "offnum out of range");
279 tgl@sss.pgh.pa.us 6322 :CBC 2236 : lp = PageGetItemId(page, offnum);
6323 [ - + ]: 2236 : if (!ItemIdIsNormal(lp))
3958 andres@anarazel.de 6324 [ # # ]:UBC 0 : elog(ERROR, "invalid lp");
6325 : :
4153 andres@anarazel.de 6326 :CBC 2236 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6327 : :
6328 : : /* NO EREPORT(ERROR) from here till changes are logged */
6329 : 2236 : START_CRIT_SECTION();
6330 : :
2738 6331 [ - + ]: 2236 : Assert(HeapTupleHeaderIsSpeculative(htup));
6332 : :
4153 6333 : 2236 : MarkBufferDirty(buffer);
6334 : :
6335 : : /*
6336 : : * Replace the speculative insertion token with a real t_ctid, pointing to
6337 : : * itself like it does on regular tuples.
6338 : : */
2738 6339 : 2236 : htup->t_ctid = *tid;
6340 : :
6341 : : /* XLOG stuff */
4153 6342 [ + + + + : 2236 : if (RelationNeedsWAL(relation))
+ - + - ]
6343 : : {
6344 : : xl_heap_confirm xlrec;
6345 : : XLogRecPtr recptr;
6346 : :
2738 6347 : 2216 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
6348 : :
4153 6349 : 2216 : XLogBeginInsert();
6350 : :
6351 : : /* We want the same filtering on this as on a plain insert */
3559 6352 : 2216 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6353 : :
586 peter@eisentraut.org 6354 : 2216 : XLogRegisterData(&xlrec, SizeOfHeapConfirm);
4153 andres@anarazel.de 6355 : 2216 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6356 : :
6357 : 2216 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6358 : :
6359 : 2216 : PageSetLSN(page, recptr);
6360 : : }
6361 : :
6362 [ - + ]: 2236 : END_CRIT_SECTION();
6363 : :
6364 : 2236 : UnlockReleaseBuffer(buffer);
6365 : 2236 : }
6366 : :
6367 : : /*
6368 : : * heap_abort_speculative - kill a speculatively inserted tuple
6369 : : *
6370 : : * Marks a tuple that was speculatively inserted in the same command as dead,
6371 : : * by setting its xmin as invalid. That makes it immediately appear as dead
6372 : : * to all transactions, including our own. In particular, it makes
6373 : : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6374 : : * inserting a duplicate key value won't unnecessarily wait for our whole
6375 : : * transaction to finish (it'll just wait for our speculative insertion to
6376 : : * finish).
6377 : : *
6378 : : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6379 : : * that arise due to a mutual dependency that is not user visible. By
6380 : : * definition, unprincipled deadlocks cannot be prevented by the user
6381 : : * reordering lock acquisition in client code, because the implementation level
6382 : : * lock acquisitions are not under the user's direct control. If speculative
6383 : : * inserters did not take this precaution, then under high concurrency they
6384 : : * could deadlock with each other, which would not be acceptable.
6385 : : *
6386 : : * This is somewhat redundant with heap_delete, but we prefer to have a
6387 : : * dedicated routine with stripped down requirements. Note that this is also
6388 : : * used to delete the TOAST tuples created during speculative insertion.
6389 : : *
6390 : : * This routine does not affect logical decoding as it only looks at
6391 : : * confirmation records.
6392 : : */
6393 : : void
325 peter@eisentraut.org 6394 : 17 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
6395 : : {
4153 andres@anarazel.de 6396 : 17 : TransactionId xid = GetCurrentTransactionId();
6397 : : ItemId lp;
6398 : : HeapTupleData tp;
6399 : : Page page;
6400 : : BlockNumber block;
6401 : : Buffer buffer;
6402 : :
6403 [ - + ]: 17 : Assert(ItemPointerIsValid(tid));
6404 : :
6405 : 17 : block = ItemPointerGetBlockNumber(tid);
6406 : 17 : buffer = ReadBuffer(relation, block);
3805 kgrittn@postgresql.o 6407 : 17 : page = BufferGetPage(buffer);
6408 : :
4153 andres@anarazel.de 6409 : 17 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6410 : :
6411 : : /*
6412 : : * Page can't be all visible, we just inserted into it, and are still
6413 : : * running.
6414 : : */
6415 [ - + ]: 17 : Assert(!PageIsAllVisible(page));
6416 : :
6417 : 17 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6418 [ - + ]: 17 : Assert(ItemIdIsNormal(lp));
6419 : :
6420 : 17 : tp.t_tableOid = RelationGetRelid(relation);
6421 : 17 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6422 : 17 : tp.t_len = ItemIdGetLength(lp);
6423 : 17 : tp.t_self = *tid;
6424 : :
6425 : : /*
6426 : : * Sanity check that the tuple really is a speculatively inserted tuple,
6427 : : * inserted by us.
6428 : : */
6429 [ - + ]: 17 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
4153 andres@anarazel.de 6430 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
3686 andres@anarazel.de 6431 [ + + - + ]:CBC 17 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
4153 andres@anarazel.de 6432 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
4153 andres@anarazel.de 6433 [ - + ]:CBC 17 : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
6434 : :
6435 : : /*
6436 : : * No need to check for serializable conflicts here. There is never a
6437 : : * need for a combo CID, either. No need to extract replica identity, or
6438 : : * do anything special with infomask bits.
6439 : : */
6440 : :
6441 : 17 : START_CRIT_SECTION();
6442 : :
6443 : : /*
6444 : : * The tuple will become DEAD immediately. Flag that this page is a
6445 : : * candidate for pruning by setting xmin to TransactionXmin. While not
6446 : : * immediately prunable, it is the oldest xid we can cheaply determine
6447 : : * that's safe against wraparound / being older than the table's
6448 : : * relfrozenxid. To defend against the unlikely case of a new relation
6449 : : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6450 : : * if so (vacuum can't subsequently move relfrozenxid to beyond
6451 : : * TransactionXmin, so there's no race here).
6452 : : */
2359 6453 [ - + ]: 17 : Assert(TransactionIdIsValid(TransactionXmin));
6454 : : {
874 noah@leadboat.com 6455 : 17 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6456 : : TransactionId prune_xid;
6457 : :
6458 [ - + ]: 17 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
874 noah@leadboat.com 6459 :UBC 0 : prune_xid = relfrozenxid;
6460 : : else
874 noah@leadboat.com 6461 :CBC 17 : prune_xid = TransactionXmin;
6462 [ - + + - : 17 : PageSetPrunable(page, prune_xid);
+ + ]
6463 : : }
6464 : :
6465 : : /* store transaction information of xact deleting the tuple */
4153 andres@anarazel.de 6466 : 17 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
6467 : 17 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6468 : :
6469 : : /*
6470 : : * Set the tuple header xmin to InvalidTransactionId. This makes the
6471 : : * tuple immediately invisible everyone. (In particular, to any
6472 : : * transactions waiting on the speculative token, woken up later.)
6473 : : */
6474 : 17 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
6475 : :
6476 : : /* Clear the speculative insertion token too */
6477 : 17 : tp.t_data->t_ctid = tp.t_self;
6478 : :
6479 : 17 : MarkBufferDirty(buffer);
6480 : :
6481 : : /*
6482 : : * XLOG stuff
6483 : : *
6484 : : * The WAL records generated here match heap_delete(). The same recovery
6485 : : * routines are used.
6486 : : */
6487 [ + + + + : 17 : if (RelationNeedsWAL(relation))
+ - + - ]
6488 : : {
6489 : : xl_heap_delete xlrec;
6490 : : XLogRecPtr recptr;
6491 : :
6492 : 12 : xlrec.flags = XLH_DELETE_IS_SUPER;
6493 : 24 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6494 : 12 : tp.t_data->t_infomask2);
6495 : 12 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6496 : 12 : xlrec.xmax = xid;
6497 : :
6498 : 12 : XLogBeginInsert();
586 peter@eisentraut.org 6499 : 12 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
4153 andres@anarazel.de 6500 : 12 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6501 : :
6502 : : /* No replica identity & replication origin logged */
6503 : :
6504 : 12 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6505 : :
6506 : 12 : PageSetLSN(page, recptr);
6507 : : }
6508 : :
6509 [ - + ]: 17 : END_CRIT_SECTION();
6510 : :
6511 : 17 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6512 : :
6513 [ + + ]: 17 : if (HeapTupleHasExternal(&tp))
6514 : : {
3686 6515 [ - + ]: 1 : Assert(!IsToastRelation(relation));
2543 rhaas@postgresql.org 6516 : 1 : heap_toast_delete(relation, &tp, true);
6517 : : }
6518 : :
6519 : : /*
6520 : : * Never need to mark tuple for invalidation, since catalogs don't support
6521 : : * speculative insertion
6522 : : */
6523 : :
6524 : : /* Now we can release the buffer */
4153 andres@anarazel.de 6525 : 17 : ReleaseBuffer(buffer);
6526 : :
6527 : : /* count deletion, as we counted the insertion too */
6528 : 17 : pgstat_count_heap_delete(relation);
6529 : 17 : }
6530 : :
6531 : : /*
6532 : : * heap_inplace_lock - protect inplace update from concurrent heap_update()
6533 : : *
6534 : : * Evaluate whether the tuple's state is compatible with a no-key update.
6535 : : * Current transaction rowmarks are fine, as is KEY SHARE from any
6536 : : * transaction. If compatible, return true with the buffer exclusive-locked,
6537 : : * and the caller must release that by calling
6538 : : * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6539 : : * an error. Otherwise, call release_callback(arg), wait for blocking
6540 : : * transactions to end, and return false.
6541 : : *
6542 : : * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6543 : : * DDL, this doesn't guarantee any particular predicate locking.
6544 : : *
6545 : : * heap_delete() is a rarer source of blocking transactions (xwait). We'll
6546 : : * wait for such a transaction just like for the normal heap_update() case.
6547 : : * Normal concurrent DROP commands won't cause that, because all inplace
6548 : : * updaters take some lock that conflicts with DROP. An explicit SQL "DELETE
6549 : : * FROM pg_class" can cause it. By waiting, if the concurrent transaction
6550 : : * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
6551 : : * can find the successor tuple.
6552 : : *
6553 : : * Readers of inplace-updated fields expect changes to those fields are
6554 : : * durable. For example, vac_truncate_clog() reads datfrozenxid from
6555 : : * pg_database tuples via catalog snapshots. A future snapshot must not
6556 : : * return a lower datfrozenxid for the same database OID (lower in the
6557 : : * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6558 : : * tuple can start while we hold a lock on its buffer. In cases like
6559 : : * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6560 : : * to this transaction. ROLLBACK then is one case where it's okay to lose
6561 : : * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6562 : : * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6563 : : * committed tuple.)
6564 : : *
6565 : : * In principle, we could avoid waiting by overwriting every tuple in the
6566 : : * updated tuple chain. Reader expectations permit updating a tuple only if
6567 : : * it's aborted, is the tail of the chain, or we already updated the tuple
6568 : : * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6569 : : * order from tail to head. That would imply either (a) mutating all tuples
6570 : : * in one critical section or (b) accepting a chance of partial completion.
6571 : : * Partial completion of a relfrozenxid update would have the weird
6572 : : * consequence that the table's next VACUUM could see the table's relfrozenxid
6573 : : * move forward between vacuum_get_cutoffs() and finishing.
6574 : : */
6575 : : bool
726 noah@leadboat.com 6576 : 114372 : heap_inplace_lock(Relation relation,
6577 : : HeapTuple oldtup_ptr, Buffer buffer,
6578 : : void (*release_callback) (void *), void *arg)
6579 : : {
6580 : 114372 : HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6581 : : TM_Result result;
6582 : : bool ret;
6583 : :
6584 : : #ifdef USE_ASSERT_CHECKING
6585 [ + + ]: 114372 : if (RelationGetRelid(relation) == RelationRelationId)
6586 : 112992 : check_inplace_rel_lock(oldtup_ptr);
6587 : : #endif
6588 : :
6589 [ - + ]: 114372 : Assert(BufferIsValid(buffer));
6590 : :
6591 : : /*
6592 : : * Register shared cache invals if necessary. Other sessions may finish
6593 : : * inplace updates of this tuple between this step and LockTuple(). Since
6594 : : * inplace updates don't change cache keys, that's harmless.
6595 : : *
6596 : : * While it's tempting to register invals only after confirming we can
6597 : : * return true, the following obstacle precludes reordering steps that
6598 : : * way. Registering invals might reach a CatalogCacheInitializeCache()
6599 : : * that locks "buffer". That would hang indefinitely if running after our
6600 : : * own LockBuffer(). Hence, we must register invals before LockBuffer().
6601 : : */
279 6602 : 114372 : CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
6603 : :
726 6604 : 114372 : LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6605 : 114372 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6606 : :
6607 : : /*----------
6608 : : * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6609 : : *
6610 : : * - wait unconditionally
6611 : : * - already locked tuple above, since inplace needs that unconditionally
6612 : : * - don't recheck header after wait: simpler to defer to next iteration
6613 : : * - don't try to continue even if the updater aborts: likewise
6614 : : * - no crosscheck
6615 : : */
6616 : 114372 : result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6617 : : buffer);
6618 : :
6619 [ - + ]: 114372 : if (result == TM_Invisible)
6620 : : {
6621 : : /* no known way this can happen */
4161 rhaas@postgresql.org 6622 [ # # ]:UBC 0 : ereport(ERROR,
6623 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6624 : : errmsg_internal("attempted to overwrite invisible tuple")));
6625 : : }
726 noah@leadboat.com 6626 [ - + ]:CBC 114372 : else if (result == TM_SelfModified)
6627 : : {
6628 : : /*
6629 : : * CREATE INDEX might reach this if an expression is silly enough to
6630 : : * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6631 : : * statements might get here after a heap_update() of the same row, in
6632 : : * the absence of an intervening CommandCounterIncrement().
6633 : : */
726 noah@leadboat.com 6634 [ # # ]:UBC 0 : ereport(ERROR,
6635 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6636 : : errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6637 : : }
726 noah@leadboat.com 6638 [ + + ]:CBC 114372 : else if (result == TM_BeingModified)
6639 : : {
6640 : : TransactionId xwait;
6641 : : uint16 infomask;
6642 : :
6643 : 61 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6644 : 61 : infomask = oldtup.t_data->t_infomask;
6645 : :
6646 [ + + ]: 61 : if (infomask & HEAP_XMAX_IS_MULTI)
6647 : : {
6648 : 5 : LockTupleMode lockmode = LockTupleNoKeyExclusive;
6649 : 5 : MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
6650 : : int remain;
6651 : :
6652 [ + + ]: 5 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6653 : : lockmode, NULL))
6654 : : {
6655 : 2 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
691 6656 : 2 : release_callback(arg);
726 6657 : 2 : ret = false;
6658 : 2 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6659 : : relation, &oldtup.t_self, XLTW_Update,
6660 : : &remain);
6661 : : }
6662 : : else
6663 : 3 : ret = true;
6664 : : }
6665 [ + + ]: 56 : else if (TransactionIdIsCurrentTransactionId(xwait))
6666 : 1 : ret = true;
6667 [ + + ]: 55 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6668 : 1 : ret = true;
6669 : : else
6670 : : {
6671 : 54 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
691 6672 : 54 : release_callback(arg);
726 6673 : 54 : ret = false;
6674 : 54 : XactLockTableWait(xwait, relation, &oldtup.t_self,
6675 : : XLTW_Update);
6676 : : }
6677 : : }
6678 : : else
6679 : : {
6680 : 114311 : ret = (result == TM_Ok);
6681 [ - + ]: 114311 : if (!ret)
6682 : : {
726 noah@leadboat.com 6683 :LBC (2) : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
691 6684 : (2) : release_callback(arg);
6685 : : }
6686 : : }
6687 : :
6688 : : /*
6689 : : * GetCatalogSnapshot() relies on invalidation messages to know when to
6690 : : * take a new snapshot. COMMIT of xwait is responsible for sending the
6691 : : * invalidation. We're not acquiring heavyweight locks sufficient to
6692 : : * block if not yet sent, so we must take a new snapshot to ensure a later
6693 : : * attempt has a fair chance. While we don't need this if xwait aborted,
6694 : : * don't bother optimizing that.
6695 : : */
726 noah@leadboat.com 6696 [ + + ]:CBC 114372 : if (!ret)
6697 : : {
6698 : 56 : UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
687 6699 : 56 : ForgetInplace_Inval();
726 6700 : 56 : InvalidateCatalogSnapshot();
6701 : : }
6702 : 114372 : return ret;
6703 : : }
6704 : :
6705 : : /*
6706 : : * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6707 : : *
6708 : : * The tuple cannot change size, and therefore its header fields and null
6709 : : * bitmap (if any) don't change either.
6710 : : *
6711 : : * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6712 : : */
6713 : : void
6714 : 79174 : heap_inplace_update_and_unlock(Relation relation,
6715 : : HeapTuple oldtup, HeapTuple tuple,
6716 : : Buffer buffer)
6717 : : {
6718 : 79174 : HeapTupleHeader htup = oldtup->t_data;
6719 : : uint32 oldlen;
6720 : : uint32 newlen;
6721 : : char *dst;
6722 : : char *src;
695 6723 : 79174 : int nmsgs = 0;
6724 : 79174 : SharedInvalidationMessage *invalMessages = NULL;
6725 : 79174 : bool RelcacheInitFileInval = false;
6726 : :
726 6727 [ - + ]: 79174 : Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6728 : 79174 : oldlen = oldtup->t_len - htup->t_hoff;
7438 tgl@sss.pgh.pa.us 6729 : 79174 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6730 [ + - - + ]: 79174 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
3958 andres@anarazel.de 6731 [ # # ]:UBC 0 : elog(ERROR, "wrong tuple length");
6732 : :
695 noah@leadboat.com 6733 :CBC 79174 : dst = (char *) htup + htup->t_hoff;
6734 : 79174 : src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6735 : :
6736 : : /* Like RecordTransactionCommit(), log only if needed */
6737 [ + + ]: 79174 : if (XLogStandbyInfoActive())
6738 : 71870 : nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6739 : : &RelcacheInitFileInval);
6740 : :
6741 : : /*
6742 : : * Unlink relcache init files as needed. If unlinking, acquire
6743 : : * RelCacheInitLock until after associated invalidations. By doing this
6744 : : * in advance, if we checkpoint and then crash between inplace
6745 : : * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6746 : : * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6747 : : * neglect to PANIC on EIO.
6748 : : */
6749 : 79174 : PreInplace_Inval();
6750 : :
6751 : : /*----------
6752 : : * NO EREPORT(ERROR) from here till changes are complete
6753 : : *
6754 : : * Our exclusive buffer lock won't stop a reader having already pinned and
6755 : : * checked visibility for this tuple. With the usual order of changes
6756 : : * (i.e. updating the buffer contents before WAL logging), a reader could
6757 : : * observe our not-yet-persistent update to relfrozenxid and update
6758 : : * datfrozenxid based on that. A crash in that moment could allow
6759 : : * datfrozenxid to overtake relfrozenxid:
6760 : : *
6761 : : * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6762 : : * ["R" is a VACUUM tbl]
6763 : : * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6764 : : * D: systable_getnext() returns pg_class tuple of tbl
6765 : : * R: memcpy() into pg_class tuple of tbl
6766 : : * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6767 : : * [crash]
6768 : : * [recovery restores datfrozenxid w/o relfrozenxid]
6769 : : *
6770 : : * We avoid that by using a temporary copy of the buffer to hide our
6771 : : * change from other backends until the change has been WAL-logged. We
6772 : : * apply our change to the temporary copy and WAL-log it, before modifying
6773 : : * the real page. That way any action a reader of the in-place-updated
6774 : : * value takes will be WAL logged after this change.
6775 : : */
6776 : 79174 : START_CRIT_SECTION();
6777 : :
194 andres@anarazel.de 6778 : 79174 : MarkBufferDirty(buffer);
6779 : :
6780 : : /* XLOG stuff */
5760 rhaas@postgresql.org 6781 [ + - + + : 79174 : if (RelationNeedsWAL(relation))
+ - + + ]
6782 : : {
6783 : : xl_heap_inplace xlrec;
6784 : : PGAlignedBlock copied_buffer;
695 noah@leadboat.com 6785 : 79170 : char *origdata = (char *) BufferGetBlock(buffer);
6786 : 79170 : Page page = BufferGetPage(buffer);
6787 : 79170 : uint16 lower = ((PageHeader) page)->pd_lower;
6788 : 79170 : uint16 upper = ((PageHeader) page)->pd_upper;
6789 : : uintptr_t dst_offset_in_block;
6790 : : RelFileLocator rlocator;
6791 : : ForkNumber forkno;
6792 : : BlockNumber blkno;
6793 : : XLogRecPtr recptr;
6794 : :
4322 heikki.linnakangas@i 6795 : 79170 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
695 noah@leadboat.com 6796 : 79170 : xlrec.dbId = MyDatabaseId;
6797 : 79170 : xlrec.tsId = MyDatabaseTableSpace;
6798 : 79170 : xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6799 : 79170 : xlrec.nmsgs = nmsgs;
6800 : :
4322 heikki.linnakangas@i 6801 : 79170 : XLogBeginInsert();
586 peter@eisentraut.org 6802 : 79170 : XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
695 noah@leadboat.com 6803 [ + + ]: 79170 : if (nmsgs != 0)
586 peter@eisentraut.org 6804 : 54876 : XLogRegisterData(invalMessages,
6805 : : nmsgs * sizeof(SharedInvalidationMessage));
6806 : :
6807 : : /* register block matching what buffer will look like after changes */
695 noah@leadboat.com 6808 : 79170 : memcpy(copied_buffer.data, origdata, lower);
6809 : 79170 : memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6810 : 79170 : dst_offset_in_block = dst - origdata;
6811 : 79170 : memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6812 : 79170 : BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6813 [ - + ]: 79170 : Assert(forkno == MAIN_FORKNUM);
6814 : 79170 : XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6815 : : REGBUF_STANDARD);
6816 : 79170 : XLogRegisterBufData(0, src, newlen);
6817 : :
6818 : : /* inplace updates aren't decoded atm, don't log the origin */
6819 : :
4322 heikki.linnakangas@i 6820 : 79170 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6821 : :
695 noah@leadboat.com 6822 : 79170 : PageSetLSN(page, recptr);
6823 : : }
6824 : :
6825 : 79174 : memcpy(dst, src, newlen);
6826 : :
6827 : 79174 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6828 : :
6829 : : /*
6830 : : * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6831 : : * do this before UnlockTuple().
6832 : : */
6833 : 79174 : AtInplace_Inval();
6834 : :
7438 tgl@sss.pgh.pa.us 6835 [ - + ]: 79174 : END_CRIT_SECTION();
695 noah@leadboat.com 6836 : 79174 : UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6837 : :
6838 : 79174 : AcceptInvalidationMessages(); /* local processing of just-sent inval */
6839 : :
6840 : : /*
6841 : : * Queue a transactional inval, for logical decoding and for third-party
6842 : : * code that might have been relying on it since long before inplace
6843 : : * update adopted immediate invalidation. See README.tuplock section
6844 : : * "Reading inplace-updated columns" for logical decoding details.
6845 : : */
7438 tgl@sss.pgh.pa.us 6846 [ + + ]: 79174 : if (!IsBootstrapProcessingMode())
5514 6847 : 62180 : CacheInvalidateHeapTuple(relation, tuple, NULL);
7438 6848 : 79174 : }
6849 : :
6850 : : /*
6851 : : * heap_inplace_unlock - reverse of heap_inplace_lock
6852 : : */
6853 : : void
726 noah@leadboat.com 6854 : 35142 : heap_inplace_unlock(Relation relation,
6855 : : HeapTuple oldtup, Buffer buffer)
6856 : : {
6857 : 35142 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6858 : 35142 : UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
687 6859 : 35142 : ForgetInplace_Inval();
726 6860 : 35142 : }
6861 : :
6862 : : #define FRM_NOOP 0x0001
6863 : : #define FRM_INVALIDATE_XMAX 0x0002
6864 : : #define FRM_RETURN_IS_XID 0x0004
6865 : : #define FRM_RETURN_IS_MULTI 0x0008
6866 : : #define FRM_MARK_COMMITTED 0x0010
6867 : :
6868 : : /*
6869 : : * FreezeMultiXactId
6870 : : * Determine what to do during freezing when a tuple is marked by a
6871 : : * MultiXactId.
6872 : : *
6873 : : * "flags" is an output value; it's used to tell caller what to do on return.
6874 : : * "pagefrz" is an input/output value, used to manage page level freezing.
6875 : : *
6876 : : * Possible values that we can set in "flags":
6877 : : * FRM_NOOP
6878 : : * don't do anything -- keep existing Xmax
6879 : : * FRM_INVALIDATE_XMAX
6880 : : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6881 : : * FRM_RETURN_IS_XID
6882 : : * The Xid return value is a single update Xid to set as xmax.
6883 : : * FRM_MARK_COMMITTED
6884 : : * Xmax can be marked as HEAP_XMAX_COMMITTED
6885 : : * FRM_RETURN_IS_MULTI
6886 : : * The return value is a new MultiXactId to set as new Xmax.
6887 : : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6888 : : *
6889 : : * Caller delegates control of page freezing to us. In practice we always
6890 : : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6891 : : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6892 : : * can never be left behind. We freely choose when and how to process each
6893 : : * Multi, without ever violating the cutoff postconditions for freezing.
6894 : : *
6895 : : * It's useful to remove Multis on a proactive timeline (relative to freezing
6896 : : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6897 : : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6898 : : * misses through eager processing.
6899 : : *
6900 : : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6901 : : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6902 : : * This can usually be put off, which is usually enough to avoid it altogether.
6903 : : * Allocating new multis during VACUUM should be avoided on general principle;
6904 : : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6905 : : * its own special risks.
6906 : : *
6907 : : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6908 : : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6909 : : *
6910 : : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6911 : : * have already forced page-level freezing, since that might incur the same
6912 : : * SLRU buffer misses that we specifically intended to avoid by freezing.
6913 : : */
6914 : : static TransactionId
4661 alvherre@alvh.no-ip. 6915 : 6 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6916 : : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6917 : : HeapPageFreeze *pagefrz)
6918 : : {
6919 : : TransactionId newxmax;
6920 : : MultiXactMember *members;
6921 : : int nmembers;
6922 : : bool need_replace;
6923 : : int nnewmembers;
6924 : : MultiXactMember *newmembers;
6925 : : bool has_lockers;
6926 : : TransactionId update_xid;
6927 : : bool update_committed;
6928 : : TransactionId FreezePageRelfrozenXid;
6929 : :
6930 : 6 : *flags = 0;
6931 : :
6932 : : /* We should only be called in Multis */
6933 [ - + ]: 6 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6934 : :
3740 6935 [ + - - + ]: 12 : if (!MultiXactIdIsValid(multi) ||
6936 : 6 : HEAP_LOCKED_UPGRADED(t_infomask))
6937 : : {
4661 alvherre@alvh.no-ip. 6938 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1362 pg@bowt.ie 6939 : 0 : pagefrz->freeze_required = true;
4661 alvherre@alvh.no-ip. 6940 : 0 : return InvalidTransactionId;
6941 : : }
1368 pg@bowt.ie 6942 [ - + ]:CBC 6 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
3233 andres@anarazel.de 6943 [ # # ]:UBC 0 : ereport(ERROR,
6944 : : (errcode(ERRCODE_DATA_CORRUPTED),
6945 : : errmsg_internal("found multixact %u from before relminmxid %u",
6946 : : multi, cutoffs->relminmxid)));
1362 pg@bowt.ie 6947 [ + + ]:CBC 6 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6948 : : {
6949 : : TransactionId update_xact;
6950 : :
6951 : : /*
6952 : : * This old multi cannot possibly have members still running, but
6953 : : * verify just in case. If it was a locker only, it can be removed
6954 : : * without any further consideration; but if it contained an update,
6955 : : * we might need to preserve it.
6956 : : */
3233 andres@anarazel.de 6957 [ - + ]: 4 : if (MultiXactIdIsRunning(multi,
6958 : 4 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
3233 andres@anarazel.de 6959 [ # # ]:UBC 0 : ereport(ERROR,
6960 : : (errcode(ERRCODE_DATA_CORRUPTED),
6961 : : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6962 : : multi, cutoffs->OldestMxact)));
6963 : :
4661 alvherre@alvh.no-ip. 6964 [ + - ]:CBC 4 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6965 : : {
6966 : 4 : *flags |= FRM_INVALIDATE_XMAX;
1362 pg@bowt.ie 6967 : 4 : pagefrz->freeze_required = true;
6968 : 4 : return InvalidTransactionId;
6969 : : }
6970 : :
6971 : : /* replace multi with single XID for its updater? */
1362 pg@bowt.ie 6972 :UBC 0 : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6973 [ # # ]: 0 : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6974 [ # # ]: 0 : ereport(ERROR,
6975 : : (errcode(ERRCODE_DATA_CORRUPTED),
6976 : : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6977 : : multi, update_xact,
6978 : : cutoffs->relfrozenxid)));
6979 [ # # ]: 0 : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6980 : : {
6981 : : /*
6982 : : * Updater XID has to have aborted (otherwise the tuple would have
6983 : : * been pruned away instead, since updater XID is < OldestXmin).
6984 : : * Just remove xmax.
6985 : : */
1356 6986 [ # # ]: 0 : if (TransactionIdDidCommit(update_xact))
1362 6987 [ # # ]: 0 : ereport(ERROR,
6988 : : (errcode(ERRCODE_DATA_CORRUPTED),
6989 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6990 : : multi, update_xact,
6991 : : cutoffs->OldestXmin)));
6992 : 0 : *flags |= FRM_INVALIDATE_XMAX;
6993 : 0 : pagefrz->freeze_required = true;
6994 : 0 : return InvalidTransactionId;
6995 : : }
6996 : :
6997 : : /* Have to keep updater XID as new xmax */
6998 : 0 : *flags |= FRM_RETURN_IS_XID;
6999 : 0 : pagefrz->freeze_required = true;
7000 : 0 : return update_xact;
7001 : : }
7002 : :
7003 : : /*
7004 : : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
7005 : : * need to walk the whole members array to figure out what to do, if
7006 : : * anything.
7007 : : */
7008 : : nmembers =
3740 alvherre@alvh.no-ip. 7009 :CBC 2 : GetMultiXactIdMembers(multi, &members, false,
4436 7010 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
4661 7011 [ - + ]: 2 : if (nmembers <= 0)
7012 : : {
7013 : : /* Nothing worth keeping */
4661 alvherre@alvh.no-ip. 7014 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1362 pg@bowt.ie 7015 : 0 : pagefrz->freeze_required = true;
4661 alvherre@alvh.no-ip. 7016 : 0 : return InvalidTransactionId;
7017 : : }
7018 : :
7019 : : /*
7020 : : * The FRM_NOOP case is the only case where we might need to ratchet back
7021 : : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
7022 : : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
7023 : : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
7024 : : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
7025 : : * trackers managed by VACUUM being ratcheting back by xmax to the degree
7026 : : * required to make it safe to leave xmax undisturbed, independent of
7027 : : * whether or not page freezing is triggered somewhere else.
7028 : : *
7029 : : * Our policy is to force freezing in every case other than FRM_NOOP,
7030 : : * which obviates the need to maintain either set of trackers, anywhere.
7031 : : * Every other case will reliably execute a freeze plan for xmax that
7032 : : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
7033 : : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
7034 : : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
7035 : : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
7036 : : */
4661 alvherre@alvh.no-ip. 7037 :CBC 2 : need_replace = false;
1362 pg@bowt.ie 7038 : 2 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
1368 7039 [ + + ]: 4 : for (int i = 0; i < nmembers; i++)
7040 : : {
7041 : 3 : TransactionId xid = members[i].xid;
7042 : :
7043 [ - + ]: 3 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7044 : :
7045 [ + + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7046 : : {
7047 : : /* Can't violate the FreezeLimit postcondition */
4661 alvherre@alvh.no-ip. 7048 : 1 : need_replace = true;
7049 : 1 : break;
7050 : : }
1362 pg@bowt.ie 7051 [ - + ]: 2 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
1362 pg@bowt.ie 7052 :UBC 0 : FreezePageRelfrozenXid = xid;
7053 : : }
7054 : :
7055 : : /* Can't violate the MultiXactCutoff postcondition, either */
1362 pg@bowt.ie 7056 [ + + ]:CBC 2 : if (!need_replace)
7057 : 1 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
7058 : :
4661 alvherre@alvh.no-ip. 7059 [ + + ]: 2 : if (!need_replace)
7060 : : {
7061 : : /*
7062 : : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
7063 : : * both together to make it safe to retain this particular multi after
7064 : : * freezing its page
7065 : : */
7066 : 1 : *flags |= FRM_NOOP;
1362 pg@bowt.ie 7067 : 1 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
7068 [ - + ]: 1 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
1362 pg@bowt.ie 7069 :UBC 0 : pagefrz->FreezePageRelminMxid = multi;
4661 alvherre@alvh.no-ip. 7070 :CBC 1 : pfree(members);
1631 pg@bowt.ie 7071 : 1 : return multi;
7072 : : }
7073 : :
7074 : : /*
7075 : : * Do a more thorough second pass over the multi to figure out which
7076 : : * member XIDs actually need to be kept. Checking the precise status of
7077 : : * individual members might even show that we don't need to keep anything.
7078 : : * That is quite possible even though the Multi must be >= OldestMxact,
7079 : : * since our second pass only keeps member XIDs when it's truly necessary;
7080 : : * even member XIDs >= OldestXmin often won't be kept by second pass.
7081 : : */
4661 alvherre@alvh.no-ip. 7082 : 1 : nnewmembers = 0;
284 michael@paquier.xyz 7083 : 1 : newmembers = palloc_array(MultiXactMember, nmembers);
4661 alvherre@alvh.no-ip. 7084 : 1 : has_lockers = false;
7085 : 1 : update_xid = InvalidTransactionId;
7086 : 1 : update_committed = false;
7087 : :
7088 : : /*
7089 : : * Determine whether to keep each member xid, or to ignore it instead
7090 : : */
1368 pg@bowt.ie 7091 [ + + ]: 3 : for (int i = 0; i < nmembers; i++)
7092 : : {
7093 : 2 : TransactionId xid = members[i].xid;
7094 : 2 : MultiXactStatus mstatus = members[i].status;
7095 : :
7096 [ - + ]: 2 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7097 : :
7098 [ + - ]: 2 : if (!ISUPDATE_from_mxstatus(mstatus))
7099 : : {
7100 : : /*
7101 : : * Locker XID (not updater XID). We only keep lockers that are
7102 : : * still running.
7103 : : */
7104 [ + - + + ]: 4 : if (TransactionIdIsCurrentTransactionId(xid) ||
7105 : 2 : TransactionIdIsInProgress(xid))
7106 : : {
1362 7107 [ - + ]: 1 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
1362 pg@bowt.ie 7108 [ # # ]:UBC 0 : ereport(ERROR,
7109 : : (errcode(ERRCODE_DATA_CORRUPTED),
7110 : : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
7111 : : multi, xid,
7112 : : cutoffs->OldestXmin)));
1368 pg@bowt.ie 7113 :CBC 1 : newmembers[nnewmembers++] = members[i];
7114 : 1 : has_lockers = true;
7115 : : }
7116 : :
7117 : 2 : continue;
7118 : : }
7119 : :
7120 : : /*
7121 : : * Updater XID (not locker XID). Should we keep it?
7122 : : *
7123 : : * Since the tuple wasn't totally removed when vacuum pruned, the
7124 : : * update Xid cannot possibly be older than OldestXmin cutoff unless
7125 : : * the updater XID aborted. If the updater transaction is known
7126 : : * aborted or crashed then it's okay to ignore it, otherwise not.
7127 : : *
7128 : : * In any case the Multi should never contain two updaters, whatever
7129 : : * their individual commit status. Check for that first, in passing.
7130 : : */
1368 pg@bowt.ie 7131 [ # # ]:UBC 0 : if (TransactionIdIsValid(update_xid))
7132 [ # # ]: 0 : ereport(ERROR,
7133 : : (errcode(ERRCODE_DATA_CORRUPTED),
7134 : : errmsg_internal("multixact %u has two or more updating members",
7135 : : multi),
7136 : : errdetail_internal("First updater XID=%u second updater XID=%u.",
7137 : : update_xid, xid)));
7138 : :
7139 : : /*
7140 : : * As with all tuple visibility routines, it's critical to test
7141 : : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
7142 : : * race conditions explained in detail in heapam_visibility.c.
7143 : : */
7144 [ # # # # ]: 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
7145 : 0 : TransactionIdIsInProgress(xid))
7146 : 0 : update_xid = xid;
7147 [ # # ]: 0 : else if (TransactionIdDidCommit(xid))
7148 : : {
7149 : : /*
7150 : : * The transaction committed, so we can tell caller to set
7151 : : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
7152 : : * transaction is not running.)
7153 : : */
7154 : 0 : update_committed = true;
7155 : 0 : update_xid = xid;
7156 : : }
7157 : : else
7158 : : {
7159 : : /*
7160 : : * Not in progress, not committed -- must be aborted or crashed;
7161 : : * we can ignore it.
7162 : : */
7163 : 0 : continue;
7164 : : }
7165 : :
7166 : : /*
7167 : : * We determined that updater must be kept -- add it to pending new
7168 : : * members list
7169 : : */
1362 7170 [ # # ]: 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
7171 [ # # ]: 0 : ereport(ERROR,
7172 : : (errcode(ERRCODE_DATA_CORRUPTED),
7173 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
7174 : : multi, xid, cutoffs->OldestXmin)));
1368 7175 : 0 : newmembers[nnewmembers++] = members[i];
7176 : : }
7177 : :
4661 alvherre@alvh.no-ip. 7178 :CBC 1 : pfree(members);
7179 : :
7180 : : /*
7181 : : * Determine what to do with caller's multi based on information gathered
7182 : : * during our second pass
7183 : : */
7184 [ - + ]: 1 : if (nnewmembers == 0)
7185 : : {
7186 : : /* Nothing worth keeping */
4661 alvherre@alvh.no-ip. 7187 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1368 pg@bowt.ie 7188 : 0 : newxmax = InvalidTransactionId;
7189 : : }
4661 alvherre@alvh.no-ip. 7190 [ - + - - ]:CBC 1 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
7191 : : {
7192 : : /*
7193 : : * If there's a single member and it's an update, pass it back alone
7194 : : * without creating a new Multi. (XXX we could do this when there's a
7195 : : * single remaining locker, too, but that would complicate the API too
7196 : : * much; moreover, the case with the single updater is more
7197 : : * interesting, because those are longer-lived.)
7198 : : */
4661 alvherre@alvh.no-ip. 7199 [ # # ]:UBC 0 : Assert(nnewmembers == 1);
7200 : 0 : *flags |= FRM_RETURN_IS_XID;
7201 [ # # ]: 0 : if (update_committed)
7202 : 0 : *flags |= FRM_MARK_COMMITTED;
1368 pg@bowt.ie 7203 : 0 : newxmax = update_xid;
7204 : : }
7205 : : else
7206 : : {
7207 : : /*
7208 : : * Create a new multixact with the surviving members of the previous
7209 : : * one, to set as new Xmax in the tuple
7210 : : */
1368 pg@bowt.ie 7211 :CBC 1 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
4661 alvherre@alvh.no-ip. 7212 : 1 : *flags |= FRM_RETURN_IS_MULTI;
7213 : : }
7214 : :
7215 : 1 : pfree(newmembers);
7216 : :
1362 pg@bowt.ie 7217 : 1 : pagefrz->freeze_required = true;
1368 7218 : 1 : return newxmax;
7219 : : }
7220 : :
7221 : : /*
7222 : : * heap_prepare_freeze_tuple
7223 : : *
7224 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7225 : : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
7226 : : * setup enough state (in the *frz output argument) to enable caller to
7227 : : * process this tuple as part of freezing its page, and return true. Return
7228 : : * false if nothing can be changed about the tuple right now.
7229 : : *
7230 : : * FreezePageConflictXid is advanced only for xmin/xvac freezing, not for xmax
7231 : : * changes. We only remove xmax state here when it is lock-only, or when the
7232 : : * updater XID (including an updater member of a MultiXact) must be aborted;
7233 : : * otherwise, the tuple would already be removable. Neither case affects
7234 : : * visibility on a standby.
7235 : : *
7236 : : * Also sets *totally_frozen to true if the tuple will be totally frozen once
7237 : : * caller executes returned freeze plan (or if the tuple was already totally
7238 : : * frozen by an earlier VACUUM). This indicates that there are no remaining
7239 : : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
7240 : : *
7241 : : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
7242 : : * tuple that we returned true for, and then execute freezing. Caller must
7243 : : * initialize pagefrz fields for page as a whole before first call here for
7244 : : * each heap page.
7245 : : *
7246 : : * VACUUM caller decides on whether or not to freeze the page as a whole.
7247 : : * We'll often prepare freeze plans for a page that caller just discards.
7248 : : * However, VACUUM doesn't always get to make a choice; it must freeze when
7249 : : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7250 : : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7251 : : * that VACUUM always follows that rule.
7252 : : *
7253 : : * We sometimes force freezing of xmax MultiXactId values long before it is
7254 : : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7255 : : * It's worth processing MultiXactIds proactively when it is cheap to do so,
7256 : : * and it's convenient to make that happen by piggy-backing it on the "force
7257 : : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7258 : : * because it is expensive right now (though only when it's still possible to
7259 : : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7260 : : *
7261 : : * It is assumed that the caller has checked the tuple with
7262 : : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7263 : : * (else we should be removing the tuple, not freezing it).
7264 : : *
7265 : : * NB: This function has side effects: it might allocate a new MultiXactId.
7266 : : * It will be set as tuple's new xmax when our *frz output is processed within
7267 : : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7268 : : * then caller had better have an exclusive lock on it already.
7269 : : */
7270 : : bool
3233 andres@anarazel.de 7271 : 5688060 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
7272 : : const struct VacuumCutoffs *cutoffs,
7273 : : HeapPageFreeze *pagefrz,
7274 : : HeapTupleFreeze *frz, bool *totally_frozen)
7275 : : {
1368 pg@bowt.ie 7276 : 5688060 : bool xmin_already_frozen = false,
7277 : 5688060 : xmax_already_frozen = false;
7278 : 5688060 : bool freeze_xmin = false,
7279 : 5688060 : replace_xvac = false,
7280 : 5688060 : replace_xmax = false,
7281 : 5688060 : freeze_xmax = false;
7282 : : TransactionId xid;
7283 : :
1356 7284 : 5688060 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
4661 alvherre@alvh.no-ip. 7285 : 5688060 : frz->t_infomask2 = tuple->t_infomask2;
7286 : 5688060 : frz->t_infomask = tuple->t_infomask;
1356 pg@bowt.ie 7287 : 5688060 : frz->frzflags = 0;
7288 : 5688060 : frz->checkflags = 0;
7289 : :
7290 : : /*
7291 : : * Process xmin, while keeping track of whether it's already frozen, or
7292 : : * will become frozen iff our freeze plan is executed by caller (could be
7293 : : * neither).
7294 : : */
7259 tgl@sss.pgh.pa.us 7295 : 5688060 : xid = HeapTupleHeaderGetXmin(tuple);
2698 alvherre@alvh.no-ip. 7296 [ + + ]: 5688060 : if (!TransactionIdIsNormal(xid))
1368 pg@bowt.ie 7297 : 901021 : xmin_already_frozen = true;
7298 : : else
7299 : : {
7300 [ - + ]: 4787039 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3233 andres@anarazel.de 7301 [ # # ]:UBC 0 : ereport(ERROR,
7302 : : (errcode(ERRCODE_DATA_CORRUPTED),
7303 : : errmsg_internal("found xmin %u from before relfrozenxid %u",
7304 : : xid, cutoffs->relfrozenxid)));
7305 : :
7306 : : /* Will set freeze_xmin flags in freeze plan below */
1362 pg@bowt.ie 7307 :CBC 4787039 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7308 : :
7309 : : /* Verify that xmin committed if and when freeze plan is executed */
1356 7310 [ + + ]: 4787039 : if (freeze_xmin)
7311 : : {
7312 : 4038791 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
194 melanieplageman@gmai 7313 [ + + ]: 4038791 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7314 : 548021 : pagefrz->FreezePageConflictXid = xid;
7315 : : }
7316 : : }
7317 : :
7318 : : /*
7319 : : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7320 : : * as we support having MOVED_OFF/MOVED_IN tuples in the database
7321 : : */
1368 pg@bowt.ie 7322 : 5688060 : xid = HeapTupleHeaderGetXvac(tuple);
7323 [ - + ]: 5688060 : if (TransactionIdIsNormal(xid))
7324 : : {
1368 pg@bowt.ie 7325 [ # # ]:UBC 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7326 [ # # ]: 0 : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7327 : :
7328 : : /*
7329 : : * For Xvac, we always freeze proactively. This allows totally_frozen
7330 : : * tracking to ignore xvac.
7331 : : */
1362 7332 : 0 : replace_xvac = pagefrz->freeze_required = true;
7333 : :
194 melanieplageman@gmai 7334 [ # # ]: 0 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7335 : 0 : pagefrz->FreezePageConflictXid = xid;
7336 : :
7337 : : /* Will set replace_xvac flags in freeze plan below */
7338 : : }
7339 : :
7340 : : /* Now process xmax */
1356 pg@bowt.ie 7341 :CBC 5688060 : xid = frz->xmax;
4679 alvherre@alvh.no-ip. 7342 [ + + ]: 5688060 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7343 : : {
7344 : : /* Raw xmax is a MultiXactId */
7345 : : TransactionId newxmax;
7346 : : uint16 flags;
7347 : :
7348 : : /*
7349 : : * We will either remove xmax completely (in the "freeze_xmax" path),
7350 : : * process xmax by replacing it (in the "replace_xmax" path), or
7351 : : * perform no-op xmax processing. The only constraint is that the
7352 : : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7353 : : */
1368 pg@bowt.ie 7354 : 6 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7355 : : &flags, pagefrz);
7356 : :
1362 7357 [ + + ]: 6 : if (flags & FRM_NOOP)
7358 : : {
7359 : : /*
7360 : : * xmax is a MultiXactId, and nothing about it changes for now.
7361 : : * This is the only case where 'freeze_required' won't have been
7362 : : * set for us by FreezeMultiXactId, as well as the only case where
7363 : : * neither freeze_xmax nor replace_xmax are set (given a multi).
7364 : : *
7365 : : * This is a no-op, but the call to FreezeMultiXactId might have
7366 : : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7367 : : * for us (the "freeze page" variants, specifically). That'll
7368 : : * make it safe for our caller to freeze the page later on, while
7369 : : * leaving this particular xmax undisturbed.
7370 : : *
7371 : : * FreezeMultiXactId is _not_ responsible for the "no freeze"
7372 : : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7373 : : * job. A call to heap_tuple_should_freeze for this same tuple
7374 : : * will take place below if 'freeze_required' isn't set already.
7375 : : * (This repeats work from FreezeMultiXactId, but allows "no
7376 : : * freeze" tracker maintenance to happen in only one place.)
7377 : : */
7378 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7379 [ + - - + ]: 1 : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7380 : : }
7381 [ - + ]: 5 : else if (flags & FRM_RETURN_IS_XID)
7382 : : {
7383 : : /*
7384 : : * xmax will become an updater Xid (original MultiXact's updater
7385 : : * member Xid will be carried forward as a simple Xid in Xmax).
7386 : : */
1368 pg@bowt.ie 7387 [ # # ]:UBC 0 : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7388 : :
7389 : : /*
7390 : : * NB -- some of these transformations are only valid because we
7391 : : * know the return Xid is a tuple updater (i.e. not merely a
7392 : : * locker.) Also note that the only reason we don't explicitly
7393 : : * worry about HEAP_KEYS_UPDATED is because it lives in
7394 : : * t_infomask2 rather than t_infomask.
7395 : : */
4661 alvherre@alvh.no-ip. 7396 : 0 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7397 : 0 : frz->xmax = newxmax;
7398 [ # # ]: 0 : if (flags & FRM_MARK_COMMITTED)
3363 teodor@sigaev.ru 7399 : 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
1368 pg@bowt.ie 7400 : 0 : replace_xmax = true;
7401 : : }
4661 alvherre@alvh.no-ip. 7402 [ + + ]:CBC 5 : else if (flags & FRM_RETURN_IS_MULTI)
7403 : : {
7404 : : uint16 newbits;
7405 : : uint16 newbits2;
7406 : :
7407 : : /*
7408 : : * xmax is an old MultiXactId that we have to replace with a new
7409 : : * MultiXactId, to carry forward two or more original member XIDs.
7410 : : */
1368 pg@bowt.ie 7411 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7412 : :
7413 : : /*
7414 : : * We can't use GetMultiXactIdHintBits directly on the new multi
7415 : : * here; that routine initializes the masks to all zeroes, which
7416 : : * would lose other bits we need. Doing it this way ensures all
7417 : : * unrelated bits remain untouched.
7418 : : */
4661 alvherre@alvh.no-ip. 7419 : 1 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7420 : 1 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7421 : 1 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7422 : 1 : frz->t_infomask |= newbits;
7423 : 1 : frz->t_infomask2 |= newbits2;
7424 : 1 : frz->xmax = newxmax;
1368 pg@bowt.ie 7425 : 1 : replace_xmax = true;
7426 : : }
7427 : : else
7428 : : {
7429 : : /*
7430 : : * Freeze plan for tuple "freezes xmax" in the strictest sense:
7431 : : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7432 : : */
7433 [ - + ]: 4 : Assert(flags & FRM_INVALIDATE_XMAX);
1631 7434 [ - + ]: 4 : Assert(!TransactionIdIsValid(newxmax));
7435 : :
7436 : : /* Will set freeze_xmax flags in freeze plan below */
1368 7437 : 4 : freeze_xmax = true;
7438 : : }
7439 : :
7440 : : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
1362 7441 [ - + - - : 6 : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
- - ]
7442 : : }
3749 rhaas@postgresql.org 7443 [ + + ]: 5688054 : else if (TransactionIdIsNormal(xid))
7444 : : {
7445 : : /* Raw xmax is normal XID */
1368 pg@bowt.ie 7446 [ - + ]: 394508 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3233 andres@anarazel.de 7447 [ # # ]:UBC 0 : ereport(ERROR,
7448 : : (errcode(ERRCODE_DATA_CORRUPTED),
7449 : : errmsg_internal("found xmax %u from before relfrozenxid %u",
7450 : : xid, cutoffs->relfrozenxid)));
7451 : :
7452 : : /* Will set freeze_xmax flags in freeze plan below */
1356 pg@bowt.ie 7453 :CBC 394508 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7454 : :
7455 : : /*
7456 : : * Verify that xmax aborted if and when freeze plan is executed,
7457 : : * provided it's from an update. (A lock-only xmax can be removed
7458 : : * independent of this, since the lock is released at xact end.)
7459 : : */
7460 [ + + + + ]: 394508 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7461 : 5760 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7462 : : }
1397 7463 [ + - ]: 5293546 : else if (!TransactionIdIsValid(xid))
7464 : : {
7465 : : /* Raw xmax is InvalidTransactionId XID */
7466 [ - + ]: 5293546 : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
3061 alvherre@alvh.no-ip. 7467 : 5293546 : xmax_already_frozen = true;
7468 : : }
7469 : : else
3061 alvherre@alvh.no-ip. 7470 [ # # ]:UBC 0 : ereport(ERROR,
7471 : : (errcode(ERRCODE_DATA_CORRUPTED),
7472 : : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7473 : : xid, tuple->t_infomask)));
7474 : :
1368 pg@bowt.ie 7475 [ + + ]:CBC 5688060 : if (freeze_xmin)
7476 : : {
7477 [ - + ]: 4038791 : Assert(!xmin_already_frozen);
7478 : :
7479 : 4038791 : frz->t_infomask |= HEAP_XMIN_FROZEN;
7480 : : }
7481 [ - + ]: 5688060 : if (replace_xvac)
7482 : : {
7483 : : /*
7484 : : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7485 : : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7486 : : * transaction succeeded.
7487 : : */
1362 pg@bowt.ie 7488 [ # # ]:UBC 0 : Assert(pagefrz->freeze_required);
1368 7489 [ # # ]: 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
7490 : 0 : frz->frzflags |= XLH_INVALID_XVAC;
7491 : : else
7492 : 0 : frz->frzflags |= XLH_FREEZE_XVAC;
7493 : : }
1368 pg@bowt.ie 7494 [ + + ]:CBC 5688060 : if (replace_xmax)
7495 : : {
7496 [ + - - + ]: 1 : Assert(!xmax_already_frozen && !freeze_xmax);
1362 7497 [ - + ]: 1 : Assert(pagefrz->freeze_required);
7498 : :
7499 : : /* Already set replace_xmax flags in freeze plan earlier */
7500 : : }
4679 alvherre@alvh.no-ip. 7501 [ + + ]: 5688060 : if (freeze_xmax)
7502 : : {
1368 pg@bowt.ie 7503 [ + - - + ]: 6848 : Assert(!xmax_already_frozen && !replace_xmax);
7504 : :
4661 alvherre@alvh.no-ip. 7505 : 6848 : frz->xmax = InvalidTransactionId;
7506 : :
7507 : : /*
7508 : : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7509 : : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7510 : : * Also get rid of the HEAP_KEYS_UPDATED bit.
7511 : : */
7512 : 6848 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7513 : 6848 : frz->t_infomask |= HEAP_XMAX_INVALID;
7514 : 6848 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7515 : 6848 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7516 : : }
7517 : :
7518 : : /*
7519 : : * Determine if this tuple is already totally frozen, or will become
7520 : : * totally frozen (provided caller executes freeze plans for the page)
7521 : : */
1368 pg@bowt.ie 7522 [ + + + + : 10621024 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
+ + ]
7523 [ + + ]: 4932964 : (freeze_xmax || xmax_already_frozen));
7524 : :
1362 7525 [ + + + + : 5688060 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
+ + ]
7526 : : xmax_already_frozen))
7527 : : {
7528 : : /*
7529 : : * So far no previous tuple from the page made freezing mandatory.
7530 : : * Does this tuple force caller to freeze the entire page?
7531 : : */
7532 : 3440275 : pagefrz->freeze_required =
7533 : 3440275 : heap_tuple_should_freeze(tuple, cutoffs,
7534 : : &pagefrz->NoFreezePageRelfrozenXid,
7535 : : &pagefrz->NoFreezePageRelminMxid);
7536 : : }
7537 : :
7538 : : /* Tell caller if this tuple has a usable freeze plan set in *frz */
1368 7539 [ + + + - : 5688060 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
+ - + + ]
7540 : : }
7541 : :
7542 : : /*
7543 : : * Perform xmin/xmax XID status sanity checks before actually executing freeze
7544 : : * plans.
7545 : : *
7546 : : * heap_prepare_freeze_tuple doesn't perform these checks directly because
7547 : : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7548 : : * successive VACUUMs that each decide against freezing the same page.
7549 : : */
7550 : : void
900 heikki.linnakangas@i 7551 : 25149 : heap_pre_freeze_checks(Buffer buffer,
7552 : : HeapTupleFreeze *tuples, int ntuples)
7553 : : {
1405 pg@bowt.ie 7554 : 25149 : Page page = BufferGetPage(buffer);
7555 : :
1356 7556 [ + + ]: 1335088 : for (int i = 0; i < ntuples; i++)
7557 : : {
7558 : 1309939 : HeapTupleFreeze *frz = tuples + i;
7559 : 1309939 : ItemId itemid = PageGetItemId(page, frz->offset);
7560 : : HeapTupleHeader htup;
7561 : :
7562 : 1309939 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7563 : :
7564 : : /* Deliberately avoid relying on tuple hint bits here */
7565 [ + + ]: 1309939 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7566 : : {
7567 : 1309938 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
7568 : :
7569 [ - + ]: 1309938 : Assert(!HeapTupleHeaderXminFrozen(htup));
7570 [ - + ]: 1309938 : if (unlikely(!TransactionIdDidCommit(xmin)))
1356 pg@bowt.ie 7571 [ # # ]:UBC 0 : ereport(ERROR,
7572 : : (errcode(ERRCODE_DATA_CORRUPTED),
7573 : : errmsg_internal("uncommitted xmin %u needs to be frozen",
7574 : : xmin)));
7575 : : }
7576 : :
7577 : : /*
7578 : : * TransactionIdDidAbort won't work reliably in the presence of XIDs
7579 : : * left behind by transactions that were in progress during a crash,
7580 : : * so we can only check that xmax didn't commit
7581 : : */
1356 pg@bowt.ie 7582 [ + + ]:CBC 1309939 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7583 : : {
7584 : 931 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
7585 : :
7586 [ - + ]: 931 : Assert(TransactionIdIsNormal(xmax));
7587 [ - + ]: 931 : if (unlikely(TransactionIdDidCommit(xmax)))
1356 pg@bowt.ie 7588 [ # # ]:UBC 0 : ereport(ERROR,
7589 : : (errcode(ERRCODE_DATA_CORRUPTED),
7590 : : errmsg_internal("cannot freeze committed xmax %u",
7591 : : xmax)));
7592 : : }
7593 : : }
900 heikki.linnakangas@i 7594 :CBC 25149 : }
7595 : :
7596 : : /*
7597 : : * Helper which executes freezing of one or more heap tuples on a page on
7598 : : * behalf of caller. Caller passes an array of tuple plans from
7599 : : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7600 : : * Must be called in a critical section that also marks the buffer dirty and,
7601 : : * if needed, emits WAL.
7602 : : */
7603 : : void
7604 : 25149 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
7605 : : {
7606 : 25149 : Page page = BufferGetPage(buffer);
7607 : :
1405 pg@bowt.ie 7608 [ + + ]: 1335088 : for (int i = 0; i < ntuples; i++)
7609 : : {
1356 7610 : 1309939 : HeapTupleFreeze *frz = tuples + i;
7611 : 1309939 : ItemId itemid = PageGetItemId(page, frz->offset);
7612 : : HeapTupleHeader htup;
7613 : :
1405 7614 : 1309939 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
1356 7615 : 1309939 : heap_execute_freeze_tuple(htup, frz);
7616 : : }
1405 7617 : 25149 : }
7618 : :
7619 : : /*
7620 : : * heap_freeze_tuple
7621 : : * Freeze tuple in place, without WAL logging.
7622 : : *
7623 : : * Useful for callers like CLUSTER that perform their own WAL logging.
7624 : : */
7625 : : bool
3233 andres@anarazel.de 7626 : 463598 : heap_freeze_tuple(HeapTupleHeader tuple,
7627 : : TransactionId relfrozenxid, TransactionId relminmxid,
7628 : : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7629 : : {
7630 : : HeapTupleFreeze frz;
7631 : : bool do_freeze;
7632 : : bool totally_frozen;
7633 : : struct VacuumCutoffs cutoffs;
7634 : : HeapPageFreeze pagefrz;
7635 : :
1368 pg@bowt.ie 7636 : 463598 : cutoffs.relfrozenxid = relfrozenxid;
7637 : 463598 : cutoffs.relminmxid = relminmxid;
7638 : 463598 : cutoffs.OldestXmin = FreezeLimit;
7639 : 463598 : cutoffs.OldestMxact = MultiXactCutoff;
7640 : 463598 : cutoffs.FreezeLimit = FreezeLimit;
7641 : 463598 : cutoffs.MultiXactCutoff = MultiXactCutoff;
7642 : :
1362 7643 : 463598 : pagefrz.freeze_required = true;
7644 : 463598 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7645 : 463598 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
194 melanieplageman@gmai 7646 : 463598 : pagefrz.FreezePageConflictXid = InvalidTransactionId;
1362 pg@bowt.ie 7647 : 463598 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7648 : 463598 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7649 : :
1368 7650 : 463598 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7651 : : &pagefrz, &frz, &totally_frozen);
7652 : :
7653 : : /*
7654 : : * Note that because this is not a WAL-logged operation, we don't need to
7655 : : * fill in the offset in the freeze record.
7656 : : */
7657 : :
4661 alvherre@alvh.no-ip. 7658 [ + + ]: 463598 : if (do_freeze)
7659 : 374466 : heap_execute_freeze_tuple(tuple, &frz);
7660 : 463598 : return do_freeze;
7661 : : }
7662 : :
7663 : : /*
7664 : : * For a given MultiXactId, return the hint bits that should be set in the
7665 : : * tuple's infomask.
7666 : : *
7667 : : * Normally this should be called for a multixact that was just created, and
7668 : : * so is on our local cache, so the GetMembers call is fast.
7669 : : */
7670 : : static void
4988 7671 : 76803 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
7672 : : uint16 *new_infomask2)
7673 : : {
7674 : : int nmembers;
7675 : : MultiXactMember *members;
7676 : : int i;
4862 bruce@momjian.us 7677 : 76803 : uint16 bits = HEAP_XMAX_IS_MULTI;
7678 : 76803 : uint16 bits2 = 0;
7679 : 76803 : bool has_update = false;
7680 : 76803 : LockTupleMode strongest = LockTupleKeyShare;
7681 : :
7682 : : /*
7683 : : * We only use this in multis we just created, so they cannot be values
7684 : : * pre-pg_upgrade.
7685 : : */
4436 alvherre@alvh.no-ip. 7686 : 76803 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7687 : :
4988 7688 [ + + ]: 1472611 : for (i = 0; i < nmembers; i++)
7689 : : {
7690 : : LockTupleMode mode;
7691 : :
7692 : : /*
7693 : : * Remember the strongest lock mode held by any member of the
7694 : : * multixact.
7695 : : */
4980 7696 : 1395808 : mode = TUPLOCK_from_mxstatus(members[i].status);
7697 [ + + ]: 1395808 : if (mode > strongest)
7698 : 2902 : strongest = mode;
7699 : :
7700 : : /* See what other bits we need */
4988 7701 [ + + + + : 1395808 : switch (members[i].status)
- ]
7702 : : {
7703 : 1393384 : case MultiXactStatusForKeyShare:
7704 : : case MultiXactStatusForShare:
7705 : : case MultiXactStatusForNoKeyUpdate:
7706 : 1393384 : break;
7707 : :
7708 : 53 : case MultiXactStatusForUpdate:
7709 : 53 : bits2 |= HEAP_KEYS_UPDATED;
7710 : 53 : break;
7711 : :
7712 : 2361 : case MultiXactStatusNoKeyUpdate:
7713 : 2361 : has_update = true;
7714 : 2361 : break;
7715 : :
7716 : 10 : case MultiXactStatusUpdate:
7717 : 10 : bits2 |= HEAP_KEYS_UPDATED;
7718 : 10 : has_update = true;
7719 : 10 : break;
7720 : : }
7721 : : }
7722 : :
4980 7723 [ + + + + ]: 76803 : if (strongest == LockTupleExclusive ||
7724 : : strongest == LockTupleNoKeyExclusive)
7725 : 2452 : bits |= HEAP_XMAX_EXCL_LOCK;
7726 [ + + ]: 74351 : else if (strongest == LockTupleShare)
7727 : 447 : bits |= HEAP_XMAX_SHR_LOCK;
7728 [ + - ]: 73904 : else if (strongest == LockTupleKeyShare)
7729 : 73904 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7730 : :
4988 7731 [ + + ]: 76803 : if (!has_update)
7732 : 74432 : bits |= HEAP_XMAX_LOCK_ONLY;
7733 : :
7734 [ + - ]: 76803 : if (nmembers > 0)
7735 : 76803 : pfree(members);
7736 : :
7737 : 76803 : *new_infomask = bits;
7738 : 76803 : *new_infomask2 = bits2;
7739 : 76803 : }
7740 : :
7741 : : /*
7742 : : * MultiXactIdGetUpdateXid
7743 : : *
7744 : : * Given a multixact Xmax and corresponding infomask, which does not have the
7745 : : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7746 : : * transaction.
7747 : : *
7748 : : * Caller is expected to check the status of the updating transaction, if
7749 : : * necessary.
7750 : : */
7751 : : static TransactionId
7752 : 162095 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7753 : : {
4862 bruce@momjian.us 7754 : 162095 : TransactionId update_xact = InvalidTransactionId;
7755 : : MultiXactMember *members;
7756 : : int nmembers;
7757 : :
4988 alvherre@alvh.no-ip. 7758 [ - + ]: 162095 : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7759 [ - + ]: 162095 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7760 : :
7761 : : /*
7762 : : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7763 : : * pre-pg_upgrade.
7764 : : */
4436 7765 : 162095 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7766 : :
4988 7767 [ + - ]: 162095 : if (nmembers > 0)
7768 : : {
7769 : : int i;
7770 : :
7771 [ + + ]: 3235170 : for (i = 0; i < nmembers; i++)
7772 : : {
7773 : : /* Ignore lockers */
4678 7774 [ + + ]: 3073075 : if (!ISUPDATE_from_mxstatus(members[i].status))
4988 7775 : 2910980 : continue;
7776 : :
7777 : : /* there can be at most one updater */
7778 [ - + ]: 162095 : Assert(update_xact == InvalidTransactionId);
7779 : 162095 : update_xact = members[i].xid;
7780 : : #ifndef USE_ASSERT_CHECKING
7781 : :
7782 : : /*
7783 : : * in an assert-enabled build, walk the whole array to ensure
7784 : : * there's no other updater.
7785 : : */
7786 : : break;
7787 : : #endif
7788 : : }
7789 : :
7790 : 162095 : pfree(members);
7791 : : }
7792 : :
7793 : 162095 : return update_xact;
7794 : : }
7795 : :
7796 : : /*
7797 : : * HeapTupleGetUpdateXid
7798 : : * As above, but use a HeapTupleHeader
7799 : : *
7800 : : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7801 : : * checking the hint bits.
7802 : : */
7803 : : TransactionId
605 peter@eisentraut.org 7804 : 159954 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
7805 : : {
7806 : 159954 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
7807 : 159954 : tup->t_infomask);
7808 : : }
7809 : :
7810 : : /*
7811 : : * Does the given multixact conflict with the current transaction grabbing a
7812 : : * tuple lock of the given strength?
7813 : : *
7814 : : * The passed infomask pairs up with the given multixact in the tuple header.
7815 : : *
7816 : : * If current_is_member is not NULL, it is set to 'true' if the current
7817 : : * transaction is a member of the given multixact.
7818 : : */
7819 : : static bool
4286 alvherre@alvh.no-ip. 7820 : 218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7821 : : LockTupleMode lockmode, bool *current_is_member)
7822 : : {
7823 : : int nmembers;
7824 : : MultiXactMember *members;
4138 bruce@momjian.us 7825 : 218 : bool result = false;
7826 : 218 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7827 : :
3740 alvherre@alvh.no-ip. 7828 [ - + ]: 218 : if (HEAP_LOCKED_UPGRADED(infomask))
3740 alvherre@alvh.no-ip. 7829 :UBC 0 : return false;
7830 : :
3740 alvherre@alvh.no-ip. 7831 :CBC 218 : nmembers = GetMultiXactIdMembers(multi, &members, false,
4286 7832 : 218 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7833 [ + - ]: 218 : if (nmembers >= 0)
7834 : : {
7835 : : int i;
7836 : :
7837 [ + + ]: 2682 : for (i = 0; i < nmembers; i++)
7838 : : {
7839 : : TransactionId memxid;
7840 : : LOCKMODE memlockmode;
7841 : :
2651 7842 [ + + + + : 2471 : if (result && (current_is_member == NULL || *current_is_member))
+ - ]
7843 : : break;
7844 : :
7845 : 2464 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7846 : :
7847 : : /* ignore members from current xact (but track their presence) */
2653 7848 : 2464 : memxid = members[i].xid;
7849 [ + + ]: 2464 : if (TransactionIdIsCurrentTransactionId(memxid))
7850 : : {
2651 7851 [ + + ]: 92 : if (current_is_member != NULL)
7852 : 78 : *current_is_member = true;
7853 : 92 : continue;
7854 : : }
7855 [ + + ]: 2372 : else if (result)
7856 : 8 : continue;
7857 : :
7858 : : /* ignore members that don't conflict with the lock we want */
7859 [ + + ]: 2364 : if (!DoLockModesConflict(memlockmode, wanted))
2653 7860 : 2325 : continue;
7861 : :
4286 7862 [ + + ]: 39 : if (ISUPDATE_from_mxstatus(members[i].status))
7863 : : {
7864 : : /* ignore aborted updaters */
7865 [ + + ]: 17 : if (TransactionIdDidAbort(memxid))
7866 : 1 : continue;
7867 : : }
7868 : : else
7869 : : {
7870 : : /* ignore lockers-only that are no longer in progress */
7871 [ + + ]: 22 : if (!TransactionIdIsInProgress(memxid))
7872 : 7 : continue;
7873 : : }
7874 : :
7875 : : /*
7876 : : * Whatever remains are either live lockers that conflict with our
7877 : : * wanted lock, and updaters that are not aborted. Those conflict
7878 : : * with what we want. Set up to return true, but keep going to
7879 : : * look for the current transaction among the multixact members,
7880 : : * if needed.
7881 : : */
7882 : 31 : result = true;
7883 : : }
7884 : 218 : pfree(members);
7885 : : }
7886 : :
7887 : 218 : return result;
7888 : : }
7889 : :
7890 : : /*
7891 : : * Do_MultiXactIdWait
7892 : : * Actual implementation for the two functions below.
7893 : : *
7894 : : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7895 : : * needed to ensure we only sleep on conflicting members, and the infomask is
7896 : : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7897 : : * indicates whether to use conditional lock acquisition, to allow callers to
7898 : : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7899 : : * context information for error messages. 'remaining', if not NULL, receives
7900 : : * the number of members that are still running, including any (non-aborted)
7901 : : * subtransactions of our own transaction. 'logLockFailure' indicates whether
7902 : : * to log details when a lock acquisition fails with 'nowait' enabled.
7903 : : *
7904 : : * We do this by sleeping on each member using XactLockTableWait. Any
7905 : : * members that belong to the current backend are *not* waited for, however;
7906 : : * this would not merely be useless but would lead to Assert failure inside
7907 : : * XactLockTableWait. By the time this returns, it is certain that all
7908 : : * transactions *of other backends* that were members of the MultiXactId
7909 : : * that conflict with the requested status are dead (and no new ones can have
7910 : : * been added, since it is not legal to add members to an existing
7911 : : * MultiXactId).
7912 : : *
7913 : : * But by the time we finish sleeping, someone else may have changed the Xmax
7914 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7915 : : *
7916 : : * Note that in case we return false, the number of remaining members is
7917 : : * not to be trusted.
7918 : : */
7919 : : static bool
4988 7920 : 61 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7921 : : uint16 infomask, bool nowait,
7922 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7923 : : int *remaining, bool logLockFailure)
7924 : : {
7925 : 61 : bool result = true;
7926 : : MultiXactMember *members;
7927 : : int nmembers;
7928 : 61 : int remain = 0;
7929 : :
7930 : : /* for pre-pg_upgrade tuples, no need to sleep at all */
3740 7931 [ + - ]: 61 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7932 : 61 : GetMultiXactIdMembers(multi, &members, false,
7933 : 61 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7934 : :
4988 7935 [ + - ]: 61 : if (nmembers >= 0)
7936 : : {
7937 : : int i;
7938 : :
7939 [ + + ]: 191 : for (i = 0; i < nmembers; i++)
7940 : : {
7941 : 136 : TransactionId memxid = members[i].xid;
7942 : 136 : MultiXactStatus memstatus = members[i].status;
7943 : :
7944 [ + + ]: 136 : if (TransactionIdIsCurrentTransactionId(memxid))
7945 : : {
7946 : 25 : remain++;
7947 : 25 : continue;
7948 : : }
7949 : :
7950 [ + + ]: 111 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7951 : 111 : LOCKMODE_from_mxstatus(status)))
7952 : : {
7953 [ + + + - ]: 22 : if (remaining && TransactionIdIsInProgress(memxid))
7954 : 8 : remain++;
7955 : 22 : continue;
7956 : : }
7957 : :
7958 : : /*
7959 : : * This member conflicts with our multi, so we have to sleep (or
7960 : : * return failure, if asked to avoid waiting.)
7961 : : *
7962 : : * Note that we don't set up an error context callback ourselves,
7963 : : * but instead we pass the info down to XactLockTableWait. This
7964 : : * might seem a bit wasteful because the context is set up and
7965 : : * tore down for each member of the multixact, but in reality it
7966 : : * should be barely noticeable, and it avoids duplicate code.
7967 : : */
7968 [ + + ]: 89 : if (nowait)
7969 : : {
555 fujii@postgresql.org 7970 : 6 : result = ConditionalXactLockTableWait(memxid, logLockFailure);
4988 alvherre@alvh.no-ip. 7971 [ + - ]: 6 : if (!result)
7972 : 6 : break;
7973 : : }
7974 : : else
4568 7975 : 83 : XactLockTableWait(memxid, rel, ctid, oper);
7976 : : }
7977 : :
4988 7978 : 61 : pfree(members);
7979 : : }
7980 : :
7981 [ + + ]: 61 : if (remaining)
7982 : 10 : *remaining = remain;
7983 : :
7984 : 61 : return result;
7985 : : }
7986 : :
7987 : : /*
7988 : : * MultiXactIdWait
7989 : : * Sleep on a MultiXactId.
7990 : : *
7991 : : * By the time we finish sleeping, someone else may have changed the Xmax
7992 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7993 : : *
7994 : : * We return (in *remaining, if not NULL) the number of members that are still
7995 : : * running, including any (non-aborted) subtransactions of our own transaction.
7996 : : */
7997 : : static void
4568 7998 : 55 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
7999 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
8000 : : int *remaining)
8001 : : {
8002 : 55 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
8003 : : rel, ctid, oper, remaining, false);
4988 8004 : 55 : }
8005 : :
8006 : : /*
8007 : : * ConditionalMultiXactIdWait
8008 : : * As above, but only lock if we can get the lock without blocking.
8009 : : *
8010 : : * By the time we finish sleeping, someone else may have changed the Xmax
8011 : : * of the containing tuple, so the caller needs to iterate on us somehow.
8012 : : *
8013 : : * If the multixact is now all gone, return true. Returns false if some
8014 : : * transactions might still be running.
8015 : : *
8016 : : * We return (in *remaining, if not NULL) the number of members that are still
8017 : : * running, including any (non-aborted) subtransactions of our own transaction.
8018 : : */
8019 : : static bool
8020 : 6 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
8021 : : uint16 infomask, Relation rel, int *remaining,
8022 : : bool logLockFailure)
8023 : : {
4568 8024 : 6 : return Do_MultiXactIdWait(multi, status, infomask, true,
8025 : : rel, NULL, XLTW_None, remaining, logLockFailure);
8026 : : }
8027 : :
8028 : : /*
8029 : : * heap_tuple_needs_eventual_freeze
8030 : : *
8031 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
8032 : : * will eventually require freezing (if tuple isn't removed by pruning first).
8033 : : */
8034 : : bool
3855 rhaas@postgresql.org 8035 : 2183686 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
8036 : : {
8037 : : TransactionId xid;
8038 : :
8039 : : /*
8040 : : * If xmin is a normal transaction ID, this tuple is definitely not
8041 : : * frozen.
8042 : : */
8043 : 2183686 : xid = HeapTupleHeaderGetXmin(tuple);
8044 [ + + ]: 2183686 : if (TransactionIdIsNormal(xid))
8045 : 38208 : return true;
8046 : :
8047 : : /*
8048 : : * If xmax is a valid xact or multixact, this tuple is also not frozen.
8049 : : */
8050 [ + + ]: 2145478 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
8051 : : {
8052 : : MultiXactId multi;
8053 : :
8054 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8055 [ + - ]: 2 : if (MultiXactIdIsValid(multi))
8056 : 2 : return true;
8057 : : }
8058 : : else
8059 : : {
8060 : 2145476 : xid = HeapTupleHeaderGetRawXmax(tuple);
8061 [ + + ]: 2145476 : if (TransactionIdIsNormal(xid))
8062 : 35 : return true;
8063 : : }
8064 : :
8065 [ - + ]: 2145441 : if (tuple->t_infomask & HEAP_MOVED)
8066 : : {
3855 rhaas@postgresql.org 8067 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
8068 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8069 : 0 : return true;
8070 : : }
8071 : :
3855 rhaas@postgresql.org 8072 :CBC 2145441 : return false;
8073 : : }
8074 : :
8075 : : /*
8076 : : * heap_tuple_should_freeze
8077 : : *
8078 : : * Return value indicates if heap_prepare_freeze_tuple sibling function would
8079 : : * (or should) force freezing of the heap page that contains caller's tuple.
8080 : : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
8081 : : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
8082 : : *
8083 : : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
8084 : : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
8085 : : * Our working assumption is that caller won't decide to freeze this tuple.
8086 : : * It's up to caller to only ratchet back its own top-level trackers after the
8087 : : * point that it fully commits to not freezing the tuple/page in question.
8088 : : */
8089 : : bool
1362 pg@bowt.ie 8090 : 3441472 : heap_tuple_should_freeze(HeapTupleHeader tuple,
8091 : : const struct VacuumCutoffs *cutoffs,
8092 : : TransactionId *NoFreezePageRelfrozenXid,
8093 : : MultiXactId *NoFreezePageRelminMxid)
8094 : : {
8095 : : TransactionId xid;
8096 : : MultiXactId multi;
1368 8097 : 3441472 : bool freeze = false;
8098 : :
8099 : : /* First deal with xmin */
5431 rhaas@postgresql.org 8100 : 3441472 : xid = HeapTupleHeaderGetXmin(tuple);
1631 pg@bowt.ie 8101 [ + + ]: 3441472 : if (TransactionIdIsNormal(xid))
8102 : : {
1368 8103 [ - + ]: 3440986 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1362 8104 [ + + ]: 3440986 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8105 : 24179 : *NoFreezePageRelfrozenXid = xid;
1368 8106 [ + + ]: 3440986 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8107 : 20632 : freeze = true;
8108 : : }
8109 : :
8110 : : /* Now deal with xmax */
1631 8111 : 3441472 : xid = InvalidTransactionId;
8112 : 3441472 : multi = InvalidMultiXactId;
8113 [ + + ]: 3441472 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
4679 alvherre@alvh.no-ip. 8114 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8115 : : else
1631 pg@bowt.ie 8116 : 3441470 : xid = HeapTupleHeaderGetRawXmax(tuple);
8117 : :
8118 [ + + ]: 3441472 : if (TransactionIdIsNormal(xid))
8119 : : {
1368 8120 [ - + ]: 375253 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8121 : : /* xmax is a non-permanent XID */
1362 8122 [ + + ]: 375253 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8123 : 17 : *NoFreezePageRelfrozenXid = xid;
1368 8124 [ + + ]: 375253 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8125 : 8 : freeze = true;
8126 : : }
1631 8127 [ + + ]: 3066219 : else if (!MultiXactIdIsValid(multi))
8128 : : {
8129 : : /* xmax is a permanent XID or invalid MultiXactId/XID */
8130 : : }
8131 [ - + ]: 2 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
8132 : : {
8133 : : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
1362 pg@bowt.ie 8134 [ # # ]:UBC 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8135 : 0 : *NoFreezePageRelminMxid = multi;
8136 : : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
1368 8137 : 0 : freeze = true;
8138 : : }
8139 : : else
8140 : : {
8141 : : /* xmax is a MultiXactId that may have an updater XID */
8142 : : MultiXactMember *members;
8143 : : int nmembers;
8144 : :
1368 pg@bowt.ie 8145 [ - + ]:CBC 2 : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
1362 8146 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8147 : 2 : *NoFreezePageRelminMxid = multi;
1368 8148 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
8149 : 2 : freeze = true;
8150 : :
8151 : : /* need to check whether any member of the mxact is old */
1631 8152 : 2 : nmembers = GetMultiXactIdMembers(multi, &members, false,
8153 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
8154 : :
8155 [ + + ]: 5 : for (int i = 0; i < nmembers; i++)
8156 : : {
8157 : 3 : xid = members[i].xid;
1368 8158 [ - + ]: 3 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1362 8159 [ - + ]: 3 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
1362 pg@bowt.ie 8160 :UBC 0 : *NoFreezePageRelfrozenXid = xid;
1368 pg@bowt.ie 8161 [ - + ]:CBC 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
1368 pg@bowt.ie 8162 :UBC 0 : freeze = true;
8163 : : }
1631 pg@bowt.ie 8164 [ + + ]:CBC 2 : if (nmembers > 0)
8165 : 1 : pfree(members);
8166 : : }
8167 : :
5431 rhaas@postgresql.org 8168 [ - + ]: 3441472 : if (tuple->t_infomask & HEAP_MOVED)
8169 : : {
5431 rhaas@postgresql.org 8170 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
1631 pg@bowt.ie 8171 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8172 : : {
1368 8173 [ # # ]: 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1362 8174 [ # # ]: 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8175 : 0 : *NoFreezePageRelfrozenXid = xid;
8176 : : /* heap_prepare_freeze_tuple forces xvac freezing */
1368 8177 : 0 : freeze = true;
8178 : : }
8179 : : }
8180 : :
1368 pg@bowt.ie 8181 :CBC 3441472 : return freeze;
8182 : : }
8183 : :
8184 : : /*
8185 : : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
8186 : : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
8187 : : * that caller is in the process of physically removing, e.g. via HOT pruning
8188 : : * or index deletion.
8189 : : *
8190 : : * Caller must initialize its value to InvalidTransactionId, which is
8191 : : * generally interpreted as "definitely no need for a recovery conflict".
8192 : : * Final value must reflect all heap tuples that caller will physically remove
8193 : : * (or remove TID references to) via its ongoing pruning/deletion operation.
8194 : : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
8195 : : * caller's WAL record) by REDO routine when it replays caller's operation.
8196 : : */
8197 : : void
1403 8198 : 4043377 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
8199 : : TransactionId *snapshotConflictHorizon)
8200 : : {
6119 simon@2ndQuadrant.co 8201 : 4043377 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
4988 alvherre@alvh.no-ip. 8202 : 4043377 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
6119 simon@2ndQuadrant.co 8203 : 4043377 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
8204 : :
6068 tgl@sss.pgh.pa.us 8205 [ - + ]: 4043377 : if (tuple->t_infomask & HEAP_MOVED)
8206 : : {
1403 pg@bowt.ie 8207 [ # # ]:UBC 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
8208 : 0 : *snapshotConflictHorizon = xvac;
8209 : : }
8210 : :
8211 : : /*
8212 : : * Ignore tuples inserted by an aborted transaction or if the tuple was
8213 : : * updated/deleted by the inserting transaction.
8214 : : *
8215 : : * Look for a committed hint bit, or if no xmin bit is set, check clog.
8216 : : */
4655 rhaas@postgresql.org 8217 [ + + ]:CBC 4043377 : if (HeapTupleHeaderXminCommitted(tuple) ||
8218 [ + + + - ]: 146822 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
8219 : : {
5764 simon@2ndQuadrant.co 8220 [ + + + + ]: 7675571 : if (xmax != xmin &&
1403 pg@bowt.ie 8221 : 3755764 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
8222 : 133105 : *snapshotConflictHorizon = xmax;
8223 : : }
6119 simon@2ndQuadrant.co 8224 : 4043377 : }
8225 : :
8226 : : #ifdef USE_PREFETCH
8227 : : /*
8228 : : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
8229 : : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
8230 : : * we can prefetch, and which have already been prefetched; each call to this
8231 : : * function picks up where the previous call left off.
8232 : : *
8233 : : * Note: we expect the deltids array to be sorted in an order that groups TIDs
8234 : : * by heap block, with all TIDs for each block appearing together in exactly
8235 : : * one group.
8236 : : */
8237 : : static void
2076 pg@bowt.ie 8238 : 24467 : index_delete_prefetch_buffer(Relation rel,
8239 : : IndexDeletePrefetchState *prefetch_state,
8240 : : int prefetch_count)
8241 : : {
2735 andres@anarazel.de 8242 : 24467 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
8243 : 24467 : int count = 0;
8244 : : int i;
2076 pg@bowt.ie 8245 : 24467 : int ndeltids = prefetch_state->ndeltids;
8246 : 24467 : TM_IndexDelete *deltids = prefetch_state->deltids;
8247 : :
2735 andres@anarazel.de 8248 : 24467 : for (i = prefetch_state->next_item;
2076 pg@bowt.ie 8249 [ + + + + ]: 872312 : i < ndeltids && count < prefetch_count;
2735 andres@anarazel.de 8250 : 847845 : i++)
8251 : : {
2076 pg@bowt.ie 8252 : 847845 : ItemPointer htid = &deltids[i].tid;
8253 : :
2735 andres@anarazel.de 8254 [ + + + + ]: 1688107 : if (cur_hblkno == InvalidBlockNumber ||
8255 : 840262 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
8256 : : {
8257 : 22622 : cur_hblkno = ItemPointerGetBlockNumber(htid);
8258 : 22622 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
8259 : 22622 : count++;
8260 : : }
8261 : : }
8262 : :
8263 : : /*
8264 : : * Save the prefetch position so that next time we can continue from that
8265 : : * position.
8266 : : */
8267 : 24467 : prefetch_state->next_item = i;
8268 : 24467 : prefetch_state->cur_hblkno = cur_hblkno;
8269 : 24467 : }
8270 : : #endif
8271 : :
8272 : : /*
8273 : : * Helper function for heap_index_delete_tuples. Checks for index corruption
8274 : : * involving an invalid TID in index AM caller's index page.
8275 : : *
8276 : : * This is an ideal place for these checks. The index AM must hold a buffer
8277 : : * lock on the index page containing the TIDs we examine here, so we don't
8278 : : * have to worry about concurrent VACUUMs at all. We can be sure that the
8279 : : * index is corrupt when htid points directly to an LP_UNUSED item or
8280 : : * heap-only tuple, which is not the case during standard index scans.
8281 : : */
8282 : : static inline void
1781 pg@bowt.ie 8283 : 695622 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
8284 : : Page page, OffsetNumber maxoff,
8285 : : const ItemPointerData *htid, TM_IndexStatus *istatus)
8286 : : {
8287 : 695622 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8288 : : ItemId iid;
8289 : :
8290 [ + - + - : 695622 : Assert(OffsetNumberIsValid(istatus->idxoffnum));
- + ]
8291 : :
8292 [ - + ]: 695622 : if (unlikely(indexpagehoffnum > maxoff))
1781 pg@bowt.ie 8293 [ # # ]:UBC 0 : ereport(ERROR,
8294 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8295 : : 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\"",
8296 : : ItemPointerGetBlockNumber(htid),
8297 : : indexpagehoffnum,
8298 : : istatus->idxoffnum, delstate->iblknum,
8299 : : RelationGetRelationName(delstate->irel))));
8300 : :
1781 pg@bowt.ie 8301 :CBC 695622 : iid = PageGetItemId(page, indexpagehoffnum);
8302 [ - + ]: 695622 : if (unlikely(!ItemIdIsUsed(iid)))
1781 pg@bowt.ie 8303 [ # # ]:UBC 0 : ereport(ERROR,
8304 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8305 : : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8306 : : ItemPointerGetBlockNumber(htid),
8307 : : indexpagehoffnum,
8308 : : istatus->idxoffnum, delstate->iblknum,
8309 : : RelationGetRelationName(delstate->irel))));
8310 : :
1781 pg@bowt.ie 8311 [ + + ]:CBC 695622 : if (ItemIdHasStorage(iid))
8312 : : {
8313 : : HeapTupleHeader htup;
8314 : :
8315 [ - + ]: 452157 : Assert(ItemIdIsNormal(iid));
8316 : 452157 : htup = (HeapTupleHeader) PageGetItem(page, iid);
8317 : :
8318 [ - + ]: 452157 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
1781 pg@bowt.ie 8319 [ # # ]:UBC 0 : ereport(ERROR,
8320 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8321 : : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8322 : : ItemPointerGetBlockNumber(htid),
8323 : : indexpagehoffnum,
8324 : : istatus->idxoffnum, delstate->iblknum,
8325 : : RelationGetRelationName(delstate->irel))));
8326 : : }
1781 pg@bowt.ie 8327 :CBC 695622 : }
8328 : :
8329 : : /*
8330 : : * heapam implementation of tableam's index_delete_tuples interface.
8331 : : *
8332 : : * This helper function is called by index AMs during index tuple deletion.
8333 : : * See tableam header comments for an explanation of the interface implemented
8334 : : * here and a general theory of operation. Note that each call here is either
8335 : : * a simple index deletion call, or a bottom-up index deletion call.
8336 : : *
8337 : : * It's possible for this to generate a fair amount of I/O, since we may be
8338 : : * deleting hundreds of tuples from a single index block. To amortize that
8339 : : * cost to some degree, this uses prefetching and combines repeat accesses to
8340 : : * the same heap block.
8341 : : */
8342 : : TransactionId
2076 8343 : 7583 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
8344 : : {
8345 : : /* Initial assumption is that earlier pruning took care of conflict */
1403 8346 : 7583 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
2090 8347 : 7583 : BlockNumber blkno = InvalidBlockNumber;
2735 andres@anarazel.de 8348 : 7583 : Buffer buf = InvalidBuffer;
2090 pg@bowt.ie 8349 : 7583 : Page page = NULL;
8350 : 7583 : OffsetNumber maxoff = InvalidOffsetNumber;
8351 : : TransactionId priorXmax;
8352 : : #ifdef USE_PREFETCH
8353 : : IndexDeletePrefetchState prefetch_state;
8354 : : int prefetch_distance;
8355 : : #endif
8356 : : SnapshotData SnapshotNonVacuumable;
2076 8357 : 7583 : int finalndeltids = 0,
8358 : 7583 : nblocksaccessed = 0;
8359 : :
8360 : : /* State that's only used in bottom-up index deletion case */
8361 : 7583 : int nblocksfavorable = 0;
8362 : 7583 : int curtargetfreespace = delstate->bottomupfreespace,
8363 : 7583 : lastfreespace = 0,
8364 : 7583 : actualfreespace = 0;
8365 : 7583 : bool bottomup_final_block = false;
8366 : :
8367 : 7583 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8368 : :
8369 : : /* Sort caller's deltids array by TID for further processing */
8370 : 7583 : index_delete_sort(delstate);
8371 : :
8372 : : /*
8373 : : * Bottom-up case: resort deltids array in an order attuned to where the
8374 : : * greatest number of promising TIDs are to be found, and determine how
8375 : : * many blocks from the start of sorted array should be considered
8376 : : * favorable. This will also shrink the deltids array in order to
8377 : : * eliminate completely unfavorable blocks up front.
8378 : : */
8379 [ + + ]: 7583 : if (delstate->bottomup)
8380 : 2982 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
8381 : :
8382 : : #ifdef USE_PREFETCH
8383 : : /* Initialize prefetch state. */
2735 andres@anarazel.de 8384 : 7583 : prefetch_state.cur_hblkno = InvalidBlockNumber;
8385 : 7583 : prefetch_state.next_item = 0;
2076 pg@bowt.ie 8386 : 7583 : prefetch_state.ndeltids = delstate->ndeltids;
8387 : 7583 : prefetch_state.deltids = delstate->deltids;
8388 : :
8389 : : /*
8390 : : * Determine the prefetch distance that we will attempt to maintain.
8391 : : *
8392 : : * Since the caller holds a buffer lock somewhere in rel, we'd better make
8393 : : * sure that isn't a catalog relation before we call code that does
8394 : : * syscache lookups, to avoid risk of deadlock.
8395 : : */
2728 tmunro@postgresql.or 8396 [ + + ]: 7583 : if (IsCatalogRelation(rel))
2379 8397 : 5303 : prefetch_distance = maintenance_io_concurrency;
8398 : : else
8399 : : prefetch_distance =
8400 : 2280 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
8401 : :
8402 : : /* Cap initial prefetch distance for bottom-up deletion caller */
2076 pg@bowt.ie 8403 [ + + ]: 7583 : if (delstate->bottomup)
8404 : : {
8405 [ - + ]: 2982 : Assert(nblocksfavorable >= 1);
8406 [ - + ]: 2982 : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8407 : 2982 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8408 : : }
8409 : :
8410 : : /* Start prefetching. */
8411 : 7583 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8412 : : #endif
8413 : :
8414 : : /* Iterate over deltids, determine which to delete, check their horizon */
8415 [ - + ]: 7583 : Assert(delstate->ndeltids > 0);
8416 [ + + ]: 703205 : for (int i = 0; i < delstate->ndeltids; i++)
8417 : : {
8418 : 698604 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8419 : 698604 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8420 : 698604 : ItemPointer htid = &ideltid->tid;
8421 : : OffsetNumber offnum;
8422 : :
8423 : : /*
8424 : : * Read buffer, and perform required extra steps each time a new block
8425 : : * is encountered. Avoid refetching if it's the same block as the one
8426 : : * from the last htid.
8427 : : */
2090 8428 [ + + + + ]: 1389625 : if (blkno == InvalidBlockNumber ||
8429 : 691021 : ItemPointerGetBlockNumber(htid) != blkno)
8430 : : {
8431 : : /*
8432 : : * Consider giving up early for bottom-up index deletion caller
8433 : : * first. (Only prefetch next-next block afterwards, when it
8434 : : * becomes clear that we're at least going to access the next
8435 : : * block in line.)
8436 : : *
8437 : : * Sometimes the first block frees so much space for bottom-up
8438 : : * caller that the deletion process can end without accessing any
8439 : : * more blocks. It is usually necessary to access 2 or 3 blocks
8440 : : * per bottom-up deletion operation, though.
8441 : : */
2076 8442 [ + + ]: 19866 : if (delstate->bottomup)
8443 : : {
8444 : : /*
8445 : : * We often allow caller to delete a few additional items
8446 : : * whose entries we reached after the point that space target
8447 : : * from caller was satisfied. The cost of accessing the page
8448 : : * was already paid at that point, so it made sense to finish
8449 : : * it off. When that happened, we finalize everything here
8450 : : * (by finishing off the whole bottom-up deletion operation
8451 : : * without needlessly paying the cost of accessing any more
8452 : : * blocks).
8453 : : */
8454 [ + + ]: 6410 : if (bottomup_final_block)
8455 : 188 : break;
8456 : :
8457 : : /*
8458 : : * Give up when we didn't enable our caller to free any
8459 : : * additional space as a result of processing the page that we
8460 : : * just finished up with. This rule is the main way in which
8461 : : * we keep the cost of bottom-up deletion under control.
8462 : : */
8463 [ + + + + ]: 6222 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8464 : 2794 : break;
8465 : 3428 : lastfreespace = actualfreespace; /* for next time */
8466 : :
8467 : : /*
8468 : : * Deletion operation (which is bottom-up) will definitely
8469 : : * access the next block in line. Prepare for that now.
8470 : : *
8471 : : * Decay target free space so that we don't hang on for too
8472 : : * long with a marginal case. (Space target is only truly
8473 : : * helpful when it allows us to recognize that we don't need
8474 : : * to access more than 1 or 2 blocks to satisfy caller due to
8475 : : * agreeable workload characteristics.)
8476 : : *
8477 : : * We are a bit more patient when we encounter contiguous
8478 : : * blocks, though: these are treated as favorable blocks. The
8479 : : * decay process is only applied when the next block in line
8480 : : * is not a favorable/contiguous block. This is not an
8481 : : * exception to the general rule; we still insist on finding
8482 : : * at least one deletable item per block accessed. See
8483 : : * bottomup_nblocksfavorable() for full details of the theory
8484 : : * behind favorable blocks and heap block locality in general.
8485 : : *
8486 : : * Note: The first block in line is always treated as a
8487 : : * favorable block, so the earliest possible point that the
8488 : : * decay can be applied is just before we access the second
8489 : : * block in line. The Assert() verifies this for us.
8490 : : */
8491 [ + + - + ]: 3428 : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8492 [ + + ]: 3428 : if (nblocksfavorable > 0)
8493 : 3218 : nblocksfavorable--;
8494 : : else
8495 : 210 : curtargetfreespace /= 2;
8496 : : }
8497 : :
8498 : : /* release old buffer */
8499 [ + + ]: 16884 : if (BufferIsValid(buf))
8500 : 9301 : UnlockReleaseBuffer(buf);
8501 : :
8502 : 16884 : blkno = ItemPointerGetBlockNumber(htid);
2090 8503 : 16884 : buf = ReadBuffer(rel, blkno);
2076 8504 : 16884 : nblocksaccessed++;
8505 [ + + - + ]: 16884 : Assert(!delstate->bottomup ||
8506 : : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8507 : :
8508 : : #ifdef USE_PREFETCH
8509 : :
8510 : : /*
8511 : : * To maintain the prefetch distance, prefetch one more page for
8512 : : * each page we read.
8513 : : */
8514 : 16884 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8515 : : #endif
8516 : :
2090 8517 : 16884 : LockBuffer(buf, BUFFER_LOCK_SHARE);
8518 : :
8519 : 16884 : page = BufferGetPage(buf);
8520 : 16884 : maxoff = PageGetMaxOffsetNumber(page);
8521 : : }
8522 : :
8523 : : /*
8524 : : * In passing, detect index corruption involving an index page with a
8525 : : * TID that points to a location in the heap that couldn't possibly be
8526 : : * correct. We only do this with actual TIDs from caller's index page
8527 : : * (not items reached by traversing through a HOT chain).
8528 : : */
1781 8529 : 695622 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8530 : :
2076 8531 [ + + ]: 695622 : if (istatus->knowndeletable)
8532 [ + - - + ]: 154011 : Assert(!delstate->bottomup && !istatus->promising);
8533 : : else
8534 : : {
8535 : 541611 : ItemPointerData tmp = *htid;
8536 : : HeapTupleData heapTuple;
8537 : :
8538 : : /* Are any tuples from this HOT chain non-vacuumable? */
8539 [ + + ]: 541611 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8540 : : &heapTuple, NULL, true))
8541 : 343092 : continue; /* can't delete entry */
8542 : :
8543 : : /* Caller will delete, since whole HOT chain is vacuumable */
8544 : 198519 : istatus->knowndeletable = true;
8545 : :
8546 : : /* Maintain index free space info for bottom-up deletion case */
8547 [ + + ]: 198519 : if (delstate->bottomup)
8548 : : {
8549 [ - + ]: 11473 : Assert(istatus->freespace > 0);
8550 : 11473 : actualfreespace += istatus->freespace;
8551 [ + + ]: 11473 : if (actualfreespace >= curtargetfreespace)
8552 : 2926 : bottomup_final_block = true;
8553 : : }
8554 : : }
8555 : :
8556 : : /*
8557 : : * Maintain snapshotConflictHorizon value for deletion operation as a
8558 : : * whole by advancing current value using heap tuple headers. This is
8559 : : * loosely based on the logic for pruning a HOT chain.
8560 : : */
2090 8561 : 352530 : offnum = ItemPointerGetOffsetNumber(htid);
8562 : 352530 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8563 : : for (;;)
2735 andres@anarazel.de 8564 : 21903 : {
8565 : : ItemId lp;
8566 : : HeapTupleHeader htup;
8567 : :
8568 : : /* Sanity check (pure paranoia) */
1824 pg@bowt.ie 8569 [ - + ]: 374433 : if (offnum < FirstOffsetNumber)
1824 pg@bowt.ie 8570 :UBC 0 : break;
8571 : :
8572 : : /*
8573 : : * An offset past the end of page's line pointer array is possible
8574 : : * when the array was truncated
8575 : : */
1824 pg@bowt.ie 8576 [ - + ]:CBC 374433 : if (offnum > maxoff)
2090 pg@bowt.ie 8577 :UBC 0 : break;
8578 : :
2090 pg@bowt.ie 8579 :CBC 374433 : lp = PageGetItemId(page, offnum);
8580 [ + + ]: 374433 : if (ItemIdIsRedirected(lp))
8581 : : {
8582 : 9721 : offnum = ItemIdGetRedirect(lp);
8583 : 9721 : continue;
8584 : : }
8585 : :
8586 : : /*
8587 : : * We'll often encounter LP_DEAD line pointers (especially with an
8588 : : * entry marked knowndeletable by our caller up front). No heap
8589 : : * tuple headers get examined for an htid that leads us to an
8590 : : * LP_DEAD item. This is okay because the earlier pruning
8591 : : * operation that made the line pointer LP_DEAD in the first place
8592 : : * must have considered the original tuple header as part of
8593 : : * generating its own snapshotConflictHorizon value.
8594 : : *
8595 : : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8596 : : * the same strategy that index vacuuming uses in all cases. Index
8597 : : * VACUUM WAL records don't even have a snapshotConflictHorizon
8598 : : * field of their own for this reason.
8599 : : */
8600 [ + + ]: 364712 : if (!ItemIdIsNormal(lp))
8601 : 212939 : break;
8602 : :
8603 : 151773 : htup = (HeapTupleHeader) PageGetItem(page, lp);
8604 : :
8605 : : /*
8606 : : * Check the tuple XMIN against prior XMAX, if any
8607 : : */
8608 [ + + - + ]: 163955 : if (TransactionIdIsValid(priorXmax) &&
8609 : 12182 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
2090 pg@bowt.ie 8610 :UBC 0 : break;
8611 : :
1403 pg@bowt.ie 8612 :CBC 151773 : HeapTupleHeaderAdvanceConflictHorizon(htup,
8613 : : &snapshotConflictHorizon);
8614 : :
8615 : : /*
8616 : : * If the tuple is not HOT-updated, then we are at the end of this
8617 : : * HOT-chain. No need to visit later tuples from the same update
8618 : : * chain (they get their own index entries) -- just move on to
8619 : : * next htid from index AM caller.
8620 : : */
2090 8621 [ + + ]: 151773 : if (!HeapTupleHeaderIsHotUpdated(htup))
8622 : 139591 : break;
8623 : :
8624 : : /* Advance to next HOT chain member */
8625 [ - + ]: 12182 : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8626 : 12182 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8627 : 12182 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8628 : : }
8629 : :
8630 : : /* Enable further/final shrinking of deltids for caller */
2076 8631 : 352530 : finalndeltids = i + 1;
8632 : : }
8633 : :
8634 : 7583 : UnlockReleaseBuffer(buf);
8635 : :
8636 : : /*
8637 : : * Shrink deltids array to exclude non-deletable entries at the end. This
8638 : : * is not just a minor optimization. Final deltids array size might be
8639 : : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8640 : : * ndeltids being zero in all cases with zero total deletable entries.
8641 : : */
8642 [ + + - + ]: 7583 : Assert(finalndeltids > 0 || delstate->bottomup);
8643 : 7583 : delstate->ndeltids = finalndeltids;
8644 : :
1403 8645 : 7583 : return snapshotConflictHorizon;
8646 : : }
8647 : :
8648 : : /*
8649 : : * Specialized inlineable comparison function for index_delete_sort()
8650 : : */
8651 : : static inline int
2076 8652 : 17654706 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
8653 : : {
8654 : 17654706 : ItemPointer tid1 = &deltid1->tid;
8655 : 17654706 : ItemPointer tid2 = &deltid2->tid;
8656 : :
8657 : : {
8658 : 17654706 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
8659 : 17654706 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
8660 : :
8661 [ + + ]: 17654706 : if (blk1 != blk2)
8662 [ + + ]: 7274212 : return (blk1 < blk2) ? -1 : 1;
8663 : : }
8664 : : {
8665 : 10380494 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
8666 : 10380494 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
8667 : :
8668 [ + - ]: 10380494 : if (pos1 != pos2)
8669 [ + + ]: 10380494 : return (pos1 < pos2) ? -1 : 1;
8670 : : }
8671 : :
1787 pg@bowt.ie 8672 :UBC 0 : Assert(false);
8673 : :
8674 : : return 0;
8675 : : }
8676 : :
8677 : : /*
8678 : : * Sort deltids array from delstate by TID. This prepares it for further
8679 : : * processing by heap_index_delete_tuples().
8680 : : *
8681 : : * This operation becomes a noticeable consumer of CPU cycles with some
8682 : : * workloads, so we go to the trouble of specialization/micro optimization.
8683 : : * We use shellsort for this because it's easy to specialize, compiles to
8684 : : * relatively few instructions, and is adaptive to presorted inputs/subsets
8685 : : * (which are typical here).
8686 : : */
8687 : : static void
2076 pg@bowt.ie 8688 :CBC 7583 : index_delete_sort(TM_IndexDeleteOp *delstate)
8689 : : {
8690 : 7583 : TM_IndexDelete *deltids = delstate->deltids;
8691 : 7583 : int ndeltids = delstate->ndeltids;
8692 : :
8693 : : /*
8694 : : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8695 : : *
8696 : : * This implementation is fast with array sizes up to ~4500. This covers
8697 : : * all supported BLCKSZ values.
8698 : : */
8699 : 7583 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8700 : :
8701 : : /* Think carefully before changing anything here -- keep swaps cheap */
8702 : : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8703 : : "element size exceeds 8 bytes");
8704 : :
71 peter@eisentraut.org 8705 [ + + ]:GNC 75830 : for (size_t g = 0; g < lengthof(gaps); g++)
8706 : : {
683 dgustafsson@postgres 8707 [ + + ]:CBC 10602016 : for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8708 : : {
2076 pg@bowt.ie 8709 : 10533769 : TM_IndexDelete d = deltids[i];
8710 : 10533769 : int j = i;
8711 : :
8712 [ + + + + ]: 18159963 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8713 : : {
8714 : 7626194 : deltids[j] = deltids[j - hi];
8715 : 7626194 : j -= hi;
8716 : : }
8717 : 10533769 : deltids[j] = d;
8718 : : }
8719 : : }
8720 : 7583 : }
8721 : :
8722 : : /*
8723 : : * Returns how many blocks should be considered favorable/contiguous for a
8724 : : * bottom-up index deletion pass. This is a number of heap blocks that starts
8725 : : * from and includes the first block in line.
8726 : : *
8727 : : * There is always at least one favorable block during bottom-up index
8728 : : * deletion. In the worst case (i.e. with totally random heap blocks) the
8729 : : * first block in line (the only favorable block) can be thought of as a
8730 : : * degenerate array of contiguous blocks that consists of a single block.
8731 : : * heap_index_delete_tuples() will expect this.
8732 : : *
8733 : : * Caller passes blockgroups, a description of the final order that deltids
8734 : : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8735 : : * processing. Note that deltids need not actually be sorted just yet (caller
8736 : : * only passes deltids to us so that we can interpret blockgroups).
8737 : : *
8738 : : * You might guess that the existence of contiguous blocks cannot matter much,
8739 : : * since in general the main factor that determines which blocks we visit is
8740 : : * the number of promising TIDs, which is a fixed hint from the index AM.
8741 : : * We're not really targeting the general case, though -- the actual goal is
8742 : : * to adapt our behavior to a wide variety of naturally occurring conditions.
8743 : : * The effects of most of the heuristics we apply are only noticeable in the
8744 : : * aggregate, over time and across many _related_ bottom-up index deletion
8745 : : * passes.
8746 : : *
8747 : : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8748 : : * workloads where heap blocks visited during bottom-up index deletion can be
8749 : : * accessed contiguously, in the sense that each newly visited block is the
8750 : : * neighbor of the block that bottom-up deletion just finished processing (or
8751 : : * close enough to it). It will likely be cheaper to access more favorable
8752 : : * blocks sooner rather than later (e.g. in this pass, not across a series of
8753 : : * related bottom-up passes). Either way it is probably only a matter of time
8754 : : * (or a matter of further correlated version churn) before all blocks that
8755 : : * appear together as a single large batch of favorable blocks get accessed by
8756 : : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8757 : : * appear almost constantly or not even once (it all depends on per-index
8758 : : * workload characteristics).
8759 : : *
8760 : : * Note that the blockgroups sort order applies a power-of-two bucketing
8761 : : * scheme that creates opportunities for contiguous groups of blocks to get
8762 : : * batched together, at least with workloads that are naturally amenable to
8763 : : * being driven by heap block locality. This doesn't just enhance the spatial
8764 : : * locality of bottom-up heap block processing in the obvious way. It also
8765 : : * enables temporal locality of access, since sorting by heap block number
8766 : : * naturally tends to make the bottom-up processing order deterministic.
8767 : : *
8768 : : * Consider the following example to get a sense of how temporal locality
8769 : : * might matter: There is a heap relation with several indexes, each of which
8770 : : * is low to medium cardinality. It is subject to constant non-HOT updates.
8771 : : * The updates are skewed (in one part of the primary key, perhaps). None of
8772 : : * the indexes are logically modified by the UPDATE statements (if they were
8773 : : * then bottom-up index deletion would not be triggered in the first place).
8774 : : * Naturally, each new round of index tuples (for each heap tuple that gets a
8775 : : * heap_update() call) will have the same heap TID in each and every index.
8776 : : * Since these indexes are low cardinality and never get logically modified,
8777 : : * heapam processing during bottom-up deletion passes will access heap blocks
8778 : : * in approximately sequential order. Temporal locality of access occurs due
8779 : : * to bottom-up deletion passes behaving very similarly across each of the
8780 : : * indexes at any given moment. This keeps the number of buffer misses needed
8781 : : * to visit heap blocks to a minimum.
8782 : : */
8783 : : static int
8784 : 2982 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8785 : : TM_IndexDelete *deltids)
8786 : : {
8787 : 2982 : int64 lastblock = -1;
8788 : 2982 : int nblocksfavorable = 0;
8789 : :
8790 [ - + ]: 2982 : Assert(nblockgroups >= 1);
8791 [ - + ]: 2982 : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8792 : :
8793 : : /*
8794 : : * We tolerate heap blocks that will be accessed only slightly out of
8795 : : * physical order. Small blips occur when a pair of almost-contiguous
8796 : : * blocks happen to fall into different buckets (perhaps due only to a
8797 : : * small difference in npromisingtids that the bucketing scheme didn't
8798 : : * quite manage to ignore). We effectively ignore these blips by applying
8799 : : * a small tolerance. The precise tolerance we use is a little arbitrary,
8800 : : * but it works well enough in practice.
8801 : : */
8802 [ + + ]: 9111 : for (int b = 0; b < nblockgroups; b++)
8803 : : {
8804 : 8806 : IndexDeleteCounts *group = blockgroups + b;
8805 : 8806 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8806 : 8806 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8807 : :
8808 [ + + ]: 8806 : if (lastblock != -1 &&
8809 [ + + ]: 5824 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8810 [ + + ]: 5114 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8811 : : break;
8812 : :
8813 : 6129 : nblocksfavorable++;
8814 : 6129 : lastblock = block;
8815 : : }
8816 : :
8817 : : /* Always indicate that there is at least 1 favorable block */
8818 [ - + ]: 2982 : Assert(nblocksfavorable >= 1);
8819 : :
8820 : 2982 : return nblocksfavorable;
8821 : : }
8822 : :
8823 : : /*
8824 : : * qsort comparison function for bottomup_sort_and_shrink()
8825 : : */
8826 : : static int
8827 : 273317 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8828 : : {
8829 : 273317 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8830 : 273317 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8831 : :
8832 : : /*
8833 : : * Most significant field is npromisingtids (which we invert the order of
8834 : : * so as to sort in desc order).
8835 : : *
8836 : : * Caller should have already normalized npromisingtids fields into
8837 : : * power-of-two values (buckets).
8838 : : */
8839 [ + + ]: 273317 : if (group1->npromisingtids > group2->npromisingtids)
8840 : 11859 : return -1;
8841 [ + + ]: 261458 : if (group1->npromisingtids < group2->npromisingtids)
8842 : 15332 : return 1;
8843 : :
8844 : : /*
8845 : : * Tiebreak: desc ntids sort order.
8846 : : *
8847 : : * We cannot expect power-of-two values for ntids fields. We should
8848 : : * behave as if they were already rounded up for us instead.
8849 : : */
8850 [ + + ]: 246126 : if (group1->ntids != group2->ntids)
8851 : : {
8852 : 179466 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8853 : 179466 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8854 : :
8855 [ + + ]: 179466 : if (ntids1 > ntids2)
8856 : 27329 : return -1;
8857 [ + + ]: 152137 : if (ntids1 < ntids2)
8858 : 35286 : return 1;
8859 : : }
8860 : :
8861 : : /*
8862 : : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8863 : : * block in deltids array) order.
8864 : : *
8865 : : * This is equivalent to sorting in ascending heap block number order
8866 : : * (among otherwise equal subsets of the array). This approach allows us
8867 : : * to avoid accessing the out-of-line TID. (We rely on the assumption
8868 : : * that the deltids array was sorted in ascending heap TID order when
8869 : : * these offsets to the first TID from each heap block group were formed.)
8870 : : */
8871 [ + + ]: 183511 : if (group1->ifirsttid > group2->ifirsttid)
8872 : 90459 : return 1;
8873 [ + - ]: 93052 : if (group1->ifirsttid < group2->ifirsttid)
8874 : 93052 : return -1;
8875 : :
2076 pg@bowt.ie 8876 :UBC 0 : pg_unreachable();
8877 : :
8878 : : return 0;
8879 : : }
8880 : :
8881 : : /*
8882 : : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8883 : : *
8884 : : * Sorts deltids array in the order needed for useful processing by bottom-up
8885 : : * deletion. The array should already be sorted in TID order when we're
8886 : : * called. The sort process groups heap TIDs from deltids into heap block
8887 : : * groupings. Earlier/more-promising groups/blocks are usually those that are
8888 : : * known to have the most "promising" TIDs.
8889 : : *
8890 : : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8891 : : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8892 : : * return. This often means that deltids will be shrunk to a small fraction
8893 : : * of its original size (we eliminate many heap blocks from consideration for
8894 : : * caller up front).
8895 : : *
8896 : : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8897 : : * for a definition and full details.
8898 : : */
8899 : : static int
2076 pg@bowt.ie 8900 :CBC 2982 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8901 : : {
8902 : : IndexDeleteCounts *blockgroups;
8903 : : TM_IndexDelete *reordereddeltids;
8904 : 2982 : BlockNumber curblock = InvalidBlockNumber;
8905 : 2982 : int nblockgroups = 0;
8906 : 2982 : int ncopied = 0;
8907 : 2982 : int nblocksfavorable = 0;
8908 : :
8909 [ - + ]: 2982 : Assert(delstate->bottomup);
8910 [ - + ]: 2982 : Assert(delstate->ndeltids > 0);
8911 : :
8912 : : /* Calculate per-heap-block count of TIDs */
284 michael@paquier.xyz 8913 : 2982 : blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
2076 pg@bowt.ie 8914 [ + + ]: 1392701 : for (int i = 0; i < delstate->ndeltids; i++)
8915 : : {
8916 : 1389719 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8917 : 1389719 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8918 : 1389719 : ItemPointer htid = &ideltid->tid;
8919 : 1389719 : bool promising = istatus->promising;
8920 : :
8921 [ + + ]: 1389719 : if (curblock != ItemPointerGetBlockNumber(htid))
8922 : : {
8923 : : /* New block group */
8924 : 53888 : nblockgroups++;
8925 : :
8926 [ + + - + ]: 53888 : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8927 : : !BlockNumberIsValid(curblock));
8928 : :
8929 : 53888 : curblock = ItemPointerGetBlockNumber(htid);
8930 : 53888 : blockgroups[nblockgroups - 1].ifirsttid = i;
8931 : 53888 : blockgroups[nblockgroups - 1].ntids = 1;
8932 : 53888 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8933 : : }
8934 : : else
8935 : : {
8936 : 1335831 : blockgroups[nblockgroups - 1].ntids++;
8937 : : }
8938 : :
8939 [ + + ]: 1389719 : if (promising)
8940 : 259811 : blockgroups[nblockgroups - 1].npromisingtids++;
8941 : : }
8942 : :
8943 : : /*
8944 : : * We're about ready to sort block groups to determine the optimal order
8945 : : * for visiting heap blocks. But before we do, round the number of
8946 : : * promising tuples for each block group up to the next power-of-two,
8947 : : * unless it is very low (less than 4), in which case we round up to 4.
8948 : : * npromisingtids is far too noisy to trust when choosing between a pair
8949 : : * of block groups that both have very low values.
8950 : : *
8951 : : * This scheme divides heap blocks/block groups into buckets. Each bucket
8952 : : * contains blocks that have _approximately_ the same number of promising
8953 : : * TIDs as each other. The goal is to ignore relatively small differences
8954 : : * in the total number of promising entries, so that the whole process can
8955 : : * give a little weight to heapam factors (like heap block locality)
8956 : : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8957 : : * would be foolish to interpret small differences in npromisingtids
8958 : : * values as anything more than noise.
8959 : : *
8960 : : * We tiebreak on nhtids when sorting block group subsets that have the
8961 : : * same npromisingtids, but this has the same issues as npromisingtids,
8962 : : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8963 : : * only reason that we don't fix nhtids in the same way here too is that
8964 : : * we'll need accurate nhtids values after the sort. We handle nhtids
8965 : : * bucketization dynamically instead (in the sort comparator).
8966 : : *
8967 : : * See bottomup_nblocksfavorable() for a full explanation of when and how
8968 : : * heap locality/favorable blocks can significantly influence when and how
8969 : : * heap blocks are accessed.
8970 : : */
8971 [ + + ]: 56870 : for (int b = 0; b < nblockgroups; b++)
8972 : : {
8973 : 53888 : IndexDeleteCounts *group = blockgroups + b;
8974 : :
8975 : : /* Better off falling back on nhtids with low npromisingtids */
8976 [ + + ]: 53888 : if (group->npromisingtids <= 4)
8977 : 45095 : group->npromisingtids = 4;
8978 : : else
8979 : 8793 : group->npromisingtids =
8980 : 8793 : pg_nextpower2_32((uint32) group->npromisingtids);
8981 : : }
8982 : :
8983 : : /* Sort groups and rearrange caller's deltids array */
8984 : 2982 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8985 : : bottomup_sort_and_shrink_cmp);
34 michael@paquier.xyz 8986 :GNC 2982 : reordereddeltids = palloc_array(TM_IndexDelete, delstate->ndeltids);
8987 : :
2076 pg@bowt.ie 8988 :CBC 2982 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8989 : : /* Determine number of favorable blocks at the start of final deltids */
8990 : 2982 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8991 : : delstate->deltids);
8992 : :
8993 [ + + ]: 19373 : for (int b = 0; b < nblockgroups; b++)
8994 : : {
8995 : 16391 : IndexDeleteCounts *group = blockgroups + b;
8996 : 16391 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8997 : :
8998 : 16391 : memcpy(reordereddeltids + ncopied, firstdtid,
8999 : 16391 : sizeof(TM_IndexDelete) * group->ntids);
9000 : 16391 : ncopied += group->ntids;
9001 : : }
9002 : :
9003 : : /* Copy final grouped and sorted TIDs back into start of caller's array */
9004 : 2982 : memcpy(delstate->deltids, reordereddeltids,
9005 : : sizeof(TM_IndexDelete) * ncopied);
9006 : 2982 : delstate->ndeltids = ncopied;
9007 : :
9008 : 2982 : pfree(reordereddeltids);
9009 : 2982 : pfree(blockgroups);
9010 : :
9011 : 2982 : return nblocksfavorable;
9012 : : }
9013 : :
9014 : : /*
9015 : : * Perform XLogInsert for a heap-update operation. Caller must already
9016 : : * have modified the buffer(s) and marked them dirty.
9017 : : */
9018 : : static XLogRecPtr
67 melanieplageman@gmai 9019 : 2383423 : log_heap_update(Relation reln, Buffer oldbuf, Buffer vmbuffer_old,
9020 : : Buffer newbuf, Buffer vmbuffer_new,
9021 : : HeapTuple oldtup, HeapTuple newtup,
9022 : : HeapTuple old_key_tuple,
9023 : : bool all_visible_cleared, bool new_all_visible_cleared,
9024 : : bool walLogical)
9025 : : {
9026 : : xl_heap_update xlrec;
9027 : : xl_heap_header xlhdr;
9028 : : xl_heap_header xlhdr_idx;
9029 : : uint8 info;
9030 : : uint16 prefix_suffix[2];
4575 heikki.linnakangas@i 9031 : 2383423 : uint16 prefixlen = 0,
9032 : 2383423 : suffixlen = 0;
9033 : : XLogRecPtr recptr;
3805 kgrittn@postgresql.o 9034 : 2383423 : Page page = BufferGetPage(newbuf);
167 alvherre@kurilemu.de 9035 [ + + + + : 2383423 : bool need_tuple_data = walLogical && RelationIsLogicallyLogged(reln);
+ + + - -
+ - - - -
+ - + + ]
9036 : : bool init;
9037 : : int bufflags;
9038 : :
9039 : : /* Caller should not call me on a non-WAL-logged relation */
5760 rhaas@postgresql.org 9040 [ + - + + : 2383423 : Assert(RelationNeedsWAL(reln));
+ - - + ]
9041 : :
4322 heikki.linnakangas@i 9042 : 2383423 : XLogBeginInsert();
9043 : :
6068 tgl@sss.pgh.pa.us 9044 [ + + ]: 2383423 : if (HeapTupleIsHeapOnly(newtup))
6940 9045 : 165293 : info = XLOG_HEAP_HOT_UPDATE;
9046 : : else
9047 : 2218130 : info = XLOG_HEAP_UPDATE;
9048 : :
9049 : : /*
9050 : : * If the old and new tuple are on the same page, we only need to log the
9051 : : * parts of the new tuple that were changed. That saves on the amount of
9052 : : * WAL we need to write. Currently, we just count any unchanged bytes in
9053 : : * the beginning and end of the tuple. That's quick to check, and
9054 : : * perfectly covers the common case that only one field is updated.
9055 : : *
9056 : : * We could do this even if the old and new tuple are on different pages,
9057 : : * but only if we don't make a full-page image of the old page, which is
9058 : : * difficult to know in advance. Also, if the old tuple is corrupt for
9059 : : * some reason, it would allow the corruption to propagate the new page,
9060 : : * so it seems best to avoid. Under the general assumption that most
9061 : : * updates tend to create the new tuple version on the same page, there
9062 : : * isn't much to be gained by doing this across pages anyway.
9063 : : *
9064 : : * Skip this if we're taking a full-page image of the new page, as we
9065 : : * don't include the new tuple in the WAL record in that case. Also
9066 : : * disable if effective_wal_level='logical', as logical decoding needs to
9067 : : * be able to read the new tuple in whole from the WAL record alone.
9068 : : */
4575 heikki.linnakangas@i 9069 [ + + + + ]: 2383423 : if (oldbuf == newbuf && !need_tuple_data &&
9070 [ + + ]: 169325 : !XLogCheckBufferNeedsBackup(newbuf))
9071 : : {
9072 : 168780 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
9073 : 168780 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
9074 : 168780 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
9075 : 168780 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
9076 : :
9077 : : /* Check for common prefix between old and new tuple */
9078 [ + + ]: 13936351 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
9079 : : {
9080 [ + + ]: 13907410 : if (newp[prefixlen] != oldp[prefixlen])
9081 : 139839 : break;
9082 : : }
9083 : :
9084 : : /*
9085 : : * Storing the length of the prefix takes 2 bytes, so we need to save
9086 : : * at least 3 bytes or there's no point.
9087 : : */
9088 [ + + ]: 168780 : if (prefixlen < 3)
9089 : 22826 : prefixlen = 0;
9090 : :
9091 : : /* Same for suffix */
9092 [ + + ]: 6073868 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
9093 : : {
9094 [ + + ]: 6044578 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
9095 : 139490 : break;
9096 : : }
9097 [ + + ]: 168780 : if (suffixlen < 3)
9098 : 41957 : suffixlen = 0;
9099 : : }
9100 : :
9101 : : /* Prepare main WAL data chain */
4667 rhaas@postgresql.org 9102 : 2383423 : xlrec.flags = 0;
9103 [ + + ]: 2383423 : if (all_visible_cleared)
4153 andres@anarazel.de 9104 : 2492 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
4667 rhaas@postgresql.org 9105 [ + + ]: 2383423 : if (new_all_visible_cleared)
4153 andres@anarazel.de 9106 : 1509 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
4575 heikki.linnakangas@i 9107 [ + + ]: 2383423 : if (prefixlen > 0)
4153 andres@anarazel.de 9108 : 145954 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
4575 heikki.linnakangas@i 9109 [ + + ]: 2383423 : if (suffixlen > 0)
4153 andres@anarazel.de 9110 : 126823 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
4322 heikki.linnakangas@i 9111 [ + + ]: 2383423 : if (need_tuple_data)
9112 : : {
4153 andres@anarazel.de 9113 : 47053 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
4322 heikki.linnakangas@i 9114 [ + + ]: 47053 : if (old_key_tuple)
9115 : : {
9116 [ + + ]: 156 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4153 andres@anarazel.de 9117 : 66 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
9118 : : else
9119 : 90 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
9120 : : }
9121 : : }
9122 : :
9123 : : /* If new tuple is the single and first tuple on page... */
4575 heikki.linnakangas@i 9124 [ + + + + ]: 2396714 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
9125 : 13291 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
9126 : : {
9127 : 12772 : info |= XLOG_HEAP_INIT_PAGE;
4322 9128 : 12772 : init = true;
9129 : : }
9130 : : else
9131 : 2370651 : init = false;
9132 : :
9133 : : /* Prepare WAL data for the old page */
9134 : 2383423 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
9135 : 2383423 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
9136 : 4766846 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
9137 : 2383423 : oldtup->t_data->t_infomask2);
9138 : :
9139 : : /* Prepare WAL data for the new page */
9140 : 2383423 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
9141 : 2383423 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
9142 : :
9143 : 2383423 : bufflags = REGBUF_STANDARD;
9144 [ + + ]: 2383423 : if (init)
9145 : 12772 : bufflags |= REGBUF_WILL_INIT;
9146 [ + + ]: 2383423 : if (need_tuple_data)
9147 : 47053 : bufflags |= REGBUF_KEEP_DATA;
9148 : :
67 melanieplageman@gmai 9149 : 2383423 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_NEW, newbuf, bufflags);
4322 heikki.linnakangas@i 9150 [ + + ]: 2383423 : if (oldbuf != newbuf)
67 melanieplageman@gmai 9151 : 2202125 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_OLD, oldbuf, REGBUF_STANDARD);
9152 : :
586 peter@eisentraut.org 9153 : 2383423 : XLogRegisterData(&xlrec, SizeOfHeapUpdate);
9154 : :
9155 : : /*
9156 : : * Prepare WAL data for the new tuple.
9157 : : */
4575 heikki.linnakangas@i 9158 [ + + + + ]: 2383423 : if (prefixlen > 0 || suffixlen > 0)
9159 : : {
9160 [ + + + + ]: 168210 : if (prefixlen > 0 && suffixlen > 0)
9161 : : {
9162 : 104567 : prefix_suffix[0] = prefixlen;
9163 : 104567 : prefix_suffix[1] = suffixlen;
67 melanieplageman@gmai 9164 : 104567 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefix_suffix,
9165 : : sizeof(uint16) * 2);
9166 : : }
4575 heikki.linnakangas@i 9167 [ + + ]: 63643 : else if (prefixlen > 0)
9168 : : {
67 melanieplageman@gmai 9169 : 41387 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefixlen,
9170 : : sizeof(uint16));
9171 : : }
9172 : : else
9173 : : {
9174 : 22256 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &suffixlen,
9175 : : sizeof(uint16));
9176 : : }
9177 : : }
9178 : :
4322 heikki.linnakangas@i 9179 : 2383423 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
9180 : 2383423 : xlhdr.t_infomask = newtup->t_data->t_infomask;
9181 : 2383423 : xlhdr.t_hoff = newtup->t_data->t_hoff;
4229 tgl@sss.pgh.pa.us 9182 [ - + ]: 2383423 : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
9183 : :
9184 : : /*
9185 : : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9186 : : *
9187 : : * The 'data' doesn't include the common prefix or suffix.
9188 : : */
67 melanieplageman@gmai 9189 : 2383423 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &xlhdr, SizeOfHeapHeader);
4575 heikki.linnakangas@i 9190 [ + + ]: 2383423 : if (prefixlen == 0)
9191 : : {
67 melanieplageman@gmai 9192 : 2237469 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
586 peter@eisentraut.org 9193 : 2237469 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3378 tgl@sss.pgh.pa.us 9194 : 2237469 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
9195 : : }
9196 : : else
9197 : : {
9198 : : /*
9199 : : * Have to write the null bitmap and data after the common prefix as
9200 : : * two separate rdata entries.
9201 : : */
9202 : : /* bitmap [+ padding] [+ oid] */
4229 9203 [ + - ]: 145954 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9204 : : {
67 melanieplageman@gmai 9205 : 145954 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
586 peter@eisentraut.org 9206 : 145954 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3378 tgl@sss.pgh.pa.us 9207 : 145954 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
9208 : : }
9209 : :
9210 : : /* data after common prefix */
67 melanieplageman@gmai 9211 : 145954 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
586 peter@eisentraut.org 9212 : 145954 : (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
3378 tgl@sss.pgh.pa.us 9213 : 145954 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9214 : : }
9215 : :
9216 : : /* We need to log a tuple identity */
4322 heikki.linnakangas@i 9217 [ + + + + ]: 2383423 : if (need_tuple_data && old_key_tuple)
9218 : : {
9219 : : /* don't really need this, but its more comfy to decode */
9220 : 156 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9221 : 156 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9222 : 156 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9223 : :
586 peter@eisentraut.org 9224 : 156 : XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
9225 : :
9226 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
4229 tgl@sss.pgh.pa.us 9227 : 156 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
9228 : 156 : old_key_tuple->t_len - SizeofHeapTupleHeader);
9229 : : }
9230 : :
9231 : : /*
9232 : : * Register VM buffers. If the old and new heap pages' VM bits are on the
9233 : : * same VM page and both their VM bits were cleared, the caller passes
9234 : : * only vmbuffer_new (mirroring the heap page convention where block 0 =
9235 : : * new is always registered).
9236 : : */
67 melanieplageman@gmai 9237 [ + + + + : 2383423 : Assert((BufferIsInvalid(vmbuffer_old) && BufferIsInvalid(vmbuffer_new)) ||
- + ]
9238 : : (vmbuffer_old != vmbuffer_new));
9239 : :
9240 [ + + ]: 2383423 : if (BufferIsValid(vmbuffer_new))
9241 : 1509 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_NEW, vmbuffer_new, 0);
9242 : :
9243 [ + + ]: 2383423 : if (BufferIsValid(vmbuffer_old))
9244 : 2318 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_OLD, vmbuffer_old, 0);
9245 : :
9246 : : /* filtering by origin on a row level is much more efficient */
3559 andres@anarazel.de 9247 : 2383423 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
9248 : :
4322 heikki.linnakangas@i 9249 : 2383423 : recptr = XLogInsert(RM_HEAP_ID, info);
9250 : :
7557 neilc@samurai.com 9251 : 2383423 : return recptr;
9252 : : }
9253 : :
9254 : : /*
9255 : : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
9256 : : *
9257 : : * This is only used when effective_wal_level is logical, and only for
9258 : : * catalog tuples.
9259 : : */
9260 : : static XLogRecPtr
4667 rhaas@postgresql.org 9261 : 27403 : log_heap_new_cid(Relation relation, HeapTuple tup)
9262 : : {
9263 : : xl_heap_new_cid xlrec;
9264 : :
9265 : : XLogRecPtr recptr;
9266 : 27403 : HeapTupleHeader hdr = tup->t_data;
9267 : :
9268 [ - + ]: 27403 : Assert(ItemPointerIsValid(&tup->t_self));
9269 [ - + ]: 27403 : Assert(tup->t_tableOid != InvalidOid);
9270 : :
9271 : 27403 : xlrec.top_xid = GetTopTransactionId();
1537 9272 : 27403 : xlrec.target_locator = relation->rd_locator;
4322 heikki.linnakangas@i 9273 : 27403 : xlrec.target_tid = tup->t_self;
9274 : :
9275 : : /*
9276 : : * If the tuple got inserted & deleted in the same TX we definitely have a
9277 : : * combo CID, set cmin and cmax.
9278 : : */
4667 rhaas@postgresql.org 9279 [ + + ]: 27403 : if (hdr->t_infomask & HEAP_COMBOCID)
9280 : : {
9281 [ - + ]: 2322 : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
4655 9282 [ - + ]: 2322 : Assert(!HeapTupleHeaderXminInvalid(hdr));
4667 9283 : 2322 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9284 : 2322 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9285 : 2322 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9286 : : }
9287 : : /* No combo CID, so only cmin or cmax can be set by this TX */
9288 : : else
9289 : : {
9290 : : /*
9291 : : * Tuple inserted.
9292 : : *
9293 : : * We need to check for LOCK ONLY because multixacts might be
9294 : : * transferred to the new tuple in case of FOR KEY SHARE updates in
9295 : : * which case there will be an xmax, although the tuple just got
9296 : : * inserted.
9297 : : */
9298 [ + + + + ]: 32850 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9299 : 7769 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
9300 : : {
9301 : 17313 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
9302 : 17313 : xlrec.cmax = InvalidCommandId;
9303 : : }
9304 : : /* Tuple from a different tx updated or deleted. */
9305 : : else
9306 : : {
9307 : 7768 : xlrec.cmin = InvalidCommandId;
9308 : 7768 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
9309 : : }
9310 : 25081 : xlrec.combocid = InvalidCommandId;
9311 : : }
9312 : :
9313 : : /*
9314 : : * Note that we don't need to register the buffer here, because this
9315 : : * operation does not modify the page. The insert/update/delete that
9316 : : * called us certainly did, but that's WAL-logged separately.
9317 : : */
4322 heikki.linnakangas@i 9318 : 27403 : XLogBeginInsert();
586 peter@eisentraut.org 9319 : 27403 : XLogRegisterData(&xlrec, SizeOfHeapNewCid);
9320 : :
9321 : : /* will be looked at irrespective of origin */
9322 : :
4322 heikki.linnakangas@i 9323 : 27403 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9324 : :
4667 rhaas@postgresql.org 9325 : 27403 : return recptr;
9326 : : }
9327 : :
9328 : : /*
9329 : : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9330 : : * the old tuple in an UPDATE or DELETE.
9331 : : *
9332 : : * Returns NULL if there's no need to log an identity or if there's no suitable
9333 : : * key defined.
9334 : : *
9335 : : * Pass key_required true if any replica identity columns changed value, or if
9336 : : * any of them have any external data. Delete must always pass true.
9337 : : *
9338 : : * *copy is set to true if the returned tuple is a modified copy rather than
9339 : : * the same tuple that was passed in.
9340 : : */
9341 : : static HeapTuple
1679 akapila@postgresql.o 9342 : 4243161 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
9343 : : bool *copy)
9344 : : {
4667 rhaas@postgresql.org 9345 : 4243161 : TupleDesc desc = RelationGetDescr(relation);
9346 : 4243161 : char replident = relation->rd_rel->relreplident;
9347 : : Bitmapset *idattrs;
9348 : : HeapTuple key_tuple;
9349 : : bool nulls[MaxHeapAttributeNumber];
9350 : : Datum values[MaxHeapAttributeNumber];
9351 : :
9352 : 4243161 : *copy = false;
9353 : :
9354 [ + + + + : 4243161 : if (!RelationIsLogicallyLogged(relation))
+ + - + -
- - - + -
+ + ]
9355 : 4142703 : return NULL;
9356 : :
9357 [ + + ]: 100458 : if (replident == REPLICA_IDENTITY_NOTHING)
9358 : 335 : return NULL;
9359 : :
9360 [ + + ]: 100123 : if (replident == REPLICA_IDENTITY_FULL)
9361 : : {
9362 : : /*
9363 : : * When logging the entire old tuple, it very well could contain
9364 : : * toasted columns. If so, force them to be inlined.
9365 : : */
9366 [ + + ]: 198 : if (HeapTupleHasExternal(tp))
9367 : : {
9368 : 4 : *copy = true;
2575 tgl@sss.pgh.pa.us 9369 : 4 : tp = toast_flatten_tuple(tp, desc);
9370 : : }
4667 rhaas@postgresql.org 9371 : 198 : return tp;
9372 : : }
9373 : :
9374 : : /* if the key isn't required and we're only logging the key, we're done */
1679 akapila@postgresql.o 9375 [ + + ]: 99925 : if (!key_required)
4667 rhaas@postgresql.org 9376 : 46921 : return NULL;
9377 : :
9378 : : /* find out the replica identity columns */
2575 tgl@sss.pgh.pa.us 9379 : 53004 : idattrs = RelationGetIndexAttrBitmap(relation,
9380 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
9381 : :
9382 : : /*
9383 : : * If there's no defined replica identity columns, treat as !key_required.
9384 : : * (This case should not be reachable from heap_update, since that should
9385 : : * calculate key_required accurately. But heap_delete just passes
9386 : : * constant true for key_required, so we can hit this case in deletes.)
9387 : : */
9388 [ + + ]: 53004 : if (bms_is_empty(idattrs))
9389 : 6021 : return NULL;
9390 : :
9391 : : /*
9392 : : * Construct a new tuple containing only the replica identity columns,
9393 : : * with nulls elsewhere. While we're at it, assert that the replica
9394 : : * identity columns aren't null.
9395 : : */
9396 : 46983 : heap_deform_tuple(tp, desc, values, nulls);
9397 : :
9398 [ + + ]: 150960 : for (int i = 0; i < desc->natts; i++)
9399 : : {
9400 [ + + ]: 103977 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
9401 : : idattrs))
9402 [ - + ]: 46995 : Assert(!nulls[i]);
9403 : : else
9404 : 56982 : nulls[i] = true;
9405 : : }
9406 : :
4667 rhaas@postgresql.org 9407 : 46983 : key_tuple = heap_form_tuple(desc, values, nulls);
9408 : 46983 : *copy = true;
9409 : :
2575 tgl@sss.pgh.pa.us 9410 : 46983 : bms_free(idattrs);
9411 : :
9412 : : /*
9413 : : * If the tuple, which by here only contains indexed columns, still has
9414 : : * toasted columns, force them to be inlined. This is somewhat unlikely
9415 : : * since there's limits on the size of indexed columns, so we don't
9416 : : * duplicate toast_flatten_tuple()s functionality in the above loop over
9417 : : * the indexed columns, even if it would be more efficient.
9418 : : */
4667 rhaas@postgresql.org 9419 [ + + ]: 46983 : if (HeapTupleHasExternal(key_tuple))
9420 : : {
4520 bruce@momjian.us 9421 : 4 : HeapTuple oldtup = key_tuple;
9422 : :
2575 tgl@sss.pgh.pa.us 9423 : 4 : key_tuple = toast_flatten_tuple(oldtup, desc);
4667 rhaas@postgresql.org 9424 : 4 : heap_freetuple(oldtup);
9425 : : }
9426 : :
9427 : 46983 : return key_tuple;
9428 : : }
9429 : :
9430 : : /*
9431 : : * HeapCheckForSerializableConflictOut
9432 : : * We are reading a tuple. If it's not visible, there may be a
9433 : : * rw-conflict out with the inserter. Otherwise, if it is visible to us
9434 : : * but has been deleted, there may be a rw-conflict out with the deleter.
9435 : : *
9436 : : * We will determine the top level xid of the writing transaction with which
9437 : : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9438 : : * for overlap with our own transaction.
9439 : : *
9440 : : * This function should be called just about anywhere in heapam.c where a
9441 : : * tuple has been read. The caller must hold at least a shared lock on the
9442 : : * buffer, because this function might set hint bits on the tuple. There is
9443 : : * currently no known reason to call this function from an index AM.
9444 : : */
9445 : : void
2427 tmunro@postgresql.or 9446 : 40686395 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
9447 : : HeapTuple tuple, Buffer buffer,
9448 : : Snapshot snapshot)
9449 : : {
9450 : : TransactionId xid;
9451 : : HTSV_Result htsvResult;
9452 : :
9453 [ + + ]: 40686395 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9454 : 40676330 : return;
9455 : :
9456 : : /*
9457 : : * Check to see whether the tuple has been written to by a concurrent
9458 : : * transaction, either to create it not visible to us, or to delete it
9459 : : * while it is visible to us. The "visible" bool indicates whether the
9460 : : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9461 : : * is going on with it.
9462 : : *
9463 : : * In the event of a concurrently inserted tuple that also happens to have
9464 : : * been concurrently updated (by a separate transaction), the xmin of the
9465 : : * tuple will be used -- not the updater's xid.
9466 : : */
9467 : 10065 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9468 [ + + + + : 10065 : switch (htsvResult)
- ]
9469 : : {
9470 : 9238 : case HEAPTUPLE_LIVE:
9471 [ + + ]: 9238 : if (visible)
9472 : 9216 : return;
9473 : 22 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9474 : 22 : break;
9475 : 364 : case HEAPTUPLE_RECENTLY_DEAD:
9476 : : case HEAPTUPLE_DELETE_IN_PROGRESS:
2292 pg@bowt.ie 9477 [ + + ]: 364 : if (visible)
9478 : 289 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9479 : : else
9480 : 75 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9481 : :
9482 [ + + ]: 364 : if (TransactionIdPrecedes(xid, TransactionXmin))
9483 : : {
9484 : : /* This is like the HEAPTUPLE_DEAD case */
9485 [ - + ]: 67 : Assert(!visible);
9486 : 67 : return;
9487 : : }
2427 tmunro@postgresql.or 9488 : 297 : break;
9489 : 345 : case HEAPTUPLE_INSERT_IN_PROGRESS:
9490 : 345 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9491 : 345 : break;
9492 : 118 : case HEAPTUPLE_DEAD:
2292 pg@bowt.ie 9493 [ - + ]: 118 : Assert(!visible);
2427 tmunro@postgresql.or 9494 : 118 : return;
2427 tmunro@postgresql.or 9495 :UBC 0 : default:
9496 : :
9497 : : /*
9498 : : * The only way to get to this default clause is if a new value is
9499 : : * added to the enum type without adding it to this switch
9500 : : * statement. That's a bug, so elog.
9501 : : */
9502 [ # # ]: 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9503 : :
9504 : : /*
9505 : : * In spite of having all enum values covered and calling elog on
9506 : : * this default, some compilers think this is a code path which
9507 : : * allows xid to be used below without initialization. Silence
9508 : : * that warning.
9509 : : */
9510 : : xid = InvalidTransactionId;
9511 : : }
9512 : :
2427 tmunro@postgresql.or 9513 [ - + ]:CBC 664 : Assert(TransactionIdIsValid(xid));
9514 [ - + ]: 664 : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
9515 : :
9516 : : /*
9517 : : * Find top level xid. Bail out if xid is too early to be a conflict, or
9518 : : * if it's our own xid.
9519 : : */
9520 [ + + ]: 664 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
9521 : 82 : return;
9522 : 582 : xid = SubTransGetTopmostTransaction(xid);
9523 [ - + ]: 582 : if (TransactionIdPrecedes(xid, TransactionXmin))
2427 tmunro@postgresql.or 9524 :UBC 0 : return;
9525 : :
2427 tmunro@postgresql.or 9526 :CBC 582 : CheckForSerializableConflictOut(relation, xid, snapshot);
9527 : : }
|