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 newbuf, HeapTuple oldtup,
64 : : HeapTuple newtup, HeapTuple old_key_tuple,
65 : : bool all_visible_cleared, bool new_all_visible_cleared,
66 : : bool walLogical);
67 : : #ifdef USE_ASSERT_CHECKING
68 : : static void check_lock_if_inplace_updateable_rel(Relation relation,
69 : : const ItemPointerData *otid,
70 : : HeapTuple newtup);
71 : : static void check_inplace_rel_lock(HeapTuple oldtup);
72 : : #endif
73 : : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
74 : : Bitmapset *interesting_cols,
75 : : Bitmapset *external_cols,
76 : : HeapTuple oldtup, HeapTuple newtup,
77 : : bool *has_external);
78 : : static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid,
79 : : LockTupleMode mode, LockWaitPolicy wait_policy,
80 : : bool *have_tuple_lock);
81 : : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
82 : : BlockNumber block,
83 : : ScanDirection dir);
84 : : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
85 : : ScanDirection dir);
86 : : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
87 : : uint16 old_infomask2, TransactionId add_to_xmax,
88 : : LockTupleMode mode, bool is_update,
89 : : TransactionId *result_xmax, uint16 *result_infomask,
90 : : uint16 *result_infomask2);
91 : : static TM_Result heap_lock_updated_tuple(Relation rel,
92 : : uint16 prior_infomask,
93 : : TransactionId prior_raw_xmax,
94 : : const ItemPointerData *prior_ctid,
95 : : TransactionId xid,
96 : : LockTupleMode mode);
97 : : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
98 : : uint16 *new_infomask2);
99 : : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
100 : : uint16 t_infomask);
101 : : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
102 : : LockTupleMode lockmode, bool *current_is_member);
103 : : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
104 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
105 : : int *remaining);
106 : : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
107 : : uint16 infomask, Relation rel, int *remaining,
108 : : bool logLockFailure);
109 : : static void index_delete_sort(TM_IndexDeleteOp *delstate);
110 : : static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
111 : : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
112 : : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
113 : : bool *copy);
114 : :
115 : :
116 : : /*
117 : : * This table lists the heavyweight lock mode that corresponds to each tuple
118 : : * lock mode, as well as one or two corresponding MultiXactStatus values:
119 : : * .lockstatus to merely lock tuples, and .updstatus to update them. The
120 : : * latter is set to -1 if the corresponding tuple lock mode does not allow
121 : : * updating tuples -- see get_mxact_status_for_lock().
122 : : *
123 : : * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
124 : : *
125 : : * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
126 : : * instead.
127 : : */
128 : : static const struct
129 : : {
130 : : LOCKMODE hwlock;
131 : : int lockstatus;
132 : : int updstatus;
133 : : } tupleLockExtraInfo[] =
134 : :
135 : : {
136 : : [LockTupleKeyShare] = {
137 : : .hwlock = AccessShareLock,
138 : : .lockstatus = MultiXactStatusForKeyShare,
139 : : /* KeyShare does not allow updating tuples */
140 : : .updstatus = -1
141 : : },
142 : : [LockTupleShare] = {
143 : : .hwlock = RowShareLock,
144 : : .lockstatus = MultiXactStatusForShare,
145 : : /* Share does not allow updating tuples */
146 : : .updstatus = -1
147 : : },
148 : : [LockTupleNoKeyExclusive] = {
149 : : .hwlock = ExclusiveLock,
150 : : .lockstatus = MultiXactStatusForNoKeyUpdate,
151 : : .updstatus = MultiXactStatusNoKeyUpdate
152 : : },
153 : : [LockTupleExclusive] = {
154 : : .hwlock = AccessExclusiveLock,
155 : : .lockstatus = MultiXactStatusForUpdate,
156 : : .updstatus = MultiXactStatusUpdate
157 : : }
158 : : };
159 : :
160 : : /* Get the LOCKMODE for a given MultiXactStatus */
161 : : #define LOCKMODE_from_mxstatus(status) \
162 : : (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
163 : :
164 : : /*
165 : : * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
166 : : * This is more readable than having every caller translate it to lock.h's
167 : : * LOCKMODE.
168 : : */
169 : : #define LockTupleTuplock(rel, tup, mode) \
170 : : LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
171 : : #define UnlockTupleTuplock(rel, tup, mode) \
172 : : UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
173 : : #define ConditionalLockTupleTuplock(rel, tup, mode, log) \
174 : : ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
175 : :
176 : : #ifdef USE_PREFETCH
177 : : /*
178 : : * heap_index_delete_tuples and index_delete_prefetch_buffer use this
179 : : * structure to coordinate prefetching activity
180 : : */
181 : : typedef struct
182 : : {
183 : : BlockNumber cur_hblkno;
184 : : int next_item;
185 : : int ndeltids;
186 : : TM_IndexDelete *deltids;
187 : : } IndexDeletePrefetchState;
188 : : #endif
189 : :
190 : : /* heap_index_delete_tuples bottom-up index deletion costing constants */
191 : : #define BOTTOMUP_MAX_NBLOCKS 6
192 : : #define BOTTOMUP_TOLERANCE_NBLOCKS 3
193 : :
194 : : /*
195 : : * heap_index_delete_tuples uses this when determining which heap blocks it
196 : : * must visit to help its bottom-up index deletion caller
197 : : */
198 : : typedef struct IndexDeleteCounts
199 : : {
200 : : int16 npromisingtids; /* Number of "promising" TIDs in group */
201 : : int16 ntids; /* Number of TIDs in group */
202 : : int16 ifirsttid; /* Offset to group's first deltid */
203 : : } IndexDeleteCounts;
204 : :
205 : : /*
206 : : * This table maps tuple lock strength values for each particular
207 : : * MultiXactStatus value.
208 : : */
209 : : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
210 : : {
211 : : LockTupleKeyShare, /* ForKeyShare */
212 : : LockTupleShare, /* ForShare */
213 : : LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
214 : : LockTupleExclusive, /* ForUpdate */
215 : : LockTupleNoKeyExclusive, /* NoKeyUpdate */
216 : : LockTupleExclusive /* Update */
217 : : };
218 : :
219 : : /* Get the LockTupleMode for a given MultiXactStatus */
220 : : #define TUPLOCK_from_mxstatus(status) \
221 : : (MultiXactStatusLock[(status)])
222 : :
223 : : /*
224 : : * Check that we have a valid snapshot if we might need TOAST access.
225 : : */
226 : : static inline void
340 nathan@postgresql.or 227 :CBC 16631353 : AssertHasSnapshotForToast(Relation rel)
228 : : {
229 : : #ifdef USE_ASSERT_CHECKING
230 : :
231 : : /* bootstrap mode in particular breaks this rule */
232 [ + + ]: 16631353 : if (!IsNormalProcessingMode())
233 : 671403 : return;
234 : :
235 : : /* if the relation doesn't have a TOAST table, we are good */
236 [ + + ]: 15959950 : if (!OidIsValid(rel->rd_rel->reltoastrelid))
237 : 10311111 : return;
238 : :
239 [ - + ]: 5648839 : Assert(HaveRegisteredOrActiveSnapshot());
240 : :
241 : : #endif /* USE_ASSERT_CHECKING */
242 : : }
243 : :
244 : : /* ----------------------------------------------------------------
245 : : * heap support routines
246 : : * ----------------------------------------------------------------
247 : : */
248 : :
249 : : /*
250 : : * Streaming read API callback for parallel sequential scans. Returns the next
251 : : * block the caller wants from the read stream or InvalidBlockNumber when done.
252 : : */
253 : : static BlockNumber
757 tmunro@postgresql.or 254 : 146318 : heap_scan_stream_read_next_parallel(ReadStream *stream,
255 : : void *callback_private_data,
256 : : void *per_buffer_data)
257 : : {
258 : 146318 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
259 : :
260 [ - + ]: 146318 : Assert(ScanDirectionIsForward(scan->rs_dir));
261 [ - + ]: 146318 : Assert(scan->rs_base.rs_parallel);
262 : :
263 [ + + ]: 146318 : if (unlikely(!scan->rs_inited))
264 : : {
265 : : /* parallel scan */
266 : 2840 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
267 : 2840 : scan->rs_parallelworkerdata,
159 drowley@postgresql.o 268 :GNC 2840 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel,
269 : : scan->rs_startblock,
270 : : scan->rs_numblocks);
271 : :
272 : : /* may return InvalidBlockNumber if there are no more blocks */
757 tmunro@postgresql.or 273 :CBC 5680 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
274 : 2840 : scan->rs_parallelworkerdata,
275 : 2840 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
276 : 2840 : scan->rs_inited = true;
277 : : }
278 : : else
279 : : {
280 : 143478 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
281 : 143478 : scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
282 : 143478 : scan->rs_base.rs_parallel);
283 : : }
284 : :
285 : 146318 : return scan->rs_prefetch_block;
286 : : }
287 : :
288 : : /*
289 : : * Streaming read API callback for serial sequential and TID range scans.
290 : : * Returns the next block the caller wants from the read stream or
291 : : * InvalidBlockNumber when done.
292 : : */
293 : : static BlockNumber
294 : 4732558 : heap_scan_stream_read_next_serial(ReadStream *stream,
295 : : void *callback_private_data,
296 : : void *per_buffer_data)
297 : : {
298 : 4732558 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
299 : :
300 [ + + ]: 4732558 : if (unlikely(!scan->rs_inited))
301 : : {
302 : 1316463 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
303 : 1316463 : scan->rs_inited = true;
304 : : }
305 : : else
306 : 3416095 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
307 : : scan->rs_prefetch_block,
308 : : scan->rs_dir);
309 : :
310 : 4732558 : return scan->rs_prefetch_block;
311 : : }
312 : :
313 : : /*
314 : : * Read stream API callback for bitmap heap scans.
315 : : * Returns the next block the caller wants from the read stream or
316 : : * InvalidBlockNumber when done.
317 : : */
318 : : static BlockNumber
416 melanieplageman@gmai 319 : 261451 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
320 : : void *per_buffer_data)
321 : : {
322 : 261451 : TBMIterateResult *tbmres = per_buffer_data;
323 : 261451 : BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
324 : 261451 : HeapScanDesc hscan = (HeapScanDesc) bscan;
325 : 261451 : TableScanDesc sscan = &hscan->rs_base;
326 : :
327 : : for (;;)
328 : : {
329 [ - + ]: 261451 : CHECK_FOR_INTERRUPTS();
330 : :
331 : : /* no more entries in the bitmap */
332 [ + + ]: 261451 : if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
333 : 15048 : return InvalidBlockNumber;
334 : :
335 : : /*
336 : : * Ignore any claimed entries past what we think is the end of the
337 : : * relation. It may have been extended after the start of our scan (we
338 : : * only hold an AccessShareLock, and it could be inserts from this
339 : : * backend). We don't take this optimization in SERIALIZABLE
340 : : * isolation though, as we need to examine all invisible tuples
341 : : * reachable by the index.
342 : : */
343 [ + + ]: 246403 : if (!IsolationIsSerializable() &&
344 [ - + ]: 246294 : tbmres->blockno >= hscan->rs_nblocks)
416 melanieplageman@gmai 345 :UBC 0 : continue;
346 : :
416 melanieplageman@gmai 347 :CBC 246403 : return tbmres->blockno;
348 : : }
349 : :
350 : : /* not reachable */
351 : : Assert(false);
352 : : }
353 : :
354 : : /* ----------------
355 : : * initscan - scan code common to heap_beginscan and heap_rescan
356 : : * ----------------
357 : : */
358 : : static void
3937 tgl@sss.pgh.pa.us 359 : 1348135 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
360 : : {
2612 andres@anarazel.de 361 : 1348135 : ParallelBlockTableScanDesc bpscan = NULL;
362 : : bool allow_strat;
363 : : bool allow_sync;
364 : :
365 : : /*
366 : : * Determine the number of blocks we have to scan.
367 : : *
368 : : * It is sufficient to do this once at scan start, since any tuples added
369 : : * while the scan is in progress will be invisible to my snapshot anyway.
370 : : * (That is not true when using a non-MVCC snapshot. However, we couldn't
371 : : * guarantee to return tuples added after scan start anyway, since they
372 : : * might go into pages we already scanned. To guarantee consistent
373 : : * results for a non-MVCC snapshot, the caller must hold some higher-level
374 : : * lock that ensures the interesting tuple(s) won't change.)
375 : : */
376 [ + + ]: 1348135 : if (scan->rs_base.rs_parallel != NULL)
377 : : {
378 : 4677 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
379 : 4677 : scan->rs_nblocks = bpscan->phs_nblocks;
380 : : }
381 : : else
382 : 1343458 : scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
383 : :
384 : : /*
385 : : * If the table is large relative to NBuffers, use a bulk-read access
386 : : * strategy and enable synchronized scanning (see syncscan.c). Although
387 : : * the thresholds for these features could be different, we make them the
388 : : * same so that there are only two behaviors to tune rather than four.
389 : : * (However, some callers need to be able to disable one or both of these
390 : : * behaviors, independently of the size of the table; also there is a GUC
391 : : * variable that can disable synchronized scanning.)
392 : : *
393 : : * Note that table_block_parallelscan_initialize has a very similar test;
394 : : * if you change this, consider changing that one, too.
395 : : */
396 [ + + ]: 1348133 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
6905 tgl@sss.pgh.pa.us 397 [ + + ]: 1338316 : scan->rs_nblocks > NBuffers / 4)
398 : : {
2543 andres@anarazel.de 399 : 16448 : allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
400 : 16448 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
401 : : }
402 : : else
6686 tgl@sss.pgh.pa.us 403 : 1331685 : allow_strat = allow_sync = false;
404 : :
405 [ + + ]: 1348133 : if (allow_strat)
406 : : {
407 : : /* During a rescan, keep the previous strategy object. */
6915 408 [ + + ]: 15095 : if (scan->rs_strategy == NULL)
409 : 14889 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
410 : : }
411 : : else
412 : : {
413 [ - + ]: 1333038 : if (scan->rs_strategy != NULL)
6915 tgl@sss.pgh.pa.us 414 :UBC 0 : FreeAccessStrategy(scan->rs_strategy);
6915 tgl@sss.pgh.pa.us 415 :CBC 1333038 : scan->rs_strategy = NULL;
416 : : }
417 : :
2612 andres@anarazel.de 418 [ + + ]: 1348133 : if (scan->rs_base.rs_parallel != NULL)
419 : : {
420 : : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
2543 421 [ + + ]: 4677 : if (scan->rs_base.rs_parallel->phs_syncscan)
422 : 5 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
423 : : else
424 : 4672 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
425 : :
426 : : /*
427 : : * If not rescanning, initialize the startblock. Finding the actual
428 : : * start location is done in table_block_parallelscan_startblock_init,
429 : : * based on whether an alternative start location has been set with
430 : : * heap_setscanlimits, or using the syncscan location, when syncscan
431 : : * is enabled.
432 : : */
158 drowley@postgresql.o 433 [ + + ]:GNC 4677 : if (!keep_startblock)
434 : 4525 : scan->rs_startblock = InvalidBlockNumber;
435 : : }
436 : : else
437 : : {
438 [ + + ]: 1343456 : if (keep_startblock)
439 : : {
440 : : /*
441 : : * When rescanning, we want to keep the previous startblock
442 : : * setting, so that rewinding a cursor doesn't generate surprising
443 : : * results. Reset the active syncscan setting, though.
444 : : */
445 [ + + + + ]: 869276 : if (allow_sync && synchronize_seqscans)
446 : 50 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
447 : : else
448 : 869226 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
449 : : }
450 [ + + + + ]: 474180 : else if (allow_sync && synchronize_seqscans)
451 : : {
452 : 78 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
453 : 78 : scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
454 : : }
455 : : else
456 : : {
457 : 474102 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
458 : 474102 : scan->rs_startblock = 0;
459 : : }
460 : : }
461 : :
4197 alvherre@alvh.no-ip. 462 :CBC 1348133 : scan->rs_numblocks = InvalidBlockNumber;
7465 tgl@sss.pgh.pa.us 463 : 1348133 : scan->rs_inited = false;
9096 464 : 1348133 : scan->rs_ctup.t_data = NULL;
7465 465 : 1348133 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
9096 466 : 1348133 : scan->rs_cbuf = InvalidBuffer;
7465 467 : 1348133 : scan->rs_cblock = InvalidBlockNumber;
503 melanieplageman@gmai 468 : 1348133 : scan->rs_ntuples = 0;
469 : 1348133 : scan->rs_cindex = 0;
470 : :
471 : : /*
472 : : * Initialize to ForwardScanDirection because it is most common and
473 : : * because heap scans go forward before going backward (e.g. CURSORs).
474 : : */
757 tmunro@postgresql.or 475 : 1348133 : scan->rs_dir = ForwardScanDirection;
476 : 1348133 : scan->rs_prefetch_block = InvalidBlockNumber;
477 : :
478 : : /* page-at-a-time fields are always invalid when not rs_inited */
479 : :
480 : : /*
481 : : * copy the scan key, if appropriate
482 : : */
1524 tgl@sss.pgh.pa.us 483 [ + + + + ]: 1348133 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
2612 andres@anarazel.de 484 : 264248 : memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
485 : :
486 : : /*
487 : : * Currently, we only have a stats counter for sequential heap scans (but
488 : : * e.g for bitmap scans the underlying bitmap index scans will be counted,
489 : : * and for sample scans we update stats for tuple fetches).
490 : : */
2543 491 [ + + ]: 1348133 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
2612 492 [ + + + + : 1319804 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
+ + ]
10892 scrappy@hub.org 493 : 1348133 : }
494 : :
495 : : /*
496 : : * heap_setscanlimits - restrict range of a heapscan
497 : : *
498 : : * startBlk is the page to start at
499 : : * numBlks is number of pages to scan (InvalidBlockNumber means "all")
500 : : */
501 : : void
2612 andres@anarazel.de 502 : 3271 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
503 : : {
504 : 3271 : HeapScanDesc scan = (HeapScanDesc) sscan;
505 : :
3941 tgl@sss.pgh.pa.us 506 [ - + ]: 3271 : Assert(!scan->rs_inited); /* else too late to change */
507 : : /* else rs_startblock is significant */
2543 andres@anarazel.de 508 [ - + ]: 3271 : Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
509 : :
510 : : /* Check startBlk is valid (but allow case of zero blocks...) */
3941 tgl@sss.pgh.pa.us 511 [ + + - + ]: 3271 : Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
512 : :
4197 alvherre@alvh.no-ip. 513 : 3271 : scan->rs_startblock = startBlk;
514 : 3271 : scan->rs_numblocks = numBlks;
515 : 3271 : }
516 : :
517 : : /*
518 : : * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
519 : : * multiple times, with constant arguments for all_visible,
520 : : * check_serializable.
521 : : */
522 : : pg_attribute_always_inline
523 : : static int
758 andres@anarazel.de 524 : 3432510 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
525 : : Page page, Buffer buffer,
526 : : BlockNumber block, int lines,
527 : : bool all_visible, bool check_serializable)
528 : : {
113 andres@anarazel.de 529 :GNC 3432510 : Oid relid = RelationGetRelid(scan->rs_base.rs_rd);
759 andres@anarazel.de 530 :CBC 3432510 : int ntup = 0;
113 andres@anarazel.de 531 :GNC 3432510 : int nvis = 0;
532 : : BatchMVCCState batchmvcc;
533 : :
534 : : /* page at a time should have been disabled otherwise */
535 [ - + ]: 3432510 : Assert(IsMVCCSnapshot(snapshot));
536 : :
537 : : /* first find all tuples on the page */
538 [ + + ]: 184823049 : for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
539 : : {
759 andres@anarazel.de 540 :CBC 181390539 : ItemId lpp = PageGetItemId(page, lineoff);
541 : : HeapTuple tup;
542 : :
113 andres@anarazel.de 543 [ + + ]:GNC 181390539 : if (unlikely(!ItemIdIsNormal(lpp)))
759 andres@anarazel.de 544 :CBC 38498494 : continue;
545 : :
546 : : /*
547 : : * If the page is not all-visible or we need to check serializability,
548 : : * maintain enough state to be able to refind the tuple efficiently,
549 : : * without again first needing to fetch the item and then via that the
550 : : * tuple.
551 : : */
113 andres@anarazel.de 552 [ + + - + ]:GNC 142892045 : if (!all_visible || check_serializable)
553 : : {
554 : 80314347 : tup = &batchmvcc.tuples[ntup];
555 : :
556 : 80314347 : tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
557 : 80314347 : tup->t_len = ItemIdGetLength(lpp);
558 : 80314347 : tup->t_tableOid = relid;
559 : 80314347 : ItemPointerSet(&(tup->t_self), block, lineoff);
560 : : }
561 : :
562 : : /*
563 : : * If the page is all visible, these fields otherwise won't be
564 : : * populated in loop below.
565 : : */
566 [ + + ]: 142892045 : if (all_visible)
567 : : {
568 [ - + ]: 62577698 : if (check_serializable)
569 : : {
113 andres@anarazel.de 570 :UNC 0 : batchmvcc.visible[ntup] = true;
571 : : }
759 andres@anarazel.de 572 :CBC 62577698 : scan->rs_vistuples[ntup] = lineoff;
573 : : }
574 : :
113 andres@anarazel.de 575 :GNC 142892045 : ntup++;
576 : : }
577 : :
759 andres@anarazel.de 578 [ - + ]:CBC 3432510 : Assert(ntup <= MaxHeapTuplesPerPage);
579 : :
580 : : /*
581 : : * Unless the page is all visible, test visibility for all tuples one go.
582 : : * That is considerably more efficient than calling
583 : : * HeapTupleSatisfiesMVCC() one-by-one.
584 : : */
113 andres@anarazel.de 585 [ + + ]:GNC 3432510 : if (all_visible)
586 : 1358610 : nvis = ntup;
587 : : else
588 : 2073900 : nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
589 : : ntup,
590 : : &batchmvcc,
591 : 2073900 : scan->rs_vistuples);
592 : :
593 : : /*
594 : : * So far we don't have batch API for testing serializabilty, so do so
595 : : * one-by-one.
596 : : */
597 [ + + ]: 3432510 : if (check_serializable)
598 : : {
599 [ + + ]: 2087 : for (int i = 0; i < ntup; i++)
600 : : {
601 : 1464 : HeapCheckForSerializableConflictOut(batchmvcc.visible[i],
602 : : scan->rs_base.rs_rd,
603 : : &batchmvcc.tuples[i],
604 : : buffer, snapshot);
605 : : }
606 : : }
607 : :
608 : 3432502 : return nvis;
609 : : }
610 : :
611 : : /*
612 : : * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
613 : : *
614 : : * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
615 : : * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
616 : : */
617 : : void
761 drowley@postgresql.o 618 :CBC 3432510 : heap_prepare_pagescan(TableScanDesc sscan)
619 : : {
2612 andres@anarazel.de 620 : 3432510 : HeapScanDesc scan = (HeapScanDesc) sscan;
761 drowley@postgresql.o 621 : 3432510 : Buffer buffer = scan->rs_cbuf;
622 : 3432510 : BlockNumber block = scan->rs_cblock;
623 : : Snapshot snapshot;
624 : : Page page;
625 : : int lines;
626 : : bool all_visible;
627 : : bool check_serializable;
628 : :
629 [ - + ]: 3432510 : Assert(BufferGetBlockNumber(buffer) == block);
630 : :
631 : : /* ensure we're not accidentally being used when not in pagemode */
632 [ - + ]: 3432510 : Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
2612 andres@anarazel.de 633 : 3432510 : snapshot = scan->rs_base.rs_snapshot;
634 : :
635 : : /*
636 : : * Prune and repair fragmentation for the whole page, if possible.
637 : : */
36 melanieplageman@gmai 638 :GNC 3432510 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer, &scan->rs_vmbuffer,
639 : 3432510 : sscan->rs_flags & SO_HINT_REL_READ_ONLY);
640 : :
641 : : /*
642 : : * We must hold share lock on the buffer content while examining tuple
643 : : * visibility. Afterwards, however, the tuples we have found to be
644 : : * visible are guaranteed good as long as we hold the buffer pin.
645 : : */
7465 tgl@sss.pgh.pa.us 646 :CBC 3432510 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
647 : :
1266 peter@eisentraut.org 648 : 3432510 : page = BufferGetPage(buffer);
649 : 3432510 : lines = PageGetMaxOffsetNumber(page);
650 : :
651 : : /*
652 : : * If the all-visible flag indicates that all tuples on the page are
653 : : * visible to everyone, we can skip the per-tuple visibility tests.
654 : : *
655 : : * Note: In hot standby, a tuple that's already visible to all
656 : : * transactions on the primary might still be invisible to a read-only
657 : : * transaction in the standby. We partly handle this problem by tracking
658 : : * the minimum xmin of visible tuples as the cut-off XID while marking a
659 : : * page all-visible on the primary and WAL log that along with the
660 : : * visibility map SET operation. In hot standby, we wait for (or abort)
661 : : * all transactions that can potentially may not see one or more tuples on
662 : : * the page. That's how index-only scans work fine in hot standby. A
663 : : * crucial difference between index-only scans and heap scans is that the
664 : : * index-only scan completely relies on the visibility map where as heap
665 : : * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
666 : : * the page-level flag can be trusted in the same way, because it might
667 : : * get propagated somehow without being explicitly WAL-logged, e.g. via a
668 : : * full page write. Until we can prove that beyond doubt, let's check each
669 : : * tuple for visibility the hard way.
670 : : */
671 [ + + + + ]: 3432510 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
672 : : check_serializable =
759 andres@anarazel.de 673 : 3432510 : CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
674 : :
675 : : /*
676 : : * We call page_collect_tuples() with constant arguments, to get the
677 : : * compiler to constant fold the constant arguments. Separate calls with
678 : : * constant arguments, rather than variables, are needed on several
679 : : * compilers to actually perform constant folding.
680 : : */
681 [ + + ]: 3432510 : if (likely(all_visible))
682 : : {
683 [ + - ]: 1358610 : if (likely(!check_serializable))
758 684 : 1358610 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
685 : : block, lines, true, false);
686 : : else
758 andres@anarazel.de 687 :UBC 0 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
688 : : block, lines, true, true);
689 : : }
690 : : else
691 : : {
759 andres@anarazel.de 692 [ + + ]:CBC 2073900 : if (likely(!check_serializable))
758 693 : 2073269 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
694 : : block, lines, false, false);
695 : : else
696 : 631 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
697 : : block, lines, false, true);
698 : : }
699 : :
7465 tgl@sss.pgh.pa.us 700 : 3432502 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
701 : 3432502 : }
702 : :
703 : : /*
704 : : * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
705 : : *
706 : : * Read the next block of the scan relation from the read stream and save it
707 : : * in the scan descriptor. It is already pinned.
708 : : */
709 : : static inline void
761 drowley@postgresql.o 710 : 4669356 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
711 : : {
757 tmunro@postgresql.or 712 [ - + ]: 4669356 : Assert(scan->rs_read_stream);
713 : :
714 : : /* release previous scan buffer, if any */
761 drowley@postgresql.o 715 [ + + ]: 4669356 : if (BufferIsValid(scan->rs_cbuf))
716 : : {
717 : 3350050 : ReleaseBuffer(scan->rs_cbuf);
718 : 3350050 : scan->rs_cbuf = InvalidBuffer;
719 : : }
720 : :
721 : : /*
722 : : * Be sure to check for interrupts at least once per page. Checks at
723 : : * higher code levels won't be able to stop a seqscan that encounters many
724 : : * pages' worth of consecutive dead tuples.
725 : : */
726 [ + + ]: 4669356 : CHECK_FOR_INTERRUPTS();
727 : :
728 : : /*
729 : : * If the scan direction is changing, reset the prefetch block to the
730 : : * current block. Otherwise, we will incorrectly prefetch the blocks
731 : : * between the prefetch block and the current block again before
732 : : * prefetching blocks in the new, correct scan direction.
733 : : */
757 tmunro@postgresql.or 734 [ + + ]: 4669351 : if (unlikely(scan->rs_dir != dir))
735 : : {
736 : 101 : scan->rs_prefetch_block = scan->rs_cblock;
737 : 101 : read_stream_reset(scan->rs_read_stream);
738 : : }
739 : :
740 : 4669351 : scan->rs_dir = dir;
741 : :
742 : 4669351 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
743 [ + + ]: 4669315 : if (BufferIsValid(scan->rs_cbuf))
744 : 3543877 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
761 drowley@postgresql.o 745 : 4669315 : }
746 : :
747 : : /*
748 : : * heapgettup_initial_block - return the first BlockNumber to scan
749 : : *
750 : : * Returns InvalidBlockNumber when there are no blocks to scan. This can
751 : : * occur with empty tables and in parallel scans when parallel workers get all
752 : : * of the pages before we can get a chance to get our first page.
753 : : */
754 : : static pg_noinline BlockNumber
1188 755 : 1316463 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
756 : : {
757 [ - + ]: 1316463 : Assert(!scan->rs_inited);
757 tmunro@postgresql.or 758 [ - + ]: 1316463 : Assert(scan->rs_base.rs_parallel == NULL);
759 : :
760 : : /* When there are no pages to scan, return InvalidBlockNumber */
1188 drowley@postgresql.o 761 [ + + + + ]: 1316463 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
762 : 767116 : return InvalidBlockNumber;
763 : :
764 [ + + ]: 549347 : if (ScanDirectionIsForward(dir))
765 : : {
757 tmunro@postgresql.or 766 : 549306 : return scan->rs_startblock;
767 : : }
768 : : else
769 : : {
770 : : /*
771 : : * Disable reporting to syncscan logic in a backwards scan; it's not
772 : : * very likely anyone else is doing the same thing at the same time,
773 : : * and much more likely that we'll just bollix things for forward
774 : : * scanners.
775 : : */
1188 drowley@postgresql.o 776 : 41 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
777 : :
778 : : /*
779 : : * Start from last page of the scan. Ensure we take into account
780 : : * rs_numblocks if it's been adjusted by heap_setscanlimits().
781 : : */
782 [ + + ]: 41 : if (scan->rs_numblocks != InvalidBlockNumber)
783 : 4 : return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
784 : :
785 [ - + ]: 37 : if (scan->rs_startblock > 0)
1188 drowley@postgresql.o 786 :UBC 0 : return scan->rs_startblock - 1;
787 : :
1188 drowley@postgresql.o 788 :CBC 37 : return scan->rs_nblocks - 1;
789 : : }
790 : : }
791 : :
792 : :
793 : : /*
794 : : * heapgettup_start_page - helper function for heapgettup()
795 : : *
796 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
797 : : * to the number of tuples on this page. Also set *lineoff to the first
798 : : * offset to scan with forward scans getting the first offset and backward
799 : : * getting the final offset on the page.
800 : : */
801 : : static Page
1187 802 : 117051 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
803 : : OffsetNumber *lineoff)
804 : : {
805 : : Page page;
806 : :
807 [ - + ]: 117051 : Assert(scan->rs_inited);
808 [ - + ]: 117051 : Assert(BufferIsValid(scan->rs_cbuf));
809 : :
810 : : /* Caller is responsible for ensuring buffer is locked if needed */
811 : 117051 : page = BufferGetPage(scan->rs_cbuf);
812 : :
1183 813 : 117051 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
814 : :
1187 815 [ + - ]: 117051 : if (ScanDirectionIsForward(dir))
816 : 117051 : *lineoff = FirstOffsetNumber;
817 : : else
1187 drowley@postgresql.o 818 :UBC 0 : *lineoff = (OffsetNumber) (*linesleft);
819 : :
820 : : /* lineoff now references the physically previous or next tid */
1187 drowley@postgresql.o 821 :CBC 117051 : return page;
822 : : }
823 : :
824 : :
825 : : /*
826 : : * heapgettup_continue_page - helper function for heapgettup()
827 : : *
828 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
829 : : * to the number of tuples left to scan on this page. Also set *lineoff to
830 : : * the next offset to scan according to the ScanDirection in 'dir'.
831 : : */
832 : : static inline Page
833 : 9423905 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
834 : : OffsetNumber *lineoff)
835 : : {
836 : : Page page;
837 : :
838 [ - + ]: 9423905 : Assert(scan->rs_inited);
839 [ - + ]: 9423905 : Assert(BufferIsValid(scan->rs_cbuf));
840 : :
841 : : /* Caller is responsible for ensuring buffer is locked if needed */
842 : 9423905 : page = BufferGetPage(scan->rs_cbuf);
843 : :
844 [ + - ]: 9423905 : if (ScanDirectionIsForward(dir))
845 : : {
846 : 9423905 : *lineoff = OffsetNumberNext(scan->rs_coffset);
847 : 9423905 : *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
848 : : }
849 : : else
850 : : {
851 : : /*
852 : : * The previous returned tuple may have been vacuumed since the
853 : : * previous scan when we use a non-MVCC snapshot, so we must
854 : : * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
855 : : */
1187 drowley@postgresql.o 856 [ # # ]:UBC 0 : *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
857 : 0 : *linesleft = *lineoff;
858 : : }
859 : :
860 : : /* lineoff now references the physically previous or next tid */
1187 drowley@postgresql.o 861 :CBC 9423905 : return page;
862 : : }
863 : :
864 : : /*
865 : : * heapgettup_advance_block - helper for heap_fetch_next_buffer()
866 : : *
867 : : * Given the current block number, the scan direction, and various information
868 : : * contained in the scan descriptor, calculate the BlockNumber to scan next
869 : : * and return it. If there are no further blocks to scan, return
870 : : * InvalidBlockNumber to indicate this fact to the caller.
871 : : *
872 : : * This should not be called to determine the initial block number -- only for
873 : : * subsequent blocks.
874 : : *
875 : : * This also adjusts rs_numblocks when a limit has been imposed by
876 : : * heap_setscanlimits().
877 : : */
878 : : static inline BlockNumber
879 : 3416095 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
880 : : {
757 tmunro@postgresql.or 881 [ - + ]: 3416095 : Assert(scan->rs_base.rs_parallel == NULL);
882 : :
883 [ + + ]: 3416095 : if (likely(ScanDirectionIsForward(dir)))
884 : : {
885 : 3416018 : block++;
886 : :
887 : : /* wrap back to the start of the heap */
888 [ + + ]: 3416018 : if (block >= scan->rs_nblocks)
889 : 427633 : block = 0;
890 : :
891 : : /*
892 : : * Report our new scan position for synchronization purposes. We don't
893 : : * do that when moving backwards, however. That would just mess up any
894 : : * other forward-moving scanners.
895 : : *
896 : : * Note: we do this before checking for end of scan so that the final
897 : : * state of the position hint is back at the start of the rel. That's
898 : : * not strictly necessary, but otherwise when you run the same query
899 : : * multiple times the starting position would shift a little bit
900 : : * backwards on every invocation, which is confusing. We don't
901 : : * guarantee any specific ordering in general, though.
902 : : */
903 [ + + ]: 3416018 : if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
904 : 38364 : ss_report_location(scan->rs_base.rs_rd, block);
905 : :
906 : : /* we're done if we're back at where we started */
907 [ + + ]: 3416018 : if (block == scan->rs_startblock)
908 : 427583 : return InvalidBlockNumber;
909 : :
910 : : /* check if the limit imposed by heap_setscanlimits() is met */
911 [ + + ]: 2988435 : if (scan->rs_numblocks != InvalidBlockNumber)
912 : : {
913 [ + + ]: 2826 : if (--scan->rs_numblocks == 0)
914 : 1596 : return InvalidBlockNumber;
915 : : }
916 : :
917 : 2986839 : return block;
918 : : }
919 : : else
920 : : {
921 : : /* we're done if the last block is the start position */
1187 drowley@postgresql.o 922 [ + - ]: 77 : if (block == scan->rs_startblock)
923 : 77 : return InvalidBlockNumber;
924 : :
925 : : /* check if the limit imposed by heap_setscanlimits() is met */
1187 drowley@postgresql.o 926 [ # # ]:UBC 0 : if (scan->rs_numblocks != InvalidBlockNumber)
927 : : {
928 [ # # ]: 0 : if (--scan->rs_numblocks == 0)
929 : 0 : return InvalidBlockNumber;
930 : : }
931 : :
932 : : /* wrap to the end of the heap when the last page was page 0 */
933 [ # # ]: 0 : if (block == 0)
934 : 0 : block = scan->rs_nblocks;
935 : :
936 : 0 : block--;
937 : :
938 : 0 : return block;
939 : : }
940 : : }
941 : :
942 : : /* ----------------
943 : : * heapgettup - fetch next heap tuple
944 : : *
945 : : * Initialize the scan if not already done; then advance to the next
946 : : * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
947 : : * or set scan->rs_ctup.t_data = NULL if no more tuples.
948 : : *
949 : : * Note: the reason nkeys/key are passed separately, even though they are
950 : : * kept in the scan descriptor, is that the caller may not want us to check
951 : : * the scankeys.
952 : : *
953 : : * Note: when we fall off the end of the scan in either direction, we
954 : : * reset rs_inited. This means that a further request with the same
955 : : * scan direction will restart the scan, which is a bit odd, but a
956 : : * request with the opposite scan direction will start a fresh scan
957 : : * in the proper direction. The latter is required behavior for cursors,
958 : : * while the former case is generally undefined behavior in Postgres
959 : : * so we don't care too much.
960 : : * ----------------
961 : : */
962 : : static void
7465 tgl@sss.pgh.pa.us 963 :CBC 9450878 : heapgettup(HeapScanDesc scan,
964 : : ScanDirection dir,
965 : : int nkeys,
966 : : ScanKey key)
967 : : {
968 : 9450878 : HeapTuple tuple = &(scan->rs_ctup);
969 : : Page page;
970 : : OffsetNumber lineoff;
971 : : int linesleft;
972 : :
761 drowley@postgresql.o 973 [ + + ]: 9450878 : if (likely(scan->rs_inited))
974 : : {
975 : : /* continue from previously returned page/tuple */
1187 976 : 9423905 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
977 : 9423905 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
1183 978 : 9423905 : goto continue_page;
979 : : }
980 : :
981 : : /*
982 : : * advance the scan until we find a qualifying tuple or run out of stuff
983 : : * to scan
984 : : */
985 : : while (true)
986 : : {
761 987 : 143164 : heap_fetch_next_buffer(scan, dir);
988 : :
989 : : /* did we run out of blocks to scan? */
990 [ + + ]: 143164 : if (!BufferIsValid(scan->rs_cbuf))
991 : 26113 : break;
992 : :
993 [ - + ]: 117051 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
994 : :
1183 995 : 117051 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
996 : 117051 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
997 : 9540956 : continue_page:
998 : :
999 : : /*
1000 : : * Only continue scanning the page while we have lines left.
1001 : : *
1002 : : * Note that this protects us from accessing line pointers past
1003 : : * PageGetMaxOffsetNumber(); both for forward scans when we resume the
1004 : : * table scan, and for when we start scanning a new page.
1005 : : */
1006 [ + + ]: 9597335 : for (; linesleft > 0; linesleft--, lineoff += dir)
1007 : : {
1008 : : bool visible;
1009 : 9481144 : ItemId lpp = PageGetItemId(page, lineoff);
1010 : :
1011 [ + + ]: 9481144 : if (!ItemIdIsNormal(lpp))
1012 : 34606 : continue;
1013 : :
1014 : 9446538 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1015 : 9446538 : tuple->t_len = ItemIdGetLength(lpp);
761 1016 : 9446538 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1017 : :
1183 1018 : 9446538 : visible = HeapTupleSatisfiesVisibility(tuple,
1019 : : scan->rs_base.rs_snapshot,
1020 : : scan->rs_cbuf);
1021 : :
1022 : 9446538 : HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
1023 : : tuple, scan->rs_cbuf,
1024 : : scan->rs_base.rs_snapshot);
1025 : :
1026 : : /* skip tuples not visible to this snapshot */
1027 [ + + ]: 9446538 : if (!visible)
1028 : 7512 : continue;
1029 : :
1030 : : /* skip any tuples that don't match the scan key */
1031 [ + + ]: 9439026 : if (key != NULL &&
1183 drowley@postgresql.o 1032 [ + + ]:GBC 14970 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1033 : : nkeys, key))
1034 : 14261 : continue;
1035 : :
1183 drowley@postgresql.o 1036 :CBC 9424765 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1037 : 9424765 : scan->rs_coffset = lineoff;
1038 : 9424765 : return;
1039 : : }
1040 : :
1041 : : /*
1042 : : * if we get here, it means we've exhausted the items on this page and
1043 : : * it's time to move to the next.
1044 : : */
7465 tgl@sss.pgh.pa.us 1045 : 116191 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1046 : : }
1047 : :
1048 : : /* end of scan */
1183 drowley@postgresql.o 1049 [ - + ]: 26113 : if (BufferIsValid(scan->rs_cbuf))
1183 drowley@postgresql.o 1050 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1051 : :
1183 drowley@postgresql.o 1052 :CBC 26113 : scan->rs_cbuf = InvalidBuffer;
1053 : 26113 : scan->rs_cblock = InvalidBlockNumber;
757 tmunro@postgresql.or 1054 : 26113 : scan->rs_prefetch_block = InvalidBlockNumber;
1183 drowley@postgresql.o 1055 : 26113 : tuple->t_data = NULL;
1056 : 26113 : scan->rs_inited = false;
1057 : : }
1058 : :
1059 : : /* ----------------
1060 : : * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
1061 : : *
1062 : : * Same API as heapgettup, but used in page-at-a-time mode
1063 : : *
1064 : : * The internal logic is much the same as heapgettup's too, but there are some
1065 : : * differences: we do not take the buffer content lock (that only needs to
1066 : : * happen inside heap_prepare_pagescan), and we iterate through just the
1067 : : * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
1068 : : * that lineindex is 0-based, where the corresponding loop variable lineoff in
1069 : : * heapgettup is 1-based.
1070 : : * ----------------
1071 : : */
1072 : : static void
7465 tgl@sss.pgh.pa.us 1073 : 69605055 : heapgettup_pagemode(HeapScanDesc scan,
1074 : : ScanDirection dir,
1075 : : int nkeys,
1076 : : ScanKey key)
1077 : : {
1078 : 69605055 : HeapTuple tuple = &(scan->rs_ctup);
1079 : : Page page;
1080 : : uint32 lineindex;
1081 : : uint32 linesleft;
1082 : :
761 drowley@postgresql.o 1083 [ + + ]: 69605055 : if (likely(scan->rs_inited))
1084 : : {
1085 : : /* continue from previously returned page/tuple */
1187 1086 : 68312722 : page = BufferGetPage(scan->rs_cbuf);
1087 : :
1088 : 68312722 : lineindex = scan->rs_cindex + dir;
1089 [ + + ]: 68312722 : if (ScanDirectionIsForward(dir))
1090 : 68312285 : linesleft = scan->rs_ntuples - lineindex;
1091 : : else
1092 : 437 : linesleft = scan->rs_cindex;
1093 : : /* lineindex now references the next or previous visible tid */
1094 : :
1183 1095 : 68312722 : goto continue_page;
1096 : : }
1097 : :
1098 : : /*
1099 : : * advance the scan until we find a qualifying tuple or run out of stuff
1100 : : * to scan
1101 : : */
1102 : : while (true)
1103 : : {
761 1104 : 4526192 : heap_fetch_next_buffer(scan, dir);
1105 : :
1106 : : /* did we run out of blocks to scan? */
1107 [ + + ]: 4526151 : if (!BufferIsValid(scan->rs_cbuf))
1108 : 1099325 : break;
1109 : :
1110 [ - + ]: 3426826 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1111 : :
1112 : : /* prune the page and determine visible tuple offsets */
1113 : 3426826 : heap_prepare_pagescan((TableScanDesc) scan);
1183 1114 : 3426818 : page = BufferGetPage(scan->rs_cbuf);
1115 : 3426818 : linesleft = scan->rs_ntuples;
1116 [ + + ]: 3426818 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1117 : :
1118 : : /* block is the same for all tuples, set it once outside the loop */
399 heikki.linnakangas@i 1119 : 3426818 : ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1120 : :
1121 : : /* lineindex now references the next or previous visible tid */
1183 drowley@postgresql.o 1122 : 71739540 : continue_page:
1123 : :
1124 [ + + ]: 132872031 : for (; linesleft > 0; linesleft--, lineindex += dir)
1125 : : {
1126 : : ItemId lpp;
1127 : : OffsetNumber lineoff;
1128 : :
120 heikki.linnakangas@i 1129 [ - + ]: 129638172 : Assert(lineindex < scan->rs_ntuples);
7465 tgl@sss.pgh.pa.us 1130 : 129638172 : lineoff = scan->rs_vistuples[lineindex];
1266 peter@eisentraut.org 1131 : 129638172 : lpp = PageGetItemId(page, lineoff);
6810 tgl@sss.pgh.pa.us 1132 [ - + ]: 129638172 : Assert(ItemIdIsNormal(lpp));
1133 : :
1266 peter@eisentraut.org 1134 : 129638172 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
7465 tgl@sss.pgh.pa.us 1135 : 129638172 : tuple->t_len = ItemIdGetLength(lpp);
399 heikki.linnakangas@i 1136 : 129638172 : ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1137 : :
1138 : : /* skip any tuples that don't match the scan key */
1183 drowley@postgresql.o 1139 [ + + ]: 129638172 : if (key != NULL &&
1140 [ + + ]: 61511530 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1141 : : nkeys, key))
1142 : 61132491 : continue;
1143 : :
1144 : 68505681 : scan->rs_cindex = lineindex;
1145 : 68505681 : return;
1146 : : }
1147 : : }
1148 : :
1149 : : /* end of scan */
1150 [ - + ]: 1099325 : if (BufferIsValid(scan->rs_cbuf))
1183 drowley@postgresql.o 1151 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1183 drowley@postgresql.o 1152 :CBC 1099325 : scan->rs_cbuf = InvalidBuffer;
1153 : 1099325 : scan->rs_cblock = InvalidBlockNumber;
757 tmunro@postgresql.or 1154 : 1099325 : scan->rs_prefetch_block = InvalidBlockNumber;
1183 drowley@postgresql.o 1155 : 1099325 : tuple->t_data = NULL;
1156 : 1099325 : scan->rs_inited = false;
1157 : : }
1158 : :
1159 : :
1160 : : /* ----------------------------------------------------------------
1161 : : * heap access method interface
1162 : : * ----------------------------------------------------------------
1163 : : */
1164 : :
1165 : :
1166 : : TableScanDesc
8751 tgl@sss.pgh.pa.us 1167 : 478707 : heap_beginscan(Relation relation, Snapshot snapshot,
1168 : : int nkeys, ScanKey key,
1169 : : ParallelTableScanDesc parallel_scan,
1170 : : uint32 flags)
1171 : : {
1172 : : HeapScanDesc scan;
1173 : :
1174 : : /*
1175 : : * increment relation ref count while scanning relation
1176 : : *
1177 : : * This is just to make really sure the relcache entry won't go away while
1178 : : * the scan has a pointer to it. Caller should be holding the rel open
1179 : : * anyway, so this is redundant in all normal scenarios...
1180 : : */
9309 1181 : 478707 : RelationIncrementReferenceCount(relation);
1182 : :
1183 : : /*
1184 : : * allocate and initialize scan descriptor
1185 : : */
474 melanieplageman@gmai 1186 [ + + ]: 478707 : if (flags & SO_TYPE_BITMAPSCAN)
1187 : : {
146 michael@paquier.xyz 1188 :GNC 12763 : BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
1189 : :
1190 : : /*
1191 : : * Bitmap Heap scans do not have any fields that a normal Heap Scan
1192 : : * does not have, so no special initializations required here.
1193 : : */
474 melanieplageman@gmai 1194 :CBC 12763 : scan = (HeapScanDesc) bscan;
1195 : : }
1196 : : else
146 michael@paquier.xyz 1197 :GNC 465944 : scan = (HeapScanDesc) palloc_object(HeapScanDescData);
1198 : :
2612 andres@anarazel.de 1199 :CBC 478707 : scan->rs_base.rs_rd = relation;
1200 : 478707 : scan->rs_base.rs_snapshot = snapshot;
1201 : 478707 : scan->rs_base.rs_nkeys = nkeys;
2543 1202 : 478707 : scan->rs_base.rs_flags = flags;
2612 1203 : 478707 : scan->rs_base.rs_parallel = parallel_scan;
28 tomas.vondra@postgre 1204 :GNC 478707 : scan->rs_base.rs_instrument = NULL;
2543 andres@anarazel.de 1205 :CBC 478707 : scan->rs_strategy = NULL; /* set in initscan */
416 melanieplageman@gmai 1206 : 478707 : scan->rs_cbuf = InvalidBuffer;
1207 : :
1208 : : /*
1209 : : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1210 : : */
2543 andres@anarazel.de 1211 [ + + + + : 478707 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
+ + ]
1212 : 38173 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1213 : :
1214 : : /* Check that a historic snapshot is not used for non-catalog tables */
256 heikki.linnakangas@i 1215 [ + + ]:GNC 478707 : if (snapshot &&
1216 [ + + ]: 467507 : IsHistoricMVCCSnapshot(snapshot) &&
1217 [ - + - - : 709 : !RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - - +
- - - - -
- - - -
- ]
1218 : : {
256 heikki.linnakangas@i 1219 [ # # ]:UNC 0 : ereport(ERROR,
1220 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1221 : : errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1222 : : RelationGetRelationName(relation))));
1223 : : }
1224 : :
1225 : : /*
1226 : : * For seqscan and sample scans in a serializable transaction, acquire a
1227 : : * predicate lock on the entire relation. This is required not only to
1228 : : * lock all the matching tuples, but also to conflict with new insertions
1229 : : * into the table. In an indexscan, we take page locks on the index pages
1230 : : * covering the range specified in the scan qual, but in a heap scan there
1231 : : * is nothing more fine-grained to lock. A bitmap scan is a different
1232 : : * story, there we have already scanned the index and locked the index
1233 : : * pages covering the predicate. But in that case we still have to lock
1234 : : * any matching heap tuples. For sample scan we could optimize the locking
1235 : : * to be at least page-level granularity, but we'd need to add per-tuple
1236 : : * locking for that.
1237 : : */
2543 andres@anarazel.de 1238 [ + + ]:CBC 478707 : if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
1239 : : {
1240 : : /*
1241 : : * Ensure a missing snapshot is noticed reliably, even if the
1242 : : * isolation mode means predicate locking isn't performed (and
1243 : : * therefore the snapshot isn't used here).
1244 : : */
1245 [ - + ]: 452939 : Assert(snapshot);
5424 heikki.linnakangas@i 1246 : 452939 : PredicateLockRelation(relation, snapshot);
1247 : : }
1248 : :
1249 : : /* we only need to set this up once */
7465 tgl@sss.pgh.pa.us 1250 : 478707 : scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1251 : :
1252 : : /*
1253 : : * Allocate memory to keep track of page allocation for parallel workers
1254 : : * when doing a parallel scan.
1255 : : */
1862 drowley@postgresql.o 1256 [ + + ]: 478707 : if (parallel_scan != NULL)
146 michael@paquier.xyz 1257 :GNC 4525 : scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
1258 : : else
1862 drowley@postgresql.o 1259 :CBC 474182 : scan->rs_parallelworkerdata = NULL;
1260 : :
1261 : : /*
1262 : : * we do this here instead of in initscan() because heap_rescan also calls
1263 : : * initscan() and we don't want to allocate memory again
1264 : : */
8751 tgl@sss.pgh.pa.us 1265 [ + + ]: 478707 : if (nkeys > 0)
146 michael@paquier.xyz 1266 :GNC 264248 : scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
1267 : : else
2612 andres@anarazel.de 1268 :CBC 214459 : scan->rs_base.rs_key = NULL;
1269 : :
6173 tgl@sss.pgh.pa.us 1270 : 478707 : initscan(scan, key, false);
1271 : :
757 tmunro@postgresql.or 1272 : 478705 : scan->rs_read_stream = NULL;
1273 : :
1274 : : /*
1275 : : * Set up a read stream for sequential scans and TID range scans. This
1276 : : * should be done after initscan() because initscan() allocates the
1277 : : * BufferAccessStrategy object passed to the read stream API.
1278 : : */
1279 [ + + ]: 478705 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1280 [ + + ]: 25862 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
1281 : 454158 : {
1282 : : ReadStreamBlockNumberCB cb;
1283 : :
1284 [ + + ]: 454158 : if (scan->rs_base.rs_parallel)
1285 : 4525 : cb = heap_scan_stream_read_next_parallel;
1286 : : else
1287 : 449633 : cb = heap_scan_stream_read_next_serial;
1288 : :
1289 : : /* ---
1290 : : * It is safe to use batchmode as the only locks taken by `cb`
1291 : : * are never taken while waiting for IO:
1292 : : * - SyncScanLock is used in the non-parallel case
1293 : : * - in the parallel case, only spinlocks and atomics are used
1294 : : * ---
1295 : : */
401 andres@anarazel.de 1296 : 454158 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
1297 : : READ_STREAM_USE_BATCHING,
1298 : : scan->rs_strategy,
1299 : : scan->rs_base.rs_rd,
1300 : : MAIN_FORKNUM,
1301 : : cb,
1302 : : scan,
1303 : : 0);
1304 : : }
416 melanieplageman@gmai 1305 [ + + ]: 24547 : else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1306 : : {
397 1307 : 12763 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
1308 : : READ_STREAM_USE_BATCHING,
1309 : : scan->rs_strategy,
1310 : : scan->rs_base.rs_rd,
1311 : : MAIN_FORKNUM,
1312 : : bitmapheap_stream_read_next,
1313 : : scan,
1314 : : sizeof(TBMIterateResult));
1315 : : }
1316 : :
1317 : : /* enable read stream instrumentation */
28 tomas.vondra@postgre 1318 [ + + + - ]:GNC 478705 : if ((flags & SO_SCAN_INSTRUMENT) && (scan->rs_read_stream != NULL))
1319 : : {
1320 : 8 : scan->rs_base.rs_instrument = palloc0_object(TableScanInstrumentation);
1321 : 8 : read_stream_enable_stats(scan->rs_read_stream,
1322 : 8 : &scan->rs_base.rs_instrument->io);
1323 : : }
1324 : :
51 melanieplageman@gmai 1325 : 478705 : scan->rs_vmbuffer = InvalidBuffer;
1326 : :
2612 andres@anarazel.de 1327 :CBC 478705 : return (TableScanDesc) scan;
1328 : : }
1329 : :
1330 : : void
1331 : 869428 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1332 : : bool allow_strat, bool allow_sync, bool allow_pagemode)
1333 : : {
1334 : 869428 : HeapScanDesc scan = (HeapScanDesc) sscan;
1335 : :
1336 [ + + ]: 869428 : if (set_params)
1337 : : {
2543 1338 [ + - ]: 19 : if (allow_strat)
1339 : 19 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1340 : : else
2543 andres@anarazel.de 1341 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1342 : :
2543 andres@anarazel.de 1343 [ + + ]:CBC 19 : if (allow_sync)
1344 : 8 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1345 : : else
1346 : 11 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1347 : :
1348 [ + - + - ]: 19 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1349 [ + - - - ]: 19 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1350 : 19 : scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
1351 : : else
2543 andres@anarazel.de 1352 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1353 : : }
1354 : :
1355 : : /*
1356 : : * unpin scan buffers
1357 : : */
9096 tgl@sss.pgh.pa.us 1358 [ + + ]:CBC 869428 : if (BufferIsValid(scan->rs_cbuf))
1359 : : {
1360 : 3180 : ReleaseBuffer(scan->rs_cbuf);
416 melanieplageman@gmai 1361 : 3180 : scan->rs_cbuf = InvalidBuffer;
1362 : : }
1363 : :
51 melanieplageman@gmai 1364 [ + + ]:GNC 869428 : if (BufferIsValid(scan->rs_vmbuffer))
1365 : : {
1366 : 19 : ReleaseBuffer(scan->rs_vmbuffer);
1367 : 19 : scan->rs_vmbuffer = InvalidBuffer;
1368 : : }
1369 : :
1370 : : /*
1371 : : * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1372 : : * additional data vs a normal HeapScan
1373 : : */
1374 : :
1375 : : /*
1376 : : * The read stream is reset on rescan. This must be done before
1377 : : * initscan(), as some state referred to by read_stream_reset() is reset
1378 : : * in initscan().
1379 : : */
757 tmunro@postgresql.or 1380 [ + + ]:CBC 869428 : if (scan->rs_read_stream)
1381 : 869405 : read_stream_reset(scan->rs_read_stream);
1382 : :
1383 : : /*
1384 : : * reinitialize scan descriptor
1385 : : */
6173 tgl@sss.pgh.pa.us 1386 : 869428 : initscan(scan, key, true);
10892 scrappy@hub.org 1387 : 869428 : }
1388 : :
1389 : : void
2612 andres@anarazel.de 1390 : 475405 : heap_endscan(TableScanDesc sscan)
1391 : : {
1392 : 475405 : HeapScanDesc scan = (HeapScanDesc) sscan;
1393 : :
1394 : : /* Note: no locking manipulations needed */
1395 : :
1396 : : /*
1397 : : * unpin scan buffers
1398 : : */
9096 tgl@sss.pgh.pa.us 1399 [ + + ]: 475405 : if (BufferIsValid(scan->rs_cbuf))
1400 : 188411 : ReleaseBuffer(scan->rs_cbuf);
1401 : :
51 melanieplageman@gmai 1402 [ + + ]:GNC 475405 : if (BufferIsValid(scan->rs_vmbuffer))
1403 : 2855 : ReleaseBuffer(scan->rs_vmbuffer);
1404 : :
1405 : : /*
1406 : : * Must free the read stream before freeing the BufferAccessStrategy.
1407 : : */
757 tmunro@postgresql.or 1408 [ + + ]:CBC 475405 : if (scan->rs_read_stream)
1409 : 463692 : read_stream_end(scan->rs_read_stream);
1410 : :
1411 : : /*
1412 : : * decrement relation reference count and free scan descriptor storage
1413 : : */
2612 andres@anarazel.de 1414 : 475405 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1415 : :
1416 [ + + ]: 475405 : if (scan->rs_base.rs_key)
1417 : 264208 : pfree(scan->rs_base.rs_key);
1418 : :
6915 tgl@sss.pgh.pa.us 1419 [ + + ]: 475405 : if (scan->rs_strategy != NULL)
1420 : 14880 : FreeAccessStrategy(scan->rs_strategy);
1421 : :
1862 drowley@postgresql.o 1422 [ + + ]: 475405 : if (scan->rs_parallelworkerdata != NULL)
1423 : 4525 : pfree(scan->rs_parallelworkerdata);
1424 : :
2543 andres@anarazel.de 1425 [ + + ]: 475405 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
2612 1426 : 45420 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1427 : :
28 tomas.vondra@postgre 1428 [ + + ]:GNC 475405 : if (scan->rs_base.rs_instrument)
1429 : 8 : pfree(scan->rs_base.rs_instrument);
1430 : :
9726 tgl@sss.pgh.pa.us 1431 :CBC 475405 : pfree(scan);
10892 scrappy@hub.org 1432 : 475405 : }
1433 : :
1434 : : HeapTuple
2612 andres@anarazel.de 1435 : 11777944 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1436 : : {
1437 : 11777944 : HeapScanDesc scan = (HeapScanDesc) sscan;
1438 : :
1439 : : /*
1440 : : * This is still widely used directly, without going through table AM, so
1441 : : * add a safety check. It's possible we should, at a later point,
1442 : : * downgrade this to an assert. The reason for checking the AM routine,
1443 : : * rather than the AM oid, is that this allows to write regression tests
1444 : : * that create another AM reusing the heap handler.
1445 : : */
1446 [ - + ]: 11777944 : if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
2612 andres@anarazel.de 1447 [ # # ]:UBC 0 : ereport(ERROR,
1448 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1449 : : errmsg_internal("only heap AM is supported")));
1450 : :
1451 : : /* Note: no locking manipulations needed */
1452 : :
2543 andres@anarazel.de 1453 [ + + ]:CBC 11777944 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
7378 neilc@samurai.com 1454 : 2916747 : heapgettup_pagemode(scan, direction,
2612 andres@anarazel.de 1455 : 2916747 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1456 : : else
1457 : 8861197 : heapgettup(scan, direction,
1458 : 8861197 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1459 : :
7465 tgl@sss.pgh.pa.us 1460 [ + + ]: 11777944 : if (scan->rs_ctup.t_data == NULL)
8751 1461 : 76708 : return NULL;
1462 : :
1463 : : /*
1464 : : * if we get here it means we have a new current scan tuple, so point to
1465 : : * the proper return buffer and return the tuple.
1466 : : */
1467 : :
2612 andres@anarazel.de 1468 [ - + - - : 11701236 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - ]
1469 : :
1470 : 11701236 : return &scan->rs_ctup;
1471 : : }
1472 : :
1473 : : bool
1474 : 67271126 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1475 : : {
1476 : 67271126 : HeapScanDesc scan = (HeapScanDesc) sscan;
1477 : :
1478 : : /* Note: no locking manipulations needed */
1479 : :
2543 1480 [ + + ]: 67271126 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1481 : 66681445 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1482 : : else
1483 : 589681 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1484 : :
2612 1485 [ + + ]: 67271088 : if (scan->rs_ctup.t_data == NULL)
1486 : : {
1487 : 1048592 : ExecClearTuple(slot);
1488 : 1048592 : return false;
1489 : : }
1490 : :
1491 : : /*
1492 : : * if we get here it means we have a new current scan tuple, so point to
1493 : : * the proper return buffer and return the tuple.
1494 : : */
1495 : :
1496 [ + + - + : 66222496 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ + ]
1497 : :
1498 : 66222496 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1499 : : scan->rs_cbuf);
1500 : 66222496 : return true;
1501 : : }
1502 : :
1503 : : void
1893 drowley@postgresql.o 1504 : 1375 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
1505 : : ItemPointer maxtid)
1506 : : {
1507 : 1375 : HeapScanDesc scan = (HeapScanDesc) sscan;
1508 : : BlockNumber startBlk;
1509 : : BlockNumber numBlks;
1510 : : ItemPointerData highestItem;
1511 : : ItemPointerData lowestItem;
1512 : :
1513 : : /*
1514 : : * For relations without any pages, we can simply leave the TID range
1515 : : * unset. There will be no tuples to scan, therefore no tuples outside
1516 : : * the given TID range.
1517 : : */
1518 [ + + ]: 1375 : if (scan->rs_nblocks == 0)
1519 : 32 : return;
1520 : :
1521 : : /*
1522 : : * Set up some ItemPointers which point to the first and last possible
1523 : : * tuples in the heap.
1524 : : */
1525 : 1367 : ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1526 : 1367 : ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1527 : :
1528 : : /*
1529 : : * If the given maximum TID is below the highest possible TID in the
1530 : : * relation, then restrict the range to that, otherwise we scan to the end
1531 : : * of the relation.
1532 : : */
1533 [ + + ]: 1367 : if (ItemPointerCompare(maxtid, &highestItem) < 0)
1534 : 173 : ItemPointerCopy(maxtid, &highestItem);
1535 : :
1536 : : /*
1537 : : * If the given minimum TID is above the lowest possible TID in the
1538 : : * relation, then restrict the range to only scan for TIDs above that.
1539 : : */
1540 [ + + ]: 1367 : if (ItemPointerCompare(mintid, &lowestItem) > 0)
1541 : 1210 : ItemPointerCopy(mintid, &lowestItem);
1542 : :
1543 : : /*
1544 : : * Check for an empty range and protect from would be negative results
1545 : : * from the numBlks calculation below.
1546 : : */
1547 [ + + ]: 1367 : if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1548 : : {
1549 : : /* Set an empty range of blocks to scan */
1550 : 24 : heap_setscanlimits(sscan, 0, 0);
1551 : 24 : return;
1552 : : }
1553 : :
1554 : : /*
1555 : : * Calculate the first block and the number of blocks we must scan. We
1556 : : * could be more aggressive here and perform some more validation to try
1557 : : * and further narrow the scope of blocks to scan by checking if the
1558 : : * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1559 : : * advance startBlk by one. Likewise, if highestItem has an offset of 0
1560 : : * we could scan one fewer blocks. However, such an optimization does not
1561 : : * seem worth troubling over, currently.
1562 : : */
1563 : 1343 : startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1564 : :
1565 : 1343 : numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1566 : 1343 : ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1567 : :
1568 : : /* Set the start block and number of blocks to scan */
1569 : 1343 : heap_setscanlimits(sscan, startBlk, numBlks);
1570 : :
1571 : : /* Finally, set the TID range in sscan */
557 melanieplageman@gmai 1572 : 1343 : ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1573 : 1343 : ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1574 : : }
1575 : :
1576 : : bool
1893 drowley@postgresql.o 1577 : 6739 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1578 : : TupleTableSlot *slot)
1579 : : {
1580 : 6739 : HeapScanDesc scan = (HeapScanDesc) sscan;
557 melanieplageman@gmai 1581 : 6739 : ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
1582 : 6739 : ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
1583 : :
1584 : : /* Note: no locking manipulations needed */
1585 : : for (;;)
1586 : : {
1893 drowley@postgresql.o 1587 [ + - ]: 6863 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1588 : 6863 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1589 : : else
1893 drowley@postgresql.o 1590 :UBC 0 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1591 : :
1893 drowley@postgresql.o 1592 [ + + ]:CBC 6852 : if (scan->rs_ctup.t_data == NULL)
1593 : : {
1594 : 138 : ExecClearTuple(slot);
1595 : 138 : return false;
1596 : : }
1597 : :
1598 : : /*
1599 : : * heap_set_tidrange will have used heap_setscanlimits to limit the
1600 : : * range of pages we scan to only ones that can contain the TID range
1601 : : * we're scanning for. Here we must filter out any tuples from these
1602 : : * pages that are outside of that range.
1603 : : */
1604 [ + + ]: 6714 : if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1605 : : {
1606 : 124 : ExecClearTuple(slot);
1607 : :
1608 : : /*
1609 : : * When scanning backwards, the TIDs will be in descending order.
1610 : : * Future tuples in this direction will be lower still, so we can
1611 : : * just return false to indicate there will be no more tuples.
1612 : : */
1613 [ - + ]: 124 : if (ScanDirectionIsBackward(direction))
1893 drowley@postgresql.o 1614 :UBC 0 : return false;
1615 : :
1893 drowley@postgresql.o 1616 :CBC 124 : continue;
1617 : : }
1618 : :
1619 : : /*
1620 : : * Likewise for the final page, we must filter out TIDs greater than
1621 : : * maxtid.
1622 : : */
1623 [ + + ]: 6590 : if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1624 : : {
1625 : 74 : ExecClearTuple(slot);
1626 : :
1627 : : /*
1628 : : * When scanning forward, the TIDs will be in ascending order.
1629 : : * Future tuples in this direction will be higher still, so we can
1630 : : * just return false to indicate there will be no more tuples.
1631 : : */
1632 [ + - ]: 74 : if (ScanDirectionIsForward(direction))
1633 : 74 : return false;
1893 drowley@postgresql.o 1634 :UBC 0 : continue;
1635 : : }
1636 : :
1893 drowley@postgresql.o 1637 :CBC 6516 : break;
1638 : : }
1639 : :
1640 : : /*
1641 : : * if we get here it means we have a new current scan tuple, so point to
1642 : : * the proper return buffer and return the tuple.
1643 : : */
1644 [ - + - - : 6516 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - ]
1645 : :
1646 : 6516 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1647 : 6516 : return true;
1648 : : }
1649 : :
1650 : : /*
1651 : : * heap_fetch - retrieve tuple with given tid
1652 : : *
1653 : : * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1654 : : * the tuple, fill in the remaining fields of *tuple, and check the tuple
1655 : : * against the specified snapshot.
1656 : : *
1657 : : * If successful (tuple found and passes snapshot time qual), then *userbuf
1658 : : * is set to the buffer holding the tuple and true is returned. The caller
1659 : : * must unpin the buffer when done with the tuple.
1660 : : *
1661 : : * If the tuple is not found (ie, item number references a deleted slot),
1662 : : * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1663 : : * and false is returned.
1664 : : *
1665 : : * If the tuple is found but fails the time qual check, then the behavior
1666 : : * depends on the keep_buf parameter. If keep_buf is false, the results
1667 : : * are the same as for the tuple-not-found case. If keep_buf is true,
1668 : : * then tuple->t_data and *userbuf are returned as for the success case,
1669 : : * and again the caller must unpin the buffer; but false is returned.
1670 : : *
1671 : : * heap_fetch does not follow HOT chains: only the exact TID requested will
1672 : : * be fetched.
1673 : : *
1674 : : * It is somewhat inconsistent that we ereport() on invalid block number but
1675 : : * return false on invalid item number. There are a couple of reasons though.
1676 : : * One is that the caller can relatively easily check the block number for
1677 : : * validity, but cannot check the item number without reading the page
1678 : : * himself. Another is that when we are following a t_ctid link, we can be
1679 : : * reasonably confident that the page number is valid (since VACUUM shouldn't
1680 : : * truncate off the destination page without having killed the referencing
1681 : : * tuple first), but the item number might well not be good.
1682 : : */
1683 : : bool
10892 scrappy@hub.org 1684 : 2839976 : heap_fetch(Relation relation,
1685 : : Snapshot snapshot,
1686 : : HeapTuple tuple,
1687 : : Buffer *userbuf,
1688 : : bool keep_buf)
1689 : : {
8747 tgl@sss.pgh.pa.us 1690 : 2839976 : ItemPointer tid = &(tuple->t_self);
1691 : : ItemId lp;
1692 : : Buffer buffer;
1693 : : Page page;
1694 : : OffsetNumber offnum;
1695 : : bool valid;
1696 : :
1697 : : /*
1698 : : * Fetch and pin the appropriate page of the relation.
1699 : : */
6606 1700 : 2839976 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1701 : :
1702 : : /*
1703 : : * Need share lock on buffer to examine tuple commit status.
1704 : : */
10003 vadim4o@yahoo.com 1705 : 2839964 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3667 kgrittn@postgresql.o 1706 : 2839964 : page = BufferGetPage(buffer);
1707 : :
1708 : : /*
1709 : : * We'd better check for out-of-range offnum in case of VACUUM since the
1710 : : * TID was obtained.
1711 : : */
10467 bruce@momjian.us 1712 : 2839964 : offnum = ItemPointerGetOffsetNumber(tid);
6505 tgl@sss.pgh.pa.us 1713 [ + - + + ]: 2839964 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1714 : : {
39 andres@anarazel.de 1715 :GNC 4 : UnlockReleaseBuffer(buffer);
2600 andres@anarazel.de 1716 :CBC 4 : *userbuf = InvalidBuffer;
7709 tgl@sss.pgh.pa.us 1717 : 4 : tuple->t_data = NULL;
1718 : 4 : return false;
1719 : : }
1720 : :
1721 : : /*
1722 : : * get the item line pointer corresponding to the requested tid
1723 : : */
6505 1724 : 2839960 : lp = PageGetItemId(page, offnum);
1725 : :
1726 : : /*
1727 : : * Must check for deleted tuple.
1728 : : */
6810 1729 [ + + ]: 2839960 : if (!ItemIdIsNormal(lp))
1730 : : {
39 andres@anarazel.de 1731 :GNC 281 : UnlockReleaseBuffer(buffer);
2600 andres@anarazel.de 1732 :CBC 281 : *userbuf = InvalidBuffer;
8747 tgl@sss.pgh.pa.us 1733 : 281 : tuple->t_data = NULL;
1734 : 281 : return false;
1735 : : }
1736 : :
1737 : : /*
1738 : : * fill in *tuple fields
1739 : : */
6505 1740 : 2839679 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10021 vadim4o@yahoo.com 1741 : 2839679 : tuple->t_len = ItemIdGetLength(lp);
7563 tgl@sss.pgh.pa.us 1742 : 2839679 : tuple->t_tableOid = RelationGetRelid(relation);
1743 : :
1744 : : /*
1745 : : * check tuple visibility, then release lock
1746 : : */
7465 1747 : 2839679 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1748 : :
5566 heikki.linnakangas@i 1749 [ + + ]: 2839679 : if (valid)
2289 tmunro@postgresql.or 1750 : 2839622 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1751 : 2839622 : HeapTupleHeaderGetXmin(tuple->t_data));
1752 : :
1753 : 2839679 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1754 : :
5541 heikki.linnakangas@i 1755 : 2839679 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1756 : :
8747 tgl@sss.pgh.pa.us 1757 [ + + ]: 2839679 : if (valid)
1758 : : {
1759 : : /*
1760 : : * All checks passed, so return the tuple as valid. Caller is now
1761 : : * responsible for releasing the buffer.
1762 : : */
9720 1763 : 2839622 : *userbuf = buffer;
1764 : :
8747 1765 : 2839622 : return true;
1766 : : }
1767 : :
1768 : : /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1483 1769 [ + + ]: 57 : if (keep_buf)
1770 : 35 : *userbuf = buffer;
1771 : : else
1772 : : {
1773 : 22 : ReleaseBuffer(buffer);
1774 : 22 : *userbuf = InvalidBuffer;
1775 : 22 : tuple->t_data = NULL;
1776 : : }
1777 : :
8747 1778 : 57 : return false;
1779 : : }
1780 : :
1781 : : /*
1782 : : * heap_get_latest_tid - get the latest tid of a specified tuple
1783 : : *
1784 : : * Actually, this gets the latest version that is visible according to the
1785 : : * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1786 : : * possibly uncommitted version.
1787 : : *
1788 : : * *tid is both an input and an output parameter: it is updated to
1789 : : * show the latest version of the row. Note that it will not be changed
1790 : : * if no version of the row passes the snapshot test.
1791 : : */
1792 : : void
2545 andres@anarazel.de 1793 : 207 : heap_get_latest_tid(TableScanDesc sscan,
1794 : : ItemPointer tid)
1795 : : {
2540 tgl@sss.pgh.pa.us 1796 : 207 : Relation relation = sscan->rs_rd;
1797 : 207 : Snapshot snapshot = sscan->rs_snapshot;
1798 : : ItemPointerData ctid;
1799 : : TransactionId priorXmax;
1800 : :
1801 : : /*
1802 : : * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1803 : : * Assume that t_ctid links are valid however - there shouldn't be invalid
1804 : : * ones in the table.
1805 : : */
2545 andres@anarazel.de 1806 [ - + ]: 207 : Assert(ItemPointerIsValid(tid));
1807 : :
1808 : : /*
1809 : : * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1810 : : * need to examine, and *tid is the TID we will return if ctid turns out
1811 : : * to be bogus.
1812 : : *
1813 : : * Note that we will loop until we reach the end of the t_ctid chain.
1814 : : * Depending on the snapshot passed, there might be at most one visible
1815 : : * version of the row, but we don't try to optimize for that.
1816 : : */
7563 tgl@sss.pgh.pa.us 1817 : 207 : ctid = *tid;
1818 : 207 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1819 : : for (;;)
1820 : 64 : {
1821 : : Buffer buffer;
1822 : : Page page;
1823 : : OffsetNumber offnum;
1824 : : ItemId lp;
1825 : : HeapTupleData tp;
1826 : : bool valid;
1827 : :
1828 : : /*
1829 : : * Read, pin, and lock the page.
1830 : : */
1831 : 271 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1832 : 271 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3667 kgrittn@postgresql.o 1833 : 271 : page = BufferGetPage(buffer);
1834 : :
1835 : : /*
1836 : : * Check for bogus item number. This is not treated as an error
1837 : : * condition because it can happen while following a t_ctid link. We
1838 : : * just assume that the prior tid is OK and return it unchanged.
1839 : : */
7563 tgl@sss.pgh.pa.us 1840 : 271 : offnum = ItemPointerGetOffsetNumber(&ctid);
6505 1841 [ + - - + ]: 271 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1842 : : {
7340 tgl@sss.pgh.pa.us 1843 :UBC 0 : UnlockReleaseBuffer(buffer);
7563 1844 : 0 : break;
1845 : : }
6505 tgl@sss.pgh.pa.us 1846 :CBC 271 : lp = PageGetItemId(page, offnum);
6810 1847 [ - + ]: 271 : if (!ItemIdIsNormal(lp))
1848 : : {
7340 tgl@sss.pgh.pa.us 1849 :UBC 0 : UnlockReleaseBuffer(buffer);
7563 1850 : 0 : break;
1851 : : }
1852 : :
1853 : : /* OK to access the tuple */
7563 tgl@sss.pgh.pa.us 1854 :CBC 271 : tp.t_self = ctid;
6505 1855 : 271 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
7563 1856 : 271 : tp.t_len = ItemIdGetLength(lp);
4670 rhaas@postgresql.org 1857 : 271 : tp.t_tableOid = RelationGetRelid(relation);
1858 : :
1859 : : /*
1860 : : * After following a t_ctid link, we might arrive at an unrelated
1861 : : * tuple. Check for XMIN match.
1862 : : */
7563 tgl@sss.pgh.pa.us 1863 [ + + - + ]: 335 : if (TransactionIdIsValid(priorXmax) &&
3106 alvherre@alvh.no-ip. 1864 : 64 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1865 : : {
7340 tgl@sss.pgh.pa.us 1866 :UBC 0 : UnlockReleaseBuffer(buffer);
7563 1867 : 0 : break;
1868 : : }
1869 : :
1870 : : /*
1871 : : * Check tuple visibility; if visible, set it as the new result
1872 : : * candidate.
1873 : : */
7465 tgl@sss.pgh.pa.us 1874 :CBC 271 : valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2289 tmunro@postgresql.or 1875 : 271 : HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
7563 tgl@sss.pgh.pa.us 1876 [ + + ]: 271 : if (valid)
1877 : 191 : *tid = ctid;
1878 : :
1879 : : /*
1880 : : * If there's a valid t_ctid link, follow it, else we're done.
1881 : : */
4850 alvherre@alvh.no-ip. 1882 [ + + + + ]: 391 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1883 [ + - ]: 200 : HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
2950 andres@anarazel.de 1884 [ + + ]: 160 : HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
7563 tgl@sss.pgh.pa.us 1885 : 80 : ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1886 : : {
7340 1887 : 207 : UnlockReleaseBuffer(buffer);
7563 1888 : 207 : break;
1889 : : }
1890 : :
1891 : 64 : ctid = tp.t_data->t_ctid;
4850 alvherre@alvh.no-ip. 1892 : 64 : priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
7340 tgl@sss.pgh.pa.us 1893 : 64 : UnlockReleaseBuffer(buffer);
1894 : : } /* end of loop */
9703 inoue@tpf.co.jp 1895 : 207 : }
1896 : :
1897 : :
1898 : : /*
1899 : : * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1900 : : *
1901 : : * This is called after we have waited for the XMAX transaction to terminate.
1902 : : * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1903 : : * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1904 : : * hint bit if possible --- but beware that that may not yet be possible,
1905 : : * if the transaction committed asynchronously.
1906 : : *
1907 : : * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1908 : : * even if it commits.
1909 : : *
1910 : : * Hence callers should look only at XMAX_INVALID.
1911 : : *
1912 : : * Note this is not allowed for tuples whose xmax is a multixact.
1913 : : */
1914 : : static void
6839 tgl@sss.pgh.pa.us 1915 : 279 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1916 : : {
4850 alvherre@alvh.no-ip. 1917 [ - + ]: 279 : Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1918 [ - + ]: 279 : Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1919 : :
6839 tgl@sss.pgh.pa.us 1920 [ + + ]: 279 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1921 : : {
4850 alvherre@alvh.no-ip. 1922 [ + + + + ]: 506 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1923 : 228 : TransactionIdDidCommit(xid))
6839 tgl@sss.pgh.pa.us 1924 : 201 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1925 : : xid);
1926 : : else
1927 : 77 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1928 : : InvalidTransactionId);
1929 : : }
1930 : 279 : }
1931 : :
1932 : :
1933 : : /*
1934 : : * GetBulkInsertState - prepare status object for a bulk insert
1935 : : */
1936 : : BulkInsertState
6389 1937 : 3536 : GetBulkInsertState(void)
1938 : : {
1939 : : BulkInsertState bistate;
1940 : :
146 michael@paquier.xyz 1941 :GNC 3536 : bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
6389 tgl@sss.pgh.pa.us 1942 :CBC 3536 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1943 : 3536 : bistate->current_buf = InvalidBuffer;
1125 andres@anarazel.de 1944 : 3536 : bistate->next_free = InvalidBlockNumber;
1945 : 3536 : bistate->last_free = InvalidBlockNumber;
995 1946 : 3536 : bistate->already_extended_by = 0;
6389 tgl@sss.pgh.pa.us 1947 : 3536 : return bistate;
1948 : : }
1949 : :
1950 : : /*
1951 : : * FreeBulkInsertState - clean up after finishing a bulk insert
1952 : : */
1953 : : void
1954 : 3295 : FreeBulkInsertState(BulkInsertState bistate)
1955 : : {
1956 [ + + ]: 3295 : if (bistate->current_buf != InvalidBuffer)
6172 bruce@momjian.us 1957 : 2592 : ReleaseBuffer(bistate->current_buf);
6389 tgl@sss.pgh.pa.us 1958 : 3295 : FreeAccessStrategy(bistate->strategy);
1959 : 3295 : pfree(bistate);
1960 : 3295 : }
1961 : :
1962 : : /*
1963 : : * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
1964 : : */
1965 : : void
3388 rhaas@postgresql.org 1966 : 90779 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
1967 : : {
1968 [ + + ]: 90779 : if (bistate->current_buf != InvalidBuffer)
1969 : 40028 : ReleaseBuffer(bistate->current_buf);
1970 : 90779 : bistate->current_buf = InvalidBuffer;
1971 : :
1972 : : /*
1973 : : * Despite the name, we also reset bulk relation extension state.
1974 : : * Otherwise we can end up erroring out due to looking for free space in
1975 : : * ->next_free of one partition, even though ->next_free was set when
1976 : : * extending another partition. It could obviously also be bad for
1977 : : * efficiency to look at existing blocks at offsets from another
1978 : : * partition, even if we don't error out.
1979 : : */
935 andres@anarazel.de 1980 : 90779 : bistate->next_free = InvalidBlockNumber;
1981 : 90779 : bistate->last_free = InvalidBlockNumber;
3388 rhaas@postgresql.org 1982 : 90779 : }
1983 : :
1984 : :
1985 : : /*
1986 : : * heap_insert - insert tuple into a heap
1987 : : *
1988 : : * The new tuple is stamped with current transaction ID and the specified
1989 : : * command ID.
1990 : : *
1991 : : * See table_tuple_insert for comments about most of the input flags, except
1992 : : * that this routine directly takes a tuple rather than a slot.
1993 : : *
1994 : : * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
1995 : : * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
1996 : : * implement table_tuple_insert_speculative().
1997 : : *
1998 : : * On return the header fields of *tup are updated to match the stored tuple;
1999 : : * in particular tup->t_self receives the actual TID where the tuple was
2000 : : * stored. But note that any toasting of fields within the tuple data is NOT
2001 : : * reflected into *tup.
2002 : : */
2003 : : void
7624 tgl@sss.pgh.pa.us 2004 : 11916449 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2005 : : uint32 options, BulkInsertState bistate)
2006 : : {
7901 2007 : 11916449 : TransactionId xid = GetCurrentTransactionId();
2008 : : HeapTuple heaptup;
2009 : : Buffer buffer;
2010 : : Page page;
5432 rhaas@postgresql.org 2011 : 11916449 : Buffer vmbuffer = InvalidBuffer;
6362 heikki.linnakangas@i 2012 : 11916449 : bool all_visible_cleared = false;
2013 : :
2014 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1821 tgl@sss.pgh.pa.us 2015 [ - + ]: 11916449 : Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
2016 : : RelationGetNumberOfAttributes(relation));
2017 : :
340 nathan@postgresql.or 2018 : 11916449 : AssertHasSnapshotForToast(relation);
2019 : :
2020 : : /*
2021 : : * Fill in tuple header fields and toast the tuple if necessary.
2022 : : *
2023 : : * Note: below this point, heaptup is the data we actually intend to store
2024 : : * into the relation; tup is the caller's original untoasted data.
2025 : : */
5291 heikki.linnakangas@i 2026 : 11916449 : heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2027 : :
2028 : : /*
2029 : : * Find buffer to insert this tuple into. If the page is all visible,
2030 : : * this will also pin the requisite visibility map page.
2031 : : */
3839 kgrittn@postgresql.o 2032 : 11916449 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2033 : : InvalidBuffer, options, bistate,
2034 : : &vmbuffer, NULL,
2035 : : 0);
2036 : :
36 melanieplageman@gmai 2037 :GNC 11916449 : page = BufferGetPage(buffer);
2038 : :
2039 : : /*
2040 : : * We're about to do the actual insert -- but check for conflict first, to
2041 : : * avoid possibly having to roll back work we've just done.
2042 : : *
2043 : : * This is safe without a recheck as long as there is no possibility of
2044 : : * another process scanning the page between this check and the insert
2045 : : * being visible to the scan (i.e., an exclusive buffer content lock is
2046 : : * continuously held from this point until the tuple insert is visible).
2047 : : *
2048 : : * For a heap insert, we only need to check for table-level SSI locks. Our
2049 : : * new tuple can't possibly conflict with existing tuple locks, and heap
2050 : : * page locks are only consolidated versions of tuple locks; they do not
2051 : : * lock "gaps" as index page locks do. So we don't need to specify a
2052 : : * buffer when making the call, which makes for a faster check.
2053 : : */
2289 tmunro@postgresql.or 2054 :CBC 11916449 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2055 : :
2056 : : /* NO EREPORT(ERROR) from here till changes are logged */
9244 tgl@sss.pgh.pa.us 2057 : 11916437 : START_CRIT_SECTION();
2058 : :
4015 andres@anarazel.de 2059 : 11916437 : RelationPutHeapTuple(relation, buffer, heaptup,
2060 : 11916437 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2061 : :
36 melanieplageman@gmai 2062 [ + + ]:GNC 11916437 : if (PageIsAllVisible(page))
2063 : : {
6362 heikki.linnakangas@i 2064 :CBC 8991 : all_visible_cleared = true;
36 melanieplageman@gmai 2065 :GNC 8991 : PageClearAllVisible(page);
5432 rhaas@postgresql.org 2066 :CBC 8991 : visibilitymap_clear(relation,
2067 : 8991 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2068 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
2069 : : }
2070 : :
2071 : : /*
2072 : : * Set pd_prune_xid to trigger heap_page_prune_and_freeze() once the page
2073 : : * is full so that we can set the page all-visible in the VM on the next
2074 : : * page access.
2075 : : *
2076 : : * Setting pd_prune_xid is also handy if the inserting transaction
2077 : : * eventually aborts making this tuple DEAD and hence available for
2078 : : * pruning. If no other tuple in this page is UPDATEd/DELETEd, the aborted
2079 : : * tuple would never otherwise be pruned until next vacuum is triggered.
2080 : : *
2081 : : * Don't set it if we are in bootstrap mode or we are inserting a frozen
2082 : : * tuple, as there is no further pruning/freezing needed in those cases.
2083 : : */
36 melanieplageman@gmai 2084 [ + + + + ]:GNC 11916437 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
2085 [ - + + + : 11263892 : PageSetPrunable(page, xid);
+ + ]
2086 : :
7340 tgl@sss.pgh.pa.us 2087 :CBC 11916437 : MarkBufferDirty(buffer);
2088 : :
2089 : : /* XLOG stuff */
2222 noah@leadboat.com 2090 [ + + + + : 11916437 : if (RelationNeedsWAL(relation))
+ + + + ]
2091 : : {
2092 : : xl_heap_insert xlrec;
2093 : : xl_heap_header xlhdr;
2094 : : XLogRecPtr recptr;
9175 bruce@momjian.us 2095 : 10706147 : uint8 info = XLOG_HEAP_INSERT;
4184 heikki.linnakangas@i 2096 : 10706147 : int bufflags = 0;
2097 : :
2098 : : /*
2099 : : * If this is a catalog, we need to transmit combo CIDs to properly
2100 : : * decode, so log that as well.
2101 : : */
4529 rhaas@postgresql.org 2102 [ + + + + : 10706147 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
2103 : 5239 : log_heap_new_cid(relation, heaptup);
2104 : :
2105 : : /*
2106 : : * If this is the single and first tuple on page, we can reinit the
2107 : : * page instead of restoring the whole thing. Set flag, and hide
2108 : : * buffer references from XLogInsert.
2109 : : */
4184 heikki.linnakangas@i 2110 [ + + + + ]: 10828545 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2111 : 122398 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2112 : : {
2113 : 120832 : info |= XLOG_HEAP_INIT_PAGE;
2114 : 120832 : bufflags |= REGBUF_WILL_INIT;
2115 : : }
2116 : :
2117 : 10706147 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
4015 andres@anarazel.de 2118 : 10706147 : xlrec.flags = 0;
2119 [ + + ]: 10706147 : if (all_visible_cleared)
2120 : 8987 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2121 [ + + ]: 10706147 : if (options & HEAP_INSERT_SPECULATIVE)
2122 : 2206 : xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
4184 heikki.linnakangas@i 2123 [ - + ]: 10706147 : Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2124 : :
2125 : : /*
2126 : : * For logical decoding, we need the tuple even if we're doing a full
2127 : : * page write, so make sure it's included even if we take a full-page
2128 : : * image. (XXX We could alternatively store a pointer into the FPW).
2129 : : */
2764 andres@anarazel.de 2130 [ + + + + : 10706147 : if (RelationIsLogicallyLogged(relation) &&
+ - - + -
- - - + -
+ + ]
2131 [ + + ]: 272979 : !(options & HEAP_INSERT_NO_LOGICAL))
2132 : : {
4015 2133 : 272867 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
4184 heikki.linnakangas@i 2134 : 272867 : bufflags |= REGBUF_KEEP_DATA;
2135 : :
2096 akapila@postgresql.o 2136 [ + + ]: 272867 : if (IsToastRelation(relation))
2137 : 1927 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2138 : : }
2139 : :
4184 heikki.linnakangas@i 2140 : 10706147 : XLogBeginInsert();
448 peter@eisentraut.org 2141 : 10706147 : XLogRegisterData(&xlrec, SizeOfHeapInsert);
2142 : :
4184 heikki.linnakangas@i 2143 : 10706147 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2144 : 10706147 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2145 : 10706147 : xlhdr.t_hoff = heaptup->t_data->t_hoff;
2146 : :
2147 : : /*
2148 : : * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2149 : : * write the whole page to the xlog, we don't need to store
2150 : : * xl_heap_header in the xlog.
2151 : : */
2152 : 10706147 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
448 peter@eisentraut.org 2153 : 10706147 : XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
2154 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
4184 heikki.linnakangas@i 2155 : 10706147 : XLogRegisterBufData(0,
4091 tgl@sss.pgh.pa.us 2156 : 10706147 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2157 : 10706147 : heaptup->t_len - SizeofHeapTupleHeader);
2158 : :
2159 : : /* filtering by origin on a row level is much more efficient */
3421 andres@anarazel.de 2160 : 10706147 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2161 : :
4184 heikki.linnakangas@i 2162 : 10706147 : recptr = XLogInsert(RM_HEAP_ID, info);
2163 : :
9259 vadim4o@yahoo.com 2164 : 10706147 : PageSetLSN(page, recptr);
2165 : : }
2166 : :
9244 tgl@sss.pgh.pa.us 2167 [ - + ]: 11916437 : END_CRIT_SECTION();
2168 : :
7340 2169 : 11916437 : UnlockReleaseBuffer(buffer);
5432 rhaas@postgresql.org 2170 [ + + ]: 11916437 : if (vmbuffer != InvalidBuffer)
2171 : 9331 : ReleaseBuffer(vmbuffer);
2172 : :
2173 : : /*
2174 : : * If tuple is cacheable, mark it for invalidation from the caches in case
2175 : : * we abort. Note it is OK to do this after releasing the buffer, because
2176 : : * the heaptup data structure is all in local memory, not in the shared
2177 : : * buffer.
2178 : : */
5376 tgl@sss.pgh.pa.us 2179 : 11916437 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2180 : :
2181 : : /* Note: speculative insertions are counted too, even if aborted later */
5291 heikki.linnakangas@i 2182 : 11916437 : pgstat_count_heap_insert(relation, 1);
2183 : :
2184 : : /*
2185 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
2186 : : * back to the caller's image, too.
2187 : : */
7471 tgl@sss.pgh.pa.us 2188 [ + + ]: 11916437 : if (heaptup != tup)
2189 : : {
2190 : 22826 : tup->t_self = heaptup->t_self;
2191 : 22826 : heap_freetuple(heaptup);
2192 : : }
10892 scrappy@hub.org 2193 : 11916437 : }
2194 : :
2195 : : /*
2196 : : * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2197 : : * tuple header fields and toasts the tuple if necessary. Returns a toasted
2198 : : * version of the tuple if it was toasted, or the original tuple if not. Note
2199 : : * that in any case, the header fields are also set in the original tuple.
2200 : : */
2201 : : static HeapTuple
5291 heikki.linnakangas@i 2202 : 13851816 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2203 : : CommandId cid, uint32 options)
2204 : : {
2205 : : /*
2206 : : * To allow parallel inserts, we need to ensure that they are safe to be
2207 : : * performed in workers. We have the infrastructure to allow parallel
2208 : : * inserts in general except for the cases where inserts generate a new
2209 : : * CommandId (eg. inserts into a table having a foreign key column).
2210 : : */
3134 rhaas@postgresql.org 2211 [ - + ]: 13851816 : if (IsParallelWorker())
4023 rhaas@postgresql.org 2212 [ # # ]:UBC 0 : ereport(ERROR,
2213 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2214 : : errmsg("cannot insert tuples in a parallel worker")));
2215 : :
5291 heikki.linnakangas@i 2216 :CBC 13851816 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2217 : 13851816 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2218 : 13851816 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
4517 rhaas@postgresql.org 2219 : 13851816 : HeapTupleHeaderSetXmin(tup->t_data, xid);
4902 simon@2ndQuadrant.co 2220 [ + + ]: 13851816 : if (options & HEAP_INSERT_FROZEN)
4517 rhaas@postgresql.org 2221 : 102651 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2222 : :
5291 heikki.linnakangas@i 2223 : 13851816 : HeapTupleHeaderSetCmin(tup->t_data, cid);
3240 tgl@sss.pgh.pa.us 2224 : 13851816 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
5291 heikki.linnakangas@i 2225 : 13851816 : tup->t_tableOid = RelationGetRelid(relation);
2226 : :
2227 : : /*
2228 : : * If the new tuple is too big for storage or contains already toasted
2229 : : * out-of-line attributes from some other relation, invoke the toaster.
2230 : : */
4811 kgrittn@postgresql.o 2231 [ + + ]: 13851816 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2232 [ + + ]: 36435 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2233 : : {
2234 : : /* toast table entries should never be recursively toasted */
5291 heikki.linnakangas@i 2235 [ - + ]: 36374 : Assert(!HeapTupleHasExternal(tup));
2236 : 36374 : return tup;
2237 : : }
2238 [ + + + + ]: 13815442 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2405 rhaas@postgresql.org 2239 : 22885 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2240 : : else
5291 heikki.linnakangas@i 2241 : 13792557 : return tup;
2242 : : }
2243 : :
2244 : : /*
2245 : : * Helper for heap_multi_insert() that computes the number of entire pages
2246 : : * that inserting the remaining heaptuples requires. Used to determine how
2247 : : * much the relation needs to be extended by.
2248 : : */
2249 : : static int
1125 andres@anarazel.de 2250 : 492091 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2251 : : {
2252 : 492091 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2253 : 492091 : int npages = 1;
2254 : :
2255 [ + + ]: 3201025 : for (int i = done; i < ntuples; i++)
2256 : : {
2257 : 2708934 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2258 : :
2259 [ + + ]: 2708934 : if (page_avail < tup_sz)
2260 : : {
2261 : 18339 : npages++;
2262 : 18339 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2263 : : }
2264 : 2708934 : page_avail -= tup_sz;
2265 : : }
2266 : :
2267 : 492091 : return npages;
2268 : : }
2269 : :
2270 : : /*
2271 : : * heap_multi_insert - insert multiple tuples into a heap
2272 : : *
2273 : : * This is like heap_insert(), but inserts multiple tuples in one operation.
2274 : : * That's faster than calling heap_insert() in a loop, because when multiple
2275 : : * tuples can be inserted on a single page, we can write just a single WAL
2276 : : * record covering all of them, and only need to lock/unlock the page once.
2277 : : *
2278 : : * Note: this leaks memory into the current memory context. You can create a
2279 : : * temporary context before calling this, if that's a problem.
2280 : : */
2281 : : void
2588 2282 : 483273 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2283 : : CommandId cid, uint32 options, BulkInsertState bistate)
2284 : : {
5291 heikki.linnakangas@i 2285 : 483273 : TransactionId xid = GetCurrentTransactionId();
2286 : : HeapTuple *heaptuples;
2287 : : int i;
2288 : : int ndone;
2289 : : PGAlignedBlock scratch;
2290 : : Page page;
1934 tomas.vondra@postgre 2291 : 483273 : Buffer vmbuffer = InvalidBuffer;
2292 : : bool needwal;
2293 : : Size saveFreeSpace;
4529 rhaas@postgresql.org 2294 [ + + + + : 483273 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
+ - - + -
- - - + -
+ + ]
2295 [ + + + + : 483273 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
+ - - + -
- - - + +
- + - - -
- - - ]
1125 andres@anarazel.de 2296 : 483273 : bool starting_with_empty_page = false;
2297 : 483273 : int npages = 0;
2298 : 483273 : int npages_used = 0;
2299 : :
2300 : : /* currently not needed (thus unsupported) for heap_multi_insert() */
1285 peter@eisentraut.org 2301 [ - + ]: 483273 : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2302 : :
340 nathan@postgresql.or 2303 : 483273 : AssertHasSnapshotForToast(relation);
2304 : :
2222 noah@leadboat.com 2305 [ + + + + : 483273 : needwal = RelationNeedsWAL(relation);
+ - + + ]
754 akorotkov@postgresql 2306 [ + + ]: 483273 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2307 : : HEAP_DEFAULT_FILLFACTOR);
2308 : :
2309 : : /* Toast and set header data in all the slots */
5291 heikki.linnakangas@i 2310 : 483273 : heaptuples = palloc(ntuples * sizeof(HeapTuple));
2311 [ + + ]: 2418640 : for (i = 0; i < ntuples; i++)
2312 : : {
2313 : : HeapTuple tuple;
2314 : :
2588 andres@anarazel.de 2315 : 1935367 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2316 : 1935367 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2317 : 1935367 : tuple->t_tableOid = slots[i]->tts_tableOid;
2318 : 1935367 : heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2319 : : options);
2320 : : }
2321 : :
2322 : : /*
2323 : : * We're about to do the actual inserts -- but check for conflict first,
2324 : : * to minimize the possibility of having to roll back work we've just
2325 : : * done.
2326 : : *
2327 : : * A check here does not definitively prevent a serialization anomaly;
2328 : : * that check MUST be done at least past the point of acquiring an
2329 : : * exclusive buffer content lock on every buffer that will be affected,
2330 : : * and MAY be done after all inserts are reflected in the buffers and
2331 : : * those locks are released; otherwise there is a race condition. Since
2332 : : * multiple buffers can be locked and unlocked in the loop below, and it
2333 : : * would not be feasible to identify and lock all of those buffers before
2334 : : * the loop, we must do a final check at the end.
2335 : : *
2336 : : * The check here could be omitted with no loss of correctness; it is
2337 : : * present strictly as an optimization.
2338 : : *
2339 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2340 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2341 : : * page locks are only consolidated versions of tuple locks; they do not
2342 : : * lock "gaps" as index page locks do. So we don't need to specify a
2343 : : * buffer when making the call, which makes for a faster check.
2344 : : */
2289 tmunro@postgresql.or 2345 : 483273 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2346 : :
5291 heikki.linnakangas@i 2347 : 483273 : ndone = 0;
2348 [ + + ]: 984997 : while (ndone < ntuples)
2349 : : {
2350 : : Buffer buffer;
2351 : 501724 : bool all_visible_cleared = false;
1934 tomas.vondra@postgre 2352 : 501724 : bool all_frozen_set = false;
2353 : : int nthispage;
2354 : :
4334 rhaas@postgresql.org 2355 [ + + ]: 501724 : CHECK_FOR_INTERRUPTS();
2356 : :
2357 : : /*
2358 : : * Compute number of pages needed to fit the to-be-inserted tuples in
2359 : : * the worst case. This will be used to determine how much to extend
2360 : : * the relation by in RelationGetBufferForTuple(), if needed. If we
2361 : : * filled a prior page from scratch, we can just update our last
2362 : : * computation, but if we started with a partially filled page,
2363 : : * recompute from scratch, the number of potentially required pages
2364 : : * can vary due to tuples needing to fit onto the page, page headers
2365 : : * etc.
2366 : : */
1125 andres@anarazel.de 2367 [ + + + + ]: 501724 : if (ndone == 0 || !starting_with_empty_page)
2368 : : {
2369 : 492091 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2370 : : saveFreeSpace);
2371 : 492091 : npages_used = 0;
2372 : : }
2373 : : else
2374 : 9633 : npages_used++;
2375 : :
2376 : : /*
2377 : : * Find buffer where at least the next tuple will fit. If the page is
2378 : : * all-visible, this will also pin the requisite visibility map page.
2379 : : *
2380 : : * Also pin visibility map page if COPY FREEZE inserts tuples into an
2381 : : * empty page. See all_frozen_set below.
2382 : : */
5291 heikki.linnakangas@i 2383 : 501724 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2384 : : InvalidBuffer, options, bistate,
2385 : : &vmbuffer, NULL,
2386 : : npages - npages_used);
3667 kgrittn@postgresql.o 2387 : 501724 : page = BufferGetPage(buffer);
2388 : :
1934 tomas.vondra@postgre 2389 : 501724 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2390 : :
2391 [ + + + + ]: 501724 : if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2392 : : {
2393 : 1665 : all_frozen_set = true;
2394 : : /* Lock the vmbuffer before entering the critical section */
208 melanieplageman@gmai 2395 :GNC 1665 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2396 : : }
2397 : :
2398 : : /* NO EREPORT(ERROR) from here till changes are logged */
5291 heikki.linnakangas@i 2399 :CBC 501724 : START_CRIT_SECTION();
2400 : :
2401 : : /*
2402 : : * RelationGetBufferForTuple has ensured that the first tuple fits.
2403 : : * Put that on the page, and then as many other tuples as fit.
2404 : : */
4015 andres@anarazel.de 2405 : 501724 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2406 : :
2407 : : /*
2408 : : * For logical decoding we need combo CIDs to properly decode the
2409 : : * catalog.
2410 : : */
2261 michael@paquier.xyz 2411 [ + + + + ]: 501724 : if (needwal && need_cids)
2412 : 7037 : log_heap_new_cid(relation, heaptuples[ndone]);
2413 : :
4892 heikki.linnakangas@i 2414 [ + + ]: 1935367 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2415 : : {
5291 2416 : 1452094 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2417 : :
5102 2418 [ + + ]: 1452094 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
5291 2419 : 18451 : break;
2420 : :
4015 andres@anarazel.de 2421 : 1433643 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2422 : :
2423 : : /*
2424 : : * For logical decoding we need combo CIDs to properly decode the
2425 : : * catalog.
2426 : : */
4184 heikki.linnakangas@i 2427 [ + + + + ]: 1433643 : if (needwal && need_cids)
2428 : 5054 : log_heap_new_cid(relation, heaptup);
2429 : : }
2430 : :
2431 : : /*
2432 : : * If the page is all visible, need to clear that, unless we're only
2433 : : * going to add further frozen rows to it.
2434 : : *
2435 : : * If we're only adding already frozen rows to a previously empty
2436 : : * page, mark it as all-frozen and update the visibility map. We're
2437 : : * already holding a pin on the vmbuffer.
2438 : : */
1934 tomas.vondra@postgre 2439 [ + + + + ]: 501724 : if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2440 : : {
5080 rhaas@postgresql.org 2441 : 5925 : all_visible_cleared = true;
2442 : 5925 : PageClearAllVisible(page);
2443 : 5925 : visibilitymap_clear(relation,
2444 : : BufferGetBlockNumber(buffer),
2445 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
2446 : : }
1934 tomas.vondra@postgre 2447 [ + + ]: 495799 : else if (all_frozen_set)
2448 : : {
2449 : 1665 : PageSetAllVisible(page);
64 melanieplageman@gmai 2450 :GNC 1665 : PageClearPrunable(page);
42 2451 : 1665 : visibilitymap_set(BufferGetBlockNumber(buffer),
2452 : : vmbuffer,
2453 : : VISIBILITYMAP_ALL_VISIBLE |
2454 : : VISIBILITYMAP_ALL_FROZEN,
2455 : : relation->rd_locator);
2456 : : }
2457 : :
2458 : : /*
2459 : : * Set pd_prune_xid. See heap_insert() for more on why we do this when
2460 : : * inserting tuples. This only makes sense if we aren't already
2461 : : * setting the page frozen in the VM and we're not in bootstrap mode.
2462 : : */
36 2463 [ + + + + ]: 501724 : if (!all_frozen_set && TransactionIdIsNormal(xid))
2464 [ - + + + : 477487 : PageSetPrunable(page, xid);
+ + ]
2465 : :
5291 heikki.linnakangas@i 2466 :CBC 501724 : MarkBufferDirty(buffer);
2467 : :
2468 : : /* XLOG stuff */
2469 [ + + ]: 501724 : if (needwal)
2470 : : {
2471 : : XLogRecPtr recptr;
2472 : : xl_heap_multi_insert *xlrec;
2473 : 497287 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2474 : : char *tupledata;
2475 : : int totaldatalen;
2803 tgl@sss.pgh.pa.us 2476 : 497287 : char *scratchptr = scratch.data;
2477 : : bool init;
4184 heikki.linnakangas@i 2478 : 497287 : int bufflags = 0;
2479 : :
2480 : : /*
2481 : : * If the page was previously empty, we can reinit the page
2482 : : * instead of restoring the whole thing.
2483 : : */
1934 tomas.vondra@postgre 2484 : 497287 : init = starting_with_empty_page;
2485 : :
2486 : : /* allocate xl_heap_multi_insert struct from the scratch area */
5291 heikki.linnakangas@i 2487 : 497287 : xlrec = (xl_heap_multi_insert *) scratchptr;
2488 : 497287 : scratchptr += SizeOfHeapMultiInsert;
2489 : :
2490 : : /*
2491 : : * Allocate offsets array. Unless we're reinitializing the page,
2492 : : * in that case the tuples are stored in order starting at
2493 : : * FirstOffsetNumber and we don't need to store the offsets
2494 : : * explicitly.
2495 : : */
2496 [ + + ]: 497287 : if (!init)
2497 : 481972 : scratchptr += nthispage * sizeof(OffsetNumber);
2498 : :
2499 : : /* the rest of the scratch space is used for tuple data */
2500 : 497287 : tupledata = scratchptr;
2501 : :
2502 : : /* check that the mutually exclusive flags are not both set */
1819 tgl@sss.pgh.pa.us 2503 [ + + - + ]: 497287 : Assert(!(all_visible_cleared && all_frozen_set));
2504 : :
1934 tomas.vondra@postgre 2505 : 497287 : xlrec->flags = 0;
2506 [ + + ]: 497287 : if (all_visible_cleared)
2507 : 5925 : xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
2508 : :
2509 : : /*
2510 : : * We don't have to worry about including a conflict xid in the
2511 : : * WAL record, as HEAP_INSERT_FROZEN intentionally violates
2512 : : * visibility rules.
2513 : : */
2514 [ + + ]: 497287 : if (all_frozen_set)
2515 : 21 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2516 : :
5291 heikki.linnakangas@i 2517 : 497287 : xlrec->ntuples = nthispage;
2518 : :
2519 : : /*
2520 : : * Write out an xl_multi_insert_tuple and the tuple data itself
2521 : : * for each tuple.
2522 : : */
2523 [ + + ]: 2125483 : for (i = 0; i < nthispage; i++)
2524 : : {
2525 : 1628196 : HeapTuple heaptup = heaptuples[ndone + i];
2526 : : xl_multi_insert_tuple *tuphdr;
2527 : : int datalen;
2528 : :
2529 [ + + ]: 1628196 : if (!init)
2530 : 989101 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2531 : : /* xl_multi_insert_tuple needs two-byte alignment. */
2532 : 1628196 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2533 : 1628196 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2534 : :
2535 : 1628196 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2536 : 1628196 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2537 : 1628196 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2538 : :
2539 : : /* write bitmap [+ padding] [+ oid] + data */
4091 tgl@sss.pgh.pa.us 2540 : 1628196 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
5291 heikki.linnakangas@i 2541 : 1628196 : memcpy(scratchptr,
4091 tgl@sss.pgh.pa.us 2542 : 1628196 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2543 : : datalen);
5291 heikki.linnakangas@i 2544 : 1628196 : tuphdr->datalen = datalen;
2545 : 1628196 : scratchptr += datalen;
2546 : : }
2547 : 497287 : totaldatalen = scratchptr - tupledata;
2803 tgl@sss.pgh.pa.us 2548 [ - + ]: 497287 : Assert((scratchptr - scratch.data) < BLCKSZ);
2549 : :
4529 rhaas@postgresql.org 2550 [ + + ]: 497287 : if (need_tuple_data)
4015 andres@anarazel.de 2551 : 72 : xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2552 : :
2553 : : /*
2554 : : * Signal that this is the last xl_heap_multi_insert record
2555 : : * emitted by this call to heap_multi_insert(). Needed for logical
2556 : : * decoding so it knows when to cleanup temporary data.
2557 : : */
4184 heikki.linnakangas@i 2558 [ + + ]: 497287 : if (ndone + nthispage == ntuples)
4015 andres@anarazel.de 2559 : 482723 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2560 : :
5291 heikki.linnakangas@i 2561 [ + + ]: 497287 : if (init)
2562 : : {
2563 : 15315 : info |= XLOG_HEAP_INIT_PAGE;
4184 2564 : 15315 : bufflags |= REGBUF_WILL_INIT;
2565 : : }
2566 : :
2567 : : /*
2568 : : * If we're doing logical decoding, include the new tuple data
2569 : : * even if we take a full-page image of the page.
2570 : : */
2571 [ + + ]: 497287 : if (need_tuple_data)
2572 : 72 : bufflags |= REGBUF_KEEP_DATA;
2573 : :
2574 : 497287 : XLogBeginInsert();
448 peter@eisentraut.org 2575 : 497287 : XLogRegisterData(xlrec, tupledata - scratch.data);
4184 heikki.linnakangas@i 2576 : 497287 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
208 melanieplageman@gmai 2577 [ + + ]:GNC 497287 : if (all_frozen_set)
2578 : 21 : XLogRegisterBuffer(1, vmbuffer, 0);
2579 : :
4184 heikki.linnakangas@i 2580 :CBC 497287 : XLogRegisterBufData(0, tupledata, totaldatalen);
2581 : :
2582 : : /* filtering by origin on a row level is much more efficient */
3421 andres@anarazel.de 2583 : 497287 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2584 : :
4184 heikki.linnakangas@i 2585 : 497287 : recptr = XLogInsert(RM_HEAP2_ID, info);
2586 : :
5291 2587 : 497287 : PageSetLSN(page, recptr);
208 melanieplageman@gmai 2588 [ + + ]:GNC 497287 : if (all_frozen_set)
2589 : : {
2590 [ - + ]: 21 : Assert(BufferIsDirty(vmbuffer));
2591 : 21 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2592 : : }
2593 : : }
2594 : :
5291 heikki.linnakangas@i 2595 [ - + ]:CBC 501724 : END_CRIT_SECTION();
2596 : :
1934 tomas.vondra@postgre 2597 [ + + ]: 501724 : if (all_frozen_set)
208 melanieplageman@gmai 2598 :GNC 1665 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2599 : :
1934 tomas.vondra@postgre 2600 :CBC 501724 : UnlockReleaseBuffer(buffer);
5291 heikki.linnakangas@i 2601 : 501724 : ndone += nthispage;
2602 : :
2603 : : /*
2604 : : * NB: Only release vmbuffer after inserting all tuples - it's fairly
2605 : : * likely that we'll insert into subsequent heap pages that are likely
2606 : : * to use the same vm page.
2607 : : */
2608 : : }
2609 : :
2610 : : /* We're done with inserting all tuples, so release the last vmbuffer. */
1934 tomas.vondra@postgre 2611 [ + + ]: 483273 : if (vmbuffer != InvalidBuffer)
2612 : 5963 : ReleaseBuffer(vmbuffer);
2613 : :
2614 : : /*
2615 : : * We're done with the actual inserts. Check for conflicts again, to
2616 : : * ensure that all rw-conflicts in to these inserts are detected. Without
2617 : : * this final check, a sequential scan of the heap may have locked the
2618 : : * table after the "before" check, missing one opportunity to detect the
2619 : : * conflict, and then scanned the table before the new tuples were there,
2620 : : * missing the other chance to detect the conflict.
2621 : : *
2622 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2623 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2624 : : * page locks are only consolidated versions of tuple locks; they do not
2625 : : * lock "gaps" as index page locks do. So we don't need to specify a
2626 : : * buffer when making the call.
2627 : : */
2289 tmunro@postgresql.or 2628 : 483273 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2629 : :
2630 : : /*
2631 : : * If tuples are cacheable, mark them for invalidation from the caches in
2632 : : * case we abort. Note it is OK to do this after releasing the buffer,
2633 : : * because the heaptuples data structure is all in local memory, not in
2634 : : * the shared buffer.
2635 : : */
4541 rhaas@postgresql.org 2636 [ + + ]: 483273 : if (IsCatalogRelation(relation))
2637 : : {
5291 heikki.linnakangas@i 2638 [ + + ]: 1598978 : for (i = 0; i < ntuples; i++)
2639 : 1117272 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2640 : : }
2641 : :
2642 : : /* copy t_self fields back to the caller's slots */
5195 2643 [ + + ]: 2418640 : for (i = 0; i < ntuples; i++)
2588 andres@anarazel.de 2644 : 1935367 : slots[i]->tts_tid = heaptuples[i]->t_self;
2645 : :
5291 heikki.linnakangas@i 2646 : 483273 : pgstat_count_heap_insert(relation, ntuples);
2647 : 483273 : }
2648 : :
2649 : : /*
2650 : : * simple_heap_insert - insert a tuple
2651 : : *
2652 : : * Currently, this routine differs from heap_insert only in supplying
2653 : : * a default command ID and not allowing access to the speedup options.
2654 : : *
2655 : : * This should be used rather than using heap_insert directly in most places
2656 : : * where we are modifying system catalogs.
2657 : : */
2658 : : void
8750 tgl@sss.pgh.pa.us 2659 : 1118566 : simple_heap_insert(Relation relation, HeapTuple tup)
2660 : : {
2723 andres@anarazel.de 2661 : 1118566 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
8750 tgl@sss.pgh.pa.us 2662 : 1118566 : }
2663 : :
2664 : : /*
2665 : : * Given infomask/infomask2, compute the bits that must be saved in the
2666 : : * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2667 : : * xl_heap_lock_updated WAL records.
2668 : : *
2669 : : * See fix_infomask_from_infobits.
2670 : : */
2671 : : static uint8
4850 alvherre@alvh.no-ip. 2672 : 6487070 : compute_infobits(uint16 infomask, uint16 infomask2)
2673 : : {
2674 : : return
2675 : 6487070 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2676 : 6487070 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2677 : 6487070 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2678 : : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2679 : 12974140 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2680 : : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2681 : 6487070 : XLHL_KEYS_UPDATED : 0);
2682 : : }
2683 : :
2684 : : /*
2685 : : * Given two versions of the same t_infomask for a tuple, compare them and
2686 : : * return whether the relevant status for a tuple Xmax has changed. This is
2687 : : * used after a buffer lock has been released and reacquired: we want to ensure
2688 : : * that the tuple state continues to be the same it was when we previously
2689 : : * examined it.
2690 : : *
2691 : : * Note the Xmax field itself must be compared separately.
2692 : : */
2693 : : static inline bool
4394 2694 : 5448 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2695 : : {
4382 bruce@momjian.us 2696 : 5448 : const uint16 interesting =
2697 : : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2698 : :
4394 alvherre@alvh.no-ip. 2699 [ + + ]: 5448 : if ((new_infomask & interesting) != (old_infomask & interesting))
2700 : 17 : return true;
2701 : :
2702 : 5431 : return false;
2703 : : }
2704 : :
2705 : : /*
2706 : : * heap_delete - delete a tuple
2707 : : *
2708 : : * See table_tuple_delete() for an explanation of the parameters, except that
2709 : : * this routine directly takes a tuple rather than a slot.
2710 : : *
2711 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2712 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2713 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2714 : : * generated by another transaction).
2715 : : */
2716 : : TM_Result
187 peter@eisentraut.org 2717 :GNC 1848039 : heap_delete(Relation relation, const ItemPointerData *tid,
2718 : : CommandId cid, uint32 options, Snapshot crosscheck,
2719 : : bool wait, TM_FailureData *tmfd)
2720 : : {
2721 : : TM_Result result;
7901 tgl@sss.pgh.pa.us 2722 :CBC 1848039 : TransactionId xid = GetCurrentTransactionId();
2723 : : ItemId lp;
2724 : : HeapTupleData tp;
2725 : : Page page;
2726 : : BlockNumber block;
2727 : : Buffer buffer;
5432 rhaas@postgresql.org 2728 : 1848039 : Buffer vmbuffer = InvalidBuffer;
2729 : : TransactionId new_xmax;
2730 : : uint16 new_infomask,
2731 : : new_infomask2;
34 alvherre@kurilemu.de 2732 :GNC 1848039 : bool changingPart = (options & TABLE_DELETE_CHANGING_PARTITION) != 0;
29 2733 : 1848039 : bool walLogical = (options & TABLE_DELETE_NO_LOGICAL) == 0;
7675 tgl@sss.pgh.pa.us 2734 :CBC 1848039 : bool have_tuple_lock = false;
2735 : : bool iscombo;
6362 heikki.linnakangas@i 2736 : 1848039 : bool all_visible_cleared = false;
4382 bruce@momjian.us 2737 : 1848039 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
4529 rhaas@postgresql.org 2738 : 1848039 : bool old_key_copied = false;
2739 : :
10467 bruce@momjian.us 2740 [ - + ]: 1848039 : Assert(ItemPointerIsValid(tid));
2741 : :
340 nathan@postgresql.or 2742 : 1848039 : AssertHasSnapshotForToast(relation);
2743 : :
2744 : : /*
2745 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
2746 : : * Other workers might need that combo CID for visibility checks, and we
2747 : : * have no provision for broadcasting it to them.
2748 : : */
4023 rhaas@postgresql.org 2749 [ - + ]: 1848039 : if (IsInParallelMode())
4023 rhaas@postgresql.org 2750 [ # # ]:UBC 0 : ereport(ERROR,
2751 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2752 : : errmsg("cannot delete tuples during a parallel operation")));
2753 : :
5432 rhaas@postgresql.org 2754 :CBC 1848039 : block = ItemPointerGetBlockNumber(tid);
2755 : 1848039 : buffer = ReadBuffer(relation, block);
3667 kgrittn@postgresql.o 2756 : 1848039 : page = BufferGetPage(buffer);
2757 : :
2758 : : /*
2759 : : * Before locking the buffer, pin the visibility map page if it appears to
2760 : : * be necessary. Since we haven't got the lock yet, someone else might be
2761 : : * in the middle of changing this, so we'll need to recheck after we have
2762 : : * the lock.
2763 : : */
5432 rhaas@postgresql.org 2764 [ + + ]: 1848039 : if (PageIsAllVisible(page))
2765 : 1936 : visibilitymap_pin(relation, block, &vmbuffer);
2766 : :
10003 vadim4o@yahoo.com 2767 : 1848039 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2768 : :
1321 jdavis@postgresql.or 2769 : 1848039 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2770 [ - + ]: 1848039 : Assert(ItemIdIsNormal(lp));
2771 : :
2772 : 1848039 : tp.t_tableOid = RelationGetRelid(relation);
2773 : 1848039 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2774 : 1848039 : tp.t_len = ItemIdGetLength(lp);
2775 : 1848039 : tp.t_self = *tid;
2776 : :
2777 : 1 : l1:
2778 : :
2779 : : /*
2780 : : * If we didn't pin the visibility map page and the page has become all
2781 : : * visible while we were busy locking the buffer, we'll have to unlock and
2782 : : * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2783 : : * unfortunate, but hopefully shouldn't happen often.
2784 : : */
5432 rhaas@postgresql.org 2785 [ + + - + ]: 1848040 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2786 : : {
5432 rhaas@postgresql.org 2787 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2788 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
2789 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2790 : : }
2791 : :
4670 rhaas@postgresql.org 2792 :CBC 1848040 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2793 : :
2600 andres@anarazel.de 2794 [ - + ]: 1848040 : if (result == TM_Invisible)
2795 : : {
7340 tgl@sss.pgh.pa.us 2796 :UBC 0 : UnlockReleaseBuffer(buffer);
3929 2797 [ # # ]: 0 : ereport(ERROR,
2798 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2799 : : errmsg("attempted to delete invisible tuple")));
2800 : : }
754 akorotkov@postgresql 2801 [ + + + - ]:CBC 1848040 : else if (result == TM_BeingModified && wait)
2802 : : {
2803 : : TransactionId xwait;
2804 : : uint16 infomask;
2805 : :
2806 : : /* must copy state data before unlocking buffer */
4850 alvherre@alvh.no-ip. 2807 : 40667 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
7675 tgl@sss.pgh.pa.us 2808 : 40667 : infomask = tp.t_data->t_infomask;
2809 : :
2810 : : /*
2811 : : * Sleep until concurrent transaction ends -- except when there's a
2812 : : * single locker and it's our own transaction. Note we don't care
2813 : : * which lock mode the locker has, because we need the strongest one.
2814 : : *
2815 : : * Before sleeping, we need to acquire tuple lock to establish our
2816 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
2817 : : * release us when we are next-in-line for the tuple.
2818 : : *
2819 : : * If we are forced to "start over" below, we keep the tuple lock;
2820 : : * this arranges that we stay at the head of the line while rechecking
2821 : : * tuple state.
2822 : : */
7677 2823 [ + + ]: 40667 : if (infomask & HEAP_XMAX_IS_MULTI)
2824 : : {
2513 alvherre@alvh.no-ip. 2825 : 8 : bool current_is_member = false;
2826 : :
4043 2827 [ + - ]: 8 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2828 : : LockTupleExclusive, ¤t_is_member))
2829 : : {
2830 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2831 : :
2832 : : /*
2833 : : * Acquire the lock, if necessary (but skip it when we're
2834 : : * requesting a lock and already have one; avoids deadlock).
2835 : : */
2513 2836 [ + + ]: 8 : if (!current_is_member)
2837 : 6 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2838 : : LockWaitBlock, &have_tuple_lock);
2839 : :
2840 : : /* wait for multixact */
4043 2841 : 8 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2842 : : relation, &(tp.t_self), XLTW_Delete,
2843 : : NULL);
2844 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2845 : :
2846 : : /*
2847 : : * If xwait had just locked the tuple then some other xact
2848 : : * could update this tuple before we get to this point. Check
2849 : : * for xmax change, and start over if so.
2850 : : *
2851 : : * We also must start over if we didn't pin the VM page, and
2852 : : * the page has become all visible.
2853 : : */
1321 jdavis@postgresql.or 2854 [ + - + - : 16 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ - ]
2855 [ - + ]: 16 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4043 alvherre@alvh.no-ip. 2856 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2857 : : xwait))
4043 alvherre@alvh.no-ip. 2858 :UBC 0 : goto l1;
2859 : : }
2860 : :
2861 : : /*
2862 : : * You might think the multixact is necessarily done here, but not
2863 : : * so: it could have surviving members, namely our own xact or
2864 : : * other subxacts of this backend. It is legal for us to delete
2865 : : * the tuple in either case, however (the latter case is
2866 : : * essentially a situation of upgrading our former shared lock to
2867 : : * exclusive). We don't bother changing the on-disk hint bits
2868 : : * since we are about to overwrite the xmax altogether.
2869 : : */
2870 : : }
4043 alvherre@alvh.no-ip. 2871 [ + + ]:CBC 40659 : else if (!TransactionIdIsCurrentTransactionId(xwait))
2872 : : {
2873 : : /*
2874 : : * Wait for regular transaction to end; but first, acquire tuple
2875 : : * lock.
2876 : : */
2877 : 70 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2878 : 70 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2879 : : LockWaitBlock, &have_tuple_lock);
4108 heikki.linnakangas@i 2880 : 70 : XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
7677 tgl@sss.pgh.pa.us 2881 : 66 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2882 : :
2883 : : /*
2884 : : * xwait is done, but if xwait had just locked the tuple then some
2885 : : * other xact could update this tuple before we get to this point.
2886 : : * Check for xmax change, and start over if so.
2887 : : *
2888 : : * We also must start over if we didn't pin the VM page, and the
2889 : : * page has become all visible.
2890 : : */
1321 jdavis@postgresql.or 2891 [ + - + - : 132 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ + ]
2892 [ - + ]: 131 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4850 alvherre@alvh.no-ip. 2893 : 65 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2894 : : xwait))
7677 tgl@sss.pgh.pa.us 2895 : 1 : goto l1;
2896 : :
2897 : : /* Otherwise check if it committed or aborted */
6839 2898 : 65 : UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2899 : : }
2900 : :
2901 : : /*
2902 : : * We may overwrite if previous xmax aborted, or if it committed but
2903 : : * only locked the tuple without updating it.
2904 : : */
4850 alvherre@alvh.no-ip. 2905 [ + + + + ]: 81304 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2906 [ + + ]: 40691 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2907 : 49 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2600 andres@anarazel.de 2908 : 40617 : result = TM_Ok;
1898 alvherre@alvh.no-ip. 2909 [ + + ]: 45 : else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2600 andres@anarazel.de 2910 : 32 : result = TM_Updated;
2911 : : else
2912 : 13 : result = TM_Deleted;
2913 : : }
2914 : :
2915 : : /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2916 [ + + ]: 1848035 : if (result != TM_Ok)
2917 : : {
2918 [ + + + + : 100 : Assert(result == TM_SelfModified ||
- + - - ]
2919 : : result == TM_Updated ||
2920 : : result == TM_Deleted ||
2921 : : result == TM_BeingModified);
7563 tgl@sss.pgh.pa.us 2922 [ - + ]: 100 : Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2600 andres@anarazel.de 2923 [ + + - + ]: 100 : Assert(result != TM_Updated ||
2924 : : !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2925 : : }
2926 : :
889 heikki.linnakangas@i 2927 [ + + + - ]: 1848035 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
2928 : : {
2929 : : /* Perform additional check for transaction-snapshot mode RI updates */
2930 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2931 : 1 : result = TM_Updated;
2932 : : }
2933 : :
2934 [ + + ]: 1848035 : if (result != TM_Ok)
2935 : : {
2600 andres@anarazel.de 2936 : 101 : tmfd->ctid = tp.t_data->t_ctid;
2937 : 101 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2938 [ + + ]: 101 : if (result == TM_SelfModified)
2939 : 36 : tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2940 : : else
2941 : 65 : tmfd->cmax = InvalidCommandId;
754 akorotkov@postgresql 2942 : 101 : UnlockReleaseBuffer(buffer);
7675 tgl@sss.pgh.pa.us 2943 [ + + ]: 101 : if (have_tuple_lock)
4850 alvherre@alvh.no-ip. 2944 : 45 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
5432 rhaas@postgresql.org 2945 [ - + ]: 101 : if (vmbuffer != InvalidBuffer)
5432 rhaas@postgresql.org 2946 :UBC 0 : ReleaseBuffer(vmbuffer);
10003 vadim4o@yahoo.com 2947 :CBC 101 : return result;
2948 : : }
2949 : :
2950 : : /*
2951 : : * We're about to do the actual delete -- check for conflict first, to
2952 : : * avoid possibly having to roll back work we've just done.
2953 : : *
2954 : : * This is safe without a recheck as long as there is no possibility of
2955 : : * another process scanning the page between this check and the delete
2956 : : * being visible to the scan (i.e., an exclusive buffer content lock is
2957 : : * continuously held from this point until the tuple delete is visible).
2958 : : */
2289 tmunro@postgresql.or 2959 : 1847934 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2960 : :
2961 : : /* replace cid with a combo CID if necessary */
7025 tgl@sss.pgh.pa.us 2962 : 1847920 : HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2963 : :
2964 : : /*
2965 : : * Compute replica identity tuple before entering the critical section so
2966 : : * we don't PANIC upon a memory allocation failure.
2967 : : */
29 alvherre@kurilemu.de 2968 :GNC 1847920 : old_key_tuple = walLogical ?
2969 [ + + ]: 1847920 : ExtractReplicaIdentity(relation, &tp, true, &old_key_copied) : NULL;
2970 : :
2971 : : /*
2972 : : * If this is the first possibly-multixact-able operation in the current
2973 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
2974 : : * certain that the transaction will never become a member of any older
2975 : : * MultiXactIds than that. (We have to do this even if we end up just
2976 : : * using our own TransactionId below, since some other backend could
2977 : : * incorporate our XID into a MultiXact immediately afterwards.)
2978 : : */
4414 heikki.linnakangas@i 2979 :CBC 1847920 : MultiXactIdSetOldestMember();
2980 : :
2981 : 1847920 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
2982 : 1847920 : tp.t_data->t_infomask, tp.t_data->t_infomask2,
2983 : : xid, LockTupleExclusive, true,
2984 : : &new_xmax, &new_infomask, &new_infomask2);
2985 : :
9244 tgl@sss.pgh.pa.us 2986 : 1847920 : START_CRIT_SECTION();
2987 : :
2988 : : /*
2989 : : * If this transaction commits, the tuple will become DEAD sooner or
2990 : : * later. Set flag that this page is a candidate for pruning once our xid
2991 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
2992 : : * the subsequent page pruning will be a no-op and the hint will be
2993 : : * cleared.
2994 : : */
6505 2995 [ - + + + : 1847920 : PageSetPrunable(page, xid);
+ + ]
2996 : :
6362 heikki.linnakangas@i 2997 [ + + ]: 1847920 : if (PageIsAllVisible(page))
2998 : : {
2999 : 1936 : all_visible_cleared = true;
3000 : 1936 : PageClearAllVisible(page);
5432 rhaas@postgresql.org 3001 : 1936 : visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3002 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
3003 : : }
3004 : :
3005 : : /* store transaction information of xact deleting the tuple */
4850 alvherre@alvh.no-ip. 3006 : 1847920 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3007 : 1847920 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3008 : 1847920 : tp.t_data->t_infomask |= new_infomask;
3009 : 1847920 : tp.t_data->t_infomask2 |= new_infomask2;
6802 tgl@sss.pgh.pa.us 3010 : 1847920 : HeapTupleHeaderClearHotUpdated(tp.t_data);
4850 alvherre@alvh.no-ip. 3011 : 1847920 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
7025 tgl@sss.pgh.pa.us 3012 : 1847920 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3013 : : /* Make sure there is no forward chain link in t_ctid */
8666 3014 : 1847920 : tp.t_data->t_ctid = tp.t_self;
3015 : :
3016 : : /* Signal that this is actually a move into another partition */
2950 andres@anarazel.de 3017 [ + + ]: 1847920 : if (changingPart)
3018 : 666 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
3019 : :
7340 tgl@sss.pgh.pa.us 3020 : 1847920 : MarkBufferDirty(buffer);
3021 : :
3022 : : /*
3023 : : * XLOG stuff
3024 : : *
3025 : : * NB: heap_abort_speculative() uses the same xlog record and replay
3026 : : * routines.
3027 : : */
5622 rhaas@postgresql.org 3028 [ + + + + : 1847920 : if (RelationNeedsWAL(relation))
+ - + + ]
3029 : : {
3030 : : xl_heap_delete xlrec;
3031 : : xl_heap_header xlhdr;
3032 : : XLogRecPtr recptr;
3033 : :
3034 : : /*
3035 : : * For logical decode we need combo CIDs to properly decode the
3036 : : * catalog
3037 : : */
4529 3038 [ + + + + : 1764677 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- - + ]
3039 : 10297 : log_heap_new_cid(relation, &tp);
3040 : :
2950 andres@anarazel.de 3041 : 1764677 : xlrec.flags = 0;
3042 [ + + ]: 1764677 : if (all_visible_cleared)
3043 : 1936 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3044 [ + + ]: 1764677 : if (changingPart)
3045 : 666 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
4850 alvherre@alvh.no-ip. 3046 : 3529354 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3047 : 1764677 : tp.t_data->t_infomask2);
4184 heikki.linnakangas@i 3048 : 1764677 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
4850 alvherre@alvh.no-ip. 3049 : 1764677 : xlrec.xmax = new_xmax;
3050 : :
4184 heikki.linnakangas@i 3051 [ + + ]: 1764677 : if (old_key_tuple != NULL)
3052 : : {
3053 [ + + ]: 47029 : if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4015 andres@anarazel.de 3054 : 135 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
3055 : : else
3056 : 46894 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
3057 : : }
3058 : :
3059 : : /*
3060 : : * Mark the change as not-for-logical-decoding if caller requested so.
3061 : : *
3062 : : * (This is used for changes that affect relations not visible to
3063 : : * other transactions, such as the transient table during concurrent
3064 : : * repack.)
3065 : : */
29 alvherre@kurilemu.de 3066 [ + + ]:GNC 1764677 : if (!walLogical)
3067 : 3 : xlrec.flags |= XLH_DELETE_NO_LOGICAL;
3068 : :
4184 heikki.linnakangas@i 3069 :CBC 1764677 : XLogBeginInsert();
448 peter@eisentraut.org 3070 : 1764677 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3071 : :
4184 heikki.linnakangas@i 3072 : 1764677 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3073 : :
3074 : : /*
3075 : : * Log replica identity of the deleted tuple if there is one
3076 : : */
4529 rhaas@postgresql.org 3077 [ + + ]: 1764677 : if (old_key_tuple != NULL)
3078 : : {
3079 : 47029 : xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3080 : 47029 : xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3081 : 47029 : xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3082 : :
448 peter@eisentraut.org 3083 : 47029 : XLogRegisterData(&xlhdr, SizeOfHeapHeader);
4184 heikki.linnakangas@i 3084 : 47029 : XLogRegisterData((char *) old_key_tuple->t_data
3085 : : + SizeofHeapTupleHeader,
3086 : 47029 : old_key_tuple->t_len
3087 : : - SizeofHeapTupleHeader);
3088 : : }
3089 : :
3090 : : /* filtering by origin on a row level is much more efficient */
3421 andres@anarazel.de 3091 : 1764677 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3092 : :
4184 heikki.linnakangas@i 3093 : 1764677 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3094 : :
6505 tgl@sss.pgh.pa.us 3095 : 1764677 : PageSetLSN(page, recptr);
3096 : : }
3097 : :
9244 3098 [ - + ]: 1847920 : END_CRIT_SECTION();
3099 : :
9241 3100 : 1847920 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3101 : :
5432 rhaas@postgresql.org 3102 [ + + ]: 1847920 : if (vmbuffer != InvalidBuffer)
3103 : 1936 : ReleaseBuffer(vmbuffer);
3104 : :
3105 : : /*
3106 : : * If the tuple has toasted out-of-line attributes, we need to delete
3107 : : * those items too. We have to do this before releasing the buffer
3108 : : * because we need to look at the contents of the tuple, but it's OK to
3109 : : * release the content lock on the buffer first.
3110 : : */
4811 kgrittn@postgresql.o 3111 [ + + ]: 1847920 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3112 [ + + ]: 3886 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3113 : : {
3114 : : /* toast table entries should never be recursively toasted */
6972 tgl@sss.pgh.pa.us 3115 [ - + ]: 3873 : Assert(!HeapTupleHasExternal(&tp));
3116 : : }
3117 [ + + ]: 1844047 : else if (HeapTupleHasExternal(&tp))
2405 rhaas@postgresql.org 3118 : 534 : heap_toast_delete(relation, &tp, false);
3119 : :
3120 : : /*
3121 : : * Mark tuple for invalidation from system caches at next command
3122 : : * boundary. We have to do this before releasing the buffer because we
3123 : : * need to look at the contents of the tuple.
3124 : : */
5376 tgl@sss.pgh.pa.us 3125 : 1847920 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3126 : :
3127 : : /* Now we can release the buffer */
754 akorotkov@postgresql 3128 : 1847920 : ReleaseBuffer(buffer);
3129 : :
3130 : : /*
3131 : : * Release the lmgr tuple lock, if we had it.
3132 : : */
7675 tgl@sss.pgh.pa.us 3133 [ + + ]: 1847920 : if (have_tuple_lock)
4850 alvherre@alvh.no-ip. 3134 : 26 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3135 : :
6918 tgl@sss.pgh.pa.us 3136 : 1847920 : pgstat_count_heap_delete(relation);
3137 : :
4529 rhaas@postgresql.org 3138 [ + + + + ]: 1847920 : if (old_key_tuple != NULL && old_key_copied)
3139 : 46895 : heap_freetuple(old_key_tuple);
3140 : :
2600 andres@anarazel.de 3141 : 1847920 : return TM_Ok;
3142 : : }
3143 : :
3144 : : /*
3145 : : * simple_heap_delete - delete a tuple
3146 : : *
3147 : : * This routine may be used to delete a tuple when concurrent updates of
3148 : : * the target tuple are not expected (for example, because we have a lock
3149 : : * on the relation associated with the tuple). Any failure is reported
3150 : : * via ereport().
3151 : : */
3152 : : void
187 peter@eisentraut.org 3153 :GNC 822668 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
3154 : : {
3155 : : TM_Result result;
3156 : : TM_FailureData tmfd;
3157 : :
8268 tgl@sss.pgh.pa.us 3158 :CBC 822668 : result = heap_delete(relation, tid,
3159 : : GetCurrentCommandId(true),
3160 : : 0,
3161 : : InvalidSnapshot,
3162 : : true /* wait for commit */ ,
3163 : : &tmfd);
9233 3164 [ - + - - : 822668 : switch (result)
- ]
3165 : : {
2600 andres@anarazel.de 3166 :UBC 0 : case TM_SelfModified:
3167 : : /* Tuple was already updated in current command? */
8324 tgl@sss.pgh.pa.us 3168 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
3169 : : break;
3170 : :
2600 andres@anarazel.de 3171 :CBC 822668 : case TM_Ok:
3172 : : /* done successfully */
9233 tgl@sss.pgh.pa.us 3173 : 822668 : break;
3174 : :
2600 andres@anarazel.de 3175 :UBC 0 : case TM_Updated:
8324 tgl@sss.pgh.pa.us 3176 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
3177 : : break;
3178 : :
2600 andres@anarazel.de 3179 : 0 : case TM_Deleted:
3180 [ # # ]: 0 : elog(ERROR, "tuple concurrently deleted");
3181 : : break;
3182 : :
9233 tgl@sss.pgh.pa.us 3183 : 0 : default:
8324 3184 [ # # ]: 0 : elog(ERROR, "unrecognized heap_delete status: %u", result);
3185 : : break;
3186 : : }
9233 tgl@sss.pgh.pa.us 3187 :CBC 822668 : }
3188 : :
3189 : : /*
3190 : : * heap_update - replace a tuple
3191 : : *
3192 : : * See table_tuple_update() for an explanation of the parameters, except that
3193 : : * this routine directly takes a tuple rather than a slot.
3194 : : *
3195 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3196 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3197 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3198 : : * generated by another transaction).
3199 : : */
3200 : : TM_Result
187 peter@eisentraut.org 3201 :GNC 2383592 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
3202 : : CommandId cid, uint32 options pg_attribute_unused(), Snapshot crosscheck, bool wait,
3203 : : TM_FailureData *tmfd, LockTupleMode *lockmode,
3204 : : TU_UpdateIndexes *update_indexes)
3205 : : {
3206 : : TM_Result result;
7901 tgl@sss.pgh.pa.us 3207 :CBC 2383592 : TransactionId xid = GetCurrentTransactionId();
3208 : : Bitmapset *hot_attrs;
3209 : : Bitmapset *sum_attrs;
3210 : : Bitmapset *key_attrs;
3211 : : Bitmapset *id_attrs;
3212 : : Bitmapset *interesting_attrs;
3213 : : Bitmapset *modified_attrs;
3214 : : ItemId lp;
3215 : : HeapTupleData oldtup;
3216 : : HeapTuple heaptup;
4529 rhaas@postgresql.org 3217 : 2383592 : HeapTuple old_key_tuple = NULL;
3218 : 2383592 : bool old_key_copied = false;
29 alvherre@kurilemu.de 3219 :GNC 2383592 : bool walLogical = (options & TABLE_UPDATE_NO_LOGICAL) == 0;
3220 : : Page page,
3221 : : newpage;
3222 : : BlockNumber block;
3223 : : MultiXactStatus mxact_status;
3224 : : Buffer buffer,
3225 : : newbuf,
5432 rhaas@postgresql.org 3226 :CBC 2383592 : vmbuffer = InvalidBuffer,
3227 : 2383592 : vmbuffer_new = InvalidBuffer;
3228 : : bool need_toast;
3229 : : Size newtupsize,
3230 : : pagefree;
7675 tgl@sss.pgh.pa.us 3231 : 2383592 : bool have_tuple_lock = false;
3232 : : bool iscombo;
6802 3233 : 2383592 : bool use_hot_update = false;
1142 tomas.vondra@postgre 3234 : 2383592 : bool summarized_update = false;
3235 : : bool key_intact;
6362 heikki.linnakangas@i 3236 : 2383592 : bool all_visible_cleared = false;
3237 : 2383592 : bool all_visible_cleared_new = false;
3238 : : bool checked_lockers;
3239 : : bool locker_remains;
1541 akapila@postgresql.o 3240 : 2383592 : bool id_has_external = false;
3241 : : TransactionId xmax_new_tuple,
3242 : : xmax_old_tuple;
3243 : : uint16 infomask_old_tuple,
3244 : : infomask2_old_tuple,
3245 : : infomask_new_tuple,
3246 : : infomask2_new_tuple;
3247 : :
10467 bruce@momjian.us 3248 [ - + ]: 2383592 : Assert(ItemPointerIsValid(otid));
3249 : :
3250 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1821 tgl@sss.pgh.pa.us 3251 [ - + ]: 2383592 : Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
3252 : : RelationGetNumberOfAttributes(relation));
3253 : :
340 nathan@postgresql.or 3254 : 2383592 : AssertHasSnapshotForToast(relation);
3255 : :
3256 : : /*
3257 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
3258 : : * Other workers might need that combo CID for visibility checks, and we
3259 : : * have no provision for broadcasting it to them.
3260 : : */
4023 rhaas@postgresql.org 3261 [ - + ]: 2383592 : if (IsInParallelMode())
4023 rhaas@postgresql.org 3262 [ # # ]:UBC 0 : ereport(ERROR,
3263 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3264 : : errmsg("cannot update tuples during a parallel operation")));
3265 : :
3266 : : #ifdef USE_ASSERT_CHECKING
588 noah@leadboat.com 3267 :CBC 2383592 : check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3268 : : #endif
3269 : :
3270 : : /*
3271 : : * Fetch the list of attributes to be checked for various operations.
3272 : : *
3273 : : * For HOT considerations, this is wasted effort if we fail to update or
3274 : : * have to put the new tuple on a different page. But we must compute the
3275 : : * list before obtaining buffer lock --- in the worst case, if we are
3276 : : * doing an update on one of the relevant system catalogs, we could
3277 : : * deadlock if we try to fetch the list later. In any case, the relcache
3278 : : * caches the data so this is usually pretty cheap.
3279 : : *
3280 : : * We also need columns used by the replica identity and columns that are
3281 : : * considered the "key" of rows in the table.
3282 : : *
3283 : : * Note that we get copies of each bitmap, so we need not worry about
3284 : : * relcache flush happening midway through.
3285 : : */
1142 tomas.vondra@postgre 3286 : 2383592 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3287 : : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3288 : 2383592 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3289 : : INDEX_ATTR_BITMAP_SUMMARIZED);
4529 rhaas@postgresql.org 3290 : 2383592 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3291 : 2383592 : id_attrs = RelationGetIndexAttrBitmap(relation,
3292 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
1621 pg@bowt.ie 3293 : 2383592 : interesting_attrs = NULL;
3294 : 2383592 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
1142 tomas.vondra@postgre 3295 : 2383592 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
1621 pg@bowt.ie 3296 : 2383592 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3297 : 2383592 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3298 : :
5432 rhaas@postgresql.org 3299 : 2383592 : block = ItemPointerGetBlockNumber(otid);
360 michael@paquier.xyz 3300 : 2383592 : INJECTION_POINT("heap_update-before-pin", NULL);
5432 rhaas@postgresql.org 3301 : 2383592 : buffer = ReadBuffer(relation, block);
3667 kgrittn@postgresql.o 3302 : 2383592 : page = BufferGetPage(buffer);
3303 : :
3304 : : /*
3305 : : * Before locking the buffer, pin the visibility map page if it appears to
3306 : : * be necessary. Since we haven't got the lock yet, someone else might be
3307 : : * in the middle of changing this, so we'll need to recheck after we have
3308 : : * the lock.
3309 : : */
5432 rhaas@postgresql.org 3310 [ + + ]: 2383592 : if (PageIsAllVisible(page))
3311 : 2308 : visibilitymap_pin(relation, block, &vmbuffer);
3312 : :
10003 vadim4o@yahoo.com 3313 : 2383592 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3314 : :
6505 tgl@sss.pgh.pa.us 3315 : 2383592 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3316 : :
3317 : : /*
3318 : : * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3319 : : * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3320 : : * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3321 : : * of which indicates concurrent pruning.
3322 : : *
3323 : : * Failing with TM_Updated would be most accurate. However, unlike other
3324 : : * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3325 : : * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3326 : : * does matter to SQL statements UPDATE and MERGE, those SQL statements
3327 : : * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3328 : : * TM_Updated and TM_Deleted affects only the wording of error messages.
3329 : : * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3330 : : * the specification of when tmfd->ctid is valid. Second, it creates
3331 : : * error log evidence that we took this branch.
3332 : : *
3333 : : * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3334 : : * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3335 : : * unrelated row, we'll fail with "duplicate key value violates unique".
3336 : : * XXX if otid is the live, newer version of the newtup row, we'll discard
3337 : : * changes originating in versions of this catalog row after the version
3338 : : * the caller got from syscache. See syscache-update-pruned.spec.
3339 : : */
465 noah@leadboat.com 3340 [ + + ]: 2383592 : if (!ItemIdIsNormal(lp))
3341 : : {
3342 [ - + ]: 1 : Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
3343 : :
3344 : 1 : UnlockReleaseBuffer(buffer);
3345 [ - + ]: 1 : Assert(!have_tuple_lock);
3346 [ + - ]: 1 : if (vmbuffer != InvalidBuffer)
3347 : 1 : ReleaseBuffer(vmbuffer);
3348 : 1 : tmfd->ctid = *otid;
3349 : 1 : tmfd->xmax = InvalidTransactionId;
3350 : 1 : tmfd->cmax = InvalidCommandId;
3351 : 1 : *update_indexes = TU_None;
3352 : :
3353 : 1 : bms_free(hot_attrs);
3354 : 1 : bms_free(sum_attrs);
3355 : 1 : bms_free(key_attrs);
3356 : 1 : bms_free(id_attrs);
3357 : : /* modified_attrs not yet initialized */
3358 : 1 : bms_free(interesting_attrs);
3359 : 1 : return TM_Deleted;
3360 : : }
3361 : :
3362 : : /*
3363 : : * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3364 : : * properly.
3365 : : */
4841 alvherre@alvh.no-ip. 3366 : 2383591 : oldtup.t_tableOid = RelationGetRelid(relation);
6505 tgl@sss.pgh.pa.us 3367 : 2383591 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
10021 vadim4o@yahoo.com 3368 : 2383591 : oldtup.t_len = ItemIdGetLength(lp);
3369 : 2383591 : oldtup.t_self = *otid;
3370 : :
3371 : : /* the new tuple is ready, except for this: */
4841 alvherre@alvh.no-ip. 3372 : 2383591 : newtup->t_tableOid = RelationGetRelid(relation);
3373 : :
3374 : : /*
3375 : : * Determine columns modified by the update. Additionally, identify
3376 : : * whether any of the unmodified replica identity key attributes in the
3377 : : * old tuple is externally stored or not. This is required because for
3378 : : * such attributes the flattened value won't be WAL logged as part of the
3379 : : * new tuple so we must include it as part of the old_key_tuple. See
3380 : : * ExtractReplicaIdentity.
3381 : : */
1541 akapila@postgresql.o 3382 : 2383591 : modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3383 : : id_attrs, &oldtup,
3384 : : newtup, &id_has_external);
3385 : :
3386 : : /*
3387 : : * If we're not updating any "key" column, we can grab a weaker lock type.
3388 : : * This allows for more concurrency when we are running simultaneously
3389 : : * with foreign key checks.
3390 : : *
3391 : : * Note that if a column gets detoasted while executing the update, but
3392 : : * the value ends up being the same, this test will fail and we will use
3393 : : * the stronger lock. This is acceptable; the important case to optimize
3394 : : * is updates that don't manipulate key columns, not those that
3395 : : * serendipitously arrive at the same key values.
3396 : : */
3324 alvherre@alvh.no-ip. 3397 [ + + ]: 2383591 : if (!bms_overlap(modified_attrs, key_attrs))
3398 : : {
2945 simon@2ndQuadrant.co 3399 : 2377692 : *lockmode = LockTupleNoKeyExclusive;
4850 alvherre@alvh.no-ip. 3400 : 2377692 : mxact_status = MultiXactStatusNoKeyUpdate;
3401 : 2377692 : key_intact = true;
3402 : :
3403 : : /*
3404 : : * If this is the first possibly-multixact-able operation in the
3405 : : * current transaction, set my per-backend OldestMemberMXactId
3406 : : * setting. We can be certain that the transaction will never become a
3407 : : * member of any older MultiXactIds than that. (We have to do this
3408 : : * even if we end up just using our own TransactionId below, since
3409 : : * some other backend could incorporate our XID into a MultiXact
3410 : : * immediately afterwards.)
3411 : : */
3412 : 2377692 : MultiXactIdSetOldestMember();
3413 : : }
3414 : : else
3415 : : {
2945 simon@2ndQuadrant.co 3416 : 5899 : *lockmode = LockTupleExclusive;
4850 alvherre@alvh.no-ip. 3417 : 5899 : mxact_status = MultiXactStatusUpdate;
3418 : 5899 : key_intact = false;
3419 : : }
3420 : :
3421 : : /*
3422 : : * Note: beyond this point, use oldtup not otid to refer to old tuple.
3423 : : * otid may very well point at newtup->t_self, which we will overwrite
3424 : : * with the new tuple's location, so there's great risk of confusion if we
3425 : : * use otid anymore.
3426 : : */
3427 : :
10003 vadim4o@yahoo.com 3428 : 1 : l2:
4850 alvherre@alvh.no-ip. 3429 : 2383592 : checked_lockers = false;
3430 : 2383592 : locker_remains = false;
4670 rhaas@postgresql.org 3431 : 2383592 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3432 : :
3433 : : /* see below about the "no wait" case */
754 akorotkov@postgresql 3434 [ + + - + ]: 2383592 : Assert(result != TM_BeingModified || wait);
3435 : :
2600 andres@anarazel.de 3436 [ - + ]: 2383592 : if (result == TM_Invisible)
3437 : : {
7340 tgl@sss.pgh.pa.us 3438 :UBC 0 : UnlockReleaseBuffer(buffer);
3929 3439 [ # # ]: 0 : ereport(ERROR,
3440 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3441 : : errmsg("attempted to update invisible tuple")));
3442 : : }
754 akorotkov@postgresql 3443 [ + + + - ]:CBC 2383592 : else if (result == TM_BeingModified && wait)
3444 : : {
3445 : : TransactionId xwait;
3446 : : uint16 infomask;
4850 alvherre@alvh.no-ip. 3447 : 36536 : bool can_continue = false;
3448 : :
3449 : : /*
3450 : : * XXX note that we don't consider the "no wait" case here. This
3451 : : * isn't a problem currently because no caller uses that case, but it
3452 : : * should be fixed if such a caller is introduced. It wasn't a
3453 : : * problem previously because this code would always wait, but now
3454 : : * that some tuple locks do not conflict with one of the lock modes we
3455 : : * use, it is possible that this case is interesting to handle
3456 : : * specially.
3457 : : *
3458 : : * This may cause failures with third-party code that calls
3459 : : * heap_update directly.
3460 : : */
3461 : :
3462 : : /* must copy state data before unlocking buffer */
3463 : 36536 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
7675 tgl@sss.pgh.pa.us 3464 : 36536 : infomask = oldtup.t_data->t_infomask;
3465 : :
3466 : : /*
3467 : : * Now we have to do something about the existing locker. If it's a
3468 : : * multi, sleep on it; we might be awakened before it is completely
3469 : : * gone (or even not sleep at all in some cases); we need to preserve
3470 : : * it as locker, unless it is gone completely.
3471 : : *
3472 : : * If it's not a multi, we need to check for sleeping conditions
3473 : : * before actually going to sleep. If the update doesn't conflict
3474 : : * with the locks, we just continue without sleeping (but making sure
3475 : : * it is preserved).
3476 : : *
3477 : : * Before sleeping, we need to acquire tuple lock to establish our
3478 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
3479 : : * release us when we are next-in-line for the tuple. Note we must
3480 : : * not acquire the tuple lock until we're sure we're going to sleep;
3481 : : * otherwise we're open for race conditions with other transactions
3482 : : * holding the tuple lock which sleep on us.
3483 : : *
3484 : : * If we are forced to "start over" below, we keep the tuple lock;
3485 : : * this arranges that we stay at the head of the line while rechecking
3486 : : * tuple state.
3487 : : */
7677 3488 [ + + ]: 36536 : if (infomask & HEAP_XMAX_IS_MULTI)
3489 : : {
3490 : : TransactionId update_xact;
3491 : : int remain;
2513 alvherre@alvh.no-ip. 3492 : 179 : bool current_is_member = false;
3493 : :
4043 3494 [ + + ]: 179 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3495 : : *lockmode, ¤t_is_member))
3496 : : {
3497 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3498 : :
3499 : : /*
3500 : : * Acquire the lock, if necessary (but skip it when we're
3501 : : * requesting a lock and already have one; avoids deadlock).
3502 : : */
2513 3503 [ - + ]: 8 : if (!current_is_member)
2513 alvherre@alvh.no-ip. 3504 :UBC 0 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3505 : : LockWaitBlock, &have_tuple_lock);
3506 : :
3507 : : /* wait for multixact */
4043 alvherre@alvh.no-ip. 3508 :CBC 8 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3509 : : relation, &oldtup.t_self, XLTW_Update,
3510 : : &remain);
3511 : 8 : checked_lockers = true;
3512 : 8 : locker_remains = remain != 0;
3513 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3514 : :
3515 : : /*
3516 : : * If xwait had just locked the tuple then some other xact
3517 : : * could update this tuple before we get to this point. Check
3518 : : * for xmax change, and start over if so.
3519 : : */
3520 [ + - ]: 8 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3521 [ - + ]: 8 : infomask) ||
3240 tgl@sss.pgh.pa.us 3522 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3523 : : xwait))
4043 alvherre@alvh.no-ip. 3524 :UBC 0 : goto l2;
3525 : : }
3526 : :
3527 : : /*
3528 : : * Note that the multixact may not be done by now. It could have
3529 : : * surviving members; our own xact or other subxacts of this
3530 : : * backend, and also any other concurrent transaction that locked
3531 : : * the tuple with LockTupleKeyShare if we only got
3532 : : * LockTupleNoKeyExclusive. If this is the case, we have to be
3533 : : * careful to mark the updated tuple with the surviving members in
3534 : : * Xmax.
3535 : : *
3536 : : * Note that there could have been another update in the
3537 : : * MultiXact. In that case, we need to check whether it committed
3538 : : * or aborted. If it aborted we are safe to update it again;
3539 : : * otherwise there is an update conflict, and we have to return
3540 : : * TableTuple{Deleted, Updated} below.
3541 : : *
3542 : : * In the LockTupleExclusive case, we still need to preserve the
3543 : : * surviving members: those would include the tuple locks we had
3544 : : * before this one, which are important to keep in case this
3545 : : * subxact aborts.
3546 : : */
4850 alvherre@alvh.no-ip. 3547 [ + + ]:CBC 179 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3548 : 8 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3549 : : else
4043 3550 : 171 : update_xact = InvalidTransactionId;
3551 : :
3552 : : /*
3553 : : * There was no UPDATE in the MultiXact; or it aborted. No
3554 : : * TransactionIdIsInProgress() call needed here, since we called
3555 : : * MultiXactIdWait() above.
3556 : : */
4850 3557 [ + + + + ]: 187 : if (!TransactionIdIsValid(update_xact) ||
3558 : 8 : TransactionIdDidAbort(update_xact))
3559 : 172 : can_continue = true;
3560 : : }
4043 3561 [ + + ]: 36357 : else if (TransactionIdIsCurrentTransactionId(xwait))
3562 : : {
3563 : : /*
3564 : : * The only locker is ourselves; we can avoid grabbing the tuple
3565 : : * lock here, but must preserve our locking information.
3566 : : */
3567 : 36229 : checked_lockers = true;
3568 : 36229 : locker_remains = true;
3569 : 36229 : can_continue = true;
3570 : : }
3571 [ + + + + ]: 128 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3572 : : {
3573 : : /*
3574 : : * If it's just a key-share locker, and we're not changing the key
3575 : : * columns, we don't need to wait for it to end; but we need to
3576 : : * preserve it as locker.
3577 : : */
3578 : 29 : checked_lockers = true;
3579 : 29 : locker_remains = true;
3580 : 29 : can_continue = true;
3581 : : }
3582 : : else
3583 : : {
3584 : : /*
3585 : : * Wait for regular transaction to end; but first, acquire tuple
3586 : : * lock.
3587 : : */
3588 : 99 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2945 simon@2ndQuadrant.co 3589 : 99 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3590 : : LockWaitBlock, &have_tuple_lock);
4043 alvherre@alvh.no-ip. 3591 : 99 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3592 : : XLTW_Update);
3593 : 99 : checked_lockers = true;
3594 : 99 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3595 : :
3596 : : /*
3597 : : * xwait is done, but if xwait had just locked the tuple then some
3598 : : * other xact could update this tuple before we get to this point.
3599 : : * Check for xmax change, and start over if so.
3600 : : */
3601 [ + + - + ]: 197 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3602 : 98 : !TransactionIdEquals(xwait,
3603 : : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3604 : 1 : goto l2;
3605 : :
3606 : : /* Otherwise check if it committed or aborted */
3607 : 98 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3608 [ + + ]: 98 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
4850 3609 : 22 : can_continue = true;
3610 : : }
3611 : :
2600 andres@anarazel.de 3612 [ + + ]: 36535 : if (can_continue)
3613 : 36452 : result = TM_Ok;
1898 alvherre@alvh.no-ip. 3614 [ + + ]: 83 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
2600 andres@anarazel.de 3615 : 69 : result = TM_Updated;
3616 : : else
3617 : 14 : result = TM_Deleted;
3618 : : }
3619 : :
3620 : : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3621 [ + + ]: 2383591 : if (result != TM_Ok)
3622 : : {
3623 [ + + + + : 207 : Assert(result == TM_SelfModified ||
- + - - ]
3624 : : result == TM_Updated ||
3625 : : result == TM_Deleted ||
3626 : : result == TM_BeingModified);
7563 tgl@sss.pgh.pa.us 3627 [ - + ]: 207 : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
2600 andres@anarazel.de 3628 [ + + - + ]: 207 : Assert(result != TM_Updated ||
3629 : : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3630 : : }
3631 : :
889 heikki.linnakangas@i 3632 [ + + + - ]: 2383591 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3633 : : {
3634 : : /* Perform additional check for transaction-snapshot mode RI updates */
3635 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3636 : 1 : result = TM_Updated;
3637 : : }
3638 : :
3639 [ + + ]: 2383591 : if (result != TM_Ok)
3640 : : {
2600 andres@anarazel.de 3641 : 208 : tmfd->ctid = oldtup.t_data->t_ctid;
3642 : 208 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3643 [ + + ]: 208 : if (result == TM_SelfModified)
3644 : 73 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3645 : : else
3646 : 135 : tmfd->cmax = InvalidCommandId;
754 akorotkov@postgresql 3647 : 208 : UnlockReleaseBuffer(buffer);
7675 tgl@sss.pgh.pa.us 3648 [ + + ]: 208 : if (have_tuple_lock)
2945 simon@2ndQuadrant.co 3649 : 76 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
5432 rhaas@postgresql.org 3650 [ - + ]: 208 : if (vmbuffer != InvalidBuffer)
5432 rhaas@postgresql.org 3651 :UBC 0 : ReleaseBuffer(vmbuffer);
1142 tomas.vondra@postgre 3652 :CBC 208 : *update_indexes = TU_None;
3653 : :
6802 tgl@sss.pgh.pa.us 3654 : 208 : bms_free(hot_attrs);
1142 tomas.vondra@postgre 3655 : 208 : bms_free(sum_attrs);
4850 alvherre@alvh.no-ip. 3656 : 208 : bms_free(key_attrs);
3541 tgl@sss.pgh.pa.us 3657 : 208 : bms_free(id_attrs);
3324 alvherre@alvh.no-ip. 3658 : 208 : bms_free(modified_attrs);
3659 : 208 : bms_free(interesting_attrs);
10003 vadim4o@yahoo.com 3660 : 208 : return result;
3661 : : }
3662 : :
3663 : : /*
3664 : : * If we didn't pin the visibility map page and the page has become all
3665 : : * visible while we were busy locking the buffer, or during some
3666 : : * subsequent window during which we had it unlocked, we'll have to unlock
3667 : : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3668 : : * bit unfortunate, especially since we'll now have to recheck whether the
3669 : : * tuple has been locked or updated under us, but hopefully it won't
3670 : : * happen very often.
3671 : : */
5426 rhaas@postgresql.org 3672 [ + + - + ]: 2383383 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3673 : : {
5426 rhaas@postgresql.org 3674 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3675 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
3676 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5334 3677 : 0 : goto l2;
3678 : : }
3679 : :
3680 : : /* Fill in transaction status data */
3681 : :
3682 : : /*
3683 : : * If the tuple we're updating is locked, we need to preserve the locking
3684 : : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3685 : : */
4850 alvherre@alvh.no-ip. 3686 :CBC 2383383 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3687 : 2383383 : oldtup.t_data->t_infomask,
3688 : 2383383 : oldtup.t_data->t_infomask2,
3689 : : xid, *lockmode, true,
3690 : : &xmax_old_tuple, &infomask_old_tuple,
3691 : : &infomask2_old_tuple);
3692 : :
3693 : : /*
3694 : : * And also prepare an Xmax value for the new copy of the tuple. If there
3695 : : * was no xmax previously, or there was one but all lockers are now gone,
3696 : : * then use InvalidTransactionId; otherwise, get the xmax from the old
3697 : : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3698 : : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3699 : : */
3700 [ + + + - ]: 2419813 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3602 3701 [ + + ]: 72860 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
4850 3702 [ - + ]: 36259 : (checked_lockers && !locker_remains))
3703 : 2346953 : xmax_new_tuple = InvalidTransactionId;
3704 : : else
3705 : 36430 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3706 : :
3707 [ + + ]: 2383383 : if (!TransactionIdIsValid(xmax_new_tuple))
3708 : : {
3709 : 2346953 : infomask_new_tuple = HEAP_XMAX_INVALID;
3710 : 2346953 : infomask2_new_tuple = 0;
3711 : : }
3712 : : else
3713 : : {
3714 : : /*
3715 : : * If we found a valid Xmax for the new tuple, then the infomask bits
3716 : : * to use on the new tuple depend on what was there on the old one.
3717 : : * Note that since we're doing an update, the only possibility is that
3718 : : * the lockers had FOR KEY SHARE lock.
3719 : : */
3720 [ + + ]: 36430 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3721 : : {
3722 : 172 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3723 : : &infomask2_new_tuple);
3724 : : }
3725 : : else
3726 : : {
3727 : 36258 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3728 : 36258 : infomask2_new_tuple = 0;
3729 : : }
3730 : : }
3731 : :
3732 : : /*
3733 : : * Prepare the new tuple with the appropriate initial values of Xmin and
3734 : : * Xmax, as well as initial infomask bits as computed above.
3735 : : */
10021 vadim4o@yahoo.com 3736 : 2383383 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
6802 tgl@sss.pgh.pa.us 3737 : 2383383 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
7901 3738 : 2383383 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
8725 bruce@momjian.us 3739 : 2383383 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
4850 alvherre@alvh.no-ip. 3740 : 2383383 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3741 : 2383383 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3742 : 2383383 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3743 : :
3744 : : /*
3745 : : * Replace cid with a combo CID if necessary. Note that we already put
3746 : : * the plain cid into the new tuple.
3747 : : */
7025 tgl@sss.pgh.pa.us 3748 : 2383383 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3749 : :
3750 : : /*
3751 : : * If the toaster needs to be activated, OR if the new tuple will not fit
3752 : : * on the same page as the old, then we need to release the content lock
3753 : : * (but not the pin!) on the old tuple's buffer while we are off doing
3754 : : * TOAST and/or table-file-extension work. We must mark the old tuple to
3755 : : * show that it's locked, else other processes may try to update it
3756 : : * themselves.
3757 : : *
3758 : : * We need to invoke the toaster if there are already any out-of-line
3759 : : * toasted values present, or if the new tuple is over-threshold.
3760 : : */
4811 kgrittn@postgresql.o 3761 [ - + ]: 2383383 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
4811 kgrittn@postgresql.o 3762 [ # # ]:UBC 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3763 : : {
3764 : : /* toast table entries should never be recursively toasted */
6972 tgl@sss.pgh.pa.us 3765 [ # # ]: 0 : Assert(!HeapTupleHasExternal(&oldtup));
3766 [ # # ]: 0 : Assert(!HeapTupleHasExternal(newtup));
3767 : 0 : need_toast = false;
3768 : : }
3769 : : else
6972 tgl@sss.pgh.pa.us 3770 [ + + ]:CBC 7149581 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3771 [ + + ]: 4766198 : HeapTupleHasExternal(newtup) ||
3772 [ + + ]: 2382783 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3773 : :
6505 3774 : 2383383 : pagefree = PageGetHeapFreeSpace(page);
3775 : :
7030 3776 : 2383383 : newtupsize = MAXALIGN(newtup->t_len);
3777 : :
9120 3778 [ + + + + ]: 2383383 : if (need_toast || newtupsize > pagefree)
9371 vadim4o@yahoo.com 3779 : 2199493 : {
3780 : : TransactionId xmax_lock_old_tuple;
3781 : : uint16 infomask_lock_old_tuple,
3782 : : infomask2_lock_old_tuple;
3578 andres@anarazel.de 3783 : 2199493 : bool cleared_all_frozen = false;
3784 : :
3785 : : /*
3786 : : * To prevent concurrent sessions from updating the tuple, we have to
3787 : : * temporarily mark it locked, while we release the page-level lock.
3788 : : *
3789 : : * To satisfy the rule that any xid potentially appearing in a buffer
3790 : : * written out to disk, we unfortunately have to WAL log this
3791 : : * temporary modification. We can reuse xl_heap_lock for this
3792 : : * purpose. If we crash/error before following through with the
3793 : : * actual update, xmax will be of an aborted transaction, allowing
3794 : : * other sessions to proceed.
3795 : : */
3796 : :
3797 : : /*
3798 : : * Compute xmax / infomask appropriate for locking the tuple. This has
3799 : : * to be done separately from the combo that's going to be used for
3800 : : * updating, because the potentially created multixact would otherwise
3801 : : * be wrong.
3802 : : */
3581 3803 : 2199493 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3804 : 2199493 : oldtup.t_data->t_infomask,
3805 : 2199493 : oldtup.t_data->t_infomask2,
3806 : : xid, *lockmode, false,
3807 : : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3808 : : &infomask2_lock_old_tuple);
3809 : :
3810 [ - + ]: 2199493 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3811 : :
3812 : 2199493 : START_CRIT_SECTION();
3813 : :
3814 : : /* Clear obsolete visibility flags ... */
4850 alvherre@alvh.no-ip. 3815 : 2199493 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3816 : 2199493 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6802 tgl@sss.pgh.pa.us 3817 : 2199493 : HeapTupleClearHotUpdated(&oldtup);
3818 : : /* ... and store info about transaction updating this tuple */
3581 andres@anarazel.de 3819 [ - + ]: 2199493 : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3820 : 2199493 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3821 : 2199493 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3822 : 2199493 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
7025 tgl@sss.pgh.pa.us 3823 : 2199493 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3824 : :
3825 : : /* temporarily make it look not-updated, but locked */
7471 3826 : 2199493 : oldtup.t_data->t_ctid = oldtup.t_self;
3827 : :
3828 : : /*
3829 : : * Clear all-frozen bit on visibility map if needed. We could
3830 : : * immediately reset ALL_VISIBLE, but given that the WAL logging
3831 : : * overhead would be unchanged, that doesn't seem necessarily
3832 : : * worthwhile.
3833 : : */
1848 3834 [ + + + + ]: 2200880 : if (PageIsAllVisible(page) &&
3578 andres@anarazel.de 3835 : 1387 : visibilitymap_clear(relation, block, vmbuffer,
3836 : : VISIBILITYMAP_ALL_FROZEN))
3837 : 890 : cleared_all_frozen = true;
3838 : :
3581 3839 : 2199493 : MarkBufferDirty(buffer);
3840 : :
3841 [ + + + + : 2199493 : if (RelationNeedsWAL(relation))
+ - + + ]
3842 : : {
3843 : : xl_heap_lock xlrec;
3844 : : XLogRecPtr recptr;
3845 : :
3846 : 2189358 : XLogBeginInsert();
3847 : 2189358 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3848 : :
3849 : 2189358 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
1120 pg@bowt.ie 3850 : 2189358 : xlrec.xmax = xmax_lock_old_tuple;
3581 andres@anarazel.de 3851 : 4378716 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3852 : 2189358 : oldtup.t_data->t_infomask2);
3578 3853 : 2189358 : xlrec.flags =
3854 : 2189358 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
448 peter@eisentraut.org 3855 : 2189358 : XLogRegisterData(&xlrec, SizeOfHeapLock);
3581 andres@anarazel.de 3856 : 2189358 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3857 : 2189358 : PageSetLSN(page, recptr);
3858 : : }
3859 : :
3860 [ - + ]: 2199493 : END_CRIT_SECTION();
3861 : :
9371 vadim4o@yahoo.com 3862 : 2199493 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3863 : :
3864 : : /*
3865 : : * Let the toaster do its thing, if needed.
3866 : : *
3867 : : * Note: below this point, heaptup is the data we actually intend to
3868 : : * store into the relation; newtup is the caller's original untoasted
3869 : : * data.
3870 : : */
9241 tgl@sss.pgh.pa.us 3871 [ + + ]: 2199493 : if (need_toast)
3872 : : {
3873 : : /* Note we always use WAL and FSM during updates */
2405 rhaas@postgresql.org 3874 : 2112 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
7471 tgl@sss.pgh.pa.us 3875 : 2112 : newtupsize = MAXALIGN(heaptup->t_len);
3876 : : }
3877 : : else
3878 : 2197381 : heaptup = newtup;
3879 : :
3880 : : /*
3881 : : * Now, do we need a new page for the tuple, or not? This is a bit
3882 : : * tricky since someone else could have added tuples to the page while
3883 : : * we weren't looking. We have to recheck the available space after
3884 : : * reacquiring the buffer lock. But don't bother to do that if the
3885 : : * former amount of free space is still not enough; it's unlikely
3886 : : * there's more free now than before.
3887 : : *
3888 : : * What's more, if we need to get a new page, we will need to acquire
3889 : : * buffer locks on both old and new pages. To avoid deadlock against
3890 : : * some other backend trying to get the same two locks in the other
3891 : : * order, we must be consistent about the order we get the locks in.
3892 : : * We use the rule "lock the lower-numbered page of the relation
3893 : : * first". To implement this, we must do RelationGetBufferForTuple
3894 : : * while not holding the lock on the old page, and we must rely on it
3895 : : * to get the locks on both pages in the correct order.
3896 : : *
3897 : : * Another consideration is that we need visibility map page pin(s) if
3898 : : * we will have to clear the all-visible flag on either page. If we
3899 : : * call RelationGetBufferForTuple, we rely on it to acquire any such
3900 : : * pins; but if we don't, we have to handle that here. Hence we need
3901 : : * a loop.
3902 : : */
3903 : : for (;;)
3904 : : {
1848 3905 [ + + ]: 2199493 : if (newtupsize > pagefree)
3906 : : {
3907 : : /* It doesn't fit, must use RelationGetBufferForTuple. */
3908 : 2198760 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3909 : : buffer, 0, NULL,
3910 : : &vmbuffer_new, &vmbuffer,
3911 : : 0);
3912 : : /* We're all done. */
3913 : 2198760 : break;
3914 : : }
3915 : : /* Acquire VM page pin if needed and we don't have it. */
3916 [ + + - + ]: 733 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
1848 tgl@sss.pgh.pa.us 3917 :UBC 0 : visibilitymap_pin(relation, block, &vmbuffer);
3918 : : /* Re-acquire the lock on the old tuple's page. */
9120 tgl@sss.pgh.pa.us 3919 :CBC 733 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3920 : : /* Re-check using the up-to-date free space */
6505 3921 : 733 : pagefree = PageGetHeapFreeSpace(page);
1848 3922 [ + - ]: 733 : if (newtupsize > pagefree ||
3923 [ + + - + ]: 733 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3924 : : {
3925 : : /*
3926 : : * Rats, it doesn't fit anymore, or somebody just now set the
3927 : : * all-visible flag. We must now unlock and loop to avoid
3928 : : * deadlock. Fortunately, this path should seldom be taken.
3929 : : */
9120 tgl@sss.pgh.pa.us 3930 :LBC (1) : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3931 : : }
3932 : : else
3933 : : {
3934 : : /* We're all done. */
9120 tgl@sss.pgh.pa.us 3935 :CBC 733 : newbuf = buffer;
1848 3936 : 733 : break;
3937 : : }
3938 : : }
3939 : : }
3940 : : else
3941 : : {
3942 : : /* No TOAST work needed, and it'll fit on same page */
9241 3943 : 183890 : newbuf = buffer;
7471 3944 : 183890 : heaptup = newtup;
3945 : : }
3946 : :
51 melanieplageman@gmai 3947 :GNC 2383383 : newpage = BufferGetPage(newbuf);
3948 : :
3949 : : /*
3950 : : * We're about to do the actual update -- check for conflict first, to
3951 : : * avoid possibly having to roll back work we've just done.
3952 : : *
3953 : : * This is safe without a recheck as long as there is no possibility of
3954 : : * another process scanning the pages between this check and the update
3955 : : * being visible to the scan (i.e., exclusive buffer content lock(s) are
3956 : : * continuously held from this point until the tuple update is visible).
3957 : : *
3958 : : * For the new tuple the only check needed is at the relation level, but
3959 : : * since both tuples are in the same relation and the check for oldtup
3960 : : * will include checking the relation level, there is no benefit to a
3961 : : * separate check for the new tuple.
3962 : : */
1848 tmunro@postgresql.or 3963 :CBC 2383383 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
3964 : : BufferGetBlockNumber(buffer));
3965 : :
3966 : : /*
3967 : : * At this point newbuf and buffer are both pinned and locked, and newbuf
3968 : : * has enough space for the new tuple. If they are the same buffer, only
3969 : : * one pin is held.
3970 : : */
3971 : :
6802 tgl@sss.pgh.pa.us 3972 [ + + ]: 2383371 : if (newbuf == buffer)
3973 : : {
3974 : : /*
3975 : : * Since the new tuple is going into the same page, we might be able
3976 : : * to do a HOT update. Check if any of the index columns have been
3977 : : * changed.
3978 : : */
1621 pg@bowt.ie 3979 [ + + ]: 184611 : if (!bms_overlap(modified_attrs, hot_attrs))
3980 : : {
6802 tgl@sss.pgh.pa.us 3981 : 168230 : use_hot_update = true;
3982 : :
3983 : : /*
3984 : : * If none of the columns that are used in hot-blocking indexes
3985 : : * were updated, we can apply HOT, but we do still need to check
3986 : : * if we need to update the summarizing indexes, and update those
3987 : : * indexes if the columns were updated, or we may fail to detect
3988 : : * e.g. value bound changes in BRIN minmax indexes.
3989 : : */
1142 tomas.vondra@postgre 3990 [ + + ]: 168230 : if (bms_overlap(modified_attrs, sum_attrs))
3991 : 2188 : summarized_update = true;
3992 : : }
3993 : : }
3994 : : else
3995 : : {
3996 : : /* Set a hint that the old page could use prune/defrag */
6505 tgl@sss.pgh.pa.us 3997 : 2198760 : PageSetFull(page);
3998 : : }
3999 : :
4000 : : /*
4001 : : * Compute replica identity tuple before entering the critical section so
4002 : : * we don't PANIC upon a memory allocation failure.
4003 : : * ExtractReplicaIdentity() will return NULL if nothing needs to be
4004 : : * logged. Pass old key required as true only if the replica identity key
4005 : : * columns are modified or it has external data.
4006 : : */
3324 alvherre@alvh.no-ip. 4007 : 2383371 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
1541 akapila@postgresql.o 4008 [ + + + + ]: 2383371 : bms_overlap(modified_attrs, id_attrs) ||
4009 : : id_has_external,
4010 : : &old_key_copied);
4011 : :
4012 : : /* NO EREPORT(ERROR) from here till changes are logged */
9244 tgl@sss.pgh.pa.us 4013 : 2383371 : START_CRIT_SECTION();
4014 : :
4015 : : /*
4016 : : * If this transaction commits, the old tuple will become DEAD sooner or
4017 : : * later. Set flag that this page is a candidate for pruning once our xid
4018 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
4019 : : * the subsequent page pruning will be a no-op and the hint will be
4020 : : * cleared.
4021 : : *
4022 : : * We set the new page prunable as well. See heap_insert() for more on why
4023 : : * we do this when inserting tuples.
4024 : : */
6505 4025 [ - + + + : 2383371 : PageSetPrunable(page, xid);
+ + ]
36 melanieplageman@gmai 4026 [ + + ]:GNC 2383371 : if (newbuf != buffer)
4027 [ - + + + : 2198760 : PageSetPrunable(newpage, xid);
+ + ]
4028 : :
6802 tgl@sss.pgh.pa.us 4029 [ + + ]:CBC 2383371 : if (use_hot_update)
4030 : : {
4031 : : /* Mark the old tuple as HOT-updated */
4032 : 168230 : HeapTupleSetHotUpdated(&oldtup);
4033 : : /* And mark the new tuple as heap-only */
4034 : 168230 : HeapTupleSetHeapOnly(heaptup);
4035 : : /* Mark the caller's copy too, in case different from heaptup */
4036 : 168230 : HeapTupleSetHeapOnly(newtup);
4037 : : }
4038 : : else
4039 : : {
4040 : : /* Make sure tuples are correctly marked as not-HOT */
4041 : 2215141 : HeapTupleClearHotUpdated(&oldtup);
4042 : 2215141 : HeapTupleClearHeapOnly(heaptup);
4043 : 2215141 : HeapTupleClearHeapOnly(newtup);
4044 : : }
4045 : :
3240 4046 : 2383371 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4047 : :
4048 : :
4049 : : /* Clear obsolete visibility flags, possibly set by ourselves above... */
3581 andres@anarazel.de 4050 : 2383371 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4051 : 2383371 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4052 : : /* ... and store info about transaction updating this tuple */
4053 [ - + ]: 2383371 : Assert(TransactionIdIsValid(xmax_old_tuple));
4054 : 2383371 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4055 : 2383371 : oldtup.t_data->t_infomask |= infomask_old_tuple;
4056 : 2383371 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4057 : 2383371 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4058 : :
4059 : : /* record address of new tuple in t_ctid of old one */
7471 tgl@sss.pgh.pa.us 4060 : 2383371 : oldtup.t_data->t_ctid = heaptup->t_self;
4061 : :
4062 : : /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
51 melanieplageman@gmai 4063 [ + + ]:GNC 2383371 : if (PageIsAllVisible(page))
4064 : : {
6098 tgl@sss.pgh.pa.us 4065 :CBC 2307 : all_visible_cleared = true;
51 melanieplageman@gmai 4066 :GNC 2307 : PageClearAllVisible(page);
5426 rhaas@postgresql.org 4067 :CBC 2307 : visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
4068 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
4069 : : }
51 melanieplageman@gmai 4070 [ + + + + ]:GNC 2383371 : if (newbuf != buffer && PageIsAllVisible(newpage))
4071 : : {
6098 tgl@sss.pgh.pa.us 4072 :CBC 1230 : all_visible_cleared_new = true;
51 melanieplageman@gmai 4073 :GNC 1230 : PageClearAllVisible(newpage);
5426 rhaas@postgresql.org 4074 :CBC 1230 : visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
4075 : : vmbuffer_new, VISIBILITYMAP_VALID_BITS);
4076 : : }
4077 : :
7340 tgl@sss.pgh.pa.us 4078 [ + + ]: 2383371 : if (newbuf != buffer)
4079 : 2198760 : MarkBufferDirty(newbuf);
4080 : 2383371 : MarkBufferDirty(buffer);
4081 : :
4082 : : /* XLOG stuff */
5622 rhaas@postgresql.org 4083 [ + + + + : 2383371 : if (RelationNeedsWAL(relation))
+ - + + ]
4084 : : {
4085 : : XLogRecPtr recptr;
4086 : :
4087 : : /*
4088 : : * For logical decoding we need combo CIDs to properly decode the
4089 : : * catalog.
4090 : : */
4529 4091 [ + + + + : 2371588 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
4092 : : {
4093 : 2682 : log_heap_new_cid(relation, &oldtup);
4094 : 2682 : log_heap_new_cid(relation, heaptup);
4095 : : }
4096 : :
4097 : 2371588 : recptr = log_heap_update(relation, buffer,
4098 : : newbuf, &oldtup, heaptup,
4099 : : old_key_tuple,
4100 : : all_visible_cleared,
4101 : : all_visible_cleared_new,
4102 : : walLogical);
9437 vadim4o@yahoo.com 4103 [ + + ]: 2371588 : if (newbuf != buffer)
4104 : : {
51 melanieplageman@gmai 4105 :GNC 2188633 : PageSetLSN(newpage, recptr);
4106 : : }
4107 : 2371588 : PageSetLSN(page, recptr);
4108 : : }
4109 : :
9244 tgl@sss.pgh.pa.us 4110 [ - + ]:CBC 2383371 : END_CRIT_SECTION();
4111 : :
9437 vadim4o@yahoo.com 4112 [ + + ]: 2383371 : if (newbuf != buffer)
4113 : 2198760 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
10003 4114 : 2383371 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4115 : :
4116 : : /*
4117 : : * Mark old tuple for invalidation from system caches at next command
4118 : : * boundary, and mark the new tuple for invalidation in case we abort. We
4119 : : * have to do this before releasing the buffer because oldtup is in the
4120 : : * buffer. (heaptup is all in local memory, but it's necessary to process
4121 : : * both tuple versions in one call to inval.c so we can avoid redundant
4122 : : * sinval messages.)
4123 : : */
5376 tgl@sss.pgh.pa.us 4124 : 2383371 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4125 : :
4126 : : /* Now we can release the buffer(s) */
9249 4127 [ + + ]: 2383371 : if (newbuf != buffer)
7340 4128 : 2198760 : ReleaseBuffer(newbuf);
754 akorotkov@postgresql 4129 : 2383371 : ReleaseBuffer(buffer);
5432 rhaas@postgresql.org 4130 [ + + ]: 2383371 : if (BufferIsValid(vmbuffer_new))
4131 : 1231 : ReleaseBuffer(vmbuffer_new);
4132 [ + + ]: 2383371 : if (BufferIsValid(vmbuffer))
4133 : 2307 : ReleaseBuffer(vmbuffer);
4134 : :
4135 : : /*
4136 : : * Release the lmgr tuple lock, if we had it.
4137 : : */
7675 tgl@sss.pgh.pa.us 4138 [ + + ]: 2383371 : if (have_tuple_lock)
2945 simon@2ndQuadrant.co 4139 : 22 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4140 : :
1139 pg@bowt.ie 4141 : 2383371 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4142 : :
4143 : : /*
4144 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
4145 : : * back to the caller's image, too.
4146 : : */
7471 tgl@sss.pgh.pa.us 4147 [ + + ]: 2383371 : if (heaptup != newtup)
4148 : : {
4149 : 2056 : newtup->t_self = heaptup->t_self;
4150 : 2056 : heap_freetuple(heaptup);
4151 : : }
4152 : :
4153 : : /*
4154 : : * If it is a HOT update, the update may still need to update summarized
4155 : : * indexes, lest we fail to update those summaries and get incorrect
4156 : : * results (for example, minmax bounds of the block may change with this
4157 : : * update).
4158 : : */
1142 tomas.vondra@postgre 4159 [ + + ]: 2383371 : if (use_hot_update)
4160 : : {
4161 [ + + ]: 168230 : if (summarized_update)
4162 : 2188 : *update_indexes = TU_Summarizing;
4163 : : else
4164 : 166042 : *update_indexes = TU_None;
4165 : : }
4166 : : else
4167 : 2215141 : *update_indexes = TU_All;
4168 : :
4529 rhaas@postgresql.org 4169 [ + + + + ]: 2383371 : if (old_key_tuple != NULL && old_key_copied)
4170 : 100 : heap_freetuple(old_key_tuple);
4171 : :
6802 tgl@sss.pgh.pa.us 4172 : 2383371 : bms_free(hot_attrs);
1142 tomas.vondra@postgre 4173 : 2383371 : bms_free(sum_attrs);
4850 alvherre@alvh.no-ip. 4174 : 2383371 : bms_free(key_attrs);
3541 tgl@sss.pgh.pa.us 4175 : 2383371 : bms_free(id_attrs);
3324 alvherre@alvh.no-ip. 4176 : 2383371 : bms_free(modified_attrs);
4177 : 2383371 : bms_free(interesting_attrs);
4178 : :
2600 andres@anarazel.de 4179 : 2383371 : return TM_Ok;
4180 : : }
4181 : :
4182 : : #ifdef USE_ASSERT_CHECKING
4183 : : /*
4184 : : * Confirm adequate lock held during heap_update(), per rules from
4185 : : * README.tuplock section "Locking to write inplace-updated tables".
4186 : : */
4187 : : static void
588 noah@leadboat.com 4188 : 2383592 : check_lock_if_inplace_updateable_rel(Relation relation,
4189 : : const ItemPointerData *otid,
4190 : : HeapTuple newtup)
4191 : : {
4192 : : /* LOCKTAG_TUPLE acceptable for any catalog */
4193 [ + + ]: 2383592 : switch (RelationGetRelid(relation))
4194 : : {
4195 : 88744 : case RelationRelationId:
4196 : : case DatabaseRelationId:
4197 : : {
4198 : : LOCKTAG tuptag;
4199 : :
4200 : 88744 : SET_LOCKTAG_TUPLE(tuptag,
4201 : : relation->rd_lockInfo.lockRelId.dbId,
4202 : : relation->rd_lockInfo.lockRelId.relId,
4203 : : ItemPointerGetBlockNumber(otid),
4204 : : ItemPointerGetOffsetNumber(otid));
4205 [ + + ]: 88744 : if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
4206 : 37598 : return;
4207 : : }
4208 : 51146 : break;
4209 : 2294848 : default:
4210 [ - + ]: 2294848 : Assert(!IsInplaceUpdateRelation(relation));
4211 : 2294848 : return;
4212 : : }
4213 : :
4214 [ + - - ]: 51146 : switch (RelationGetRelid(relation))
4215 : : {
4216 : 51146 : case RelationRelationId:
4217 : : {
4218 : : /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4219 : 51146 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
4220 : 51146 : Oid relid = classForm->oid;
4221 : : Oid dbid;
4222 : : LOCKTAG tag;
4223 : :
4224 [ + + ]: 51146 : if (IsSharedRelation(relid))
4225 : 47 : dbid = InvalidOid;
4226 : : else
4227 : 51099 : dbid = MyDatabaseId;
4228 : :
4229 [ + + ]: 51146 : if (classForm->relkind == RELKIND_INDEX)
4230 : : {
4231 : 1273 : Relation irel = index_open(relid, AccessShareLock);
4232 : :
4233 : 1273 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4234 : 1273 : index_close(irel, AccessShareLock);
4235 : : }
4236 : : else
4237 : 49873 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4238 : :
4239 [ + + ]: 51146 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4240 [ - + ]: 46670 : !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
588 noah@leadboat.com 4241 [ # # ]:UBC 0 : elog(WARNING,
4242 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4243 : : NameStr(classForm->relname),
4244 : : relid,
4245 : : classForm->relkind,
4246 : : ItemPointerGetBlockNumber(otid),
4247 : : ItemPointerGetOffsetNumber(otid));
4248 : : }
588 noah@leadboat.com 4249 :CBC 51146 : break;
588 noah@leadboat.com 4250 :UBC 0 : case DatabaseRelationId:
4251 : : {
4252 : : /* LOCKTAG_TUPLE required */
4253 : 0 : Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
4254 : :
4255 [ # # ]: 0 : elog(WARNING,
4256 : : "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4257 : : NameStr(dbForm->datname),
4258 : : dbForm->oid,
4259 : : ItemPointerGetBlockNumber(otid),
4260 : : ItemPointerGetOffsetNumber(otid));
4261 : : }
4262 : 0 : break;
4263 : : }
4264 : : }
4265 : :
4266 : : /*
4267 : : * Confirm adequate relation lock held, per rules from README.tuplock section
4268 : : * "Locking to write inplace-updated tables".
4269 : : */
4270 : : static void
588 noah@leadboat.com 4271 :CBC 115812 : check_inplace_rel_lock(HeapTuple oldtup)
4272 : : {
4273 : 115812 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
4274 : 115812 : Oid relid = classForm->oid;
4275 : : Oid dbid;
4276 : : LOCKTAG tag;
4277 : :
4278 [ + + ]: 115812 : if (IsSharedRelation(relid))
4279 : 9795 : dbid = InvalidOid;
4280 : : else
4281 : 106017 : dbid = MyDatabaseId;
4282 : :
4283 [ + + ]: 115812 : if (classForm->relkind == RELKIND_INDEX)
4284 : : {
4285 : 50599 : Relation irel = index_open(relid, AccessShareLock);
4286 : :
4287 : 50599 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4288 : 50599 : index_close(irel, AccessShareLock);
4289 : : }
4290 : : else
4291 : 65213 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4292 : :
4293 [ - + ]: 115812 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
588 noah@leadboat.com 4294 [ # # ]:UBC 0 : elog(WARNING,
4295 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4296 : : NameStr(classForm->relname),
4297 : : relid,
4298 : : classForm->relkind,
4299 : : ItemPointerGetBlockNumber(&oldtup->t_self),
4300 : : ItemPointerGetOffsetNumber(&oldtup->t_self));
588 noah@leadboat.com 4301 :CBC 115812 : }
4302 : : #endif
4303 : :
4304 : : /*
4305 : : * Check if the specified attribute's values are the same. Subroutine for
4306 : : * HeapDetermineColumnsInfo.
4307 : : */
4308 : : static bool
1541 akapila@postgresql.o 4309 : 982009 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4310 : : bool isnull1, bool isnull2)
4311 : : {
4312 : : /*
4313 : : * If one value is NULL and other is not, then they are certainly not
4314 : : * equal
4315 : : */
6802 tgl@sss.pgh.pa.us 4316 [ + + ]: 982009 : if (isnull1 != isnull2)
4317 : 60 : return false;
4318 : :
4319 : : /*
4320 : : * If both are NULL, they can be considered equal.
4321 : : */
4322 [ + + ]: 981949 : if (isnull1)
4323 : 6641 : return true;
4324 : :
4325 : : /*
4326 : : * We do simple binary comparison of the two datums. This may be overly
4327 : : * strict because there can be multiple binary representations for the
4328 : : * same logical value. But we should be OK as long as there are no false
4329 : : * positives. Using a type-specific equality operator is messy because
4330 : : * there could be multiple notions of equality in different operator
4331 : : * classes; furthermore, we cannot safely invoke user-defined functions
4332 : : * while holding exclusive buffer lock.
4333 : : */
4334 [ - + ]: 975308 : if (attrnum <= 0)
4335 : : {
4336 : : /* The only allowed system columns are OIDs, so do this */
6802 tgl@sss.pgh.pa.us 4337 :UBC 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4338 : : }
4339 : : else
4340 : : {
4341 : : CompactAttribute *att;
4342 : :
6802 tgl@sss.pgh.pa.us 4343 [ - + ]:CBC 975308 : Assert(attrnum <= tupdesc->natts);
501 drowley@postgresql.o 4344 : 975308 : att = TupleDescCompactAttr(tupdesc, attrnum - 1);
6802 tgl@sss.pgh.pa.us 4345 : 975308 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4346 : : }
4347 : : }
4348 : :
4349 : : /*
4350 : : * Check which columns are being updated.
4351 : : *
4352 : : * Given an updated tuple, determine (and return into the output bitmapset),
4353 : : * from those listed as interesting, the set of columns that changed.
4354 : : *
4355 : : * has_external indicates if any of the unmodified attributes (from those
4356 : : * listed as interesting) of the old tuple is a member of external_cols and is
4357 : : * stored externally.
4358 : : */
4359 : : static Bitmapset *
1541 akapila@postgresql.o 4360 : 2383591 : HeapDetermineColumnsInfo(Relation relation,
4361 : : Bitmapset *interesting_cols,
4362 : : Bitmapset *external_cols,
4363 : : HeapTuple oldtup, HeapTuple newtup,
4364 : : bool *has_external)
4365 : : {
4366 : : int attidx;
3275 bruce@momjian.us 4367 : 2383591 : Bitmapset *modified = NULL;
1541 akapila@postgresql.o 4368 : 2383591 : TupleDesc tupdesc = RelationGetDescr(relation);
4369 : :
1160 tgl@sss.pgh.pa.us 4370 : 2383591 : attidx = -1;
4371 [ + + ]: 3365600 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4372 : : {
4373 : : /* attidx is zero-based, attrnum is the normal attribute number */
4374 : 982009 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4375 : : Datum value1,
4376 : : value2;
4377 : : bool isnull1,
4378 : : isnull2;
4379 : :
4380 : : /*
4381 : : * If it's a whole-tuple reference, say "not equal". It's not really
4382 : : * worth supporting this case, since it could only succeed after a
4383 : : * no-op update, which is hardly a case worth optimizing for.
4384 : : */
1541 akapila@postgresql.o 4385 [ - + ]: 982009 : if (attrnum == 0)
4386 : : {
1160 tgl@sss.pgh.pa.us 4387 :UBC 0 : modified = bms_add_member(modified, attidx);
1541 akapila@postgresql.o 4388 :CBC 949613 : continue;
4389 : : }
4390 : :
4391 : : /*
4392 : : * Likewise, automatically say "not equal" for any system attribute
4393 : : * other than tableOID; we cannot expect these to be consistent in a
4394 : : * HOT chain, or even to be set correctly yet in the new tuple.
4395 : : */
4396 [ - + ]: 982009 : if (attrnum < 0)
4397 : : {
1541 akapila@postgresql.o 4398 [ # # ]:UBC 0 : if (attrnum != TableOidAttributeNumber)
4399 : : {
1160 tgl@sss.pgh.pa.us 4400 : 0 : modified = bms_add_member(modified, attidx);
1541 akapila@postgresql.o 4401 : 0 : continue;
4402 : : }
4403 : : }
4404 : :
4405 : : /*
4406 : : * Extract the corresponding values. XXX this is pretty inefficient
4407 : : * if there are many indexed columns. Should we do a single
4408 : : * heap_deform_tuple call on each tuple, instead? But that doesn't
4409 : : * work for system columns ...
4410 : : */
1541 akapila@postgresql.o 4411 :CBC 982009 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4412 : 982009 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4413 : :
4414 [ + + ]: 982009 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4415 : : value2, isnull1, isnull2))
4416 : : {
1160 tgl@sss.pgh.pa.us 4417 : 54535 : modified = bms_add_member(modified, attidx);
1541 akapila@postgresql.o 4418 : 54535 : continue;
4419 : : }
4420 : :
4421 : : /*
4422 : : * No need to check attributes that can't be stored externally. Note
4423 : : * that system attributes can't be stored externally.
4424 : : */
4425 [ + - + + ]: 927474 : if (attrnum < 0 || isnull1 ||
501 drowley@postgresql.o 4426 [ + + ]: 920833 : TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
1541 akapila@postgresql.o 4427 : 895078 : continue;
4428 : :
4429 : : /*
4430 : : * Check if the old tuple's attribute is stored externally and is a
4431 : : * member of external_cols.
4432 : : */
83 michael@paquier.xyz 4433 [ + + + + ]:GNC 32401 : if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
1160 tgl@sss.pgh.pa.us 4434 :CBC 5 : bms_is_member(attidx, external_cols))
1541 akapila@postgresql.o 4435 : 2 : *has_external = true;
4436 : : }
4437 : :
3324 alvherre@alvh.no-ip. 4438 : 2383591 : return modified;
4439 : : }
4440 : :
4441 : : /*
4442 : : * simple_heap_update - replace a tuple
4443 : : *
4444 : : * This routine may be used to update a tuple when concurrent updates of
4445 : : * the target tuple are not expected (for example, because we have a lock
4446 : : * on the relation associated with the tuple). Any failure is reported
4447 : : * via ereport().
4448 : : */
4449 : : void
187 peter@eisentraut.org 4450 :GNC 139201 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
4451 : : TU_UpdateIndexes *update_indexes)
4452 : : {
4453 : : TM_Result result;
4454 : : TM_FailureData tmfd;
4455 : : LockTupleMode lockmode;
4456 : :
8268 tgl@sss.pgh.pa.us 4457 :CBC 139201 : result = heap_update(relation, otid, tup,
4458 : : GetCurrentCommandId(true), 0,
4459 : : InvalidSnapshot,
4460 : : true /* wait for commit */ ,
4461 : : &tmfd, &lockmode, update_indexes);
9233 4462 [ - + - + : 139201 : switch (result)
- ]
4463 : : {
2600 andres@anarazel.de 4464 :UBC 0 : case TM_SelfModified:
4465 : : /* Tuple was already updated in current command? */
8324 tgl@sss.pgh.pa.us 4466 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
4467 : : break;
4468 : :
2600 andres@anarazel.de 4469 :CBC 139200 : case TM_Ok:
4470 : : /* done successfully */
9233 tgl@sss.pgh.pa.us 4471 : 139200 : break;
4472 : :
2600 andres@anarazel.de 4473 :UBC 0 : case TM_Updated:
8324 tgl@sss.pgh.pa.us 4474 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
4475 : : break;
4476 : :
2600 andres@anarazel.de 4477 :CBC 1 : case TM_Deleted:
4478 [ + - ]: 1 : elog(ERROR, "tuple concurrently deleted");
4479 : : break;
4480 : :
9233 tgl@sss.pgh.pa.us 4481 :UBC 0 : default:
8324 4482 [ # # ]: 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4483 : : break;
4484 : : }
9233 tgl@sss.pgh.pa.us 4485 :CBC 139200 : }
4486 : :
4487 : :
4488 : : /*
4489 : : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4490 : : */
4491 : : static MultiXactStatus
4850 alvherre@alvh.no-ip. 4492 : 115526 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4493 : : {
4494 : : int retval;
4495 : :
4496 [ + + ]: 115526 : if (is_update)
4497 : 216 : retval = tupleLockExtraInfo[mode].updstatus;
4498 : : else
4499 : 115310 : retval = tupleLockExtraInfo[mode].lockstatus;
4500 : :
4501 [ - + ]: 115526 : if (retval == -1)
4850 alvherre@alvh.no-ip. 4502 [ # # # # ]:UBC 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4503 : : is_update ? "true" : "false");
4504 : :
4697 alvherre@alvh.no-ip. 4505 :CBC 115526 : return (MultiXactStatus) retval;
4506 : : }
4507 : :
4508 : : /*
4509 : : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4510 : : *
4511 : : * Note that this acquires a buffer pin, which the caller must release.
4512 : : *
4513 : : * Input parameters:
4514 : : * relation: relation containing tuple (caller must hold suitable lock)
4515 : : * cid: current command ID (used for visibility test, and stored into
4516 : : * tuple's cmax if lock is successful)
4517 : : * mode: indicates if shared or exclusive tuple lock is desired
4518 : : * wait_policy: what to do if tuple lock is not available
4519 : : * follow_updates: if true, follow the update chain to also lock descendant
4520 : : * tuples.
4521 : : *
4522 : : * Output parameters:
4523 : : * *tuple: all fields filled in
4524 : : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4525 : : * *tmfd: filled in failure cases (see below)
4526 : : *
4527 : : * Function results are the same as the ones for table_tuple_lock().
4528 : : *
4529 : : * In the failure cases other than TM_Invisible, the routine fills
4530 : : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4531 : : * if necessary), and t_cmax (the last only for TM_SelfModified,
4532 : : * since we cannot obtain cmax from a combo CID generated by another
4533 : : * transaction).
4534 : : * See comments for struct TM_FailureData for additional info.
4535 : : *
4536 : : * See README.tuplock for a thorough explanation of this mechanism.
4537 : : */
4538 : : TM_Result
754 akorotkov@postgresql 4539 : 570474 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4540 : : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4541 : : bool follow_updates,
4542 : : Buffer *buffer, TM_FailureData *tmfd)
4543 : : {
4544 : : TM_Result result;
4545 : 570474 : ItemPointer tid = &(tuple->t_self);
4546 : : ItemId lp;
4547 : : Page page;
3578 andres@anarazel.de 4548 : 570474 : Buffer vmbuffer = InvalidBuffer;
4549 : : BlockNumber block;
4550 : : TransactionId xid,
4551 : : xmax;
4552 : : uint16 old_infomask,
4553 : : new_infomask,
4554 : : new_infomask2;
4043 alvherre@alvh.no-ip. 4555 : 570474 : bool first_time = true;
2513 4556 : 570474 : bool skip_tuple_lock = false;
7675 tgl@sss.pgh.pa.us 4557 : 570474 : bool have_tuple_lock = false;
3578 andres@anarazel.de 4558 : 570474 : bool cleared_all_frozen = false;
4559 : :
754 akorotkov@postgresql 4560 : 570474 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3578 andres@anarazel.de 4561 : 570474 : block = ItemPointerGetBlockNumber(tid);
4562 : :
4563 : : /*
4564 : : * Before locking the buffer, pin the visibility map page if it appears to
4565 : : * be necessary. Since we haven't got the lock yet, someone else might be
4566 : : * in the middle of changing this, so we'll need to recheck after we have
4567 : : * the lock.
4568 : : */
754 akorotkov@postgresql 4569 [ + + ]: 570474 : if (PageIsAllVisible(BufferGetPage(*buffer)))
3578 andres@anarazel.de 4570 : 413504 : visibilitymap_pin(relation, block, &vmbuffer);
4571 : :
754 akorotkov@postgresql 4572 : 570474 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4573 : :
4574 : 570474 : page = BufferGetPage(*buffer);
6505 tgl@sss.pgh.pa.us 4575 : 570474 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6810 4576 [ - + ]: 570474 : Assert(ItemIdIsNormal(lp));
4577 : :
6505 4578 : 570474 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10003 vadim4o@yahoo.com 4579 : 570474 : tuple->t_len = ItemIdGetLength(lp);
7563 tgl@sss.pgh.pa.us 4580 : 570474 : tuple->t_tableOid = RelationGetRelid(relation);
4581 : :
10003 vadim4o@yahoo.com 4582 : 16 : l3:
754 akorotkov@postgresql 4583 : 570490 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4584 : :
2600 andres@anarazel.de 4585 [ + + ]: 570490 : if (result == TM_Invisible)
4586 : : {
4587 : : /*
4588 : : * This is possible, but only when locking a tuple for ON CONFLICT DO
4589 : : * SELECT/UPDATE. We return this value here rather than throwing an
4590 : : * error in order to give that case the opportunity to throw a more
4591 : : * specific error.
4592 : : */
4593 : 28 : result = TM_Invisible;
3578 4594 : 28 : goto out_locked;
4595 : : }
2600 4596 [ + + + + ]: 570462 : else if (result == TM_BeingModified ||
4597 [ + + ]: 80198 : result == TM_Updated ||
4598 : : result == TM_Deleted)
4599 : : {
4600 : : TransactionId xwait;
4601 : : uint16 infomask;
4602 : : uint16 infomask2;
4603 : : bool require_sleep;
4604 : : ItemPointerData t_ctid;
4605 : :
4606 : : /* must copy state data before unlocking buffer */
4850 alvherre@alvh.no-ip. 4607 : 490266 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
7675 tgl@sss.pgh.pa.us 4608 : 490266 : infomask = tuple->t_data->t_infomask;
4850 alvherre@alvh.no-ip. 4609 : 490266 : infomask2 = tuple->t_data->t_infomask2;
4610 : 490266 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4611 : :
754 akorotkov@postgresql 4612 : 490266 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4613 : :
4614 : : /*
4615 : : * If any subtransaction of the current top transaction already holds
4616 : : * a lock as strong as or stronger than what we're requesting, we
4617 : : * effectively hold the desired lock already. We *must* succeed
4618 : : * without trying to take the tuple lock, else we will deadlock
4619 : : * against anyone wanting to acquire a stronger lock.
4620 : : *
4621 : : * Note we only do this the first time we loop on the HTSU result;
4622 : : * there is no point in testing in subsequent passes, because
4623 : : * evidently our own transaction cannot have acquired a new lock after
4624 : : * the first time we checked.
4625 : : */
4043 alvherre@alvh.no-ip. 4626 [ + + ]: 490266 : if (first_time)
4627 : : {
4628 : 490254 : first_time = false;
4629 : :
4630 [ + + ]: 490254 : if (infomask & HEAP_XMAX_IS_MULTI)
4631 : : {
4632 : : int i;
4633 : : int nmembers;
4634 : : MultiXactMember *members;
4635 : :
4636 : : /*
4637 : : * We don't need to allow old multixacts here; if that had
4638 : : * been the case, HeapTupleSatisfiesUpdate would have returned
4639 : : * MayBeUpdated and we wouldn't be here.
4640 : : */
4641 : : nmembers =
4642 : 73295 : GetMultiXactIdMembers(xwait, &members, false,
4643 : 73295 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4644 : :
4645 [ + + ]: 1422654 : for (i = 0; i < nmembers; i++)
4646 : : {
4647 : : /* only consider members of our own transaction */
4648 [ + + ]: 1349373 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4649 : 1349323 : continue;
4650 : :
4651 [ + + ]: 50 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4652 : : {
4850 4653 : 14 : pfree(members);
2600 andres@anarazel.de 4654 : 14 : result = TM_Ok;
3578 4655 : 14 : goto out_unlocked;
4656 : : }
4657 : : else
4658 : : {
4659 : : /*
4660 : : * Disable acquisition of the heavyweight tuple lock.
4661 : : * Otherwise, when promoting a weaker lock, we might
4662 : : * deadlock with another locker that has acquired the
4663 : : * heavyweight tuple lock and is waiting for our
4664 : : * transaction to finish.
4665 : : *
4666 : : * Note that in this case we still need to wait for
4667 : : * the multixact if required, to avoid acquiring
4668 : : * conflicting locks.
4669 : : */
2513 alvherre@alvh.no-ip. 4670 : 36 : skip_tuple_lock = true;
4671 : : }
4672 : : }
4673 : :
4043 4674 [ + - ]: 73281 : if (members)
4675 : 73281 : pfree(members);
4676 : : }
4677 [ + + ]: 416959 : else if (TransactionIdIsCurrentTransactionId(xwait))
4678 : : {
4679 [ + + + + : 415531 : switch (mode)
- ]
4680 : : {
4681 : 409097 : case LockTupleKeyShare:
4682 [ - + - - : 409097 : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
- - ]
4683 : : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4684 : : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
2600 andres@anarazel.de 4685 : 409097 : result = TM_Ok;
3578 4686 : 409097 : goto out_unlocked;
4043 alvherre@alvh.no-ip. 4687 : 31 : case LockTupleShare:
4688 [ + + - + ]: 37 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4689 : 6 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4690 : : {
2600 andres@anarazel.de 4691 : 25 : result = TM_Ok;
3578 4692 : 25 : goto out_unlocked;
4693 : : }
4043 alvherre@alvh.no-ip. 4694 : 6 : break;
4695 : 82 : case LockTupleNoKeyExclusive:
4696 [ + + ]: 82 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4697 : : {
2600 andres@anarazel.de 4698 : 70 : result = TM_Ok;
3578 4699 : 70 : goto out_unlocked;
4700 : : }
4043 alvherre@alvh.no-ip. 4701 : 12 : break;
4702 : 6321 : case LockTupleExclusive:
4703 [ + + ]: 6321 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4704 [ + + ]: 1279 : infomask2 & HEAP_KEYS_UPDATED)
4705 : : {
2600 andres@anarazel.de 4706 : 1251 : result = TM_Ok;
3578 4707 : 1251 : goto out_unlocked;
4708 : : }
4043 alvherre@alvh.no-ip. 4709 : 5070 : break;
4710 : : }
4711 : : }
4712 : : }
4713 : :
4714 : : /*
4715 : : * Initially assume that we will have to wait for the locking
4716 : : * transaction(s) to finish. We check various cases below in which
4717 : : * this can be turned off.
4718 : : */
4850 4719 : 79809 : require_sleep = true;
4720 [ + + ]: 79809 : if (mode == LockTupleKeyShare)
4721 : : {
4722 : : /*
4723 : : * If we're requesting KeyShare, and there's no update present, we
4724 : : * don't need to wait. Even if there is an update, we can still
4725 : : * continue if the key hasn't been modified.
4726 : : *
4727 : : * However, if there are updates, we need to walk the update chain
4728 : : * to mark future versions of the row as locked, too. That way,
4729 : : * if somebody deletes that future version, we're protected
4730 : : * against the key going away. This locking of future versions
4731 : : * could block momentarily, if a concurrent transaction is
4732 : : * deleting a key; or it could return a value to the effect that
4733 : : * the transaction deleting the key has already committed. So we
4734 : : * do this before re-locking the buffer; otherwise this would be
4735 : : * prone to deadlocks.
4736 : : *
4737 : : * Note that the TID we're locking was grabbed before we unlocked
4738 : : * the buffer. For it to change while we're not looking, the
4739 : : * other properties we're testing for below after re-locking the
4740 : : * buffer would also change, in which case we would restart this
4741 : : * loop above.
4742 : : */
4743 [ + + ]: 73902 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4744 : : {
4745 : : bool updated;
4746 : :
4747 : 73855 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4748 : :
4749 : : /*
4750 : : * If there are updates, follow the update chain; bail out if
4751 : : * that cannot be done.
4752 : : */
133 heikki.linnakangas@i 4753 [ + - + + ]: 73855 : if (follow_updates && updated &&
4754 [ + - ]: 2171 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
4755 : : {
4756 : : TM_Result res;
4757 : :
4758 : 2171 : res = heap_lock_updated_tuple(relation,
4759 : : infomask, xwait, &t_ctid,
4760 : : GetCurrentTransactionId(),
4761 : : mode);
2600 andres@anarazel.de 4762 [ + + ]: 2171 : if (res != TM_Ok)
4763 : : {
4850 alvherre@alvh.no-ip. 4764 : 6 : result = res;
4765 : : /* recovery code expects to have buffer lock held */
754 akorotkov@postgresql 4766 : 6 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4850 alvherre@alvh.no-ip. 4767 : 206 : goto failed;
4768 : : }
4769 : : }
4770 : :
754 akorotkov@postgresql 4771 : 73849 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4772 : :
4773 : : /*
4774 : : * Make sure it's still an appropriate lock, else start over.
4775 : : * Also, if it wasn't updated before we released the lock, but
4776 : : * is updated now, we start over too; the reason is that we
4777 : : * now need to follow the update chain to lock the new
4778 : : * versions.
4779 : : */
4850 alvherre@alvh.no-ip. 4780 [ + + ]: 73849 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4781 [ + - ]: 2153 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4782 [ - + ]: 2153 : !updated))
4783 : 16 : goto l3;
4784 : :
4785 : : /* Things look okay, so we can skip sleeping */
4786 : 73849 : require_sleep = false;
4787 : :
4788 : : /*
4789 : : * Note we allow Xmax to change here; other updaters/lockers
4790 : : * could have modified it before we grabbed the buffer lock.
4791 : : * However, this is not a problem, because with the recheck we
4792 : : * just did we ensure that they still don't conflict with the
4793 : : * lock we want.
4794 : : */
4795 : : }
4796 : : }
4797 [ + + ]: 5907 : else if (mode == LockTupleShare)
4798 : : {
4799 : : /*
4800 : : * If we're requesting Share, we can similarly avoid sleeping if
4801 : : * there's no update and no exclusive lock present.
4802 : : */
4803 [ + - ]: 480 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4804 [ + + ]: 480 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4805 : : {
754 akorotkov@postgresql 4806 : 474 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4807 : :
4808 : : /*
4809 : : * Make sure it's still an appropriate lock, else start over.
4810 : : * See above about allowing xmax to change.
4811 : : */
4850 alvherre@alvh.no-ip. 4812 [ + - - + ]: 948 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4813 : 474 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
4850 alvherre@alvh.no-ip. 4814 :UBC 0 : goto l3;
4850 alvherre@alvh.no-ip. 4815 :CBC 474 : require_sleep = false;
4816 : : }
4817 : : }
4818 [ + + ]: 5427 : else if (mode == LockTupleNoKeyExclusive)
4819 : : {
4820 : : /*
4821 : : * If we're requesting NoKeyExclusive, we might also be able to
4822 : : * avoid sleeping; just ensure that there no conflicting lock
4823 : : * already acquired.
4824 : : */
4825 [ + + ]: 172 : if (infomask & HEAP_XMAX_IS_MULTI)
4826 : : {
4148 4827 [ + + ]: 26 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4828 : : mode, NULL))
4829 : : {
4830 : : /*
4831 : : * No conflict, but if the xmax changed under us in the
4832 : : * meantime, start over.
4833 : : */
754 akorotkov@postgresql 4834 : 13 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4148 alvherre@alvh.no-ip. 4835 [ + - - + ]: 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4836 : 13 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4837 : : xwait))
4148 alvherre@alvh.no-ip. 4838 :UBC 0 : goto l3;
4839 : :
4840 : : /* otherwise, we're good */
4148 alvherre@alvh.no-ip. 4841 :CBC 13 : require_sleep = false;
4842 : : }
4843 : : }
4850 4844 [ + + ]: 146 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4845 : : {
754 akorotkov@postgresql 4846 : 18 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4847 : :
4848 : : /* if the xmax changed in the meantime, start over */
4394 alvherre@alvh.no-ip. 4849 [ + - - + ]: 36 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
2287 4850 : 18 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4851 : : xwait))
4850 alvherre@alvh.no-ip. 4852 :UBC 0 : goto l3;
4853 : : /* otherwise, we're good */
4850 alvherre@alvh.no-ip. 4854 :CBC 18 : require_sleep = false;
4855 : : }
4856 : : }
4857 : :
4858 : : /*
4859 : : * As a check independent from those above, we can also avoid sleeping
4860 : : * if the current transaction is the sole locker of the tuple. Note
4861 : : * that the strength of the lock already held is irrelevant; this is
4862 : : * not about recording the lock in Xmax (which will be done regardless
4863 : : * of this optimization, below). Also, note that the cases where we
4864 : : * hold a lock stronger than we are requesting are already handled
4865 : : * above by not doing anything.
4866 : : *
4867 : : * Note we only deal with the non-multixact case here; MultiXactIdWait
4868 : : * is well equipped to deal with this situation on its own.
4869 : : */
4043 4870 [ + + + + : 85208 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
+ + ]
4871 : 5405 : TransactionIdIsCurrentTransactionId(xwait))
4872 : : {
4873 : : /* ... but if the xmax changed in the meantime, start over */
754 akorotkov@postgresql 4874 : 5070 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4043 alvherre@alvh.no-ip. 4875 [ + - - + ]: 10140 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4876 : 5070 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4877 : : xwait))
4043 alvherre@alvh.no-ip. 4878 :UBC 0 : goto l3;
4043 alvherre@alvh.no-ip. 4879 [ - + ]:CBC 5070 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
4880 : 5070 : require_sleep = false;
4881 : : }
4882 : :
4883 : : /*
4884 : : * Time to sleep on the other transaction/multixact, if necessary.
4885 : : *
4886 : : * If the other transaction is an update/delete that's already
4887 : : * committed, then sleeping cannot possibly do any good: if we're
4888 : : * required to sleep, get out to raise an error instead.
4889 : : *
4890 : : * By here, we either have already acquired the buffer exclusive lock,
4891 : : * or we must wait for the locking transaction or multixact; so below
4892 : : * we ensure that we grab buffer lock after the sleep.
4893 : : */
2600 andres@anarazel.de 4894 [ + + + + : 79803 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
+ + ]
4895 : : {
754 akorotkov@postgresql 4896 : 161 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3581 alvherre@alvh.no-ip. 4897 : 161 : goto failed;
4898 : : }
4899 [ + + ]: 79642 : else if (require_sleep)
4900 : : {
4901 : : /*
4902 : : * Acquire tuple lock to establish our priority for the tuple, or
4903 : : * die trying. LockTuple will release us when we are next-in-line
4904 : : * for the tuple. We must do this even if we are share-locking,
4905 : : * but not if we already have a weaker lock on the tuple.
4906 : : *
4907 : : * If we are forced to "start over" below, we keep the tuple lock;
4908 : : * this arranges that we stay at the head of the line while
4909 : : * rechecking tuple state.
4910 : : */
2513 4911 [ + + ]: 218 : if (!skip_tuple_lock &&
4912 [ + + ]: 201 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4913 : : &have_tuple_lock))
4914 : : {
4915 : : /*
4916 : : * This can only happen if wait_policy is Skip and the lock
4917 : : * couldn't be obtained.
4918 : : */
2600 andres@anarazel.de 4919 : 1 : result = TM_WouldBlock;
4920 : : /* recovery code expects to have buffer lock held */
754 akorotkov@postgresql 4921 : 1 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4148 alvherre@alvh.no-ip. 4922 : 1 : goto failed;
4923 : : }
4924 : :
4850 4925 [ + + ]: 216 : if (infomask & HEAP_XMAX_IS_MULTI)
4926 : : {
4927 : 43 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
4928 : :
4929 : : /* We only ever lock tuples, never update them */
4930 [ - + ]: 43 : if (status >= MultiXactStatusNoKeyUpdate)
4850 alvherre@alvh.no-ip. 4931 [ # # ]:UBC 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
4932 : :
4933 : : /* wait for multixact to end, or die trying */
4228 alvherre@alvh.no-ip. 4934 [ + + + - ]:CBC 43 : switch (wait_policy)
4935 : : {
4936 : 37 : case LockWaitBlock:
4937 : 37 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
3240 tgl@sss.pgh.pa.us 4938 :GIC 37 : relation, &tuple->t_self, XLTW_Lock, NULL);
4228 alvherre@alvh.no-ip. 4939 :CBC 37 : break;
4940 : 2 : case LockWaitSkip:
4941 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4942 : : status, infomask, relation,
4943 : : NULL, false))
4944 : : {
2600 andres@anarazel.de 4945 : 2 : result = TM_WouldBlock;
4946 : : /* recovery code expects to have buffer lock held */
754 akorotkov@postgresql 4947 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4228 alvherre@alvh.no-ip. 4948 : 2 : goto failed;
4949 : : }
4228 alvherre@alvh.no-ip. 4950 :UBC 0 : break;
4228 alvherre@alvh.no-ip. 4951 :CBC 4 : case LockWaitError:
4952 [ + - ]: 4 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4953 : : status, infomask, relation,
4954 : : NULL, log_lock_failures))
4955 [ + - ]: 4 : ereport(ERROR,
4956 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4957 : : errmsg("could not obtain lock on row in relation \"%s\"",
4958 : : RelationGetRelationName(relation))));
4959 : :
4228 alvherre@alvh.no-ip. 4960 :UBC 0 : break;
4961 : : }
4962 : :
4963 : : /*
4964 : : * Of course, the multixact might not be done here: if we're
4965 : : * requesting a light lock mode, other transactions with light
4966 : : * locks could still be alive, as well as locks owned by our
4967 : : * own xact or other subxacts of this backend. We need to
4968 : : * preserve the surviving MultiXact members. Note that it
4969 : : * isn't absolutely necessary in the latter case, but doing so
4970 : : * is simpler.
4971 : : */
4972 : : }
4973 : : else
4974 : : {
4975 : : /* wait for regular transaction to end, or die trying */
4228 alvherre@alvh.no-ip. 4976 [ + + + - ]:CBC 173 : switch (wait_policy)
4977 : : {
4978 : 132 : case LockWaitBlock:
4108 heikki.linnakangas@i 4979 : 132 : XactLockTableWait(xwait, relation, &tuple->t_self,
4980 : : XLTW_Lock);
4228 alvherre@alvh.no-ip. 4981 : 132 : break;
4982 : 33 : case LockWaitSkip:
417 fujii@postgresql.org 4983 [ + - ]: 33 : if (!ConditionalXactLockTableWait(xwait, false))
4984 : : {
2600 andres@anarazel.de 4985 : 33 : result = TM_WouldBlock;
4986 : : /* recovery code expects to have buffer lock held */
754 akorotkov@postgresql 4987 : 33 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4228 alvherre@alvh.no-ip. 4988 : 33 : goto failed;
4989 : : }
4228 alvherre@alvh.no-ip. 4990 :UBC 0 : break;
4228 alvherre@alvh.no-ip. 4991 :CBC 8 : case LockWaitError:
336 fujii@postgresql.org 4992 [ + - ]: 8 : if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
4228 alvherre@alvh.no-ip. 4993 [ + - ]: 8 : ereport(ERROR,
4994 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4995 : : errmsg("could not obtain lock on row in relation \"%s\"",
4996 : : RelationGetRelationName(relation))));
4228 alvherre@alvh.no-ip. 4997 :UBC 0 : break;
4998 : : }
4999 : : }
5000 : :
5001 : : /* if there are updates, follow the update chain */
133 heikki.linnakangas@i 5002 [ + + + + ]:CBC 169 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5003 [ + + ]: 75 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
5004 : : {
5005 : : TM_Result res;
5006 : :
5007 : 55 : res = heap_lock_updated_tuple(relation,
5008 : : infomask, xwait, &t_ctid,
5009 : : GetCurrentTransactionId(),
5010 : : mode);
2600 andres@anarazel.de 5011 [ + + ]: 55 : if (res != TM_Ok)
5012 : : {
4043 alvherre@alvh.no-ip. 5013 : 3 : result = res;
5014 : : /* recovery code expects to have buffer lock held */
754 akorotkov@postgresql 5015 : 3 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4043 alvherre@alvh.no-ip. 5016 : 3 : goto failed;
5017 : : }
5018 : : }
5019 : :
754 akorotkov@postgresql 5020 : 166 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5021 : :
5022 : : /*
5023 : : * xwait is done, but if xwait had just locked the tuple then some
5024 : : * other xact could update this tuple before we get to this point.
5025 : : * Check for xmax change, and start over if so.
5026 : : */
4043 alvherre@alvh.no-ip. 5027 [ + + + + ]: 317 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5028 : 151 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5029 : : xwait))
5030 : 16 : goto l3;
5031 : :
5032 [ + + ]: 150 : if (!(infomask & HEAP_XMAX_IS_MULTI))
5033 : : {
5034 : : /*
5035 : : * Otherwise check if it committed or aborted. Note we cannot
5036 : : * be here if the tuple was only locked by somebody who didn't
5037 : : * conflict with us; that would have been handled above. So
5038 : : * that transaction must necessarily be gone by now. But
5039 : : * don't check for this in the multixact case, because some
5040 : : * locker transactions might still be running.
5041 : : */
754 akorotkov@postgresql 5042 : 116 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5043 : : }
5044 : : }
5045 : :
5046 : : /* By here, we're certain that we hold buffer exclusive lock again */
5047 : :
5048 : : /*
5049 : : * We may lock if previous xmax aborted, or if it committed but only
5050 : : * locked the tuple without updating it; or if we didn't have to wait
5051 : : * at all for whatever reason.
5052 : : */
4850 alvherre@alvh.no-ip. 5053 [ + + ]: 79574 : if (!require_sleep ||
5054 [ + + + + ]: 264 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5055 [ + + ]: 212 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5056 : 98 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
2600 andres@anarazel.de 5057 : 79484 : result = TM_Ok;
1898 alvherre@alvh.no-ip. 5058 [ + + ]: 90 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
2600 andres@anarazel.de 5059 : 65 : result = TM_Updated;
5060 : : else
5061 : 25 : result = TM_Deleted;
5062 : : }
5063 : :
4850 alvherre@alvh.no-ip. 5064 : 80196 : failed:
2600 andres@anarazel.de 5065 [ + + ]: 159976 : if (result != TM_Ok)
5066 : : {
5067 [ + + + + : 304 : Assert(result == TM_SelfModified || result == TM_Updated ||
+ + - + ]
5068 : : result == TM_Deleted || result == TM_WouldBlock);
5069 : :
5070 : : /*
5071 : : * When locking a tuple under LockWaitSkip semantics and we fail with
5072 : : * TM_WouldBlock above, it's possible for concurrent transactions to
5073 : : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5074 : : * this assert is slightly different from the equivalent one in
5075 : : * heap_delete and heap_update.
5076 : : */
1582 alvherre@alvh.no-ip. 5077 [ + + - + ]: 304 : Assert((result == TM_WouldBlock) ||
5078 : : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
2600 andres@anarazel.de 5079 [ + + - + ]: 304 : Assert(result != TM_Updated ||
5080 : : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5081 : 304 : tmfd->ctid = tuple->t_data->t_ctid;
5082 : 304 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5083 [ + + ]: 304 : if (result == TM_SelfModified)
5084 : 8 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5085 : : else
5086 : 296 : tmfd->cmax = InvalidCommandId;
3578 5087 : 304 : goto out_locked;
5088 : : }
5089 : :
5090 : : /*
5091 : : * If we didn't pin the visibility map page and the page has become all
5092 : : * visible while we were busy locking the buffer, or during some
5093 : : * subsequent window during which we had it unlocked, we'll have to unlock
5094 : : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5095 : : * unfortunate, especially since we'll now have to recheck whether the
5096 : : * tuple has been locked or updated under us, but hopefully it won't
5097 : : * happen very often.
5098 : : */
3561 5099 [ + + - + ]: 159672 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5100 : : {
754 akorotkov@postgresql 5101 :UBC 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3561 andres@anarazel.de 5102 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
754 akorotkov@postgresql 5103 : 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3561 andres@anarazel.de 5104 : 0 : goto l3;
5105 : : }
5106 : :
4850 alvherre@alvh.no-ip. 5107 :CBC 159672 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5108 : 159672 : old_infomask = tuple->t_data->t_infomask;
5109 : :
5110 : : /*
5111 : : * If this is the first possibly-multixact-able operation in the current
5112 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
5113 : : * certain that the transaction will never become a member of any older
5114 : : * MultiXactIds than that. (We have to do this even if we end up just
5115 : : * using our own TransactionId below, since some other backend could
5116 : : * incorporate our XID into a MultiXact immediately afterwards.)
5117 : : */
5118 : 159672 : MultiXactIdSetOldestMember();
5119 : :
5120 : : /*
5121 : : * Compute the new xmax and infomask to store into the tuple. Note we do
5122 : : * not modify the tuple just yet, because that would leave it in the wrong
5123 : : * state if multixact.c elogs.
5124 : : */
5125 : 159672 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5126 : : GetCurrentTransactionId(), mode, false,
5127 : : &xid, &new_infomask, &new_infomask2);
5128 : :
7677 tgl@sss.pgh.pa.us 5129 : 159672 : START_CRIT_SECTION();
5130 : :
5131 : : /*
5132 : : * Store transaction information of xact locking the tuple.
5133 : : *
5134 : : * Note: Cmax is meaningless in this context, so don't set it; this avoids
5135 : : * possibly generating a useless combo CID. Moreover, if we're locking a
5136 : : * previously updated tuple, it's important to preserve the Cmax.
5137 : : *
5138 : : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5139 : : * we would break the HOT chain.
5140 : : */
4850 alvherre@alvh.no-ip. 5141 : 159672 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5142 : 159672 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5143 : 159672 : tuple->t_data->t_infomask |= new_infomask;
5144 : 159672 : tuple->t_data->t_infomask2 |= new_infomask2;
5145 [ + + ]: 159672 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5146 : 157523 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
7901 tgl@sss.pgh.pa.us 5147 : 159672 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
5148 : :
5149 : : /*
5150 : : * Make sure there is no forward chain link in t_ctid. Note that in the
5151 : : * cases where the tuple has been updated, we must not overwrite t_ctid,
5152 : : * because it was set by the updater. Moreover, if the tuple has been
5153 : : * updated, we need to follow the update chain to lock the new versions of
5154 : : * the tuple as well.
5155 : : */
4850 alvherre@alvh.no-ip. 5156 [ + + ]: 159672 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5157 : 157523 : tuple->t_data->t_ctid = *tid;
5158 : :
5159 : : /* Clear only the all-frozen bit on visibility map if needed */
3578 andres@anarazel.de 5160 [ + + + + ]: 163279 : if (PageIsAllVisible(page) &&
5161 : 3607 : visibilitymap_clear(relation, block, vmbuffer,
5162 : : VISIBILITYMAP_ALL_FROZEN))
5163 : 15 : cleared_all_frozen = true;
5164 : :
5165 : :
754 akorotkov@postgresql 5166 : 159672 : MarkBufferDirty(*buffer);
5167 : :
5168 : : /*
5169 : : * XLOG stuff. You might think that we don't need an XLOG record because
5170 : : * there is no state change worth restoring after a crash. You would be
5171 : : * wrong however: we have just written either a TransactionId or a
5172 : : * MultiXactId that may never have been seen on disk before, and we need
5173 : : * to make sure that there are XLOG entries covering those ID numbers.
5174 : : * Else the same IDs might be re-used after a crash, which would be
5175 : : * disastrous if this page made it to disk before the crash. Essentially
5176 : : * we have to enforce the WAL log-before-data rule even in this case.
5177 : : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5178 : : * entries for everything anyway.)
5179 : : */
5622 rhaas@postgresql.org 5180 [ + + + + : 159672 : if (RelationNeedsWAL(relation))
+ - + - ]
5181 : : {
5182 : : xl_heap_lock xlrec;
5183 : : XLogRecPtr recptr;
5184 : :
4184 heikki.linnakangas@i 5185 : 159244 : XLogBeginInsert();
754 akorotkov@postgresql 5186 : 159244 : XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
5187 : :
4184 heikki.linnakangas@i 5188 : 159244 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
1120 pg@bowt.ie 5189 : 159244 : xlrec.xmax = xid;
4850 alvherre@alvh.no-ip. 5190 : 318488 : xlrec.infobits_set = compute_infobits(new_infomask,
5191 : 159244 : tuple->t_data->t_infomask2);
3578 andres@anarazel.de 5192 : 159244 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
448 peter@eisentraut.org 5193 : 159244 : XLogRegisterData(&xlrec, SizeOfHeapLock);
5194 : :
5195 : : /* we don't decode row locks atm, so no need to log the origin */
5196 : :
4184 heikki.linnakangas@i 5197 : 159244 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5198 : :
6505 tgl@sss.pgh.pa.us 5199 : 159244 : PageSetLSN(page, recptr);
5200 : : }
5201 : :
7677 5202 [ - + ]: 159672 : END_CRIT_SECTION();
5203 : :
2600 andres@anarazel.de 5204 : 159672 : result = TM_Ok;
5205 : :
3578 5206 : 160004 : out_locked:
754 akorotkov@postgresql 5207 : 160004 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
5208 : :
3578 andres@anarazel.de 5209 : 570461 : out_unlocked:
5210 [ + + ]: 570461 : if (BufferIsValid(vmbuffer))
5211 : 413504 : ReleaseBuffer(vmbuffer);
5212 : :
5213 : : /*
5214 : : * Don't update the visibility map here. Locking a tuple doesn't change
5215 : : * visibility info.
5216 : : */
5217 : :
5218 : : /*
5219 : : * Now that we have successfully marked the tuple as locked, we can
5220 : : * release the lmgr tuple lock, if we had it.
5221 : : */
7675 tgl@sss.pgh.pa.us 5222 [ + + ]: 570461 : if (have_tuple_lock)
4850 alvherre@alvh.no-ip. 5223 : 182 : UnlockTupleTuplock(relation, tid, mode);
5224 : :
3578 andres@anarazel.de 5225 : 570461 : return result;
5226 : : }
5227 : :
5228 : : /*
5229 : : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5230 : : * its normal, Xmax-based tuple lock.
5231 : : *
5232 : : * have_tuple_lock is an input and output parameter: on input, it indicates
5233 : : * whether the lock has previously been acquired (and this function does
5234 : : * nothing in that case). If this function returns success, have_tuple_lock
5235 : : * has been flipped to true.
5236 : : *
5237 : : * Returns false if it was unable to obtain the lock; this can only happen if
5238 : : * wait_policy is Skip.
5239 : : */
5240 : : static bool
187 peter@eisentraut.org 5241 :GNC 376 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
5242 : : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5243 : : {
4148 alvherre@alvh.no-ip. 5244 [ + + ]:CBC 376 : if (*have_tuple_lock)
5245 : 9 : return true;
5246 : :
5247 [ + + + - ]: 367 : switch (wait_policy)
5248 : : {
5249 : 322 : case LockWaitBlock:
5250 : 322 : LockTupleTuplock(relation, tid, mode);
5251 : 322 : break;
5252 : :
5253 : 34 : case LockWaitSkip:
417 fujii@postgresql.org 5254 [ + + ]: 34 : if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
4148 alvherre@alvh.no-ip. 5255 : 1 : return false;
5256 : 33 : break;
5257 : :
5258 : 11 : case LockWaitError:
336 fujii@postgresql.org 5259 [ + + ]: 11 : if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
4148 alvherre@alvh.no-ip. 5260 [ + - ]: 1 : ereport(ERROR,
5261 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5262 : : errmsg("could not obtain lock on row in relation \"%s\"",
5263 : : RelationGetRelationName(relation))));
5264 : 10 : break;
5265 : : }
5266 : 365 : *have_tuple_lock = true;
5267 : :
5268 : 365 : return true;
5269 : : }
5270 : :
5271 : : /*
5272 : : * Given an original set of Xmax and infomask, and a transaction (identified by
5273 : : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5274 : : * corresponding infomasks to use on the tuple.
5275 : : *
5276 : : * Note that this might have side effects such as creating a new MultiXactId.
5277 : : *
5278 : : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5279 : : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5280 : : * but it was not running anymore. There is a race condition, which is that the
5281 : : * MultiXactId may have finished since then, but that uncommon case is handled
5282 : : * either here, or within MultiXactIdExpand.
5283 : : *
5284 : : * There is a similar race condition possible when the old xmax was a regular
5285 : : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5286 : : * window, but it's still possible to end up creating an unnecessary
5287 : : * MultiXactId. Fortunately this is harmless.
5288 : : */
5289 : : static void
4850 5290 : 6592659 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5291 : : uint16 old_infomask2, TransactionId add_to_xmax,
5292 : : LockTupleMode mode, bool is_update,
5293 : : TransactionId *result_xmax, uint16 *result_infomask,
5294 : : uint16 *result_infomask2)
5295 : : {
5296 : : TransactionId new_xmax;
5297 : : uint16 new_infomask,
5298 : : new_infomask2;
5299 : :
4520 5300 [ + - ]: 6592659 : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5301 : :
4850 5302 : 6697256 : l5:
5303 : 6697256 : new_infomask = 0;
5304 : 6697256 : new_infomask2 = 0;
5305 [ + + ]: 6697256 : if (old_infomask & HEAP_XMAX_INVALID)
5306 : : {
5307 : : /*
5308 : : * No previous locker; we just insert our own TransactionId.
5309 : : *
5310 : : * Note that it's critical that this case be the first one checked,
5311 : : * because there are several blocks below that come back to this one
5312 : : * to implement certain optimizations; old_infomask might contain
5313 : : * other dirty bits in those cases, but we don't really care.
5314 : : */
5315 [ + + ]: 6515957 : if (is_update)
5316 : : {
5317 : 4231087 : new_xmax = add_to_xmax;
5318 [ + + ]: 4231087 : if (mode == LockTupleExclusive)
5319 : 1885874 : new_infomask2 |= HEAP_KEYS_UPDATED;
5320 : : }
5321 : : else
5322 : : {
5323 : 2284870 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5324 [ + + + + : 2284870 : switch (mode)
- ]
5325 : : {
5326 : 4983 : case LockTupleKeyShare:
5327 : 4983 : new_xmax = add_to_xmax;
5328 : 4983 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5329 : 4983 : break;
5330 : 801 : case LockTupleShare:
5331 : 801 : new_xmax = add_to_xmax;
5332 : 801 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5333 : 801 : break;
5334 : 2182993 : case LockTupleNoKeyExclusive:
5335 : 2182993 : new_xmax = add_to_xmax;
5336 : 2182993 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5337 : 2182993 : break;
5338 : 96093 : case LockTupleExclusive:
5339 : 96093 : new_xmax = add_to_xmax;
5340 : 96093 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5341 : 96093 : new_infomask2 |= HEAP_KEYS_UPDATED;
5342 : 96093 : break;
4850 alvherre@alvh.no-ip. 5343 :UBC 0 : default:
5344 : 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5345 [ # # ]: 0 : elog(ERROR, "invalid lock mode");
5346 : : }
5347 : : }
5348 : : }
4850 alvherre@alvh.no-ip. 5349 [ + + ]:CBC 181299 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5350 : : {
5351 : : MultiXactStatus new_status;
5352 : :
5353 : : /*
5354 : : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5355 : : * cross-check.
5356 : : */
5357 [ - + ]: 75558 : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5358 : :
5359 : : /*
5360 : : * A multixact together with LOCK_ONLY set but neither lock bit set
5361 : : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5362 : : * anymore. This check is critical for databases upgraded by
5363 : : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5364 : : * that such multis are never passed.
5365 : : */
3602 5366 [ - + ]: 75558 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5367 : : {
4850 alvherre@alvh.no-ip. 5368 :UBC 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5369 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5370 : 0 : goto l5;
5371 : : }
5372 : :
5373 : : /*
5374 : : * If the XMAX is already a MultiXactId, then we need to expand it to
5375 : : * include add_to_xmax; but if all the members were lockers and are
5376 : : * all gone, we can do away with the IS_MULTI bit and just set
5377 : : * add_to_xmax as the only locker/updater. If all lockers are gone
5378 : : * and we have an updater that aborted, we can also do without a
5379 : : * multi.
5380 : : *
5381 : : * The cost of doing GetMultiXactIdMembers would be paid by
5382 : : * MultiXactIdExpand if we weren't to do this, so this check is not
5383 : : * incurring extra work anyhow.
5384 : : */
4298 alvherre@alvh.no-ip. 5385 [ + + ]:CBC 75558 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5386 : : {
4850 5387 [ + + ]: 25 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4043 5388 [ + - ]: 9 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5389 : : old_infomask)))
5390 : : {
5391 : : /*
5392 : : * Reset these bits and restart; otherwise fall through to
5393 : : * create a new multi below.
5394 : : */
4850 5395 : 25 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5396 : 25 : old_infomask |= HEAP_XMAX_INVALID;
5397 : 25 : goto l5;
5398 : : }
5399 : : }
5400 : :
5401 : 75533 : new_status = get_mxact_status_for_lock(mode, is_update);
5402 : :
5403 : 75533 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5404 : : new_status);
5405 : 75533 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5406 : : }
5407 [ + + ]: 105741 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5408 : : {
5409 : : /*
5410 : : * It's a committed update, so we need to preserve him as updater of
5411 : : * the tuple.
5412 : : */
5413 : : MultiXactStatus status;
5414 : : MultiXactStatus new_status;
5415 : :
5416 [ - + ]: 13 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4850 alvherre@alvh.no-ip. 5417 :UBC 0 : status = MultiXactStatusUpdate;
5418 : : else
4850 alvherre@alvh.no-ip. 5419 :CBC 13 : status = MultiXactStatusNoKeyUpdate;
5420 : :
5421 : 13 : new_status = get_mxact_status_for_lock(mode, is_update);
5422 : :
5423 : : /*
5424 : : * since it's not running, it's obviously impossible for the old
5425 : : * updater to be identical to the current one, so we need not check
5426 : : * for that case as we do in the block above.
5427 : : */
5428 : 13 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5429 : 13 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5430 : : }
5431 [ + + ]: 105728 : else if (TransactionIdIsInProgress(xmax))
5432 : : {
5433 : : /*
5434 : : * If the XMAX is a valid, in-progress TransactionId, then we need to
5435 : : * create a new MultiXactId that includes both the old locker or
5436 : : * updater and our own TransactionId.
5437 : : */
5438 : : MultiXactStatus new_status;
5439 : : MultiXactStatus old_status;
5440 : : LockTupleMode old_mode;
5441 : :
5442 [ + + ]: 105713 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5443 : : {
5444 [ + + ]: 105685 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4520 5445 : 5730 : old_status = MultiXactStatusForKeyShare;
4850 5446 [ + + ]: 99955 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4520 5447 : 471 : old_status = MultiXactStatusForShare;
4850 5448 [ + - ]: 99484 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5449 : : {
5450 [ + + ]: 99484 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4520 5451 : 92953 : old_status = MultiXactStatusForUpdate;
5452 : : else
5453 : 6531 : old_status = MultiXactStatusForNoKeyUpdate;
5454 : : }
5455 : : else
5456 : : {
5457 : : /*
5458 : : * LOCK_ONLY can be present alone only when a page has been
5459 : : * upgraded by pg_upgrade. But in that case,
5460 : : * TransactionIdIsInProgress() should have returned false. We
5461 : : * assume it's no longer locked in this case.
5462 : : */
4850 alvherre@alvh.no-ip. 5463 [ # # ]:UBC 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5464 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5465 : 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5466 : 0 : goto l5;
5467 : : }
5468 : : }
5469 : : else
5470 : : {
5471 : : /* it's an update, but which kind? */
4850 alvherre@alvh.no-ip. 5472 [ - + ]:CBC 28 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4520 alvherre@alvh.no-ip. 5473 :UBC 0 : old_status = MultiXactStatusUpdate;
5474 : : else
4520 alvherre@alvh.no-ip. 5475 :CBC 28 : old_status = MultiXactStatusNoKeyUpdate;
5476 : : }
5477 : :
5478 : 105713 : old_mode = TUPLOCK_from_mxstatus(old_status);
5479 : :
5480 : : /*
5481 : : * If the lock to be acquired is for the same TransactionId as the
5482 : : * existing lock, there's an optimization possible: consider only the
5483 : : * strongest of both locks as the only one present, and restart.
5484 : : */
4850 5485 [ + + ]: 105713 : if (xmax == add_to_xmax)
5486 : : {
5487 : : /*
5488 : : * Note that it's not possible for the original tuple to be
5489 : : * updated: we wouldn't be here because the tuple would have been
5490 : : * invisible and we wouldn't try to update it. As a subtlety,
5491 : : * this code can also run when traversing an update chain to lock
5492 : : * future versions of a tuple. But we wouldn't be here either,
5493 : : * because the add_to_xmax would be different from the original
5494 : : * updater.
5495 : : */
4520 5496 [ - + ]: 104558 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5497 : :
5498 : : /* acquire the strongest of both */
5499 [ + + ]: 104558 : if (mode < old_mode)
5500 : 52261 : mode = old_mode;
5501 : : /* mustn't touch is_update */
5502 : :
5503 : 104558 : old_infomask |= HEAP_XMAX_INVALID;
5504 : 104558 : goto l5;
5505 : : }
5506 : :
5507 : : /* otherwise, just fall back to creating a new multixact */
5508 : 1155 : new_status = get_mxact_status_for_lock(mode, is_update);
5509 : 1155 : new_xmax = MultiXactIdCreate(xmax, old_status,
5510 : : add_to_xmax, new_status);
4850 5511 : 1155 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5512 : : }
5513 [ + + + + ]: 20 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5514 : 5 : TransactionIdDidCommit(xmax))
5515 : 1 : {
5516 : : /*
5517 : : * It's a committed update, so we gotta preserve him as updater of the
5518 : : * tuple.
5519 : : */
5520 : : MultiXactStatus status;
5521 : : MultiXactStatus new_status;
5522 : :
5523 [ - + ]: 1 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4850 alvherre@alvh.no-ip. 5524 :UBC 0 : status = MultiXactStatusUpdate;
5525 : : else
4850 alvherre@alvh.no-ip. 5526 :CBC 1 : status = MultiXactStatusNoKeyUpdate;
5527 : :
5528 : 1 : new_status = get_mxact_status_for_lock(mode, is_update);
5529 : :
5530 : : /*
5531 : : * since it's not running, it's obviously impossible for the old
5532 : : * updater to be identical to the current one, so we need not check
5533 : : * for that case as we do in the block above.
5534 : : */
5535 : 1 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5536 : 1 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5537 : : }
5538 : : else
5539 : : {
5540 : : /*
5541 : : * Can get here iff the locking/updating transaction was running when
5542 : : * the infomask was extracted from the tuple, but finished before
5543 : : * TransactionIdIsInProgress got to run. Deal with it as if there was
5544 : : * no locker at all in the first place.
5545 : : */
5546 : 14 : old_infomask |= HEAP_XMAX_INVALID;
5547 : 14 : goto l5;
5548 : : }
5549 : :
5550 : 6592659 : *result_infomask = new_infomask;
5551 : 6592659 : *result_infomask2 = new_infomask2;
5552 : 6592659 : *result_xmax = new_xmax;
5553 : 6592659 : }
5554 : :
5555 : : /*
5556 : : * Subroutine for heap_lock_updated_tuple_rec.
5557 : : *
5558 : : * Given a hypothetical multixact status held by the transaction identified
5559 : : * with the given xid, does the current transaction need to wait, fail, or can
5560 : : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5561 : : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5562 : : * returned. If the lock is already held by the current transaction, return
5563 : : * TM_SelfModified. In case of a conflict with another transaction, a
5564 : : * different HeapTupleSatisfiesUpdate return code is returned.
5565 : : *
5566 : : * The held status is said to be hypothetical because it might correspond to a
5567 : : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5568 : : * way for simplicity of API.
5569 : : */
5570 : : static TM_Result
4542 5571 : 38781 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5572 : : LockTupleMode mode, HeapTuple tup,
5573 : : bool *needwait)
5574 : : {
5575 : : MultiXactStatus wantedstatus;
5576 : :
5577 : 38781 : *needwait = false;
5578 : 38781 : wantedstatus = get_mxact_status_for_lock(mode, false);
5579 : :
5580 : : /*
5581 : : * Note: we *must* check TransactionIdIsInProgress before
5582 : : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5583 : : * for an explanation.
5584 : : */
5585 [ - + ]: 38781 : if (TransactionIdIsCurrentTransactionId(xid))
5586 : : {
5587 : : /*
5588 : : * The tuple has already been locked by our own transaction. This is
5589 : : * very rare but can happen if multiple transactions are trying to
5590 : : * lock an ancient version of the same tuple.
5591 : : */
2600 andres@anarazel.de 5592 :UBC 0 : return TM_SelfModified;
5593 : : }
4542 alvherre@alvh.no-ip. 5594 [ + + ]:CBC 38781 : else if (TransactionIdIsInProgress(xid))
5595 : : {
5596 : : /*
5597 : : * If the locking transaction is running, what we do depends on
5598 : : * whether the lock modes conflict: if they do, then we must wait for
5599 : : * it to finish; otherwise we can fall through to lock this tuple
5600 : : * version without waiting.
5601 : : */
5602 [ + + ]: 36539 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5603 : 36539 : LOCKMODE_from_mxstatus(wantedstatus)))
5604 : : {
5605 : 8 : *needwait = true;
5606 : : }
5607 : :
5608 : : /*
5609 : : * If we set needwait above, then this value doesn't matter;
5610 : : * otherwise, this value signals to caller that it's okay to proceed.
5611 : : */
2600 andres@anarazel.de 5612 : 36539 : return TM_Ok;
5613 : : }
4542 alvherre@alvh.no-ip. 5614 [ + + ]: 2242 : else if (TransactionIdDidAbort(xid))
2600 andres@anarazel.de 5615 : 206 : return TM_Ok;
4542 alvherre@alvh.no-ip. 5616 [ + - ]: 2036 : else if (TransactionIdDidCommit(xid))
5617 : : {
5618 : : /*
5619 : : * The other transaction committed. If it was only a locker, then the
5620 : : * lock is completely gone now and we can return success; but if it
5621 : : * was an update, then what we do depends on whether the two lock
5622 : : * modes conflict. If they conflict, then we must report error to
5623 : : * caller. But if they don't, we can fall through to allow the current
5624 : : * transaction to lock the tuple.
5625 : : *
5626 : : * Note: the reason we worry about ISUPDATE here is because as soon as
5627 : : * a transaction ends, all its locks are gone and meaningless, and
5628 : : * thus we can ignore them; whereas its updates persist. In the
5629 : : * TransactionIdIsInProgress case, above, we don't need to check
5630 : : * because we know the lock is still "alive" and thus a conflict needs
5631 : : * always be checked.
5632 : : */
4534 5633 [ + + ]: 2036 : if (!ISUPDATE_from_mxstatus(status))
2600 andres@anarazel.de 5634 : 2026 : return TM_Ok;
5635 : :
4542 alvherre@alvh.no-ip. 5636 [ + + ]: 10 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5637 : 10 : LOCKMODE_from_mxstatus(wantedstatus)))
5638 : : {
5639 : : /* bummer */
1898 5640 [ + + ]: 9 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
2600 andres@anarazel.de 5641 : 7 : return TM_Updated;
5642 : : else
5643 : 2 : return TM_Deleted;
5644 : : }
5645 : :
5646 : 1 : return TM_Ok;
5647 : : }
5648 : :
5649 : : /* Not in progress, not aborted, not committed -- must have crashed */
2600 andres@anarazel.de 5650 :UBC 0 : return TM_Ok;
5651 : : }
5652 : :
5653 : :
5654 : : /*
5655 : : * Recursive part of heap_lock_updated_tuple
5656 : : *
5657 : : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5658 : : * xid with the given mode; if this tuple is updated, recurse to lock the new
5659 : : * version as well.
5660 : : */
5661 : : static TM_Result
133 heikki.linnakangas@i 5662 :CBC 2224 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
5663 : : const ItemPointerData *tid, TransactionId xid,
5664 : : LockTupleMode mode)
5665 : : {
5666 : : TM_Result result;
5667 : : ItemPointerData tupid;
5668 : : HeapTupleData mytup;
5669 : : Buffer buf;
5670 : : uint16 new_infomask,
5671 : : new_infomask2,
5672 : : old_infomask,
5673 : : old_infomask2;
5674 : : TransactionId xmax,
5675 : : new_xmax;
3578 andres@anarazel.de 5676 : 2224 : bool cleared_all_frozen = false;
5677 : : bool pinned_desired_page;
5678 : 2224 : Buffer vmbuffer = InvalidBuffer;
5679 : : BlockNumber block;
5680 : :
4850 alvherre@alvh.no-ip. 5681 : 2224 : ItemPointerCopy(tid, &tupid);
5682 : :
5683 : : for (;;)
5684 : : {
5685 : 2227 : new_infomask = 0;
5686 : 2227 : new_xmax = InvalidTransactionId;
3578 andres@anarazel.de 5687 : 2227 : block = ItemPointerGetBlockNumber(&tupid);
4850 alvherre@alvh.no-ip. 5688 : 2227 : ItemPointerCopy(&tupid, &(mytup.t_self));
5689 : :
1483 tgl@sss.pgh.pa.us 5690 [ + - ]: 2227 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5691 : : {
5692 : : /*
5693 : : * if we fail to find the updated version of the tuple, it's
5694 : : * because it was vacuumed/pruned away after its creator
5695 : : * transaction aborted. So behave as if we got to the end of the
5696 : : * chain, and there's no further tuple to lock: return success to
5697 : : * caller.
5698 : : */
2600 andres@anarazel.de 5699 :UBC 0 : result = TM_Ok;
2986 tgl@sss.pgh.pa.us 5700 : 0 : goto out_unlocked;
5701 : : }
5702 : :
4850 alvherre@alvh.no-ip. 5703 :CBC 2227 : l4:
5704 [ - + ]: 2235 : CHECK_FOR_INTERRUPTS();
5705 : :
5706 : : /*
5707 : : * Before locking the buffer, pin the visibility map page if it
5708 : : * appears to be necessary. Since we haven't got the lock yet,
5709 : : * someone else might be in the middle of changing this, so we'll need
5710 : : * to recheck after we have the lock.
5711 : : */
3578 andres@anarazel.de 5712 [ - + ]: 2235 : if (PageIsAllVisible(BufferGetPage(buf)))
5713 : : {
3578 andres@anarazel.de 5714 :UBC 0 : visibilitymap_pin(rel, block, &vmbuffer);
2986 tgl@sss.pgh.pa.us 5715 : 0 : pinned_desired_page = true;
5716 : : }
5717 : : else
2986 tgl@sss.pgh.pa.us 5718 :CBC 2235 : pinned_desired_page = false;
5719 : :
4850 alvherre@alvh.no-ip. 5720 : 2235 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5721 : :
5722 : : /*
5723 : : * If we didn't pin the visibility map page and the page has become
5724 : : * all visible while we were busy locking the buffer, we'll have to
5725 : : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5726 : : * That's a bit unfortunate, but hopefully shouldn't happen often.
5727 : : *
5728 : : * Note: in some paths through this function, we will reach here
5729 : : * holding a pin on a vm page that may or may not be the one matching
5730 : : * this page. If this page isn't all-visible, we won't use the vm
5731 : : * page, but we hold onto such a pin till the end of the function.
5732 : : */
2986 tgl@sss.pgh.pa.us 5733 [ + - - + ]: 2235 : if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5734 : : {
3561 andres@anarazel.de 5735 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5736 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5737 : 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5738 : : }
5739 : :
5740 : : /*
5741 : : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5742 : : * end of the chain, we're done, so return success.
5743 : : */
4542 alvherre@alvh.no-ip. 5744 [ + - + + ]:CBC 4470 : if (TransactionIdIsValid(priorXmax) &&
3106 5745 : 2235 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5746 : : priorXmax))
5747 : : {
2600 andres@anarazel.de 5748 : 2 : result = TM_Ok;
3578 5749 : 2 : goto out_locked;
5750 : : }
5751 : :
5752 : : /*
5753 : : * Also check Xmin: if this tuple was created by an aborted
5754 : : * (sub)transaction, then we already locked the last live one in the
5755 : : * chain, thus we're done, so return success.
5756 : : */
3525 alvherre@alvh.no-ip. 5757 [ + + ]: 2233 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
5758 : : {
2600 andres@anarazel.de 5759 : 25 : result = TM_Ok;
2986 tgl@sss.pgh.pa.us 5760 : 25 : goto out_locked;
5761 : : }
5762 : :
4850 alvherre@alvh.no-ip. 5763 : 2208 : old_infomask = mytup.t_data->t_infomask;
4542 5764 : 2208 : old_infomask2 = mytup.t_data->t_infomask2;
4850 5765 : 2208 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5766 : :
5767 : : /*
5768 : : * If this tuple version has been updated or locked by some concurrent
5769 : : * transaction(s), what we do depends on whether our lock mode
5770 : : * conflicts with what those other transactions hold, and also on the
5771 : : * status of them.
5772 : : */
4542 5773 [ + + ]: 2208 : if (!(old_infomask & HEAP_XMAX_INVALID))
5774 : : {
5775 : : TransactionId rawxmax;
5776 : : bool needwait;
5777 : :
5778 : 2145 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5779 [ + + ]: 2145 : if (old_infomask & HEAP_XMAX_IS_MULTI)
5780 : : {
5781 : : int nmembers;
5782 : : int i;
5783 : : MultiXactMember *members;
5784 : :
5785 : : /*
5786 : : * We don't need a test for pg_upgrade'd tuples: this is only
5787 : : * applied to tuples after the first in an update chain. Said
5788 : : * first tuple in the chain may well be locked-in-9.2-and-
5789 : : * pg_upgraded, but that one was already locked by our caller,
5790 : : * not us; and any subsequent ones cannot be because our
5791 : : * caller must necessarily have obtained a snapshot later than
5792 : : * the pg_upgrade itself.
5793 : : */
3602 5794 [ - + ]: 2109 : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
5795 : :
4298 5796 : 2109 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
3240 tgl@sss.pgh.pa.us 5797 : 2109 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4542 alvherre@alvh.no-ip. 5798 [ + + ]: 40854 : for (i = 0; i < nmembers; i++)
5799 : : {
3578 andres@anarazel.de 5800 : 38745 : result = test_lockmode_for_conflict(members[i].status,
5801 : 38745 : members[i].xid,
5802 : : mode,
5803 : : &mytup,
5804 : : &needwait);
5805 : :
5806 : : /*
5807 : : * If the tuple was already locked by ourselves in a
5808 : : * previous iteration of this (say heap_lock_tuple was
5809 : : * forced to restart the locking loop because of a change
5810 : : * in xmax), then we hold the lock already on this tuple
5811 : : * version and we don't need to do anything; and this is
5812 : : * not an error condition either. We just need to skip
5813 : : * this tuple and continue locking the next version in the
5814 : : * update chain.
5815 : : */
2600 5816 [ - + ]: 38745 : if (result == TM_SelfModified)
5817 : : {
3205 alvherre@alvh.no-ip. 5818 :UBC 0 : pfree(members);
5819 : 0 : goto next;
5820 : : }
5821 : :
4542 alvherre@alvh.no-ip. 5822 [ - + ]:CBC 38745 : if (needwait)
5823 : : {
4542 alvherre@alvh.no-ip. 5824 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4430 5825 : 0 : XactLockTableWait(members[i].xid, rel,
5826 : : &mytup.t_self,
5827 : : XLTW_LockUpdated);
4542 5828 : 0 : pfree(members);
5829 : 0 : goto l4;
5830 : : }
2600 andres@anarazel.de 5831 [ - + ]:CBC 38745 : if (result != TM_Ok)
5832 : : {
4542 alvherre@alvh.no-ip. 5833 :UBC 0 : pfree(members);
3578 andres@anarazel.de 5834 : 0 : goto out_locked;
5835 : : }
5836 : : }
4542 alvherre@alvh.no-ip. 5837 [ + - ]:CBC 2109 : if (members)
5838 : 2109 : pfree(members);
5839 : : }
5840 : : else
5841 : : {
5842 : : MultiXactStatus status;
5843 : :
5844 : : /*
5845 : : * For a non-multi Xmax, we first need to compute the
5846 : : * corresponding MultiXactStatus by using the infomask bits.
5847 : : */
5848 [ + + ]: 36 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5849 : : {
5850 [ + - ]: 16 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5851 : 16 : status = MultiXactStatusForKeyShare;
4542 alvherre@alvh.no-ip. 5852 [ # # ]:UBC 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5853 : 0 : status = MultiXactStatusForShare;
5854 [ # # ]: 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5855 : : {
5856 [ # # ]: 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5857 : 0 : status = MultiXactStatusForUpdate;
5858 : : else
5859 : 0 : status = MultiXactStatusForNoKeyUpdate;
5860 : : }
5861 : : else
5862 : : {
5863 : : /*
5864 : : * LOCK_ONLY present alone (a pg_upgraded tuple marked
5865 : : * as share-locked in the old cluster) shouldn't be
5866 : : * seen in the middle of an update chain.
5867 : : */
5868 [ # # ]: 0 : elog(ERROR, "invalid lock status in tuple");
5869 : : }
5870 : : }
5871 : : else
5872 : : {
5873 : : /* it's an update, but which kind? */
4542 alvherre@alvh.no-ip. 5874 [ + + ]:CBC 20 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5875 : 15 : status = MultiXactStatusUpdate;
5876 : : else
5877 : 5 : status = MultiXactStatusNoKeyUpdate;
5878 : : }
5879 : :
3578 andres@anarazel.de 5880 : 36 : result = test_lockmode_for_conflict(status, rawxmax, mode,
5881 : : &mytup, &needwait);
5882 : :
5883 : : /*
5884 : : * If the tuple was already locked by ourselves in a previous
5885 : : * iteration of this (say heap_lock_tuple was forced to
5886 : : * restart the locking loop because of a change in xmax), then
5887 : : * we hold the lock already on this tuple version and we don't
5888 : : * need to do anything; and this is not an error condition
5889 : : * either. We just need to skip this tuple and continue
5890 : : * locking the next version in the update chain.
5891 : : */
2600 5892 [ - + ]: 36 : if (result == TM_SelfModified)
3205 alvherre@alvh.no-ip. 5893 :UBC 0 : goto next;
5894 : :
4542 alvherre@alvh.no-ip. 5895 [ + + ]:CBC 36 : if (needwait)
5896 : : {
5897 : 8 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4108 heikki.linnakangas@i 5898 : 8 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
5899 : : XLTW_LockUpdated);
4542 alvherre@alvh.no-ip. 5900 : 8 : goto l4;
5901 : : }
2600 andres@anarazel.de 5902 [ + + ]: 28 : if (result != TM_Ok)
5903 : : {
3578 5904 : 9 : goto out_locked;
5905 : : }
5906 : : }
5907 : : }
5908 : :
5909 : : /* compute the new Xmax and infomask values for the tuple ... */
4850 alvherre@alvh.no-ip. 5910 : 2191 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5911 : : xid, mode, false,
5912 : : &new_xmax, &new_infomask, &new_infomask2);
5913 : :
3578 andres@anarazel.de 5914 [ - + - - ]: 2191 : if (PageIsAllVisible(BufferGetPage(buf)) &&
3578 andres@anarazel.de 5915 :UBC 0 : visibilitymap_clear(rel, block, vmbuffer,
5916 : : VISIBILITYMAP_ALL_FROZEN))
5917 : 0 : cleared_all_frozen = true;
5918 : :
4850 alvherre@alvh.no-ip. 5919 :CBC 2191 : START_CRIT_SECTION();
5920 : :
5921 : : /* ... and set them */
5922 : 2191 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5923 : 2191 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5924 : 2191 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5925 : 2191 : mytup.t_data->t_infomask |= new_infomask;
5926 : 2191 : mytup.t_data->t_infomask2 |= new_infomask2;
5927 : :
5928 : 2191 : MarkBufferDirty(buf);
5929 : :
5930 : : /* XLOG stuff */
5931 [ + - + + : 2191 : if (RelationNeedsWAL(rel))
+ - + - ]
5932 : : {
5933 : : xl_heap_lock_updated xlrec;
5934 : : XLogRecPtr recptr;
3667 kgrittn@postgresql.o 5935 : 2191 : Page page = BufferGetPage(buf);
5936 : :
4184 heikki.linnakangas@i 5937 : 2191 : XLogBeginInsert();
5938 : 2191 : XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
5939 : :
5940 : 2191 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
4850 alvherre@alvh.no-ip. 5941 : 2191 : xlrec.xmax = new_xmax;
5942 : 2191 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
3578 andres@anarazel.de 5943 : 2191 : xlrec.flags =
5944 : 2191 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5945 : :
448 peter@eisentraut.org 5946 : 2191 : XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
5947 : :
4184 heikki.linnakangas@i 5948 : 2191 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5949 : :
4850 alvherre@alvh.no-ip. 5950 : 2191 : PageSetLSN(page, recptr);
5951 : : }
5952 : :
5953 [ - + ]: 2191 : END_CRIT_SECTION();
5954 : :
3205 5955 : 2191 : next:
5956 : : /* if we find the end of update chain, we're done. */
4850 5957 [ + - + - ]: 4382 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
2950 andres@anarazel.de 5958 [ + + ]: 4382 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
4724 bruce@momjian.us 5959 [ + + ]: 2195 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
4850 alvherre@alvh.no-ip. 5960 : 4 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
5961 : : {
2600 andres@anarazel.de 5962 : 2188 : result = TM_Ok;
3578 5963 : 2188 : goto out_locked;
5964 : : }
5965 : :
5966 : : /* tail recursion */
4542 alvherre@alvh.no-ip. 5967 : 3 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
4850 5968 : 3 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5969 : 3 : UnlockReleaseBuffer(buf);
5970 : : }
5971 : :
5972 : : result = TM_Ok;
5973 : :
3578 andres@anarazel.de 5974 : 2224 : out_locked:
5975 : 2224 : UnlockReleaseBuffer(buf);
5976 : :
2986 tgl@sss.pgh.pa.us 5977 : 2224 : out_unlocked:
3578 andres@anarazel.de 5978 [ - + ]: 2224 : if (vmbuffer != InvalidBuffer)
3578 andres@anarazel.de 5979 :UBC 0 : ReleaseBuffer(vmbuffer);
5980 : :
3578 andres@anarazel.de 5981 :CBC 2224 : return result;
5982 : : }
5983 : :
5984 : : /*
5985 : : * heap_lock_updated_tuple
5986 : : * Follow update chain when locking an updated tuple, acquiring locks (row
5987 : : * marks) on the updated versions.
5988 : : *
5989 : : * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
5990 : : * fields from the initial tuple. We will lock the tuples starting from the
5991 : : * one that 'prior_ctid' points to. Note: This function does not lock the
5992 : : * initial tuple itself.
5993 : : *
5994 : : * This function doesn't check visibility, it just unconditionally marks the
5995 : : * tuple(s) as locked. If any tuple in the updated chain is being deleted
5996 : : * concurrently (or updated with the key being modified), sleep until the
5997 : : * transaction doing it is finished.
5998 : : *
5999 : : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6000 : : * when we have to wait for other transactions to release them, as opposed to
6001 : : * what heap_lock_tuple does. The reason is that having more than one
6002 : : * transaction walking the chain is probably uncommon enough that risk of
6003 : : * starvation is not likely: one of the preconditions for being here is that
6004 : : * the snapshot in use predates the update that created this tuple (because we
6005 : : * started at an earlier version of the tuple), but at the same time such a
6006 : : * transaction cannot be using repeatable read or serializable isolation
6007 : : * levels, because that would lead to a serializability failure.
6008 : : */
6009 : : static TM_Result
133 heikki.linnakangas@i 6010 : 2226 : heap_lock_updated_tuple(Relation rel,
6011 : : uint16 prior_infomask,
6012 : : TransactionId prior_raw_xmax,
6013 : : const ItemPointerData *prior_ctid,
6014 : : TransactionId xid, LockTupleMode mode)
6015 : : {
6016 : 2226 : INJECTION_POINT("heap_lock_updated_tuple", NULL);
6017 : :
6018 : : /*
6019 : : * If the tuple has moved into another partition (effectively a delete)
6020 : : * stop here.
6021 : : */
6022 [ + + ]: 2226 : if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
6023 : : {
6024 : : TransactionId prior_xmax;
6025 : :
6026 : : /*
6027 : : * If this is the first possibly-multixact-able operation in the
6028 : : * current transaction, set my per-backend OldestMemberMXactId
6029 : : * setting. We can be certain that the transaction will never become a
6030 : : * member of any older MultiXactIds than that. (We have to do this
6031 : : * even if we end up just using our own TransactionId below, since
6032 : : * some other backend could incorporate our XID into a MultiXact
6033 : : * immediately afterwards.)
6034 : : */
4850 alvherre@alvh.no-ip. 6035 : 2224 : MultiXactIdSetOldestMember();
6036 : :
133 heikki.linnakangas@i 6037 : 4448 : prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
6038 [ + + ]: 2224 : MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
6039 : 2224 : return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
6040 : : }
6041 : :
6042 : : /* nothing to lock */
2600 andres@anarazel.de 6043 : 2 : return TM_Ok;
6044 : : }
6045 : :
6046 : : /*
6047 : : * heap_finish_speculative - mark speculative insertion as successful
6048 : : *
6049 : : * To successfully finish a speculative insertion we have to clear speculative
6050 : : * token from tuple. To do so the t_ctid field, which will contain a
6051 : : * speculative token value, is modified in place to point to the tuple itself,
6052 : : * which is characteristic of a newly inserted ordinary tuple.
6053 : : *
6054 : : * NB: It is not ok to commit without either finishing or aborting a
6055 : : * speculative insertion. We could treat speculative tuples of committed
6056 : : * transactions implicitly as completed, but then we would have to be prepared
6057 : : * to deal with speculative tokens on committed tuples. That wouldn't be
6058 : : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6059 : : * but clearing the token at completion isn't very expensive either.
6060 : : * An explicit confirmation WAL record also makes logical decoding simpler.
6061 : : */
6062 : : void
187 peter@eisentraut.org 6063 :GNC 2214 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
6064 : : {
6065 : : Buffer buffer;
6066 : : Page page;
6067 : : OffsetNumber offnum;
6068 : : ItemId lp;
6069 : : HeapTupleHeader htup;
6070 : :
2600 andres@anarazel.de 6071 :CBC 2214 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4015 6072 : 2214 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
249 peter@eisentraut.org 6073 :GNC 2214 : page = BufferGetPage(buffer);
6074 : :
2600 andres@anarazel.de 6075 :CBC 2214 : offnum = ItemPointerGetOffsetNumber(tid);
141 tgl@sss.pgh.pa.us 6076 [ + - - + ]:GNC 2214 : if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
141 tgl@sss.pgh.pa.us 6077 [ # # ]:UNC 0 : elog(ERROR, "offnum out of range");
141 tgl@sss.pgh.pa.us 6078 :GNC 2214 : lp = PageGetItemId(page, offnum);
6079 [ - + ]: 2214 : if (!ItemIdIsNormal(lp))
3820 andres@anarazel.de 6080 [ # # ]:UBC 0 : elog(ERROR, "invalid lp");
6081 : :
4015 andres@anarazel.de 6082 :CBC 2214 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6083 : :
6084 : : /* NO EREPORT(ERROR) from here till changes are logged */
6085 : 2214 : START_CRIT_SECTION();
6086 : :
2600 6087 [ - + ]: 2214 : Assert(HeapTupleHeaderIsSpeculative(htup));
6088 : :
4015 6089 : 2214 : MarkBufferDirty(buffer);
6090 : :
6091 : : /*
6092 : : * Replace the speculative insertion token with a real t_ctid, pointing to
6093 : : * itself like it does on regular tuples.
6094 : : */
2600 6095 : 2214 : htup->t_ctid = *tid;
6096 : :
6097 : : /* XLOG stuff */
4015 6098 [ + + + + : 2214 : if (RelationNeedsWAL(relation))
+ - + - ]
6099 : : {
6100 : : xl_heap_confirm xlrec;
6101 : : XLogRecPtr recptr;
6102 : :
2600 6103 : 2195 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
6104 : :
4015 6105 : 2195 : XLogBeginInsert();
6106 : :
6107 : : /* We want the same filtering on this as on a plain insert */
3421 6108 : 2195 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6109 : :
448 peter@eisentraut.org 6110 : 2195 : XLogRegisterData(&xlrec, SizeOfHeapConfirm);
4015 andres@anarazel.de 6111 : 2195 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6112 : :
6113 : 2195 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6114 : :
6115 : 2195 : PageSetLSN(page, recptr);
6116 : : }
6117 : :
6118 [ - + ]: 2214 : END_CRIT_SECTION();
6119 : :
6120 : 2214 : UnlockReleaseBuffer(buffer);
6121 : 2214 : }
6122 : :
6123 : : /*
6124 : : * heap_abort_speculative - kill a speculatively inserted tuple
6125 : : *
6126 : : * Marks a tuple that was speculatively inserted in the same command as dead,
6127 : : * by setting its xmin as invalid. That makes it immediately appear as dead
6128 : : * to all transactions, including our own. In particular, it makes
6129 : : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6130 : : * inserting a duplicate key value won't unnecessarily wait for our whole
6131 : : * transaction to finish (it'll just wait for our speculative insertion to
6132 : : * finish).
6133 : : *
6134 : : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6135 : : * that arise due to a mutual dependency that is not user visible. By
6136 : : * definition, unprincipled deadlocks cannot be prevented by the user
6137 : : * reordering lock acquisition in client code, because the implementation level
6138 : : * lock acquisitions are not under the user's direct control. If speculative
6139 : : * inserters did not take this precaution, then under high concurrency they
6140 : : * could deadlock with each other, which would not be acceptable.
6141 : : *
6142 : : * This is somewhat redundant with heap_delete, but we prefer to have a
6143 : : * dedicated routine with stripped down requirements. Note that this is also
6144 : : * used to delete the TOAST tuples created during speculative insertion.
6145 : : *
6146 : : * This routine does not affect logical decoding as it only looks at
6147 : : * confirmation records.
6148 : : */
6149 : : void
187 peter@eisentraut.org 6150 :GNC 16 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
6151 : : {
4015 andres@anarazel.de 6152 :CBC 16 : TransactionId xid = GetCurrentTransactionId();
6153 : : ItemId lp;
6154 : : HeapTupleData tp;
6155 : : Page page;
6156 : : BlockNumber block;
6157 : : Buffer buffer;
6158 : :
6159 [ - + ]: 16 : Assert(ItemPointerIsValid(tid));
6160 : :
6161 : 16 : block = ItemPointerGetBlockNumber(tid);
6162 : 16 : buffer = ReadBuffer(relation, block);
3667 kgrittn@postgresql.o 6163 : 16 : page = BufferGetPage(buffer);
6164 : :
4015 andres@anarazel.de 6165 : 16 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6166 : :
6167 : : /*
6168 : : * Page can't be all visible, we just inserted into it, and are still
6169 : : * running.
6170 : : */
6171 [ - + ]: 16 : Assert(!PageIsAllVisible(page));
6172 : :
6173 : 16 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6174 [ - + ]: 16 : Assert(ItemIdIsNormal(lp));
6175 : :
6176 : 16 : tp.t_tableOid = RelationGetRelid(relation);
6177 : 16 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6178 : 16 : tp.t_len = ItemIdGetLength(lp);
6179 : 16 : tp.t_self = *tid;
6180 : :
6181 : : /*
6182 : : * Sanity check that the tuple really is a speculatively inserted tuple,
6183 : : * inserted by us.
6184 : : */
6185 [ - + ]: 16 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
4015 andres@anarazel.de 6186 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
3548 andres@anarazel.de 6187 [ + + - + ]:CBC 16 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
4015 andres@anarazel.de 6188 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
4015 andres@anarazel.de 6189 [ - + ]:CBC 16 : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
6190 : :
6191 : : /*
6192 : : * No need to check for serializable conflicts here. There is never a
6193 : : * need for a combo CID, either. No need to extract replica identity, or
6194 : : * do anything special with infomask bits.
6195 : : */
6196 : :
6197 : 16 : START_CRIT_SECTION();
6198 : :
6199 : : /*
6200 : : * The tuple will become DEAD immediately. Flag that this page is a
6201 : : * candidate for pruning by setting xmin to TransactionXmin. While not
6202 : : * immediately prunable, it is the oldest xid we can cheaply determine
6203 : : * that's safe against wraparound / being older than the table's
6204 : : * relfrozenxid. To defend against the unlikely case of a new relation
6205 : : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6206 : : * if so (vacuum can't subsequently move relfrozenxid to beyond
6207 : : * TransactionXmin, so there's no race here).
6208 : : */
2221 6209 [ - + ]: 16 : Assert(TransactionIdIsValid(TransactionXmin));
6210 : : {
736 noah@leadboat.com 6211 : 16 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6212 : : TransactionId prune_xid;
6213 : :
6214 [ - + ]: 16 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
736 noah@leadboat.com 6215 :UBC 0 : prune_xid = relfrozenxid;
6216 : : else
736 noah@leadboat.com 6217 :CBC 16 : prune_xid = TransactionXmin;
6218 [ - + + - : 16 : PageSetPrunable(page, prune_xid);
+ + ]
6219 : : }
6220 : :
6221 : : /* store transaction information of xact deleting the tuple */
4015 andres@anarazel.de 6222 : 16 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
6223 : 16 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6224 : :
6225 : : /*
6226 : : * Set the tuple header xmin to InvalidTransactionId. This makes the
6227 : : * tuple immediately invisible everyone. (In particular, to any
6228 : : * transactions waiting on the speculative token, woken up later.)
6229 : : */
6230 : 16 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
6231 : :
6232 : : /* Clear the speculative insertion token too */
6233 : 16 : tp.t_data->t_ctid = tp.t_self;
6234 : :
6235 : 16 : MarkBufferDirty(buffer);
6236 : :
6237 : : /*
6238 : : * XLOG stuff
6239 : : *
6240 : : * The WAL records generated here match heap_delete(). The same recovery
6241 : : * routines are used.
6242 : : */
6243 [ + + + + : 16 : if (RelationNeedsWAL(relation))
+ - + - ]
6244 : : {
6245 : : xl_heap_delete xlrec;
6246 : : XLogRecPtr recptr;
6247 : :
6248 : 12 : xlrec.flags = XLH_DELETE_IS_SUPER;
6249 : 24 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6250 : 12 : tp.t_data->t_infomask2);
6251 : 12 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6252 : 12 : xlrec.xmax = xid;
6253 : :
6254 : 12 : XLogBeginInsert();
448 peter@eisentraut.org 6255 : 12 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
4015 andres@anarazel.de 6256 : 12 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6257 : :
6258 : : /* No replica identity & replication origin logged */
6259 : :
6260 : 12 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6261 : :
6262 : 12 : PageSetLSN(page, recptr);
6263 : : }
6264 : :
6265 [ - + ]: 16 : END_CRIT_SECTION();
6266 : :
6267 : 16 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6268 : :
6269 [ + + ]: 16 : if (HeapTupleHasExternal(&tp))
6270 : : {
3548 6271 [ - + ]: 1 : Assert(!IsToastRelation(relation));
2405 rhaas@postgresql.org 6272 : 1 : heap_toast_delete(relation, &tp, true);
6273 : : }
6274 : :
6275 : : /*
6276 : : * Never need to mark tuple for invalidation, since catalogs don't support
6277 : : * speculative insertion
6278 : : */
6279 : :
6280 : : /* Now we can release the buffer */
4015 andres@anarazel.de 6281 : 16 : ReleaseBuffer(buffer);
6282 : :
6283 : : /* count deletion, as we counted the insertion too */
6284 : 16 : pgstat_count_heap_delete(relation);
6285 : 16 : }
6286 : :
6287 : : /*
6288 : : * heap_inplace_lock - protect inplace update from concurrent heap_update()
6289 : : *
6290 : : * Evaluate whether the tuple's state is compatible with a no-key update.
6291 : : * Current transaction rowmarks are fine, as is KEY SHARE from any
6292 : : * transaction. If compatible, return true with the buffer exclusive-locked,
6293 : : * and the caller must release that by calling
6294 : : * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6295 : : * an error. Otherwise, call release_callback(arg), wait for blocking
6296 : : * transactions to end, and return false.
6297 : : *
6298 : : * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6299 : : * DDL, this doesn't guarantee any particular predicate locking.
6300 : : *
6301 : : * heap_delete() is a rarer source of blocking transactions (xwait). We'll
6302 : : * wait for such a transaction just like for the normal heap_update() case.
6303 : : * Normal concurrent DROP commands won't cause that, because all inplace
6304 : : * updaters take some lock that conflicts with DROP. An explicit SQL "DELETE
6305 : : * FROM pg_class" can cause it. By waiting, if the concurrent transaction
6306 : : * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
6307 : : * can find the successor tuple.
6308 : : *
6309 : : * Readers of inplace-updated fields expect changes to those fields are
6310 : : * durable. For example, vac_truncate_clog() reads datfrozenxid from
6311 : : * pg_database tuples via catalog snapshots. A future snapshot must not
6312 : : * return a lower datfrozenxid for the same database OID (lower in the
6313 : : * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6314 : : * tuple can start while we hold a lock on its buffer. In cases like
6315 : : * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6316 : : * to this transaction. ROLLBACK then is one case where it's okay to lose
6317 : : * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6318 : : * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6319 : : * committed tuple.)
6320 : : *
6321 : : * In principle, we could avoid waiting by overwriting every tuple in the
6322 : : * updated tuple chain. Reader expectations permit updating a tuple only if
6323 : : * it's aborted, is the tail of the chain, or we already updated the tuple
6324 : : * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6325 : : * order from tail to head. That would imply either (a) mutating all tuples
6326 : : * in one critical section or (b) accepting a chance of partial completion.
6327 : : * Partial completion of a relfrozenxid update would have the weird
6328 : : * consequence that the table's next VACUUM could see the table's relfrozenxid
6329 : : * move forward between vacuum_get_cutoffs() and finishing.
6330 : : */
6331 : : bool
588 noah@leadboat.com 6332 : 117041 : heap_inplace_lock(Relation relation,
6333 : : HeapTuple oldtup_ptr, Buffer buffer,
6334 : : void (*release_callback) (void *), void *arg)
6335 : : {
6336 : 117041 : HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6337 : : TM_Result result;
6338 : : bool ret;
6339 : :
6340 : : #ifdef USE_ASSERT_CHECKING
6341 [ + + ]: 117041 : if (RelationGetRelid(relation) == RelationRelationId)
6342 : 115812 : check_inplace_rel_lock(oldtup_ptr);
6343 : : #endif
6344 : :
6345 [ - + ]: 117041 : Assert(BufferIsValid(buffer));
6346 : :
6347 : : /*
6348 : : * Register shared cache invals if necessary. Other sessions may finish
6349 : : * inplace updates of this tuple between this step and LockTuple(). Since
6350 : : * inplace updates don't change cache keys, that's harmless.
6351 : : *
6352 : : * While it's tempting to register invals only after confirming we can
6353 : : * return true, the following obstacle precludes reordering steps that
6354 : : * way. Registering invals might reach a CatalogCacheInitializeCache()
6355 : : * that locks "buffer". That would hang indefinitely if running after our
6356 : : * own LockBuffer(). Hence, we must register invals before LockBuffer().
6357 : : */
141 6358 : 117041 : CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
6359 : :
588 6360 : 117041 : LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6361 : 117041 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6362 : :
6363 : : /*----------
6364 : : * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6365 : : *
6366 : : * - wait unconditionally
6367 : : * - already locked tuple above, since inplace needs that unconditionally
6368 : : * - don't recheck header after wait: simpler to defer to next iteration
6369 : : * - don't try to continue even if the updater aborts: likewise
6370 : : * - no crosscheck
6371 : : */
6372 : 117041 : result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6373 : : buffer);
6374 : :
6375 [ - + ]: 117041 : if (result == TM_Invisible)
6376 : : {
6377 : : /* no known way this can happen */
4023 rhaas@postgresql.org 6378 [ # # ]:UBC 0 : ereport(ERROR,
6379 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6380 : : errmsg_internal("attempted to overwrite invisible tuple")));
6381 : : }
588 noah@leadboat.com 6382 [ - + ]:CBC 117041 : else if (result == TM_SelfModified)
6383 : : {
6384 : : /*
6385 : : * CREATE INDEX might reach this if an expression is silly enough to
6386 : : * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6387 : : * statements might get here after a heap_update() of the same row, in
6388 : : * the absence of an intervening CommandCounterIncrement().
6389 : : */
588 noah@leadboat.com 6390 [ # # ]:UBC 0 : ereport(ERROR,
6391 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6392 : : errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6393 : : }
588 noah@leadboat.com 6394 [ + + ]:CBC 117041 : else if (result == TM_BeingModified)
6395 : : {
6396 : : TransactionId xwait;
6397 : : uint16 infomask;
6398 : :
6399 : 53 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6400 : 53 : infomask = oldtup.t_data->t_infomask;
6401 : :
6402 [ + + ]: 53 : if (infomask & HEAP_XMAX_IS_MULTI)
6403 : : {
6404 : 5 : LockTupleMode lockmode = LockTupleNoKeyExclusive;
6405 : 5 : MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
6406 : : int remain;
6407 : :
6408 [ + + ]: 5 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6409 : : lockmode, NULL))
6410 : : {
6411 : 2 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
553 6412 : 2 : release_callback(arg);
588 6413 : 2 : ret = false;
6414 : 2 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6415 : : relation, &oldtup.t_self, XLTW_Update,
6416 : : &remain);
6417 : : }
6418 : : else
6419 : 3 : ret = true;
6420 : : }
6421 [ + + ]: 48 : else if (TransactionIdIsCurrentTransactionId(xwait))
6422 : 1 : ret = true;
6423 [ + + ]: 47 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6424 : 1 : ret = true;
6425 : : else
6426 : : {
6427 : 46 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
553 6428 : 46 : release_callback(arg);
588 6429 : 46 : ret = false;
6430 : 46 : XactLockTableWait(xwait, relation, &oldtup.t_self,
6431 : : XLTW_Update);
6432 : : }
6433 : : }
6434 : : else
6435 : : {
6436 : 116988 : ret = (result == TM_Ok);
6437 [ + + ]: 116988 : if (!ret)
6438 : : {
6439 : 1 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
553 6440 : 1 : release_callback(arg);
6441 : : }
6442 : : }
6443 : :
6444 : : /*
6445 : : * GetCatalogSnapshot() relies on invalidation messages to know when to
6446 : : * take a new snapshot. COMMIT of xwait is responsible for sending the
6447 : : * invalidation. We're not acquiring heavyweight locks sufficient to
6448 : : * block if not yet sent, so we must take a new snapshot to ensure a later
6449 : : * attempt has a fair chance. While we don't need this if xwait aborted,
6450 : : * don't bother optimizing that.
6451 : : */
588 6452 [ + + ]: 117041 : if (!ret)
6453 : : {
6454 : 49 : UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
549 6455 : 49 : ForgetInplace_Inval();
588 6456 : 49 : InvalidateCatalogSnapshot();
6457 : : }
6458 : 117041 : return ret;
6459 : : }
6460 : :
6461 : : /*
6462 : : * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6463 : : *
6464 : : * The tuple cannot change size, and therefore its header fields and null
6465 : : * bitmap (if any) don't change either.
6466 : : *
6467 : : * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6468 : : */
6469 : : void
6470 : 81297 : heap_inplace_update_and_unlock(Relation relation,
6471 : : HeapTuple oldtup, HeapTuple tuple,
6472 : : Buffer buffer)
6473 : : {
6474 : 81297 : HeapTupleHeader htup = oldtup->t_data;
6475 : : uint32 oldlen;
6476 : : uint32 newlen;
6477 : : char *dst;
6478 : : char *src;
557 6479 : 81297 : int nmsgs = 0;
6480 : 81297 : SharedInvalidationMessage *invalMessages = NULL;
6481 : 81297 : bool RelcacheInitFileInval = false;
6482 : :
588 6483 [ - + ]: 81297 : Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6484 : 81297 : oldlen = oldtup->t_len - htup->t_hoff;
7300 tgl@sss.pgh.pa.us 6485 : 81297 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6486 [ + - - + ]: 81297 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
3820 andres@anarazel.de 6487 [ # # ]:UBC 0 : elog(ERROR, "wrong tuple length");
6488 : :
557 noah@leadboat.com 6489 :CBC 81297 : dst = (char *) htup + htup->t_hoff;
6490 : 81297 : src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6491 : :
6492 : : /* Like RecordTransactionCommit(), log only if needed */
6493 [ + + ]: 81297 : if (XLogStandbyInfoActive())
6494 : 73737 : nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6495 : : &RelcacheInitFileInval);
6496 : :
6497 : : /*
6498 : : * Unlink relcache init files as needed. If unlinking, acquire
6499 : : * RelCacheInitLock until after associated invalidations. By doing this
6500 : : * in advance, if we checkpoint and then crash between inplace
6501 : : * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6502 : : * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6503 : : * neglect to PANIC on EIO.
6504 : : */
6505 : 81297 : PreInplace_Inval();
6506 : :
6507 : : /*----------
6508 : : * NO EREPORT(ERROR) from here till changes are complete
6509 : : *
6510 : : * Our exclusive buffer lock won't stop a reader having already pinned and
6511 : : * checked visibility for this tuple. With the usual order of changes
6512 : : * (i.e. updating the buffer contents before WAL logging), a reader could
6513 : : * observe our not-yet-persistent update to relfrozenxid and update
6514 : : * datfrozenxid based on that. A crash in that moment could allow
6515 : : * datfrozenxid to overtake relfrozenxid:
6516 : : *
6517 : : * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6518 : : * ["R" is a VACUUM tbl]
6519 : : * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6520 : : * D: systable_getnext() returns pg_class tuple of tbl
6521 : : * R: memcpy() into pg_class tuple of tbl
6522 : : * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6523 : : * [crash]
6524 : : * [recovery restores datfrozenxid w/o relfrozenxid]
6525 : : *
6526 : : * We avoid that by using a temporary copy of the buffer to hide our
6527 : : * change from other backends until the change has been WAL-logged. We
6528 : : * apply our change to the temporary copy and WAL-log it, before modifying
6529 : : * the real page. That way any action a reader of the in-place-updated
6530 : : * value takes will be WAL logged after this change.
6531 : : */
6532 : 81297 : START_CRIT_SECTION();
6533 : :
56 andres@anarazel.de 6534 :GNC 81297 : MarkBufferDirty(buffer);
6535 : :
6536 : : /* XLOG stuff */
5622 rhaas@postgresql.org 6537 [ + - + + :CBC 81297 : if (RelationNeedsWAL(relation))
+ - + + ]
6538 : : {
6539 : : xl_heap_inplace xlrec;
6540 : : PGAlignedBlock copied_buffer;
557 noah@leadboat.com 6541 : 81293 : char *origdata = (char *) BufferGetBlock(buffer);
6542 : 81293 : Page page = BufferGetPage(buffer);
6543 : 81293 : uint16 lower = ((PageHeader) page)->pd_lower;
6544 : 81293 : uint16 upper = ((PageHeader) page)->pd_upper;
6545 : : uintptr_t dst_offset_in_block;
6546 : : RelFileLocator rlocator;
6547 : : ForkNumber forkno;
6548 : : BlockNumber blkno;
6549 : : XLogRecPtr recptr;
6550 : :
4184 heikki.linnakangas@i 6551 : 81293 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
557 noah@leadboat.com 6552 : 81293 : xlrec.dbId = MyDatabaseId;
6553 : 81293 : xlrec.tsId = MyDatabaseTableSpace;
6554 : 81293 : xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6555 : 81293 : xlrec.nmsgs = nmsgs;
6556 : :
4184 heikki.linnakangas@i 6557 : 81293 : XLogBeginInsert();
448 peter@eisentraut.org 6558 : 81293 : XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
557 noah@leadboat.com 6559 [ + + ]: 81293 : if (nmsgs != 0)
448 peter@eisentraut.org 6560 : 55782 : XLogRegisterData(invalMessages,
6561 : : nmsgs * sizeof(SharedInvalidationMessage));
6562 : :
6563 : : /* register block matching what buffer will look like after changes */
557 noah@leadboat.com 6564 : 81293 : memcpy(copied_buffer.data, origdata, lower);
6565 : 81293 : memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6566 : 81293 : dst_offset_in_block = dst - origdata;
6567 : 81293 : memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6568 : 81293 : BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6569 [ - + ]: 81293 : Assert(forkno == MAIN_FORKNUM);
6570 : 81293 : XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6571 : : REGBUF_STANDARD);
6572 : 81293 : XLogRegisterBufData(0, src, newlen);
6573 : :
6574 : : /* inplace updates aren't decoded atm, don't log the origin */
6575 : :
4184 heikki.linnakangas@i 6576 : 81293 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6577 : :
557 noah@leadboat.com 6578 : 81293 : PageSetLSN(page, recptr);
6579 : : }
6580 : :
6581 : 81297 : memcpy(dst, src, newlen);
6582 : :
6583 : 81297 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6584 : :
6585 : : /*
6586 : : * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6587 : : * do this before UnlockTuple().
6588 : : */
6589 : 81297 : AtInplace_Inval();
6590 : :
7300 tgl@sss.pgh.pa.us 6591 [ - + ]: 81297 : END_CRIT_SECTION();
557 noah@leadboat.com 6592 : 81297 : UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6593 : :
6594 : 81297 : AcceptInvalidationMessages(); /* local processing of just-sent inval */
6595 : :
6596 : : /*
6597 : : * Queue a transactional inval, for logical decoding and for third-party
6598 : : * code that might have been relying on it since long before inplace
6599 : : * update adopted immediate invalidation. See README.tuplock section
6600 : : * "Reading inplace-updated columns" for logical decoding details.
6601 : : */
7300 tgl@sss.pgh.pa.us 6602 [ + + ]: 81297 : if (!IsBootstrapProcessingMode())
5376 6603 : 63342 : CacheInvalidateHeapTuple(relation, tuple, NULL);
7300 6604 : 81297 : }
6605 : :
6606 : : /*
6607 : : * heap_inplace_unlock - reverse of heap_inplace_lock
6608 : : */
6609 : : void
588 noah@leadboat.com 6610 : 35695 : heap_inplace_unlock(Relation relation,
6611 : : HeapTuple oldtup, Buffer buffer)
6612 : : {
6613 : 35695 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6614 : 35695 : UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
549 6615 : 35695 : ForgetInplace_Inval();
588 6616 : 35695 : }
6617 : :
6618 : : #define FRM_NOOP 0x0001
6619 : : #define FRM_INVALIDATE_XMAX 0x0002
6620 : : #define FRM_RETURN_IS_XID 0x0004
6621 : : #define FRM_RETURN_IS_MULTI 0x0008
6622 : : #define FRM_MARK_COMMITTED 0x0010
6623 : :
6624 : : /*
6625 : : * FreezeMultiXactId
6626 : : * Determine what to do during freezing when a tuple is marked by a
6627 : : * MultiXactId.
6628 : : *
6629 : : * "flags" is an output value; it's used to tell caller what to do on return.
6630 : : * "pagefrz" is an input/output value, used to manage page level freezing.
6631 : : *
6632 : : * Possible values that we can set in "flags":
6633 : : * FRM_NOOP
6634 : : * don't do anything -- keep existing Xmax
6635 : : * FRM_INVALIDATE_XMAX
6636 : : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6637 : : * FRM_RETURN_IS_XID
6638 : : * The Xid return value is a single update Xid to set as xmax.
6639 : : * FRM_MARK_COMMITTED
6640 : : * Xmax can be marked as HEAP_XMAX_COMMITTED
6641 : : * FRM_RETURN_IS_MULTI
6642 : : * The return value is a new MultiXactId to set as new Xmax.
6643 : : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6644 : : *
6645 : : * Caller delegates control of page freezing to us. In practice we always
6646 : : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6647 : : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6648 : : * can never be left behind. We freely choose when and how to process each
6649 : : * Multi, without ever violating the cutoff postconditions for freezing.
6650 : : *
6651 : : * It's useful to remove Multis on a proactive timeline (relative to freezing
6652 : : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6653 : : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6654 : : * misses through eager processing.
6655 : : *
6656 : : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6657 : : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6658 : : * This can usually be put off, which is usually enough to avoid it altogether.
6659 : : * Allocating new multis during VACUUM should be avoided on general principle;
6660 : : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6661 : : * its own special risks.
6662 : : *
6663 : : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6664 : : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6665 : : *
6666 : : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6667 : : * have already forced page-level freezing, since that might incur the same
6668 : : * SLRU buffer misses that we specifically intended to avoid by freezing.
6669 : : */
6670 : : static TransactionId
4523 alvherre@alvh.no-ip. 6671 : 8 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6672 : : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6673 : : HeapPageFreeze *pagefrz)
6674 : : {
6675 : : TransactionId newxmax;
6676 : : MultiXactMember *members;
6677 : : int nmembers;
6678 : : bool need_replace;
6679 : : int nnewmembers;
6680 : : MultiXactMember *newmembers;
6681 : : bool has_lockers;
6682 : : TransactionId update_xid;
6683 : : bool update_committed;
6684 : : TransactionId FreezePageRelfrozenXid;
6685 : :
6686 : 8 : *flags = 0;
6687 : :
6688 : : /* We should only be called in Multis */
6689 [ - + ]: 8 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6690 : :
3602 6691 [ + - - + ]: 16 : if (!MultiXactIdIsValid(multi) ||
6692 : 8 : HEAP_LOCKED_UPGRADED(t_infomask))
6693 : : {
4523 alvherre@alvh.no-ip. 6694 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1224 pg@bowt.ie 6695 : 0 : pagefrz->freeze_required = true;
4523 alvherre@alvh.no-ip. 6696 : 0 : return InvalidTransactionId;
6697 : : }
1230 pg@bowt.ie 6698 [ - + ]:CBC 8 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
3095 andres@anarazel.de 6699 [ # # ]:UBC 0 : ereport(ERROR,
6700 : : (errcode(ERRCODE_DATA_CORRUPTED),
6701 : : errmsg_internal("found multixact %u from before relminmxid %u",
6702 : : multi, cutoffs->relminmxid)));
1224 pg@bowt.ie 6703 [ + + ]:CBC 8 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6704 : : {
6705 : : TransactionId update_xact;
6706 : :
6707 : : /*
6708 : : * This old multi cannot possibly have members still running, but
6709 : : * verify just in case. If it was a locker only, it can be removed
6710 : : * without any further consideration; but if it contained an update,
6711 : : * we might need to preserve it.
6712 : : */
3095 andres@anarazel.de 6713 [ - + ]: 6 : if (MultiXactIdIsRunning(multi,
6714 : 6 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
3095 andres@anarazel.de 6715 [ # # ]:UBC 0 : ereport(ERROR,
6716 : : (errcode(ERRCODE_DATA_CORRUPTED),
6717 : : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6718 : : multi, cutoffs->OldestMxact)));
6719 : :
4523 alvherre@alvh.no-ip. 6720 [ + - ]:CBC 6 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6721 : : {
6722 : 6 : *flags |= FRM_INVALIDATE_XMAX;
1224 pg@bowt.ie 6723 : 6 : pagefrz->freeze_required = true;
6724 : 6 : return InvalidTransactionId;
6725 : : }
6726 : :
6727 : : /* replace multi with single XID for its updater? */
1224 pg@bowt.ie 6728 :LBC (2) : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6729 [ # # ]: (2) : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
1224 pg@bowt.ie 6730 [ # # ]:UBC 0 : ereport(ERROR,
6731 : : (errcode(ERRCODE_DATA_CORRUPTED),
6732 : : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6733 : : multi, update_xact,
6734 : : cutoffs->relfrozenxid)));
1224 pg@bowt.ie 6735 [ # # ]:LBC (2) : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6736 : : {
6737 : : /*
6738 : : * Updater XID has to have aborted (otherwise the tuple would have
6739 : : * been pruned away instead, since updater XID is < OldestXmin).
6740 : : * Just remove xmax.
6741 : : */
1218 pg@bowt.ie 6742 [ # # ]:UBC 0 : if (TransactionIdDidCommit(update_xact))
1224 6743 [ # # ]: 0 : ereport(ERROR,
6744 : : (errcode(ERRCODE_DATA_CORRUPTED),
6745 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6746 : : multi, update_xact,
6747 : : cutoffs->OldestXmin)));
6748 : 0 : *flags |= FRM_INVALIDATE_XMAX;
6749 : 0 : pagefrz->freeze_required = true;
6750 : 0 : return InvalidTransactionId;
6751 : : }
6752 : :
6753 : : /* Have to keep updater XID as new xmax */
1224 pg@bowt.ie 6754 :LBC (2) : *flags |= FRM_RETURN_IS_XID;
6755 : (2) : pagefrz->freeze_required = true;
6756 : (2) : return update_xact;
6757 : : }
6758 : :
6759 : : /*
6760 : : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6761 : : * need to walk the whole members array to figure out what to do, if
6762 : : * anything.
6763 : : */
6764 : : nmembers =
3602 alvherre@alvh.no-ip. 6765 :CBC 2 : GetMultiXactIdMembers(multi, &members, false,
4298 6766 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
4523 6767 [ - + ]: 2 : if (nmembers <= 0)
6768 : : {
6769 : : /* Nothing worth keeping */
4523 alvherre@alvh.no-ip. 6770 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1224 pg@bowt.ie 6771 : 0 : pagefrz->freeze_required = true;
4523 alvherre@alvh.no-ip. 6772 : 0 : return InvalidTransactionId;
6773 : : }
6774 : :
6775 : : /*
6776 : : * The FRM_NOOP case is the only case where we might need to ratchet back
6777 : : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6778 : : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6779 : : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6780 : : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6781 : : * trackers managed by VACUUM being ratcheting back by xmax to the degree
6782 : : * required to make it safe to leave xmax undisturbed, independent of
6783 : : * whether or not page freezing is triggered somewhere else.
6784 : : *
6785 : : * Our policy is to force freezing in every case other than FRM_NOOP,
6786 : : * which obviates the need to maintain either set of trackers, anywhere.
6787 : : * Every other case will reliably execute a freeze plan for xmax that
6788 : : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6789 : : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6790 : : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6791 : : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6792 : : */
4523 alvherre@alvh.no-ip. 6793 :CBC 2 : need_replace = false;
1224 pg@bowt.ie 6794 : 2 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
1230 6795 [ + + ]: 4 : for (int i = 0; i < nmembers; i++)
6796 : : {
6797 : 3 : TransactionId xid = members[i].xid;
6798 : :
6799 [ - + ]: 3 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6800 : :
6801 [ + + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6802 : : {
6803 : : /* Can't violate the FreezeLimit postcondition */
4523 alvherre@alvh.no-ip. 6804 :GBC 1 : need_replace = true;
6805 : 1 : break;
6806 : : }
1224 pg@bowt.ie 6807 [ - + ]:CBC 2 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
1224 pg@bowt.ie 6808 :UBC 0 : FreezePageRelfrozenXid = xid;
6809 : : }
6810 : :
6811 : : /* Can't violate the MultiXactCutoff postcondition, either */
1224 pg@bowt.ie 6812 [ + + ]:CBC 2 : if (!need_replace)
6813 : 1 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6814 : :
4523 alvherre@alvh.no-ip. 6815 [ + + ]: 2 : if (!need_replace)
6816 : : {
6817 : : /*
6818 : : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6819 : : * both together to make it safe to retain this particular multi after
6820 : : * freezing its page
6821 : : */
6822 : 1 : *flags |= FRM_NOOP;
1224 pg@bowt.ie 6823 : 1 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6824 [ - + ]: 1 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
1224 pg@bowt.ie 6825 :UBC 0 : pagefrz->FreezePageRelminMxid = multi;
4523 alvherre@alvh.no-ip. 6826 :CBC 1 : pfree(members);
1493 pg@bowt.ie 6827 : 1 : return multi;
6828 : : }
6829 : :
6830 : : /*
6831 : : * Do a more thorough second pass over the multi to figure out which
6832 : : * member XIDs actually need to be kept. Checking the precise status of
6833 : : * individual members might even show that we don't need to keep anything.
6834 : : * That is quite possible even though the Multi must be >= OldestMxact,
6835 : : * since our second pass only keeps member XIDs when it's truly necessary;
6836 : : * even member XIDs >= OldestXmin often won't be kept by second pass.
6837 : : */
4523 alvherre@alvh.no-ip. 6838 :GBC 1 : nnewmembers = 0;
146 michael@paquier.xyz 6839 :GNC 1 : newmembers = palloc_array(MultiXactMember, nmembers);
4523 alvherre@alvh.no-ip. 6840 :GBC 1 : has_lockers = false;
6841 : 1 : update_xid = InvalidTransactionId;
6842 : 1 : update_committed = false;
6843 : :
6844 : : /*
6845 : : * Determine whether to keep each member xid, or to ignore it instead
6846 : : */
1230 pg@bowt.ie 6847 [ + + ]: 3 : for (int i = 0; i < nmembers; i++)
6848 : : {
6849 : 2 : TransactionId xid = members[i].xid;
6850 : 2 : MultiXactStatus mstatus = members[i].status;
6851 : :
6852 [ - + ]: 2 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6853 : :
6854 [ + - ]: 2 : if (!ISUPDATE_from_mxstatus(mstatus))
6855 : : {
6856 : : /*
6857 : : * Locker XID (not updater XID). We only keep lockers that are
6858 : : * still running.
6859 : : */
6860 [ + - + + ]: 4 : if (TransactionIdIsCurrentTransactionId(xid) ||
6861 : 2 : TransactionIdIsInProgress(xid))
6862 : : {
1224 6863 [ - + ]: 1 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
1224 pg@bowt.ie 6864 [ # # ]:UBC 0 : ereport(ERROR,
6865 : : (errcode(ERRCODE_DATA_CORRUPTED),
6866 : : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6867 : : multi, xid,
6868 : : cutoffs->OldestXmin)));
1230 pg@bowt.ie 6869 :GBC 1 : newmembers[nnewmembers++] = members[i];
6870 : 1 : has_lockers = true;
6871 : : }
6872 : :
6873 : 2 : continue;
6874 : : }
6875 : :
6876 : : /*
6877 : : * Updater XID (not locker XID). Should we keep it?
6878 : : *
6879 : : * Since the tuple wasn't totally removed when vacuum pruned, the
6880 : : * update Xid cannot possibly be older than OldestXmin cutoff unless
6881 : : * the updater XID aborted. If the updater transaction is known
6882 : : * aborted or crashed then it's okay to ignore it, otherwise not.
6883 : : *
6884 : : * In any case the Multi should never contain two updaters, whatever
6885 : : * their individual commit status. Check for that first, in passing.
6886 : : */
1230 pg@bowt.ie 6887 [ # # ]:UBC 0 : if (TransactionIdIsValid(update_xid))
6888 [ # # ]: 0 : ereport(ERROR,
6889 : : (errcode(ERRCODE_DATA_CORRUPTED),
6890 : : errmsg_internal("multixact %u has two or more updating members",
6891 : : multi),
6892 : : errdetail_internal("First updater XID=%u second updater XID=%u.",
6893 : : update_xid, xid)));
6894 : :
6895 : : /*
6896 : : * As with all tuple visibility routines, it's critical to test
6897 : : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6898 : : * race conditions explained in detail in heapam_visibility.c.
6899 : : */
6900 [ # # # # ]: 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
6901 : 0 : TransactionIdIsInProgress(xid))
6902 : 0 : update_xid = xid;
6903 [ # # ]: 0 : else if (TransactionIdDidCommit(xid))
6904 : : {
6905 : : /*
6906 : : * The transaction committed, so we can tell caller to set
6907 : : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6908 : : * transaction is not running.)
6909 : : */
6910 : 0 : update_committed = true;
6911 : 0 : update_xid = xid;
6912 : : }
6913 : : else
6914 : : {
6915 : : /*
6916 : : * Not in progress, not committed -- must be aborted or crashed;
6917 : : * we can ignore it.
6918 : : */
6919 : 0 : continue;
6920 : : }
6921 : :
6922 : : /*
6923 : : * We determined that updater must be kept -- add it to pending new
6924 : : * members list
6925 : : */
1224 6926 [ # # ]: 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6927 [ # # ]: 0 : ereport(ERROR,
6928 : : (errcode(ERRCODE_DATA_CORRUPTED),
6929 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6930 : : multi, xid, cutoffs->OldestXmin)));
1230 6931 : 0 : newmembers[nnewmembers++] = members[i];
6932 : : }
6933 : :
4523 alvherre@alvh.no-ip. 6934 :GBC 1 : pfree(members);
6935 : :
6936 : : /*
6937 : : * Determine what to do with caller's multi based on information gathered
6938 : : * during our second pass
6939 : : */
6940 [ - + ]: 1 : if (nnewmembers == 0)
6941 : : {
6942 : : /* Nothing worth keeping */
4523 alvherre@alvh.no-ip. 6943 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1230 pg@bowt.ie 6944 : 0 : newxmax = InvalidTransactionId;
6945 : : }
4523 alvherre@alvh.no-ip. 6946 [ - + - - ]:GBC 1 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
6947 : : {
6948 : : /*
6949 : : * If there's a single member and it's an update, pass it back alone
6950 : : * without creating a new Multi. (XXX we could do this when there's a
6951 : : * single remaining locker, too, but that would complicate the API too
6952 : : * much; moreover, the case with the single updater is more
6953 : : * interesting, because those are longer-lived.)
6954 : : */
4523 alvherre@alvh.no-ip. 6955 [ # # ]:UBC 0 : Assert(nnewmembers == 1);
6956 : 0 : *flags |= FRM_RETURN_IS_XID;
6957 [ # # ]: 0 : if (update_committed)
6958 : 0 : *flags |= FRM_MARK_COMMITTED;
1230 pg@bowt.ie 6959 : 0 : newxmax = update_xid;
6960 : : }
6961 : : else
6962 : : {
6963 : : /*
6964 : : * Create a new multixact with the surviving members of the previous
6965 : : * one, to set as new Xmax in the tuple
6966 : : */
1230 pg@bowt.ie 6967 :GBC 1 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
4523 alvherre@alvh.no-ip. 6968 : 1 : *flags |= FRM_RETURN_IS_MULTI;
6969 : : }
6970 : :
6971 : 1 : pfree(newmembers);
6972 : :
1224 pg@bowt.ie 6973 : 1 : pagefrz->freeze_required = true;
1230 6974 : 1 : return newxmax;
6975 : : }
6976 : :
6977 : : /*
6978 : : * heap_prepare_freeze_tuple
6979 : : *
6980 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
6981 : : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
6982 : : * setup enough state (in the *frz output argument) to enable caller to
6983 : : * process this tuple as part of freezing its page, and return true. Return
6984 : : * false if nothing can be changed about the tuple right now.
6985 : : *
6986 : : * FreezePageConflictXid is advanced only for xmin/xvac freezing, not for xmax
6987 : : * changes. We only remove xmax state here when it is lock-only, or when the
6988 : : * updater XID (including an updater member of a MultiXact) must be aborted;
6989 : : * otherwise, the tuple would already be removable. Neither case affects
6990 : : * visibility on a standby.
6991 : : *
6992 : : * Also sets *totally_frozen to true if the tuple will be totally frozen once
6993 : : * caller executes returned freeze plan (or if the tuple was already totally
6994 : : * frozen by an earlier VACUUM). This indicates that there are no remaining
6995 : : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
6996 : : *
6997 : : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
6998 : : * tuple that we returned true for, and then execute freezing. Caller must
6999 : : * initialize pagefrz fields for page as a whole before first call here for
7000 : : * each heap page.
7001 : : *
7002 : : * VACUUM caller decides on whether or not to freeze the page as a whole.
7003 : : * We'll often prepare freeze plans for a page that caller just discards.
7004 : : * However, VACUUM doesn't always get to make a choice; it must freeze when
7005 : : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7006 : : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7007 : : * that VACUUM always follows that rule.
7008 : : *
7009 : : * We sometimes force freezing of xmax MultiXactId values long before it is
7010 : : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7011 : : * It's worth processing MultiXactIds proactively when it is cheap to do so,
7012 : : * and it's convenient to make that happen by piggy-backing it on the "force
7013 : : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7014 : : * because it is expensive right now (though only when it's still possible to
7015 : : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7016 : : *
7017 : : * It is assumed that the caller has checked the tuple with
7018 : : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7019 : : * (else we should be removing the tuple, not freezing it).
7020 : : *
7021 : : * NB: This function has side effects: it might allocate a new MultiXactId.
7022 : : * It will be set as tuple's new xmax when our *frz output is processed within
7023 : : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7024 : : * then caller had better have an exclusive lock on it already.
7025 : : */
7026 : : bool
3095 andres@anarazel.de 7027 :CBC 5479442 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
7028 : : const struct VacuumCutoffs *cutoffs,
7029 : : HeapPageFreeze *pagefrz,
7030 : : HeapTupleFreeze *frz, bool *totally_frozen)
7031 : : {
1230 pg@bowt.ie 7032 : 5479442 : bool xmin_already_frozen = false,
7033 : 5479442 : xmax_already_frozen = false;
7034 : 5479442 : bool freeze_xmin = false,
7035 : 5479442 : replace_xvac = false,
7036 : 5479442 : replace_xmax = false,
7037 : 5479442 : freeze_xmax = false;
7038 : : TransactionId xid;
7039 : :
1218 7040 : 5479442 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
4523 alvherre@alvh.no-ip. 7041 : 5479442 : frz->t_infomask2 = tuple->t_infomask2;
7042 : 5479442 : frz->t_infomask = tuple->t_infomask;
1218 pg@bowt.ie 7043 : 5479442 : frz->frzflags = 0;
7044 : 5479442 : frz->checkflags = 0;
7045 : :
7046 : : /*
7047 : : * Process xmin, while keeping track of whether it's already frozen, or
7048 : : * will become frozen iff our freeze plan is executed by caller (could be
7049 : : * neither).
7050 : : */
7121 tgl@sss.pgh.pa.us 7051 : 5479442 : xid = HeapTupleHeaderGetXmin(tuple);
2560 alvherre@alvh.no-ip. 7052 [ + + ]: 5479442 : if (!TransactionIdIsNormal(xid))
1230 pg@bowt.ie 7053 : 868699 : xmin_already_frozen = true;
7054 : : else
7055 : : {
7056 [ - + ]: 4610743 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3095 andres@anarazel.de 7057 [ # # ]:UBC 0 : ereport(ERROR,
7058 : : (errcode(ERRCODE_DATA_CORRUPTED),
7059 : : errmsg_internal("found xmin %u from before relfrozenxid %u",
7060 : : xid, cutoffs->relfrozenxid)));
7061 : :
7062 : : /* Will set freeze_xmin flags in freeze plan below */
1224 pg@bowt.ie 7063 :CBC 4610743 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7064 : :
7065 : : /* Verify that xmin committed if and when freeze plan is executed */
1218 7066 [ + + ]: 4610743 : if (freeze_xmin)
7067 : : {
7068 : 3825398 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
56 melanieplageman@gmai 7069 [ + + ]:GNC 3825398 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7070 : 530366 : pagefrz->FreezePageConflictXid = xid;
7071 : : }
7072 : : }
7073 : :
7074 : : /*
7075 : : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7076 : : * as we support having MOVED_OFF/MOVED_IN tuples in the database
7077 : : */
1230 pg@bowt.ie 7078 :CBC 5479442 : xid = HeapTupleHeaderGetXvac(tuple);
7079 [ - + ]: 5479442 : if (TransactionIdIsNormal(xid))
7080 : : {
1230 pg@bowt.ie 7081 [ # # ]:UBC 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7082 [ # # ]: 0 : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7083 : :
7084 : : /*
7085 : : * For Xvac, we always freeze proactively. This allows totally_frozen
7086 : : * tracking to ignore xvac.
7087 : : */
1224 7088 : 0 : replace_xvac = pagefrz->freeze_required = true;
7089 : :
56 melanieplageman@gmai 7090 [ # # ]:UNC 0 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7091 : 0 : pagefrz->FreezePageConflictXid = xid;
7092 : :
7093 : : /* Will set replace_xvac flags in freeze plan below */
7094 : : }
7095 : :
7096 : : /* Now process xmax */
1218 pg@bowt.ie 7097 :CBC 5479442 : xid = frz->xmax;
4541 alvherre@alvh.no-ip. 7098 [ + + ]: 5479442 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7099 : : {
7100 : : /* Raw xmax is a MultiXactId */
7101 : : TransactionId newxmax;
7102 : : uint16 flags;
7103 : :
7104 : : /*
7105 : : * We will either remove xmax completely (in the "freeze_xmax" path),
7106 : : * process xmax by replacing it (in the "replace_xmax" path), or
7107 : : * perform no-op xmax processing. The only constraint is that the
7108 : : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7109 : : */
1230 pg@bowt.ie 7110 : 8 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7111 : : &flags, pagefrz);
7112 : :
1224 7113 [ + + ]: 8 : if (flags & FRM_NOOP)
7114 : : {
7115 : : /*
7116 : : * xmax is a MultiXactId, and nothing about it changes for now.
7117 : : * This is the only case where 'freeze_required' won't have been
7118 : : * set for us by FreezeMultiXactId, as well as the only case where
7119 : : * neither freeze_xmax nor replace_xmax are set (given a multi).
7120 : : *
7121 : : * This is a no-op, but the call to FreezeMultiXactId might have
7122 : : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7123 : : * for us (the "freeze page" variants, specifically). That'll
7124 : : * make it safe for our caller to freeze the page later on, while
7125 : : * leaving this particular xmax undisturbed.
7126 : : *
7127 : : * FreezeMultiXactId is _not_ responsible for the "no freeze"
7128 : : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7129 : : * job. A call to heap_tuple_should_freeze for this same tuple
7130 : : * will take place below if 'freeze_required' isn't set already.
7131 : : * (This repeats work from FreezeMultiXactId, but allows "no
7132 : : * freeze" tracker maintenance to happen in only one place.)
7133 : : */
7134 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7135 [ + - - + ]: 1 : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7136 : : }
7137 [ - + ]: 7 : else if (flags & FRM_RETURN_IS_XID)
7138 : : {
7139 : : /*
7140 : : * xmax will become an updater Xid (original MultiXact's updater
7141 : : * member Xid will be carried forward as a simple Xid in Xmax).
7142 : : */
1230 pg@bowt.ie 7143 [ # # ]:LBC (2) : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7144 : :
7145 : : /*
7146 : : * NB -- some of these transformations are only valid because we
7147 : : * know the return Xid is a tuple updater (i.e. not merely a
7148 : : * locker.) Also note that the only reason we don't explicitly
7149 : : * worry about HEAP_KEYS_UPDATED is because it lives in
7150 : : * t_infomask2 rather than t_infomask.
7151 : : */
4523 alvherre@alvh.no-ip. 7152 : (2) : frz->t_infomask &= ~HEAP_XMAX_BITS;
7153 : (2) : frz->xmax = newxmax;
7154 [ # # ]: (2) : if (flags & FRM_MARK_COMMITTED)
3225 teodor@sigaev.ru 7155 :UBC 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
1230 pg@bowt.ie 7156 :LBC (2) : replace_xmax = true;
7157 : : }
4523 alvherre@alvh.no-ip. 7158 [ + + ]:CBC 7 : else if (flags & FRM_RETURN_IS_MULTI)
7159 : : {
7160 : : uint16 newbits;
7161 : : uint16 newbits2;
7162 : :
7163 : : /*
7164 : : * xmax is an old MultiXactId that we have to replace with a new
7165 : : * MultiXactId, to carry forward two or more original member XIDs.
7166 : : */
1230 pg@bowt.ie 7167 [ - + ]:GBC 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7168 : :
7169 : : /*
7170 : : * We can't use GetMultiXactIdHintBits directly on the new multi
7171 : : * here; that routine initializes the masks to all zeroes, which
7172 : : * would lose other bits we need. Doing it this way ensures all
7173 : : * unrelated bits remain untouched.
7174 : : */
4523 alvherre@alvh.no-ip. 7175 : 1 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7176 : 1 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7177 : 1 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7178 : 1 : frz->t_infomask |= newbits;
7179 : 1 : frz->t_infomask2 |= newbits2;
7180 : 1 : frz->xmax = newxmax;
1230 pg@bowt.ie 7181 : 1 : replace_xmax = true;
7182 : : }
7183 : : else
7184 : : {
7185 : : /*
7186 : : * Freeze plan for tuple "freezes xmax" in the strictest sense:
7187 : : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7188 : : */
1230 pg@bowt.ie 7189 [ - + ]:CBC 6 : Assert(flags & FRM_INVALIDATE_XMAX);
1493 7190 [ - + ]: 6 : Assert(!TransactionIdIsValid(newxmax));
7191 : :
7192 : : /* Will set freeze_xmax flags in freeze plan below */
1230 7193 : 6 : freeze_xmax = true;
7194 : : }
7195 : :
7196 : : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
1224 7197 [ - + - - : 8 : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
- - ]
7198 : : }
3611 rhaas@postgresql.org 7199 [ + + ]: 5479434 : else if (TransactionIdIsNormal(xid))
7200 : : {
7201 : : /* Raw xmax is normal XID */
1230 pg@bowt.ie 7202 [ - + ]: 351609 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3095 andres@anarazel.de 7203 [ # # ]:UBC 0 : ereport(ERROR,
7204 : : (errcode(ERRCODE_DATA_CORRUPTED),
7205 : : errmsg_internal("found xmax %u from before relfrozenxid %u",
7206 : : xid, cutoffs->relfrozenxid)));
7207 : :
7208 : : /* Will set freeze_xmax flags in freeze plan below */
1218 pg@bowt.ie 7209 :CBC 351609 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7210 : :
7211 : : /*
7212 : : * Verify that xmax aborted if and when freeze plan is executed,
7213 : : * provided it's from an update. (A lock-only xmax can be removed
7214 : : * independent of this, since the lock is released at xact end.)
7215 : : */
7216 [ + + + + ]: 351609 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7217 : 3776 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7218 : : }
1259 7219 [ + - ]: 5127825 : else if (!TransactionIdIsValid(xid))
7220 : : {
7221 : : /* Raw xmax is InvalidTransactionId XID */
7222 [ - + ]: 5127825 : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
2923 alvherre@alvh.no-ip. 7223 : 5127825 : xmax_already_frozen = true;
7224 : : }
7225 : : else
2923 alvherre@alvh.no-ip. 7226 [ # # ]:UBC 0 : ereport(ERROR,
7227 : : (errcode(ERRCODE_DATA_CORRUPTED),
7228 : : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7229 : : xid, tuple->t_infomask)));
7230 : :
1230 pg@bowt.ie 7231 [ + + ]:CBC 5479442 : if (freeze_xmin)
7232 : : {
7233 [ - + ]: 3825398 : Assert(!xmin_already_frozen);
7234 : :
7235 : 3825398 : frz->t_infomask |= HEAP_XMIN_FROZEN;
7236 : : }
7237 [ - + ]: 5479442 : if (replace_xvac)
7238 : : {
7239 : : /*
7240 : : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7241 : : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7242 : : * transaction succeeded.
7243 : : */
1224 pg@bowt.ie 7244 [ # # ]:UBC 0 : Assert(pagefrz->freeze_required);
1230 7245 [ # # ]: 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
7246 : 0 : frz->frzflags |= XLH_INVALID_XVAC;
7247 : : else
7248 : 0 : frz->frzflags |= XLH_FREEZE_XVAC;
7249 : : }
1230 pg@bowt.ie 7250 [ + + ]:CBC 5479442 : if (replace_xmax)
7251 : : {
7252 [ + - - + ]: 1 : Assert(!xmax_already_frozen && !freeze_xmax);
1224 7253 [ - + ]: 1 : Assert(pagefrz->freeze_required);
7254 : :
7255 : : /* Already set replace_xmax flags in freeze plan earlier */
7256 : : }
4541 alvherre@alvh.no-ip. 7257 [ + + ]: 5479442 : if (freeze_xmax)
7258 : : {
1230 pg@bowt.ie 7259 [ + - - + ]: 4726 : Assert(!xmax_already_frozen && !replace_xmax);
7260 : :
4523 alvherre@alvh.no-ip. 7261 : 4726 : frz->xmax = InvalidTransactionId;
7262 : :
7263 : : /*
7264 : : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7265 : : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7266 : : * Also get rid of the HEAP_KEYS_UPDATED bit.
7267 : : */
7268 : 4726 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7269 : 4726 : frz->t_infomask |= HEAP_XMAX_INVALID;
7270 : 4726 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7271 : 4726 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7272 : : }
7273 : :
7274 : : /*
7275 : : * Determine if this tuple is already totally frozen, or will become
7276 : : * totally frozen (provided caller executes freeze plans for the page)
7277 : : */
1230 pg@bowt.ie 7278 [ + + + + : 10168813 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
+ + ]
7279 [ + + ]: 4689371 : (freeze_xmax || xmax_already_frozen));
7280 : :
1224 7281 [ + + + + : 5479442 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
+ + ]
7282 : : xmax_already_frozen))
7283 : : {
7284 : : /*
7285 : : * So far no previous tuple from the page made freezing mandatory.
7286 : : * Does this tuple force caller to freeze the entire page?
7287 : : */
7288 : 3224586 : pagefrz->freeze_required =
7289 : 3224586 : heap_tuple_should_freeze(tuple, cutoffs,
7290 : : &pagefrz->NoFreezePageRelfrozenXid,
7291 : : &pagefrz->NoFreezePageRelminMxid);
7292 : : }
7293 : :
7294 : : /* Tell caller if this tuple has a usable freeze plan set in *frz */
1230 7295 [ + + + - : 5479442 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
+ - + + ]
7296 : : }
7297 : :
7298 : : /*
7299 : : * Perform xmin/xmax XID status sanity checks before actually executing freeze
7300 : : * plans.
7301 : : *
7302 : : * heap_prepare_freeze_tuple doesn't perform these checks directly because
7303 : : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7304 : : * successive VACUUMs that each decide against freezing the same page.
7305 : : */
7306 : : void
762 heikki.linnakangas@i 7307 : 26152 : heap_pre_freeze_checks(Buffer buffer,
7308 : : HeapTupleFreeze *tuples, int ntuples)
7309 : : {
1267 pg@bowt.ie 7310 : 26152 : Page page = BufferGetPage(buffer);
7311 : :
1218 7312 [ + + ]: 1396720 : for (int i = 0; i < ntuples; i++)
7313 : : {
7314 : 1370568 : HeapTupleFreeze *frz = tuples + i;
7315 : 1370568 : ItemId itemid = PageGetItemId(page, frz->offset);
7316 : : HeapTupleHeader htup;
7317 : :
7318 : 1370568 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7319 : :
7320 : : /* Deliberately avoid relying on tuple hint bits here */
7321 [ + + ]: 1370568 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7322 : : {
7323 : 1370567 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
7324 : :
7325 [ - + ]: 1370567 : Assert(!HeapTupleHeaderXminFrozen(htup));
7326 [ - + ]: 1370567 : if (unlikely(!TransactionIdDidCommit(xmin)))
1218 pg@bowt.ie 7327 [ # # ]:UBC 0 : ereport(ERROR,
7328 : : (errcode(ERRCODE_DATA_CORRUPTED),
7329 : : errmsg_internal("uncommitted xmin %u needs to be frozen",
7330 : : xmin)));
7331 : : }
7332 : :
7333 : : /*
7334 : : * TransactionIdDidAbort won't work reliably in the presence of XIDs
7335 : : * left behind by transactions that were in progress during a crash,
7336 : : * so we can only check that xmax didn't commit
7337 : : */
1218 pg@bowt.ie 7338 [ + + ]:CBC 1370568 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7339 : : {
7340 : 1060 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
7341 : :
7342 [ - + ]: 1060 : Assert(TransactionIdIsNormal(xmax));
7343 [ - + ]: 1060 : if (unlikely(TransactionIdDidCommit(xmax)))
1218 pg@bowt.ie 7344 [ # # ]:UBC 0 : ereport(ERROR,
7345 : : (errcode(ERRCODE_DATA_CORRUPTED),
7346 : : errmsg_internal("cannot freeze committed xmax %u",
7347 : : xmax)));
7348 : : }
7349 : : }
762 heikki.linnakangas@i 7350 :CBC 26152 : }
7351 : :
7352 : : /*
7353 : : * Helper which executes freezing of one or more heap tuples on a page on
7354 : : * behalf of caller. Caller passes an array of tuple plans from
7355 : : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7356 : : * Must be called in a critical section that also marks the buffer dirty and,
7357 : : * if needed, emits WAL.
7358 : : */
7359 : : void
7360 : 26152 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
7361 : : {
7362 : 26152 : Page page = BufferGetPage(buffer);
7363 : :
1267 pg@bowt.ie 7364 [ + + ]: 1396720 : for (int i = 0; i < ntuples; i++)
7365 : : {
1218 7366 : 1370568 : HeapTupleFreeze *frz = tuples + i;
7367 : 1370568 : ItemId itemid = PageGetItemId(page, frz->offset);
7368 : : HeapTupleHeader htup;
7369 : :
1267 7370 : 1370568 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
1218 7371 : 1370568 : heap_execute_freeze_tuple(htup, frz);
7372 : : }
1267 7373 : 26152 : }
7374 : :
7375 : : /*
7376 : : * heap_freeze_tuple
7377 : : * Freeze tuple in place, without WAL logging.
7378 : : *
7379 : : * Useful for callers like CLUSTER that perform their own WAL logging.
7380 : : */
7381 : : bool
3095 andres@anarazel.de 7382 : 463302 : heap_freeze_tuple(HeapTupleHeader tuple,
7383 : : TransactionId relfrozenxid, TransactionId relminmxid,
7384 : : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7385 : : {
7386 : : HeapTupleFreeze frz;
7387 : : bool do_freeze;
7388 : : bool totally_frozen;
7389 : : struct VacuumCutoffs cutoffs;
7390 : : HeapPageFreeze pagefrz;
7391 : :
1230 pg@bowt.ie 7392 : 463302 : cutoffs.relfrozenxid = relfrozenxid;
7393 : 463302 : cutoffs.relminmxid = relminmxid;
7394 : 463302 : cutoffs.OldestXmin = FreezeLimit;
7395 : 463302 : cutoffs.OldestMxact = MultiXactCutoff;
7396 : 463302 : cutoffs.FreezeLimit = FreezeLimit;
7397 : 463302 : cutoffs.MultiXactCutoff = MultiXactCutoff;
7398 : :
1224 7399 : 463302 : pagefrz.freeze_required = true;
7400 : 463302 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7401 : 463302 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
56 melanieplageman@gmai 7402 :GNC 463302 : pagefrz.FreezePageConflictXid = InvalidTransactionId;
1224 pg@bowt.ie 7403 :CBC 463302 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7404 : 463302 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7405 : :
1230 7406 : 463302 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7407 : : &pagefrz, &frz, &totally_frozen);
7408 : :
7409 : : /*
7410 : : * Note that because this is not a WAL-logged operation, we don't need to
7411 : : * fill in the offset in the freeze record.
7412 : : */
7413 : :
4523 alvherre@alvh.no-ip. 7414 [ + + ]: 463302 : if (do_freeze)
7415 : 378038 : heap_execute_freeze_tuple(tuple, &frz);
7416 : 463302 : return do_freeze;
7417 : : }
7418 : :
7419 : : /*
7420 : : * For a given MultiXactId, return the hint bits that should be set in the
7421 : : * tuple's infomask.
7422 : : *
7423 : : * Normally this should be called for a multixact that was just created, and
7424 : : * so is on our local cache, so the GetMembers call is fast.
7425 : : */
7426 : : static void
4850 7427 : 76875 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
7428 : : uint16 *new_infomask2)
7429 : : {
7430 : : int nmembers;
7431 : : MultiXactMember *members;
7432 : : int i;
4724 bruce@momjian.us 7433 : 76875 : uint16 bits = HEAP_XMAX_IS_MULTI;
7434 : 76875 : uint16 bits2 = 0;
7435 : 76875 : bool has_update = false;
7436 : 76875 : LockTupleMode strongest = LockTupleKeyShare;
7437 : :
7438 : : /*
7439 : : * We only use this in multis we just created, so they cannot be values
7440 : : * pre-pg_upgrade.
7441 : : */
4298 alvherre@alvh.no-ip. 7442 : 76875 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7443 : :
4850 7444 [ + + ]: 1472829 : for (i = 0; i < nmembers; i++)
7445 : : {
7446 : : LockTupleMode mode;
7447 : :
7448 : : /*
7449 : : * Remember the strongest lock mode held by any member of the
7450 : : * multixact.
7451 : : */
4842 7452 : 1395954 : mode = TUPLOCK_from_mxstatus(members[i].status);
7453 [ + + ]: 1395954 : if (mode > strongest)
7454 : 2929 : strongest = mode;
7455 : :
7456 : : /* See what other bits we need */
4850 7457 [ + + + + : 1395954 : switch (members[i].status)
- ]
7458 : : {
7459 : 1393532 : case MultiXactStatusForKeyShare:
7460 : : case MultiXactStatusForShare:
7461 : : case MultiXactStatusForNoKeyUpdate:
7462 : 1393532 : break;
7463 : :
7464 : 53 : case MultiXactStatusForUpdate:
7465 : 53 : bits2 |= HEAP_KEYS_UPDATED;
7466 : 53 : break;
7467 : :
7468 : 2359 : case MultiXactStatusNoKeyUpdate:
7469 : 2359 : has_update = true;
7470 : 2359 : break;
7471 : :
7472 : 10 : case MultiXactStatusUpdate:
7473 : 10 : bits2 |= HEAP_KEYS_UPDATED;
7474 : 10 : has_update = true;
7475 : 10 : break;
7476 : : }
7477 : : }
7478 : :
4842 7479 [ + + + + ]: 76875 : if (strongest == LockTupleExclusive ||
7480 : : strongest == LockTupleNoKeyExclusive)
7481 : 2450 : bits |= HEAP_XMAX_EXCL_LOCK;
7482 [ + + ]: 74425 : else if (strongest == LockTupleShare)
7483 : 476 : bits |= HEAP_XMAX_SHR_LOCK;
7484 [ + - ]: 73949 : else if (strongest == LockTupleKeyShare)
7485 : 73949 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7486 : :
4850 7487 [ + + ]: 76875 : if (!has_update)
7488 : 74506 : bits |= HEAP_XMAX_LOCK_ONLY;
7489 : :
7490 [ + - ]: 76875 : if (nmembers > 0)
7491 : 76875 : pfree(members);
7492 : :
7493 : 76875 : *new_infomask = bits;
7494 : 76875 : *new_infomask2 = bits2;
7495 : 76875 : }
7496 : :
7497 : : /*
7498 : : * MultiXactIdGetUpdateXid
7499 : : *
7500 : : * Given a multixact Xmax and corresponding infomask, which does not have the
7501 : : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7502 : : * transaction.
7503 : : *
7504 : : * Caller is expected to check the status of the updating transaction, if
7505 : : * necessary.
7506 : : */
7507 : : static TransactionId
7508 : 162092 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7509 : : {
4724 bruce@momjian.us 7510 : 162092 : TransactionId update_xact = InvalidTransactionId;
7511 : : MultiXactMember *members;
7512 : : int nmembers;
7513 : :
4850 alvherre@alvh.no-ip. 7514 [ - + ]: 162092 : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7515 [ - + ]: 162092 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7516 : :
7517 : : /*
7518 : : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7519 : : * pre-pg_upgrade.
7520 : : */
4298 7521 : 162092 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7522 : :
4850 7523 [ + - ]: 162092 : if (nmembers > 0)
7524 : : {
7525 : : int i;
7526 : :
7527 [ + + ]: 3235162 : for (i = 0; i < nmembers; i++)
7528 : : {
7529 : : /* Ignore lockers */
4540 7530 [ + + ]: 3073070 : if (!ISUPDATE_from_mxstatus(members[i].status))
4850 7531 : 2910978 : continue;
7532 : :
7533 : : /* there can be at most one updater */
7534 [ - + ]: 162092 : Assert(update_xact == InvalidTransactionId);
7535 : 162092 : update_xact = members[i].xid;
7536 : : #ifndef USE_ASSERT_CHECKING
7537 : :
7538 : : /*
7539 : : * in an assert-enabled build, walk the whole array to ensure
7540 : : * there's no other updater.
7541 : : */
7542 : : break;
7543 : : #endif
7544 : : }
7545 : :
7546 : 162092 : pfree(members);
7547 : : }
7548 : :
7549 : 162092 : return update_xact;
7550 : : }
7551 : :
7552 : : /*
7553 : : * HeapTupleGetUpdateXid
7554 : : * As above, but use a HeapTupleHeader
7555 : : *
7556 : : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7557 : : * checking the hint bits.
7558 : : */
7559 : : TransactionId
467 peter@eisentraut.org 7560 : 159952 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
7561 : : {
7562 : 159952 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
7563 : 159952 : tup->t_infomask);
7564 : : }
7565 : :
7566 : : /*
7567 : : * Does the given multixact conflict with the current transaction grabbing a
7568 : : * tuple lock of the given strength?
7569 : : *
7570 : : * The passed infomask pairs up with the given multixact in the tuple header.
7571 : : *
7572 : : * If current_is_member is not NULL, it is set to 'true' if the current
7573 : : * transaction is a member of the given multixact.
7574 : : */
7575 : : static bool
4148 alvherre@alvh.no-ip. 7576 : 218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7577 : : LockTupleMode lockmode, bool *current_is_member)
7578 : : {
7579 : : int nmembers;
7580 : : MultiXactMember *members;
4000 bruce@momjian.us 7581 : 218 : bool result = false;
7582 : 218 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7583 : :
3602 alvherre@alvh.no-ip. 7584 [ - + ]: 218 : if (HEAP_LOCKED_UPGRADED(infomask))
3602 alvherre@alvh.no-ip. 7585 :UBC 0 : return false;
7586 : :
3602 alvherre@alvh.no-ip. 7587 :CBC 218 : nmembers = GetMultiXactIdMembers(multi, &members, false,
4148 7588 : 218 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7589 [ + - ]: 218 : if (nmembers >= 0)
7590 : : {
7591 : : int i;
7592 : :
7593 [ + + ]: 2682 : for (i = 0; i < nmembers; i++)
7594 : : {
7595 : : TransactionId memxid;
7596 : : LOCKMODE memlockmode;
7597 : :
2513 7598 [ + + + + : 2471 : if (result && (current_is_member == NULL || *current_is_member))
+ - ]
7599 : : break;
7600 : :
7601 : 2464 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7602 : :
7603 : : /* ignore members from current xact (but track their presence) */
2515 7604 : 2464 : memxid = members[i].xid;
7605 [ + + ]: 2464 : if (TransactionIdIsCurrentTransactionId(memxid))
7606 : : {
2513 7607 [ + + ]: 92 : if (current_is_member != NULL)
7608 : 78 : *current_is_member = true;
7609 : 92 : continue;
7610 : : }
7611 [ + + ]: 2372 : else if (result)
7612 : 8 : continue;
7613 : :
7614 : : /* ignore members that don't conflict with the lock we want */
7615 [ + + ]: 2364 : if (!DoLockModesConflict(memlockmode, wanted))
2515 7616 : 2325 : continue;
7617 : :
4148 7618 [ + + ]: 39 : if (ISUPDATE_from_mxstatus(members[i].status))
7619 : : {
7620 : : /* ignore aborted updaters */
7621 [ + + ]: 17 : if (TransactionIdDidAbort(memxid))
7622 : 1 : continue;
7623 : : }
7624 : : else
7625 : : {
7626 : : /* ignore lockers-only that are no longer in progress */
7627 [ + + ]: 22 : if (!TransactionIdIsInProgress(memxid))
7628 : 7 : continue;
7629 : : }
7630 : :
7631 : : /*
7632 : : * Whatever remains are either live lockers that conflict with our
7633 : : * wanted lock, and updaters that are not aborted. Those conflict
7634 : : * with what we want. Set up to return true, but keep going to
7635 : : * look for the current transaction among the multixact members,
7636 : : * if needed.
7637 : : */
7638 : 31 : result = true;
7639 : : }
7640 : 218 : pfree(members);
7641 : : }
7642 : :
7643 : 218 : return result;
7644 : : }
7645 : :
7646 : : /*
7647 : : * Do_MultiXactIdWait
7648 : : * Actual implementation for the two functions below.
7649 : : *
7650 : : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7651 : : * needed to ensure we only sleep on conflicting members, and the infomask is
7652 : : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7653 : : * indicates whether to use conditional lock acquisition, to allow callers to
7654 : : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7655 : : * context information for error messages. 'remaining', if not NULL, receives
7656 : : * the number of members that are still running, including any (non-aborted)
7657 : : * subtransactions of our own transaction. 'logLockFailure' indicates whether
7658 : : * to log details when a lock acquisition fails with 'nowait' enabled.
7659 : : *
7660 : : * We do this by sleeping on each member using XactLockTableWait. Any
7661 : : * members that belong to the current backend are *not* waited for, however;
7662 : : * this would not merely be useless but would lead to Assert failure inside
7663 : : * XactLockTableWait. By the time this returns, it is certain that all
7664 : : * transactions *of other backends* that were members of the MultiXactId
7665 : : * that conflict with the requested status are dead (and no new ones can have
7666 : : * been added, since it is not legal to add members to an existing
7667 : : * MultiXactId).
7668 : : *
7669 : : * But by the time we finish sleeping, someone else may have changed the Xmax
7670 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7671 : : *
7672 : : * Note that in case we return false, the number of remaining members is
7673 : : * not to be trusted.
7674 : : */
7675 : : static bool
4850 7676 : 61 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7677 : : uint16 infomask, bool nowait,
7678 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7679 : : int *remaining, bool logLockFailure)
7680 : : {
7681 : 61 : bool result = true;
7682 : : MultiXactMember *members;
7683 : : int nmembers;
7684 : 61 : int remain = 0;
7685 : :
7686 : : /* for pre-pg_upgrade tuples, no need to sleep at all */
3602 7687 [ + - ]: 61 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7688 : 61 : GetMultiXactIdMembers(multi, &members, false,
7689 : 61 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7690 : :
4850 7691 [ + - ]: 61 : if (nmembers >= 0)
7692 : : {
7693 : : int i;
7694 : :
7695 [ + + ]: 191 : for (i = 0; i < nmembers; i++)
7696 : : {
7697 : 136 : TransactionId memxid = members[i].xid;
7698 : 136 : MultiXactStatus memstatus = members[i].status;
7699 : :
7700 [ + + ]: 136 : if (TransactionIdIsCurrentTransactionId(memxid))
7701 : : {
7702 : 25 : remain++;
7703 : 25 : continue;
7704 : : }
7705 : :
7706 [ + + ]: 111 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7707 : 111 : LOCKMODE_from_mxstatus(status)))
7708 : : {
7709 [ + + + - ]: 22 : if (remaining && TransactionIdIsInProgress(memxid))
7710 : 8 : remain++;
7711 : 22 : continue;
7712 : : }
7713 : :
7714 : : /*
7715 : : * This member conflicts with our multi, so we have to sleep (or
7716 : : * return failure, if asked to avoid waiting.)
7717 : : *
7718 : : * Note that we don't set up an error context callback ourselves,
7719 : : * but instead we pass the info down to XactLockTableWait. This
7720 : : * might seem a bit wasteful because the context is set up and
7721 : : * tore down for each member of the multixact, but in reality it
7722 : : * should be barely noticeable, and it avoids duplicate code.
7723 : : */
7724 [ + + ]: 89 : if (nowait)
7725 : : {
417 fujii@postgresql.org 7726 : 6 : result = ConditionalXactLockTableWait(memxid, logLockFailure);
4850 alvherre@alvh.no-ip. 7727 [ + - ]: 6 : if (!result)
7728 : 6 : break;
7729 : : }
7730 : : else
4430 7731 : 83 : XactLockTableWait(memxid, rel, ctid, oper);
7732 : : }
7733 : :
4850 7734 : 61 : pfree(members);
7735 : : }
7736 : :
7737 [ + + ]: 61 : if (remaining)
7738 : 10 : *remaining = remain;
7739 : :
7740 : 61 : return result;
7741 : : }
7742 : :
7743 : : /*
7744 : : * MultiXactIdWait
7745 : : * Sleep on a MultiXactId.
7746 : : *
7747 : : * By the time we finish sleeping, someone else may have changed the Xmax
7748 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7749 : : *
7750 : : * We return (in *remaining, if not NULL) the number of members that are still
7751 : : * running, including any (non-aborted) subtransactions of our own transaction.
7752 : : */
7753 : : static void
4430 7754 : 55 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
7755 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7756 : : int *remaining)
7757 : : {
7758 : 55 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
7759 : : rel, ctid, oper, remaining, false);
4850 7760 : 55 : }
7761 : :
7762 : : /*
7763 : : * ConditionalMultiXactIdWait
7764 : : * As above, but only lock if we can get the lock without blocking.
7765 : : *
7766 : : * By the time we finish sleeping, someone else may have changed the Xmax
7767 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7768 : : *
7769 : : * If the multixact is now all gone, return true. Returns false if some
7770 : : * transactions might still be running.
7771 : : *
7772 : : * We return (in *remaining, if not NULL) the number of members that are still
7773 : : * running, including any (non-aborted) subtransactions of our own transaction.
7774 : : */
7775 : : static bool
7776 : 6 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7777 : : uint16 infomask, Relation rel, int *remaining,
7778 : : bool logLockFailure)
7779 : : {
4430 7780 : 6 : return Do_MultiXactIdWait(multi, status, infomask, true,
7781 : : rel, NULL, XLTW_None, remaining, logLockFailure);
7782 : : }
7783 : :
7784 : : /*
7785 : : * heap_tuple_needs_eventual_freeze
7786 : : *
7787 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7788 : : * will eventually require freezing (if tuple isn't removed by pruning first).
7789 : : */
7790 : : bool
3717 rhaas@postgresql.org 7791 : 2218515 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
7792 : : {
7793 : : TransactionId xid;
7794 : :
7795 : : /*
7796 : : * If xmin is a normal transaction ID, this tuple is definitely not
7797 : : * frozen.
7798 : : */
7799 : 2218515 : xid = HeapTupleHeaderGetXmin(tuple);
7800 [ + + ]: 2218515 : if (TransactionIdIsNormal(xid))
7801 : 35541 : return true;
7802 : :
7803 : : /*
7804 : : * If xmax is a valid xact or multixact, this tuple is also not frozen.
7805 : : */
7806 [ + + ]: 2182974 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7807 : : {
7808 : : MultiXactId multi;
7809 : :
7810 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
7811 [ + - ]: 2 : if (MultiXactIdIsValid(multi))
7812 : 2 : return true;
7813 : : }
7814 : : else
7815 : : {
7816 : 2182972 : xid = HeapTupleHeaderGetRawXmax(tuple);
7817 [ + + ]: 2182972 : if (TransactionIdIsNormal(xid))
7818 : 29 : return true;
7819 : : }
7820 : :
7821 [ - + ]: 2182943 : if (tuple->t_infomask & HEAP_MOVED)
7822 : : {
3717 rhaas@postgresql.org 7823 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
7824 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
7825 : 0 : return true;
7826 : : }
7827 : :
3717 rhaas@postgresql.org 7828 :CBC 2182943 : return false;
7829 : : }
7830 : :
7831 : : /*
7832 : : * heap_tuple_should_freeze
7833 : : *
7834 : : * Return value indicates if heap_prepare_freeze_tuple sibling function would
7835 : : * (or should) force freezing of the heap page that contains caller's tuple.
7836 : : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
7837 : : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
7838 : : *
7839 : : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
7840 : : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
7841 : : * Our working assumption is that caller won't decide to freeze this tuple.
7842 : : * It's up to caller to only ratchet back its own top-level trackers after the
7843 : : * point that it fully commits to not freezing the tuple/page in question.
7844 : : */
7845 : : bool
1224 pg@bowt.ie 7846 : 3225383 : heap_tuple_should_freeze(HeapTupleHeader tuple,
7847 : : const struct VacuumCutoffs *cutoffs,
7848 : : TransactionId *NoFreezePageRelfrozenXid,
7849 : : MultiXactId *NoFreezePageRelminMxid)
7850 : : {
7851 : : TransactionId xid;
7852 : : MultiXactId multi;
1230 7853 : 3225383 : bool freeze = false;
7854 : :
7855 : : /* First deal with xmin */
5293 rhaas@postgresql.org 7856 : 3225383 : xid = HeapTupleHeaderGetXmin(tuple);
1493 pg@bowt.ie 7857 [ + + ]: 3225383 : if (TransactionIdIsNormal(xid))
7858 : : {
1230 7859 [ - + ]: 3223282 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1224 7860 [ + + ]: 3223282 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7861 : 24669 : *NoFreezePageRelfrozenXid = xid;
1230 7862 [ + + ]: 3223282 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7863 : 21584 : freeze = true;
7864 : : }
7865 : :
7866 : : /* Now deal with xmax */
1493 7867 : 3225383 : xid = InvalidTransactionId;
7868 : 3225383 : multi = InvalidMultiXactId;
7869 [ + + ]: 3225383 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
4541 alvherre@alvh.no-ip. 7870 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
7871 : : else
1493 pg@bowt.ie 7872 : 3225381 : xid = HeapTupleHeaderGetRawXmax(tuple);
7873 : :
7874 [ + + ]: 3225383 : if (TransactionIdIsNormal(xid))
7875 : : {
1230 7876 [ - + ]: 333753 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7877 : : /* xmax is a non-permanent XID */
1224 7878 [ + + ]: 333753 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7879 : 10 : *NoFreezePageRelfrozenXid = xid;
1230 7880 [ + + ]: 333753 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7881 : 23 : freeze = true;
7882 : : }
1493 7883 [ + + ]: 2891630 : else if (!MultiXactIdIsValid(multi))
7884 : : {
7885 : : /* xmax is a permanent XID or invalid MultiXactId/XID */
7886 : : }
7887 [ - + ]: 2 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7888 : : {
7889 : : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
1224 pg@bowt.ie 7890 [ # # ]:UBC 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7891 : 0 : *NoFreezePageRelminMxid = multi;
7892 : : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
1230 7893 : 0 : freeze = true;
7894 : : }
7895 : : else
7896 : : {
7897 : : /* xmax is a MultiXactId that may have an updater XID */
7898 : : MultiXactMember *members;
7899 : : int nmembers;
7900 : :
1230 pg@bowt.ie 7901 [ - + ]:CBC 2 : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
1224 7902 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7903 : 2 : *NoFreezePageRelminMxid = multi;
1230 7904 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
7905 : 2 : freeze = true;
7906 : :
7907 : : /* need to check whether any member of the mxact is old */
1493 7908 : 2 : nmembers = GetMultiXactIdMembers(multi, &members, false,
7909 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
7910 : :
7911 [ + + ]: 5 : for (int i = 0; i < nmembers; i++)
7912 : : {
7913 : 3 : xid = members[i].xid;
1230 7914 [ - + ]: 3 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1224 7915 [ - + ]: 3 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
1224 pg@bowt.ie 7916 :UBC 0 : *NoFreezePageRelfrozenXid = xid;
1230 pg@bowt.ie 7917 [ - + ]:CBC 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
1230 pg@bowt.ie 7918 :UBC 0 : freeze = true;
7919 : : }
1493 pg@bowt.ie 7920 [ + + ]:CBC 2 : if (nmembers > 0)
7921 : 1 : pfree(members);
7922 : : }
7923 : :
5293 rhaas@postgresql.org 7924 [ - + ]: 3225383 : if (tuple->t_infomask & HEAP_MOVED)
7925 : : {
5293 rhaas@postgresql.org 7926 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
1493 pg@bowt.ie 7927 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
7928 : : {
1230 7929 [ # # ]: 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1224 7930 [ # # ]: 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7931 : 0 : *NoFreezePageRelfrozenXid = xid;
7932 : : /* heap_prepare_freeze_tuple forces xvac freezing */
1230 7933 : 0 : freeze = true;
7934 : : }
7935 : : }
7936 : :
1230 pg@bowt.ie 7937 :CBC 3225383 : return freeze;
7938 : : }
7939 : :
7940 : : /*
7941 : : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
7942 : : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
7943 : : * that caller is in the process of physically removing, e.g. via HOT pruning
7944 : : * or index deletion.
7945 : : *
7946 : : * Caller must initialize its value to InvalidTransactionId, which is
7947 : : * generally interpreted as "definitely no need for a recovery conflict".
7948 : : * Final value must reflect all heap tuples that caller will physically remove
7949 : : * (or remove TID references to) via its ongoing pruning/deletion operation.
7950 : : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
7951 : : * caller's WAL record) by REDO routine when it replays caller's operation.
7952 : : */
7953 : : void
1265 7954 : 4038657 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
7955 : : TransactionId *snapshotConflictHorizon)
7956 : : {
5981 simon@2ndQuadrant.co 7957 : 4038657 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
4850 alvherre@alvh.no-ip. 7958 : 4038657 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
5981 simon@2ndQuadrant.co 7959 : 4038657 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
7960 : :
5930 tgl@sss.pgh.pa.us 7961 [ - + ]: 4038657 : if (tuple->t_infomask & HEAP_MOVED)
7962 : : {
1265 pg@bowt.ie 7963 [ # # ]:UBC 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
7964 : 0 : *snapshotConflictHorizon = xvac;
7965 : : }
7966 : :
7967 : : /*
7968 : : * Ignore tuples inserted by an aborted transaction or if the tuple was
7969 : : * updated/deleted by the inserting transaction.
7970 : : *
7971 : : * Look for a committed hint bit, or if no xmin bit is set, check clog.
7972 : : */
4517 rhaas@postgresql.org 7973 [ + + ]:CBC 4038657 : if (HeapTupleHeaderXminCommitted(tuple) ||
7974 [ + + + - ]: 147856 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
7975 : : {
5626 simon@2ndQuadrant.co 7976 [ + + + + ]: 7634392 : if (xmax != xmin &&
1265 pg@bowt.ie 7977 : 3717227 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
7978 : 133269 : *snapshotConflictHorizon = xmax;
7979 : : }
5981 simon@2ndQuadrant.co 7980 : 4038657 : }
7981 : :
7982 : : #ifdef USE_PREFETCH
7983 : : /*
7984 : : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
7985 : : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
7986 : : * we can prefetch, and which have already been prefetched; each call to this
7987 : : * function picks up where the previous call left off.
7988 : : *
7989 : : * Note: we expect the deltids array to be sorted in an order that groups TIDs
7990 : : * by heap block, with all TIDs for each block appearing together in exactly
7991 : : * one group.
7992 : : */
7993 : : static void
1938 pg@bowt.ie 7994 : 25834 : index_delete_prefetch_buffer(Relation rel,
7995 : : IndexDeletePrefetchState *prefetch_state,
7996 : : int prefetch_count)
7997 : : {
2597 andres@anarazel.de 7998 : 25834 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
7999 : 25834 : int count = 0;
8000 : : int i;
1938 pg@bowt.ie 8001 : 25834 : int ndeltids = prefetch_state->ndeltids;
8002 : 25834 : TM_IndexDelete *deltids = prefetch_state->deltids;
8003 : :
2597 andres@anarazel.de 8004 : 25834 : for (i = prefetch_state->next_item;
1938 pg@bowt.ie 8005 [ + + + + ]: 891967 : i < ndeltids && count < prefetch_count;
2597 andres@anarazel.de 8006 : 866133 : i++)
8007 : : {
1938 pg@bowt.ie 8008 : 866133 : ItemPointer htid = &deltids[i].tid;
8009 : :
2597 andres@anarazel.de 8010 [ + + + + ]: 1724389 : if (cur_hblkno == InvalidBlockNumber ||
8011 : 858256 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
8012 : : {
8013 : 23362 : cur_hblkno = ItemPointerGetBlockNumber(htid);
8014 : 23362 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
8015 : 23362 : count++;
8016 : : }
8017 : : }
8018 : :
8019 : : /*
8020 : : * Save the prefetch position so that next time we can continue from that
8021 : : * position.
8022 : : */
8023 : 25834 : prefetch_state->next_item = i;
8024 : 25834 : prefetch_state->cur_hblkno = cur_hblkno;
8025 : 25834 : }
8026 : : #endif
8027 : :
8028 : : /*
8029 : : * Helper function for heap_index_delete_tuples. Checks for index corruption
8030 : : * involving an invalid TID in index AM caller's index page.
8031 : : *
8032 : : * This is an ideal place for these checks. The index AM must hold a buffer
8033 : : * lock on the index page containing the TIDs we examine here, so we don't
8034 : : * have to worry about concurrent VACUUMs at all. We can be sure that the
8035 : : * index is corrupt when htid points directly to an LP_UNUSED item or
8036 : : * heap-only tuple, which is not the case during standard index scans.
8037 : : */
8038 : : static inline void
1643 pg@bowt.ie 8039 : 711158 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
8040 : : Page page, OffsetNumber maxoff,
8041 : : const ItemPointerData *htid, TM_IndexStatus *istatus)
8042 : : {
8043 : 711158 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8044 : : ItemId iid;
8045 : :
8046 [ + - + - : 711158 : Assert(OffsetNumberIsValid(istatus->idxoffnum));
- + ]
8047 : :
8048 [ - + ]: 711158 : if (unlikely(indexpagehoffnum > maxoff))
1643 pg@bowt.ie 8049 [ # # ]:UBC 0 : ereport(ERROR,
8050 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8051 : : 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\"",
8052 : : ItemPointerGetBlockNumber(htid),
8053 : : indexpagehoffnum,
8054 : : istatus->idxoffnum, delstate->iblknum,
8055 : : RelationGetRelationName(delstate->irel))));
8056 : :
1643 pg@bowt.ie 8057 :CBC 711158 : iid = PageGetItemId(page, indexpagehoffnum);
8058 [ - + ]: 711158 : if (unlikely(!ItemIdIsUsed(iid)))
1643 pg@bowt.ie 8059 [ # # ]:UBC 0 : ereport(ERROR,
8060 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8061 : : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8062 : : ItemPointerGetBlockNumber(htid),
8063 : : indexpagehoffnum,
8064 : : istatus->idxoffnum, delstate->iblknum,
8065 : : RelationGetRelationName(delstate->irel))));
8066 : :
1643 pg@bowt.ie 8067 [ + + ]:CBC 711158 : if (ItemIdHasStorage(iid))
8068 : : {
8069 : : HeapTupleHeader htup;
8070 : :
8071 [ - + ]: 446382 : Assert(ItemIdIsNormal(iid));
8072 : 446382 : htup = (HeapTupleHeader) PageGetItem(page, iid);
8073 : :
8074 [ - + ]: 446382 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
1643 pg@bowt.ie 8075 [ # # ]:UBC 0 : ereport(ERROR,
8076 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8077 : : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8078 : : ItemPointerGetBlockNumber(htid),
8079 : : indexpagehoffnum,
8080 : : istatus->idxoffnum, delstate->iblknum,
8081 : : RelationGetRelationName(delstate->irel))));
8082 : : }
1643 pg@bowt.ie 8083 :CBC 711158 : }
8084 : :
8085 : : /*
8086 : : * heapam implementation of tableam's index_delete_tuples interface.
8087 : : *
8088 : : * This helper function is called by index AMs during index tuple deletion.
8089 : : * See tableam header comments for an explanation of the interface implemented
8090 : : * here and a general theory of operation. Note that each call here is either
8091 : : * a simple index deletion call, or a bottom-up index deletion call.
8092 : : *
8093 : : * It's possible for this to generate a fair amount of I/O, since we may be
8094 : : * deleting hundreds of tuples from a single index block. To amortize that
8095 : : * cost to some degree, this uses prefetching and combines repeat accesses to
8096 : : * the same heap block.
8097 : : */
8098 : : TransactionId
1938 8099 : 7877 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
8100 : : {
8101 : : /* Initial assumption is that earlier pruning took care of conflict */
1265 8102 : 7877 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
1952 8103 : 7877 : BlockNumber blkno = InvalidBlockNumber;
2597 andres@anarazel.de 8104 : 7877 : Buffer buf = InvalidBuffer;
1952 pg@bowt.ie 8105 : 7877 : Page page = NULL;
8106 : 7877 : OffsetNumber maxoff = InvalidOffsetNumber;
8107 : : TransactionId priorXmax;
8108 : : #ifdef USE_PREFETCH
8109 : : IndexDeletePrefetchState prefetch_state;
8110 : : int prefetch_distance;
8111 : : #endif
8112 : : SnapshotData SnapshotNonVacuumable;
1938 8113 : 7877 : int finalndeltids = 0,
8114 : 7877 : nblocksaccessed = 0;
8115 : :
8116 : : /* State that's only used in bottom-up index deletion case */
8117 : 7877 : int nblocksfavorable = 0;
8118 : 7877 : int curtargetfreespace = delstate->bottomupfreespace,
8119 : 7877 : lastfreespace = 0,
8120 : 7877 : actualfreespace = 0;
8121 : 7877 : bool bottomup_final_block = false;
8122 : :
8123 : 7877 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8124 : :
8125 : : /* Sort caller's deltids array by TID for further processing */
8126 : 7877 : index_delete_sort(delstate);
8127 : :
8128 : : /*
8129 : : * Bottom-up case: resort deltids array in an order attuned to where the
8130 : : * greatest number of promising TIDs are to be found, and determine how
8131 : : * many blocks from the start of sorted array should be considered
8132 : : * favorable. This will also shrink the deltids array in order to
8133 : : * eliminate completely unfavorable blocks up front.
8134 : : */
8135 [ + + ]: 7877 : if (delstate->bottomup)
8136 : 2774 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
8137 : :
8138 : : #ifdef USE_PREFETCH
8139 : : /* Initialize prefetch state. */
2597 andres@anarazel.de 8140 : 7877 : prefetch_state.cur_hblkno = InvalidBlockNumber;
8141 : 7877 : prefetch_state.next_item = 0;
1938 pg@bowt.ie 8142 : 7877 : prefetch_state.ndeltids = delstate->ndeltids;
8143 : 7877 : prefetch_state.deltids = delstate->deltids;
8144 : :
8145 : : /*
8146 : : * Determine the prefetch distance that we will attempt to maintain.
8147 : : *
8148 : : * Since the caller holds a buffer lock somewhere in rel, we'd better make
8149 : : * sure that isn't a catalog relation before we call code that does
8150 : : * syscache lookups, to avoid risk of deadlock.
8151 : : */
2590 tmunro@postgresql.or 8152 [ + + ]: 7877 : if (IsCatalogRelation(rel))
2241 8153 : 5716 : prefetch_distance = maintenance_io_concurrency;
8154 : : else
8155 : : prefetch_distance =
8156 : 2161 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
8157 : :
8158 : : /* Cap initial prefetch distance for bottom-up deletion caller */
1938 pg@bowt.ie 8159 [ + + ]: 7877 : if (delstate->bottomup)
8160 : : {
8161 [ - + ]: 2774 : Assert(nblocksfavorable >= 1);
8162 [ - + ]: 2774 : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8163 : 2774 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8164 : : }
8165 : :
8166 : : /* Start prefetching. */
8167 : 7877 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8168 : : #endif
8169 : :
8170 : : /* Iterate over deltids, determine which to delete, check their horizon */
8171 [ - + ]: 7877 : Assert(delstate->ndeltids > 0);
8172 [ + + ]: 719035 : for (int i = 0; i < delstate->ndeltids; i++)
8173 : : {
8174 : 713932 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8175 : 713932 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8176 : 713932 : ItemPointer htid = &ideltid->tid;
8177 : : OffsetNumber offnum;
8178 : :
8179 : : /*
8180 : : * Read buffer, and perform required extra steps each time a new block
8181 : : * is encountered. Avoid refetching if it's the same block as the one
8182 : : * from the last htid.
8183 : : */
1952 8184 [ + + + + ]: 1419987 : if (blkno == InvalidBlockNumber ||
8185 : 706055 : ItemPointerGetBlockNumber(htid) != blkno)
8186 : : {
8187 : : /*
8188 : : * Consider giving up early for bottom-up index deletion caller
8189 : : * first. (Only prefetch next-next block afterwards, when it
8190 : : * becomes clear that we're at least going to access the next
8191 : : * block in line.)
8192 : : *
8193 : : * Sometimes the first block frees so much space for bottom-up
8194 : : * caller that the deletion process can end without accessing any
8195 : : * more blocks. It is usually necessary to access 2 or 3 blocks
8196 : : * per bottom-up deletion operation, though.
8197 : : */
1938 8198 [ + + ]: 20731 : if (delstate->bottomup)
8199 : : {
8200 : : /*
8201 : : * We often allow caller to delete a few additional items
8202 : : * whose entries we reached after the point that space target
8203 : : * from caller was satisfied. The cost of accessing the page
8204 : : * was already paid at that point, so it made sense to finish
8205 : : * it off. When that happened, we finalize everything here
8206 : : * (by finishing off the whole bottom-up deletion operation
8207 : : * without needlessly paying the cost of accessing any more
8208 : : * blocks).
8209 : : */
8210 [ + + ]: 5960 : if (bottomup_final_block)
8211 : 125 : break;
8212 : :
8213 : : /*
8214 : : * Give up when we didn't enable our caller to free any
8215 : : * additional space as a result of processing the page that we
8216 : : * just finished up with. This rule is the main way in which
8217 : : * we keep the cost of bottom-up deletion under control.
8218 : : */
8219 [ + + + + ]: 5835 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8220 : 2649 : break;
8221 : 3186 : lastfreespace = actualfreespace; /* for next time */
8222 : :
8223 : : /*
8224 : : * Deletion operation (which is bottom-up) will definitely
8225 : : * access the next block in line. Prepare for that now.
8226 : : *
8227 : : * Decay target free space so that we don't hang on for too
8228 : : * long with a marginal case. (Space target is only truly
8229 : : * helpful when it allows us to recognize that we don't need
8230 : : * to access more than 1 or 2 blocks to satisfy caller due to
8231 : : * agreeable workload characteristics.)
8232 : : *
8233 : : * We are a bit more patient when we encounter contiguous
8234 : : * blocks, though: these are treated as favorable blocks. The
8235 : : * decay process is only applied when the next block in line
8236 : : * is not a favorable/contiguous block. This is not an
8237 : : * exception to the general rule; we still insist on finding
8238 : : * at least one deletable item per block accessed. See
8239 : : * bottomup_nblocksfavorable() for full details of the theory
8240 : : * behind favorable blocks and heap block locality in general.
8241 : : *
8242 : : * Note: The first block in line is always treated as a
8243 : : * favorable block, so the earliest possible point that the
8244 : : * decay can be applied is just before we access the second
8245 : : * block in line. The Assert() verifies this for us.
8246 : : */
8247 [ + + - + ]: 3186 : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8248 [ + + ]: 3186 : if (nblocksfavorable > 0)
8249 : 2928 : nblocksfavorable--;
8250 : : else
8251 : 258 : curtargetfreespace /= 2;
8252 : : }
8253 : :
8254 : : /* release old buffer */
8255 [ + + ]: 17957 : if (BufferIsValid(buf))
8256 : 10080 : UnlockReleaseBuffer(buf);
8257 : :
8258 : 17957 : blkno = ItemPointerGetBlockNumber(htid);
1952 8259 : 17957 : buf = ReadBuffer(rel, blkno);
1938 8260 : 17957 : nblocksaccessed++;
8261 [ + + - + ]: 17957 : Assert(!delstate->bottomup ||
8262 : : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8263 : :
8264 : : #ifdef USE_PREFETCH
8265 : :
8266 : : /*
8267 : : * To maintain the prefetch distance, prefetch one more page for
8268 : : * each page we read.
8269 : : */
8270 : 17957 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8271 : : #endif
8272 : :
1952 8273 : 17957 : LockBuffer(buf, BUFFER_LOCK_SHARE);
8274 : :
8275 : 17957 : page = BufferGetPage(buf);
8276 : 17957 : maxoff = PageGetMaxOffsetNumber(page);
8277 : : }
8278 : :
8279 : : /*
8280 : : * In passing, detect index corruption involving an index page with a
8281 : : * TID that points to a location in the heap that couldn't possibly be
8282 : : * correct. We only do this with actual TIDs from caller's index page
8283 : : * (not items reached by traversing through a HOT chain).
8284 : : */
1643 8285 : 711158 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8286 : :
1938 8287 [ + + ]: 711158 : if (istatus->knowndeletable)
8288 [ + - - + ]: 161935 : Assert(!delstate->bottomup && !istatus->promising);
8289 : : else
8290 : : {
8291 : 549223 : ItemPointerData tmp = *htid;
8292 : : HeapTupleData heapTuple;
8293 : :
8294 : : /* Are any tuples from this HOT chain non-vacuumable? */
8295 [ + + ]: 549223 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8296 : : &heapTuple, NULL, true))
8297 : 339907 : continue; /* can't delete entry */
8298 : :
8299 : : /* Caller will delete, since whole HOT chain is vacuumable */
8300 : 209316 : istatus->knowndeletable = true;
8301 : :
8302 : : /* Maintain index free space info for bottom-up deletion case */
8303 [ + + ]: 209316 : if (delstate->bottomup)
8304 : : {
8305 [ - + ]: 9936 : Assert(istatus->freespace > 0);
8306 : 9936 : actualfreespace += istatus->freespace;
8307 [ + + ]: 9936 : if (actualfreespace >= curtargetfreespace)
8308 : 2107 : bottomup_final_block = true;
8309 : : }
8310 : : }
8311 : :
8312 : : /*
8313 : : * Maintain snapshotConflictHorizon value for deletion operation as a
8314 : : * whole by advancing current value using heap tuple headers. This is
8315 : : * loosely based on the logic for pruning a HOT chain.
8316 : : */
1952 8317 : 371251 : offnum = ItemPointerGetOffsetNumber(htid);
8318 : 371251 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8319 : : for (;;)
2597 andres@anarazel.de 8320 : 23625 : {
8321 : : ItemId lp;
8322 : : HeapTupleHeader htup;
8323 : :
8324 : : /* Sanity check (pure paranoia) */
1686 pg@bowt.ie 8325 [ - + ]: 394876 : if (offnum < FirstOffsetNumber)
1686 pg@bowt.ie 8326 :UBC 0 : break;
8327 : :
8328 : : /*
8329 : : * An offset past the end of page's line pointer array is possible
8330 : : * when the array was truncated
8331 : : */
1686 pg@bowt.ie 8332 [ - + ]:CBC 394876 : if (offnum > maxoff)
1952 pg@bowt.ie 8333 :UBC 0 : break;
8334 : :
1952 pg@bowt.ie 8335 :CBC 394876 : lp = PageGetItemId(page, offnum);
8336 [ + + ]: 394876 : if (ItemIdIsRedirected(lp))
8337 : : {
8338 : 11307 : offnum = ItemIdGetRedirect(lp);
8339 : 11307 : continue;
8340 : : }
8341 : :
8342 : : /*
8343 : : * We'll often encounter LP_DEAD line pointers (especially with an
8344 : : * entry marked knowndeletable by our caller up front). No heap
8345 : : * tuple headers get examined for an htid that leads us to an
8346 : : * LP_DEAD item. This is okay because the earlier pruning
8347 : : * operation that made the line pointer LP_DEAD in the first place
8348 : : * must have considered the original tuple header as part of
8349 : : * generating its own snapshotConflictHorizon value.
8350 : : *
8351 : : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8352 : : * the same strategy that index vacuuming uses in all cases. Index
8353 : : * VACUUM WAL records don't even have a snapshotConflictHorizon
8354 : : * field of their own for this reason.
8355 : : */
8356 [ + + ]: 383569 : if (!ItemIdIsNormal(lp))
8357 : 238567 : break;
8358 : :
8359 : 145002 : htup = (HeapTupleHeader) PageGetItem(page, lp);
8360 : :
8361 : : /*
8362 : : * Check the tuple XMIN against prior XMAX, if any
8363 : : */
8364 [ + + - + ]: 157320 : if (TransactionIdIsValid(priorXmax) &&
8365 : 12318 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
1952 pg@bowt.ie 8366 :UBC 0 : break;
8367 : :
1265 pg@bowt.ie 8368 :CBC 145002 : HeapTupleHeaderAdvanceConflictHorizon(htup,
8369 : : &snapshotConflictHorizon);
8370 : :
8371 : : /*
8372 : : * If the tuple is not HOT-updated, then we are at the end of this
8373 : : * HOT-chain. No need to visit later tuples from the same update
8374 : : * chain (they get their own index entries) -- just move on to
8375 : : * next htid from index AM caller.
8376 : : */
1952 8377 [ + + ]: 145002 : if (!HeapTupleHeaderIsHotUpdated(htup))
8378 : 132684 : break;
8379 : :
8380 : : /* Advance to next HOT chain member */
8381 [ - + ]: 12318 : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8382 : 12318 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8383 : 12318 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8384 : : }
8385 : :
8386 : : /* Enable further/final shrinking of deltids for caller */
1938 8387 : 371251 : finalndeltids = i + 1;
8388 : : }
8389 : :
8390 : 7877 : UnlockReleaseBuffer(buf);
8391 : :
8392 : : /*
8393 : : * Shrink deltids array to exclude non-deletable entries at the end. This
8394 : : * is not just a minor optimization. Final deltids array size might be
8395 : : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8396 : : * ndeltids being zero in all cases with zero total deletable entries.
8397 : : */
8398 [ + + - + ]: 7877 : Assert(finalndeltids > 0 || delstate->bottomup);
8399 : 7877 : delstate->ndeltids = finalndeltids;
8400 : :
1265 8401 : 7877 : return snapshotConflictHorizon;
8402 : : }
8403 : :
8404 : : /*
8405 : : * Specialized inlineable comparison function for index_delete_sort()
8406 : : */
8407 : : static inline int
1938 8408 : 17309104 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
8409 : : {
8410 : 17309104 : ItemPointer tid1 = &deltid1->tid;
8411 : 17309104 : ItemPointer tid2 = &deltid2->tid;
8412 : :
8413 : : {
8414 : 17309104 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
8415 : 17309104 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
8416 : :
8417 [ + + ]: 17309104 : if (blk1 != blk2)
8418 [ + + ]: 7019886 : return (blk1 < blk2) ? -1 : 1;
8419 : : }
8420 : : {
8421 : 10289218 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
8422 : 10289218 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
8423 : :
8424 [ + - ]: 10289218 : if (pos1 != pos2)
8425 [ + + ]: 10289218 : return (pos1 < pos2) ? -1 : 1;
8426 : : }
8427 : :
1649 pg@bowt.ie 8428 :UBC 0 : Assert(false);
8429 : :
8430 : : return 0;
8431 : : }
8432 : :
8433 : : /*
8434 : : * Sort deltids array from delstate by TID. This prepares it for further
8435 : : * processing by heap_index_delete_tuples().
8436 : : *
8437 : : * This operation becomes a noticeable consumer of CPU cycles with some
8438 : : * workloads, so we go to the trouble of specialization/micro optimization.
8439 : : * We use shellsort for this because it's easy to specialize, compiles to
8440 : : * relatively few instructions, and is adaptive to presorted inputs/subsets
8441 : : * (which are typical here).
8442 : : */
8443 : : static void
1938 pg@bowt.ie 8444 :CBC 7877 : index_delete_sort(TM_IndexDeleteOp *delstate)
8445 : : {
8446 : 7877 : TM_IndexDelete *deltids = delstate->deltids;
8447 : 7877 : int ndeltids = delstate->ndeltids;
8448 : :
8449 : : /*
8450 : : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8451 : : *
8452 : : * This implementation is fast with array sizes up to ~4500. This covers
8453 : : * all supported BLCKSZ values.
8454 : : */
8455 : 7877 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8456 : :
8457 : : /* Think carefully before changing anything here -- keep swaps cheap */
8458 : : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8459 : : "element size exceeds 8 bytes");
8460 : :
8461 [ + + ]: 78770 : for (int g = 0; g < lengthof(gaps); g++)
8462 : : {
545 dgustafsson@postgres 8463 [ + + ]: 10435075 : for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8464 : : {
1938 pg@bowt.ie 8465 : 10364182 : TM_IndexDelete d = deltids[i];
8466 : 10364182 : int j = i;
8467 : :
8468 [ + + + + ]: 17812394 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8469 : : {
8470 : 7448212 : deltids[j] = deltids[j - hi];
8471 : 7448212 : j -= hi;
8472 : : }
8473 : 10364182 : deltids[j] = d;
8474 : : }
8475 : : }
8476 : 7877 : }
8477 : :
8478 : : /*
8479 : : * Returns how many blocks should be considered favorable/contiguous for a
8480 : : * bottom-up index deletion pass. This is a number of heap blocks that starts
8481 : : * from and includes the first block in line.
8482 : : *
8483 : : * There is always at least one favorable block during bottom-up index
8484 : : * deletion. In the worst case (i.e. with totally random heap blocks) the
8485 : : * first block in line (the only favorable block) can be thought of as a
8486 : : * degenerate array of contiguous blocks that consists of a single block.
8487 : : * heap_index_delete_tuples() will expect this.
8488 : : *
8489 : : * Caller passes blockgroups, a description of the final order that deltids
8490 : : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8491 : : * processing. Note that deltids need not actually be sorted just yet (caller
8492 : : * only passes deltids to us so that we can interpret blockgroups).
8493 : : *
8494 : : * You might guess that the existence of contiguous blocks cannot matter much,
8495 : : * since in general the main factor that determines which blocks we visit is
8496 : : * the number of promising TIDs, which is a fixed hint from the index AM.
8497 : : * We're not really targeting the general case, though -- the actual goal is
8498 : : * to adapt our behavior to a wide variety of naturally occurring conditions.
8499 : : * The effects of most of the heuristics we apply are only noticeable in the
8500 : : * aggregate, over time and across many _related_ bottom-up index deletion
8501 : : * passes.
8502 : : *
8503 : : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8504 : : * workloads where heap blocks visited during bottom-up index deletion can be
8505 : : * accessed contiguously, in the sense that each newly visited block is the
8506 : : * neighbor of the block that bottom-up deletion just finished processing (or
8507 : : * close enough to it). It will likely be cheaper to access more favorable
8508 : : * blocks sooner rather than later (e.g. in this pass, not across a series of
8509 : : * related bottom-up passes). Either way it is probably only a matter of time
8510 : : * (or a matter of further correlated version churn) before all blocks that
8511 : : * appear together as a single large batch of favorable blocks get accessed by
8512 : : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8513 : : * appear almost constantly or not even once (it all depends on per-index
8514 : : * workload characteristics).
8515 : : *
8516 : : * Note that the blockgroups sort order applies a power-of-two bucketing
8517 : : * scheme that creates opportunities for contiguous groups of blocks to get
8518 : : * batched together, at least with workloads that are naturally amenable to
8519 : : * being driven by heap block locality. This doesn't just enhance the spatial
8520 : : * locality of bottom-up heap block processing in the obvious way. It also
8521 : : * enables temporal locality of access, since sorting by heap block number
8522 : : * naturally tends to make the bottom-up processing order deterministic.
8523 : : *
8524 : : * Consider the following example to get a sense of how temporal locality
8525 : : * might matter: There is a heap relation with several indexes, each of which
8526 : : * is low to medium cardinality. It is subject to constant non-HOT updates.
8527 : : * The updates are skewed (in one part of the primary key, perhaps). None of
8528 : : * the indexes are logically modified by the UPDATE statements (if they were
8529 : : * then bottom-up index deletion would not be triggered in the first place).
8530 : : * Naturally, each new round of index tuples (for each heap tuple that gets a
8531 : : * heap_update() call) will have the same heap TID in each and every index.
8532 : : * Since these indexes are low cardinality and never get logically modified,
8533 : : * heapam processing during bottom-up deletion passes will access heap blocks
8534 : : * in approximately sequential order. Temporal locality of access occurs due
8535 : : * to bottom-up deletion passes behaving very similarly across each of the
8536 : : * indexes at any given moment. This keeps the number of buffer misses needed
8537 : : * to visit heap blocks to a minimum.
8538 : : */
8539 : : static int
8540 : 2774 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8541 : : TM_IndexDelete *deltids)
8542 : : {
8543 : 2774 : int64 lastblock = -1;
8544 : 2774 : int nblocksfavorable = 0;
8545 : :
8546 [ - + ]: 2774 : Assert(nblockgroups >= 1);
8547 [ - + ]: 2774 : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8548 : :
8549 : : /*
8550 : : * We tolerate heap blocks that will be accessed only slightly out of
8551 : : * physical order. Small blips occur when a pair of almost-contiguous
8552 : : * blocks happen to fall into different buckets (perhaps due only to a
8553 : : * small difference in npromisingtids that the bucketing scheme didn't
8554 : : * quite manage to ignore). We effectively ignore these blips by applying
8555 : : * a small tolerance. The precise tolerance we use is a little arbitrary,
8556 : : * but it works well enough in practice.
8557 : : */
8558 [ + + ]: 8702 : for (int b = 0; b < nblockgroups; b++)
8559 : : {
8560 : 8284 : IndexDeleteCounts *group = blockgroups + b;
8561 : 8284 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8562 : 8284 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8563 : :
8564 [ + + ]: 8284 : if (lastblock != -1 &&
8565 [ + + ]: 5510 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8566 [ + + ]: 4893 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8567 : : break;
8568 : :
8569 : 5928 : nblocksfavorable++;
8570 : 5928 : lastblock = block;
8571 : : }
8572 : :
8573 : : /* Always indicate that there is at least 1 favorable block */
8574 [ - + ]: 2774 : Assert(nblocksfavorable >= 1);
8575 : :
8576 : 2774 : return nblocksfavorable;
8577 : : }
8578 : :
8579 : : /*
8580 : : * qsort comparison function for bottomup_sort_and_shrink()
8581 : : */
8582 : : static int
8583 : 259891 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8584 : : {
8585 : 259891 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8586 : 259891 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8587 : :
8588 : : /*
8589 : : * Most significant field is npromisingtids (which we invert the order of
8590 : : * so as to sort in desc order).
8591 : : *
8592 : : * Caller should have already normalized npromisingtids fields into
8593 : : * power-of-two values (buckets).
8594 : : */
8595 [ + + ]: 259891 : if (group1->npromisingtids > group2->npromisingtids)
8596 : 12666 : return -1;
8597 [ + + ]: 247225 : if (group1->npromisingtids < group2->npromisingtids)
8598 : 15496 : return 1;
8599 : :
8600 : : /*
8601 : : * Tiebreak: desc ntids sort order.
8602 : : *
8603 : : * We cannot expect power-of-two values for ntids fields. We should
8604 : : * behave as if they were already rounded up for us instead.
8605 : : */
8606 [ + + ]: 231729 : if (group1->ntids != group2->ntids)
8607 : : {
8608 : 166329 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8609 : 166329 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8610 : :
8611 [ + + ]: 166329 : if (ntids1 > ntids2)
8612 : 27032 : return -1;
8613 [ + + ]: 139297 : if (ntids1 < ntids2)
8614 : 30006 : return 1;
8615 : : }
8616 : :
8617 : : /*
8618 : : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8619 : : * block in deltids array) order.
8620 : : *
8621 : : * This is equivalent to sorting in ascending heap block number order
8622 : : * (among otherwise equal subsets of the array). This approach allows us
8623 : : * to avoid accessing the out-of-line TID. (We rely on the assumption
8624 : : * that the deltids array was sorted in ascending heap TID order when
8625 : : * these offsets to the first TID from each heap block group were formed.)
8626 : : */
8627 [ + + ]: 174691 : if (group1->ifirsttid > group2->ifirsttid)
8628 : 84809 : return 1;
8629 [ + - ]: 89882 : if (group1->ifirsttid < group2->ifirsttid)
8630 : 89882 : return -1;
8631 : :
1938 pg@bowt.ie 8632 :UBC 0 : pg_unreachable();
8633 : :
8634 : : return 0;
8635 : : }
8636 : :
8637 : : /*
8638 : : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8639 : : *
8640 : : * Sorts deltids array in the order needed for useful processing by bottom-up
8641 : : * deletion. The array should already be sorted in TID order when we're
8642 : : * called. The sort process groups heap TIDs from deltids into heap block
8643 : : * groupings. Earlier/more-promising groups/blocks are usually those that are
8644 : : * known to have the most "promising" TIDs.
8645 : : *
8646 : : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8647 : : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8648 : : * return. This often means that deltids will be shrunk to a small fraction
8649 : : * of its original size (we eliminate many heap blocks from consideration for
8650 : : * caller up front).
8651 : : *
8652 : : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8653 : : * for a definition and full details.
8654 : : */
8655 : : static int
1938 pg@bowt.ie 8656 :CBC 2774 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8657 : : {
8658 : : IndexDeleteCounts *blockgroups;
8659 : : TM_IndexDelete *reordereddeltids;
8660 : 2774 : BlockNumber curblock = InvalidBlockNumber;
8661 : 2774 : int nblockgroups = 0;
8662 : 2774 : int ncopied = 0;
8663 : 2774 : int nblocksfavorable = 0;
8664 : :
8665 [ - + ]: 2774 : Assert(delstate->bottomup);
8666 [ - + ]: 2774 : Assert(delstate->ndeltids > 0);
8667 : :
8668 : : /* Calculate per-heap-block count of TIDs */
146 michael@paquier.xyz 8669 :GNC 2774 : blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
1938 pg@bowt.ie 8670 [ + + ]:CBC 1338607 : for (int i = 0; i < delstate->ndeltids; i++)
8671 : : {
8672 : 1335833 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8673 : 1335833 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8674 : 1335833 : ItemPointer htid = &ideltid->tid;
8675 : 1335833 : bool promising = istatus->promising;
8676 : :
8677 [ + + ]: 1335833 : if (curblock != ItemPointerGetBlockNumber(htid))
8678 : : {
8679 : : /* New block group */
8680 : 50611 : nblockgroups++;
8681 : :
8682 [ + + - + ]: 50611 : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8683 : : !BlockNumberIsValid(curblock));
8684 : :
8685 : 50611 : curblock = ItemPointerGetBlockNumber(htid);
8686 : 50611 : blockgroups[nblockgroups - 1].ifirsttid = i;
8687 : 50611 : blockgroups[nblockgroups - 1].ntids = 1;
8688 : 50611 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8689 : : }
8690 : : else
8691 : : {
8692 : 1285222 : blockgroups[nblockgroups - 1].ntids++;
8693 : : }
8694 : :
8695 [ + + ]: 1335833 : if (promising)
8696 : 219703 : blockgroups[nblockgroups - 1].npromisingtids++;
8697 : : }
8698 : :
8699 : : /*
8700 : : * We're about ready to sort block groups to determine the optimal order
8701 : : * for visiting heap blocks. But before we do, round the number of
8702 : : * promising tuples for each block group up to the next power-of-two,
8703 : : * unless it is very low (less than 4), in which case we round up to 4.
8704 : : * npromisingtids is far too noisy to trust when choosing between a pair
8705 : : * of block groups that both have very low values.
8706 : : *
8707 : : * This scheme divides heap blocks/block groups into buckets. Each bucket
8708 : : * contains blocks that have _approximately_ the same number of promising
8709 : : * TIDs as each other. The goal is to ignore relatively small differences
8710 : : * in the total number of promising entries, so that the whole process can
8711 : : * give a little weight to heapam factors (like heap block locality)
8712 : : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8713 : : * would be foolish to interpret small differences in npromisingtids
8714 : : * values as anything more than noise.
8715 : : *
8716 : : * We tiebreak on nhtids when sorting block group subsets that have the
8717 : : * same npromisingtids, but this has the same issues as npromisingtids,
8718 : : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8719 : : * only reason that we don't fix nhtids in the same way here too is that
8720 : : * we'll need accurate nhtids values after the sort. We handle nhtids
8721 : : * bucketization dynamically instead (in the sort comparator).
8722 : : *
8723 : : * See bottomup_nblocksfavorable() for a full explanation of when and how
8724 : : * heap locality/favorable blocks can significantly influence when and how
8725 : : * heap blocks are accessed.
8726 : : */
8727 [ + + ]: 53385 : for (int b = 0; b < nblockgroups; b++)
8728 : : {
8729 : 50611 : IndexDeleteCounts *group = blockgroups + b;
8730 : :
8731 : : /* Better off falling back on nhtids with low npromisingtids */
8732 [ + + ]: 50611 : if (group->npromisingtids <= 4)
8733 : 42448 : group->npromisingtids = 4;
8734 : : else
8735 : 8163 : group->npromisingtids =
8736 : 8163 : pg_nextpower2_32((uint32) group->npromisingtids);
8737 : : }
8738 : :
8739 : : /* Sort groups and rearrange caller's deltids array */
8740 : 2774 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8741 : : bottomup_sort_and_shrink_cmp);
8742 : 2774 : reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8743 : :
8744 : 2774 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8745 : : /* Determine number of favorable blocks at the start of final deltids */
8746 : 2774 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8747 : : delstate->deltids);
8748 : :
8749 [ + + ]: 18081 : for (int b = 0; b < nblockgroups; b++)
8750 : : {
8751 : 15307 : IndexDeleteCounts *group = blockgroups + b;
8752 : 15307 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8753 : :
8754 : 15307 : memcpy(reordereddeltids + ncopied, firstdtid,
8755 : 15307 : sizeof(TM_IndexDelete) * group->ntids);
8756 : 15307 : ncopied += group->ntids;
8757 : : }
8758 : :
8759 : : /* Copy final grouped and sorted TIDs back into start of caller's array */
8760 : 2774 : memcpy(delstate->deltids, reordereddeltids,
8761 : : sizeof(TM_IndexDelete) * ncopied);
8762 : 2774 : delstate->ndeltids = ncopied;
8763 : :
8764 : 2774 : pfree(reordereddeltids);
8765 : 2774 : pfree(blockgroups);
8766 : :
8767 : 2774 : return nblocksfavorable;
8768 : : }
8769 : :
8770 : : /*
8771 : : * Perform XLogInsert for a heap-update operation. Caller must already
8772 : : * have modified the buffer(s) and marked them dirty.
8773 : : */
8774 : : static XLogRecPtr
4850 alvherre@alvh.no-ip. 8775 : 2371588 : log_heap_update(Relation reln, Buffer oldbuf,
8776 : : Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
8777 : : HeapTuple old_key_tuple,
8778 : : bool all_visible_cleared, bool new_all_visible_cleared,
8779 : : bool walLogical)
8780 : : {
8781 : : xl_heap_update xlrec;
8782 : : xl_heap_header xlhdr;
8783 : : xl_heap_header xlhdr_idx;
8784 : : uint8 info;
8785 : : uint16 prefix_suffix[2];
4437 heikki.linnakangas@i 8786 : 2371588 : uint16 prefixlen = 0,
8787 : 2371588 : suffixlen = 0;
8788 : : XLogRecPtr recptr;
3667 kgrittn@postgresql.o 8789 : 2371588 : Page page = BufferGetPage(newbuf);
29 alvherre@kurilemu.de 8790 [ + + + + :GNC 2371588 : bool need_tuple_data = walLogical && RelationIsLogicallyLogged(reln);
+ + + - -
+ - - - -
+ - + + ]
8791 : : bool init;
8792 : : int bufflags;
8793 : :
8794 : : /* Caller should not call me on a non-WAL-logged relation */
5622 rhaas@postgresql.org 8795 [ + - + + :CBC 2371588 : Assert(RelationNeedsWAL(reln));
+ - - + ]
8796 : :
4184 heikki.linnakangas@i 8797 : 2371588 : XLogBeginInsert();
8798 : :
5930 tgl@sss.pgh.pa.us 8799 [ + + ]: 2371588 : if (HeapTupleIsHeapOnly(newtup))
6802 8800 : 166650 : info = XLOG_HEAP_HOT_UPDATE;
8801 : : else
8802 : 2204938 : info = XLOG_HEAP_UPDATE;
8803 : :
8804 : : /*
8805 : : * If the old and new tuple are on the same page, we only need to log the
8806 : : * parts of the new tuple that were changed. That saves on the amount of
8807 : : * WAL we need to write. Currently, we just count any unchanged bytes in
8808 : : * the beginning and end of the tuple. That's quick to check, and
8809 : : * perfectly covers the common case that only one field is updated.
8810 : : *
8811 : : * We could do this even if the old and new tuple are on different pages,
8812 : : * but only if we don't make a full-page image of the old page, which is
8813 : : * difficult to know in advance. Also, if the old tuple is corrupt for
8814 : : * some reason, it would allow the corruption to propagate the new page,
8815 : : * so it seems best to avoid. Under the general assumption that most
8816 : : * updates tend to create the new tuple version on the same page, there
8817 : : * isn't much to be gained by doing this across pages anyway.
8818 : : *
8819 : : * Skip this if we're taking a full-page image of the new page, as we
8820 : : * don't include the new tuple in the WAL record in that case. Also
8821 : : * disable if effective_wal_level='logical', as logical decoding needs to
8822 : : * be able to read the new tuple in whole from the WAL record alone.
8823 : : */
4437 heikki.linnakangas@i 8824 [ + + + + ]: 2371588 : if (oldbuf == newbuf && !need_tuple_data &&
8825 [ + + ]: 170982 : !XLogCheckBufferNeedsBackup(newbuf))
8826 : : {
8827 : 170419 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8828 : 170419 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8829 : 170419 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8830 : 170419 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
8831 : :
8832 : : /* Check for common prefix between old and new tuple */
8833 [ + + ]: 14403965 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8834 : : {
8835 [ + + ]: 14376373 : if (newp[prefixlen] != oldp[prefixlen])
8836 : 142827 : break;
8837 : : }
8838 : :
8839 : : /*
8840 : : * Storing the length of the prefix takes 2 bytes, so we need to save
8841 : : * at least 3 bytes or there's no point.
8842 : : */
8843 [ + + ]: 170419 : if (prefixlen < 3)
8844 : 22827 : prefixlen = 0;
8845 : :
8846 : : /* Same for suffix */
8847 [ + + ]: 6212991 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
8848 : : {
8849 [ + + ]: 6185070 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
8850 : 142498 : break;
8851 : : }
8852 [ + + ]: 170419 : if (suffixlen < 3)
8853 : 41639 : suffixlen = 0;
8854 : : }
8855 : :
8856 : : /* Prepare main WAL data chain */
4529 rhaas@postgresql.org 8857 : 2371588 : xlrec.flags = 0;
8858 [ + + ]: 2371588 : if (all_visible_cleared)
4015 andres@anarazel.de 8859 : 2306 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
4529 rhaas@postgresql.org 8860 [ + + ]: 2371588 : if (new_all_visible_cleared)
4015 andres@anarazel.de 8861 : 1230 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
4437 heikki.linnakangas@i 8862 [ + + ]: 2371588 : if (prefixlen > 0)
4015 andres@anarazel.de 8863 : 147592 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
4437 heikki.linnakangas@i 8864 [ + + ]: 2371588 : if (suffixlen > 0)
4015 andres@anarazel.de 8865 : 128780 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
4184 heikki.linnakangas@i 8866 [ + + ]: 2371588 : if (need_tuple_data)
8867 : : {
4015 andres@anarazel.de 8868 : 47055 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
4184 heikki.linnakangas@i 8869 [ + + ]: 47055 : if (old_key_tuple)
8870 : : {
8871 [ + + ]: 165 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4015 andres@anarazel.de 8872 : 68 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
8873 : : else
8874 : 97 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
8875 : : }
8876 : : }
8877 : :
8878 : : /* If new tuple is the single and first tuple on page... */
4437 heikki.linnakangas@i 8879 [ + + + + ]: 2384709 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
8880 : 13121 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
8881 : : {
8882 : 12767 : info |= XLOG_HEAP_INIT_PAGE;
4184 8883 : 12767 : init = true;
8884 : : }
8885 : : else
8886 : 2358821 : init = false;
8887 : :
8888 : : /* Prepare WAL data for the old page */
8889 : 2371588 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
8890 : 2371588 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
8891 : 4743176 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
8892 : 2371588 : oldtup->t_data->t_infomask2);
8893 : :
8894 : : /* Prepare WAL data for the new page */
8895 : 2371588 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
8896 : 2371588 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
8897 : :
8898 : 2371588 : bufflags = REGBUF_STANDARD;
8899 [ + + ]: 2371588 : if (init)
8900 : 12767 : bufflags |= REGBUF_WILL_INIT;
8901 [ + + ]: 2371588 : if (need_tuple_data)
8902 : 47055 : bufflags |= REGBUF_KEEP_DATA;
8903 : :
8904 : 2371588 : XLogRegisterBuffer(0, newbuf, bufflags);
8905 [ + + ]: 2371588 : if (oldbuf != newbuf)
8906 : 2188633 : XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
8907 : :
448 peter@eisentraut.org 8908 : 2371588 : XLogRegisterData(&xlrec, SizeOfHeapUpdate);
8909 : :
8910 : : /*
8911 : : * Prepare WAL data for the new tuple.
8912 : : */
4437 heikki.linnakangas@i 8913 [ + + + + ]: 2371588 : if (prefixlen > 0 || suffixlen > 0)
8914 : : {
8915 [ + + + + ]: 169846 : if (prefixlen > 0 && suffixlen > 0)
8916 : : {
8917 : 106526 : prefix_suffix[0] = prefixlen;
8918 : 106526 : prefix_suffix[1] = suffixlen;
448 peter@eisentraut.org 8919 : 106526 : XLogRegisterBufData(0, &prefix_suffix, sizeof(uint16) * 2);
8920 : : }
4437 heikki.linnakangas@i 8921 [ + + ]: 63320 : else if (prefixlen > 0)
8922 : : {
448 peter@eisentraut.org 8923 : 41066 : XLogRegisterBufData(0, &prefixlen, sizeof(uint16));
8924 : : }
8925 : : else
8926 : : {
8927 : 22254 : XLogRegisterBufData(0, &suffixlen, sizeof(uint16));
8928 : : }
8929 : : }
8930 : :
4184 heikki.linnakangas@i 8931 : 2371588 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
8932 : 2371588 : xlhdr.t_infomask = newtup->t_data->t_infomask;
8933 : 2371588 : xlhdr.t_hoff = newtup->t_data->t_hoff;
4091 tgl@sss.pgh.pa.us 8934 [ - + ]: 2371588 : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
8935 : :
8936 : : /*
8937 : : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
8938 : : *
8939 : : * The 'data' doesn't include the common prefix or suffix.
8940 : : */
448 peter@eisentraut.org 8941 : 2371588 : XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
4437 heikki.linnakangas@i 8942 [ + + ]: 2371588 : if (prefixlen == 0)
8943 : : {
4184 8944 : 2223996 : XLogRegisterBufData(0,
448 peter@eisentraut.org 8945 : 2223996 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3240 tgl@sss.pgh.pa.us 8946 : 2223996 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
8947 : : }
8948 : : else
8949 : : {
8950 : : /*
8951 : : * Have to write the null bitmap and data after the common prefix as
8952 : : * two separate rdata entries.
8953 : : */
8954 : : /* bitmap [+ padding] [+ oid] */
4091 8955 [ + - ]: 147592 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
8956 : : {
4184 heikki.linnakangas@i 8957 : 147592 : XLogRegisterBufData(0,
448 peter@eisentraut.org 8958 : 147592 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3240 tgl@sss.pgh.pa.us 8959 : 147592 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
8960 : : }
8961 : :
8962 : : /* data after common prefix */
4184 heikki.linnakangas@i 8963 : 147592 : XLogRegisterBufData(0,
448 peter@eisentraut.org 8964 : 147592 : (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
3240 tgl@sss.pgh.pa.us 8965 : 147592 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
8966 : : }
8967 : :
8968 : : /* We need to log a tuple identity */
4184 heikki.linnakangas@i 8969 [ + + + + ]: 2371588 : if (need_tuple_data && old_key_tuple)
8970 : : {
8971 : : /* don't really need this, but its more comfy to decode */
8972 : 165 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
8973 : 165 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
8974 : 165 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
8975 : :
448 peter@eisentraut.org 8976 : 165 : XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
8977 : :
8978 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
4091 tgl@sss.pgh.pa.us 8979 : 165 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
8980 : 165 : old_key_tuple->t_len - SizeofHeapTupleHeader);
8981 : : }
8982 : :
8983 : : /* filtering by origin on a row level is much more efficient */
3421 andres@anarazel.de 8984 : 2371588 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
8985 : :
4184 heikki.linnakangas@i 8986 : 2371588 : recptr = XLogInsert(RM_HEAP_ID, info);
8987 : :
7419 neilc@samurai.com 8988 : 2371588 : return recptr;
8989 : : }
8990 : :
8991 : : /*
8992 : : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
8993 : : *
8994 : : * This is only used when effective_wal_level is logical, and only for
8995 : : * catalog tuples.
8996 : : */
8997 : : static XLogRecPtr
4529 rhaas@postgresql.org 8998 : 32991 : log_heap_new_cid(Relation relation, HeapTuple tup)
8999 : : {
9000 : : xl_heap_new_cid xlrec;
9001 : :
9002 : : XLogRecPtr recptr;
9003 : 32991 : HeapTupleHeader hdr = tup->t_data;
9004 : :
9005 [ - + ]: 32991 : Assert(ItemPointerIsValid(&tup->t_self));
9006 [ - + ]: 32991 : Assert(tup->t_tableOid != InvalidOid);
9007 : :
9008 : 32991 : xlrec.top_xid = GetTopTransactionId();
1399 9009 : 32991 : xlrec.target_locator = relation->rd_locator;
4184 heikki.linnakangas@i 9010 : 32991 : xlrec.target_tid = tup->t_self;
9011 : :
9012 : : /*
9013 : : * If the tuple got inserted & deleted in the same TX we definitely have a
9014 : : * combo CID, set cmin and cmax.
9015 : : */
4529 rhaas@postgresql.org 9016 [ + + ]: 32991 : if (hdr->t_infomask & HEAP_COMBOCID)
9017 : : {
9018 [ - + ]: 2256 : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
4517 9019 [ - + ]: 2256 : Assert(!HeapTupleHeaderXminInvalid(hdr));
4529 9020 : 2256 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9021 : 2256 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9022 : 2256 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9023 : : }
9024 : : /* No combo CID, so only cmin or cmax can be set by this TX */
9025 : : else
9026 : : {
9027 : : /*
9028 : : * Tuple inserted.
9029 : : *
9030 : : * We need to check for LOCK ONLY because multixacts might be
9031 : : * transferred to the new tuple in case of FOR KEY SHARE updates in
9032 : : * which case there will be an xmax, although the tuple just got
9033 : : * inserted.
9034 : : */
9035 [ + + + + ]: 41459 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9036 : 10724 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
9037 : : {
9038 : 20012 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
9039 : 20012 : xlrec.cmax = InvalidCommandId;
9040 : : }
9041 : : /* Tuple from a different tx updated or deleted. */
9042 : : else
9043 : : {
9044 : 10723 : xlrec.cmin = InvalidCommandId;
9045 : 10723 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
9046 : : }
9047 : 30735 : xlrec.combocid = InvalidCommandId;
9048 : : }
9049 : :
9050 : : /*
9051 : : * Note that we don't need to register the buffer here, because this
9052 : : * operation does not modify the page. The insert/update/delete that
9053 : : * called us certainly did, but that's WAL-logged separately.
9054 : : */
4184 heikki.linnakangas@i 9055 : 32991 : XLogBeginInsert();
448 peter@eisentraut.org 9056 : 32991 : XLogRegisterData(&xlrec, SizeOfHeapNewCid);
9057 : :
9058 : : /* will be looked at irrespective of origin */
9059 : :
4184 heikki.linnakangas@i 9060 : 32991 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9061 : :
4529 rhaas@postgresql.org 9062 : 32991 : return recptr;
9063 : : }
9064 : :
9065 : : /*
9066 : : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9067 : : * the old tuple in an UPDATE or DELETE.
9068 : : *
9069 : : * Returns NULL if there's no need to log an identity or if there's no suitable
9070 : : * key defined.
9071 : : *
9072 : : * Pass key_required true if any replica identity columns changed value, or if
9073 : : * any of them have any external data. Delete must always pass true.
9074 : : *
9075 : : * *copy is set to true if the returned tuple is a modified copy rather than
9076 : : * the same tuple that was passed in.
9077 : : */
9078 : : static HeapTuple
1541 akapila@postgresql.o 9079 : 4231288 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
9080 : : bool *copy)
9081 : : {
4529 rhaas@postgresql.org 9082 : 4231288 : TupleDesc desc = RelationGetDescr(relation);
9083 : 4231288 : char replident = relation->rd_rel->relreplident;
9084 : : Bitmapset *idattrs;
9085 : : HeapTuple key_tuple;
9086 : : bool nulls[MaxHeapAttributeNumber];
9087 : : Datum values[MaxHeapAttributeNumber];
9088 : :
9089 : 4231288 : *copy = false;
9090 : :
9091 [ + + + + : 4231288 : if (!RelationIsLogicallyLogged(relation))
+ + - + -
- - - + -
+ + ]
9092 : 4130891 : return NULL;
9093 : :
9094 [ + + ]: 100397 : if (replident == REPLICA_IDENTITY_NOTHING)
9095 : 272 : return NULL;
9096 : :
9097 [ + + ]: 100125 : if (replident == REPLICA_IDENTITY_FULL)
9098 : : {
9099 : : /*
9100 : : * When logging the entire old tuple, it very well could contain
9101 : : * toasted columns. If so, force them to be inlined.
9102 : : */
9103 [ + + ]: 203 : if (HeapTupleHasExternal(tp))
9104 : : {
9105 : 4 : *copy = true;
2437 tgl@sss.pgh.pa.us 9106 : 4 : tp = toast_flatten_tuple(tp, desc);
9107 : : }
4529 rhaas@postgresql.org 9108 : 203 : return tp;
9109 : : }
9110 : :
9111 : : /* if the key isn't required and we're only logging the key, we're done */
1541 akapila@postgresql.o 9112 [ + + ]: 99922 : if (!key_required)
4529 rhaas@postgresql.org 9113 : 46910 : return NULL;
9114 : :
9115 : : /* find out the replica identity columns */
2437 tgl@sss.pgh.pa.us 9116 : 53012 : idattrs = RelationGetIndexAttrBitmap(relation,
9117 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
9118 : :
9119 : : /*
9120 : : * If there's no defined replica identity columns, treat as !key_required.
9121 : : * (This case should not be reachable from heap_update, since that should
9122 : : * calculate key_required accurately. But heap_delete just passes
9123 : : * constant true for key_required, so we can hit this case in deletes.)
9124 : : */
9125 [ + + ]: 53012 : if (bms_is_empty(idattrs))
9126 : 6021 : return NULL;
9127 : :
9128 : : /*
9129 : : * Construct a new tuple containing only the replica identity columns,
9130 : : * with nulls elsewhere. While we're at it, assert that the replica
9131 : : * identity columns aren't null.
9132 : : */
9133 : 46991 : heap_deform_tuple(tp, desc, values, nulls);
9134 : :
9135 [ + + ]: 150982 : for (int i = 0; i < desc->natts; i++)
9136 : : {
9137 [ + + ]: 103991 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
9138 : : idattrs))
9139 [ - + ]: 47011 : Assert(!nulls[i]);
9140 : : else
9141 : 56980 : nulls[i] = true;
9142 : : }
9143 : :
4529 rhaas@postgresql.org 9144 : 46991 : key_tuple = heap_form_tuple(desc, values, nulls);
9145 : 46991 : *copy = true;
9146 : :
2437 tgl@sss.pgh.pa.us 9147 : 46991 : bms_free(idattrs);
9148 : :
9149 : : /*
9150 : : * If the tuple, which by here only contains indexed columns, still has
9151 : : * toasted columns, force them to be inlined. This is somewhat unlikely
9152 : : * since there's limits on the size of indexed columns, so we don't
9153 : : * duplicate toast_flatten_tuple()s functionality in the above loop over
9154 : : * the indexed columns, even if it would be more efficient.
9155 : : */
4529 rhaas@postgresql.org 9156 [ + + ]: 46991 : if (HeapTupleHasExternal(key_tuple))
9157 : : {
4382 bruce@momjian.us 9158 : 4 : HeapTuple oldtup = key_tuple;
9159 : :
2437 tgl@sss.pgh.pa.us 9160 : 4 : key_tuple = toast_flatten_tuple(oldtup, desc);
4529 rhaas@postgresql.org 9161 : 4 : heap_freetuple(oldtup);
9162 : : }
9163 : :
9164 : 46991 : return key_tuple;
9165 : : }
9166 : :
9167 : : /*
9168 : : * HeapCheckForSerializableConflictOut
9169 : : * We are reading a tuple. If it's not visible, there may be a
9170 : : * rw-conflict out with the inserter. Otherwise, if it is visible to us
9171 : : * but has been deleted, there may be a rw-conflict out with the deleter.
9172 : : *
9173 : : * We will determine the top level xid of the writing transaction with which
9174 : : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9175 : : * for overlap with our own transaction.
9176 : : *
9177 : : * This function should be called just about anywhere in heapam.c where a
9178 : : * tuple has been read. The caller must hold at least a shared lock on the
9179 : : * buffer, because this function might set hint bits on the tuple. There is
9180 : : * currently no known reason to call this function from an index AM.
9181 : : */
9182 : : void
2289 tmunro@postgresql.or 9183 : 41411070 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
9184 : : HeapTuple tuple, Buffer buffer,
9185 : : Snapshot snapshot)
9186 : : {
9187 : : TransactionId xid;
9188 : : HTSV_Result htsvResult;
9189 : :
9190 [ + + ]: 41411070 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9191 : 41403125 : return;
9192 : :
9193 : : /*
9194 : : * Check to see whether the tuple has been written to by a concurrent
9195 : : * transaction, either to create it not visible to us, or to delete it
9196 : : * while it is visible to us. The "visible" bool indicates whether the
9197 : : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9198 : : * is going on with it.
9199 : : *
9200 : : * In the event of a concurrently inserted tuple that also happens to have
9201 : : * been concurrently updated (by a separate transaction), the xmin of the
9202 : : * tuple will be used -- not the updater's xid.
9203 : : */
9204 : 7945 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9205 [ + + + + : 7945 : switch (htsvResult)
- ]
9206 : : {
9207 : 7137 : case HEAPTUPLE_LIVE:
9208 [ + + ]: 7137 : if (visible)
9209 : 7124 : return;
9210 : 13 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9211 : 13 : break;
9212 : 361 : case HEAPTUPLE_RECENTLY_DEAD:
9213 : : case HEAPTUPLE_DELETE_IN_PROGRESS:
2154 pg@bowt.ie 9214 [ + + ]: 361 : if (visible)
9215 : 286 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9216 : : else
9217 : 75 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9218 : :
9219 [ + + ]: 361 : if (TransactionIdPrecedes(xid, TransactionXmin))
9220 : : {
9221 : : /* This is like the HEAPTUPLE_DEAD case */
9222 [ - + ]: 67 : Assert(!visible);
9223 : 67 : return;
9224 : : }
2289 tmunro@postgresql.or 9225 : 294 : break;
9226 : 327 : case HEAPTUPLE_INSERT_IN_PROGRESS:
9227 : 327 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9228 : 327 : break;
9229 : 120 : case HEAPTUPLE_DEAD:
2154 pg@bowt.ie 9230 [ - + ]: 120 : Assert(!visible);
2289 tmunro@postgresql.or 9231 : 120 : return;
2289 tmunro@postgresql.or 9232 :UBC 0 : default:
9233 : :
9234 : : /*
9235 : : * The only way to get to this default clause is if a new value is
9236 : : * added to the enum type without adding it to this switch
9237 : : * statement. That's a bug, so elog.
9238 : : */
9239 [ # # ]: 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9240 : :
9241 : : /*
9242 : : * In spite of having all enum values covered and calling elog on
9243 : : * this default, some compilers think this is a code path which
9244 : : * allows xid to be used below without initialization. Silence
9245 : : * that warning.
9246 : : */
9247 : : xid = InvalidTransactionId;
9248 : : }
9249 : :
2289 tmunro@postgresql.or 9250 [ - + ]:CBC 634 : Assert(TransactionIdIsValid(xid));
9251 [ - + ]: 634 : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
9252 : :
9253 : : /*
9254 : : * Find top level xid. Bail out if xid is too early to be a conflict, or
9255 : : * if it's our own xid.
9256 : : */
9257 [ + + ]: 634 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
9258 : 64 : return;
9259 : 570 : xid = SubTransGetTopmostTransaction(xid);
9260 [ - + ]: 570 : if (TransactionIdPrecedes(xid, TransactionXmin))
2289 tmunro@postgresql.or 9261 :UBC 0 : return;
9262 : :
2289 tmunro@postgresql.or 9263 :CBC 570 : CheckForSerializableConflictOut(relation, xid, snapshot);
9264 : : }
|