Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * heapam.c
4 : : * heap access method code
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/access/heap/heapam.c
12 : : *
13 : : *
14 : : * INTERFACE ROUTINES
15 : : * heap_beginscan - begin relation scan
16 : : * heap_rescan - restart a relation scan
17 : : * heap_endscan - end relation scan
18 : : * heap_getnext - retrieve next tuple in scan
19 : : * heap_fetch - retrieve tuple with given tid
20 : : * heap_insert - insert tuple into a relation
21 : : * heap_multi_insert - insert multiple tuples into a relation
22 : : * heap_delete - delete a tuple from a relation
23 : : * heap_update - replace a tuple in a relation with another tuple
24 : : *
25 : : * NOTES
26 : : * This file contains the heap_ routines which implement
27 : : * the POSTGRES heap access method used for all POSTGRES
28 : : * relations.
29 : : *
30 : : *-------------------------------------------------------------------------
31 : : */
32 : : #include "postgres.h"
33 : :
34 : : #include "access/heapam.h"
35 : : #include "access/heaptoast.h"
36 : : #include "access/hio.h"
37 : : #include "access/multixact.h"
38 : : #include "access/subtrans.h"
39 : : #include "access/syncscan.h"
40 : : #include "access/valid.h"
41 : : #include "access/visibilitymap.h"
42 : : #include "access/xloginsert.h"
43 : : #include "catalog/pg_database.h"
44 : : #include "catalog/pg_database_d.h"
45 : : #include "commands/vacuum.h"
46 : : #include "executor/instrument_node.h"
47 : : #include "pgstat.h"
48 : : #include "port/pg_bitutils.h"
49 : : #include "storage/lmgr.h"
50 : : #include "storage/predicate.h"
51 : : #include "storage/proc.h"
52 : : #include "storage/procarray.h"
53 : : #include "utils/datum.h"
54 : : #include "utils/injection_point.h"
55 : : #include "utils/inval.h"
56 : : #include "utils/spccache.h"
57 : : #include "utils/syscache.h"
58 : :
59 : :
60 : : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
61 : : TransactionId xid, CommandId cid, uint32 options);
62 : : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
63 : : Buffer vmbuffer_old, Buffer newbuf,
64 : : Buffer vmbuffer_new, HeapTuple oldtup,
65 : : HeapTuple newtup, HeapTuple old_key_tuple,
66 : : bool all_visible_cleared, bool new_all_visible_cleared,
67 : : bool walLogical);
68 : : #ifdef USE_ASSERT_CHECKING
69 : : static void check_lock_if_inplace_updateable_rel(Relation relation,
70 : : const ItemPointerData *otid,
71 : : HeapTuple newtup);
72 : : static void check_inplace_rel_lock(HeapTuple oldtup);
73 : : #endif
74 : : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
75 : : Bitmapset *interesting_cols,
76 : : Bitmapset *external_cols,
77 : : HeapTuple oldtup, HeapTuple newtup,
78 : : bool *has_external);
79 : : static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid,
80 : : LockTupleMode mode, LockWaitPolicy wait_policy,
81 : : bool *have_tuple_lock);
82 : : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
83 : : BlockNumber block,
84 : : ScanDirection dir);
85 : : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
86 : : ScanDirection dir);
87 : : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
88 : : uint16 old_infomask2, TransactionId add_to_xmax,
89 : : LockTupleMode mode, bool is_update,
90 : : TransactionId *result_xmax, uint16 *result_infomask,
91 : : uint16 *result_infomask2);
92 : : static TM_Result heap_lock_updated_tuple(Relation rel,
93 : : uint16 prior_infomask,
94 : : TransactionId prior_raw_xmax,
95 : : const ItemPointerData *prior_ctid,
96 : : TransactionId xid,
97 : : LockTupleMode mode);
98 : : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
99 : : uint16 *new_infomask2);
100 : : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
101 : : uint16 t_infomask);
102 : : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
103 : : LockTupleMode lockmode, bool *current_is_member);
104 : : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
105 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
106 : : int *remaining);
107 : : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
108 : : uint16 infomask, Relation rel, int *remaining,
109 : : bool logLockFailure);
110 : : static void index_delete_sort(TM_IndexDeleteOp *delstate);
111 : : static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
112 : : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
113 : : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
114 : : bool *copy);
115 : :
116 : :
117 : : /*
118 : : * This table lists the heavyweight lock mode that corresponds to each tuple
119 : : * lock mode, as well as one or two corresponding MultiXactStatus values:
120 : : * .lockstatus to merely lock tuples, and .updstatus to update them. The
121 : : * latter is set to -1 if the corresponding tuple lock mode does not allow
122 : : * updating tuples -- see get_mxact_status_for_lock().
123 : : *
124 : : * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
125 : : *
126 : : * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
127 : : * instead.
128 : : */
129 : : static const struct
130 : : {
131 : : LOCKMODE hwlock;
132 : : int lockstatus;
133 : : int updstatus;
134 : : } tupleLockExtraInfo[] =
135 : :
136 : : {
137 : : [LockTupleKeyShare] = {
138 : : .hwlock = AccessShareLock,
139 : : .lockstatus = MultiXactStatusForKeyShare,
140 : : /* KeyShare does not allow updating tuples */
141 : : .updstatus = -1
142 : : },
143 : : [LockTupleShare] = {
144 : : .hwlock = RowShareLock,
145 : : .lockstatus = MultiXactStatusForShare,
146 : : /* Share does not allow updating tuples */
147 : : .updstatus = -1
148 : : },
149 : : [LockTupleNoKeyExclusive] = {
150 : : .hwlock = ExclusiveLock,
151 : : .lockstatus = MultiXactStatusForNoKeyUpdate,
152 : : .updstatus = MultiXactStatusNoKeyUpdate
153 : : },
154 : : [LockTupleExclusive] = {
155 : : .hwlock = AccessExclusiveLock,
156 : : .lockstatus = MultiXactStatusForUpdate,
157 : : .updstatus = MultiXactStatusUpdate
158 : : }
159 : : };
160 : :
161 : : /* Get the LOCKMODE for a given MultiXactStatus */
162 : : #define LOCKMODE_from_mxstatus(status) \
163 : : (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
164 : :
165 : : /*
166 : : * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
167 : : * This is more readable than having every caller translate it to lock.h's
168 : : * LOCKMODE.
169 : : */
170 : : #define LockTupleTuplock(rel, tup, mode) \
171 : : LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
172 : : #define UnlockTupleTuplock(rel, tup, mode) \
173 : : UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
174 : : #define ConditionalLockTupleTuplock(rel, tup, mode, log) \
175 : : ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
176 : :
177 : : #ifdef USE_PREFETCH
178 : : /*
179 : : * heap_index_delete_tuples and index_delete_prefetch_buffer use this
180 : : * structure to coordinate prefetching activity
181 : : */
182 : : typedef struct
183 : : {
184 : : BlockNumber cur_hblkno;
185 : : int next_item;
186 : : int ndeltids;
187 : : TM_IndexDelete *deltids;
188 : : } IndexDeletePrefetchState;
189 : : #endif
190 : :
191 : : /* heap_index_delete_tuples bottom-up index deletion costing constants */
192 : : #define BOTTOMUP_MAX_NBLOCKS 6
193 : : #define BOTTOMUP_TOLERANCE_NBLOCKS 3
194 : :
195 : : /*
196 : : * heap_index_delete_tuples uses this when determining which heap blocks it
197 : : * must visit to help its bottom-up index deletion caller
198 : : */
199 : : typedef struct IndexDeleteCounts
200 : : {
201 : : int16 npromisingtids; /* Number of "promising" TIDs in group */
202 : : int16 ntids; /* Number of TIDs in group */
203 : : int16 ifirsttid; /* Offset to group's first deltid */
204 : : } IndexDeleteCounts;
205 : :
206 : : /*
207 : : * This table maps tuple lock strength values for each particular
208 : : * MultiXactStatus value.
209 : : */
210 : : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
211 : : {
212 : : LockTupleKeyShare, /* ForKeyShare */
213 : : LockTupleShare, /* ForShare */
214 : : LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
215 : : LockTupleExclusive, /* ForUpdate */
216 : : LockTupleNoKeyExclusive, /* NoKeyUpdate */
217 : : LockTupleExclusive /* Update */
218 : : };
219 : :
220 : : /* Get the LockTupleMode for a given MultiXactStatus */
221 : : #define TUPLOCK_from_mxstatus(status) \
222 : : (MultiXactStatusLock[(status)])
223 : :
224 : : /*
225 : : * Check that we have a valid snapshot if we might need TOAST access.
226 : : */
227 : : static inline void
547 nathan@postgresql.or 228 :CBC 16874871 : AssertHasSnapshotForToast(Relation rel)
229 : : {
230 : : #ifdef USE_ASSERT_CHECKING
231 : :
232 : : /* bootstrap mode in particular breaks this rule */
233 [ + + ]: 16874871 : if (!IsNormalProcessingMode())
234 : 705240 : return;
235 : :
236 : : /* if the relation doesn't have a TOAST table, we are good */
237 [ + + ]: 16169631 : if (!OidIsValid(rel->rd_rel->reltoastrelid))
238 : 10375700 : return;
239 : :
240 [ - + ]: 5793931 : Assert(HaveRegisteredOrActiveSnapshot());
241 : :
242 : : #endif /* USE_ASSERT_CHECKING */
243 : : }
244 : :
245 : : /* ----------------------------------------------------------------
246 : : * heap support routines
247 : : * ----------------------------------------------------------------
248 : : */
249 : :
250 : : /*
251 : : * Streaming read API callback for parallel sequential scans. Returns the next
252 : : * block the caller wants from the read stream or InvalidBlockNumber when done.
253 : : */
254 : : static BlockNumber
964 tmunro@postgresql.or 255 : 146734 : heap_scan_stream_read_next_parallel(ReadStream *stream,
256 : : void *callback_private_data,
257 : : void *per_buffer_data)
258 : : {
259 : 146734 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
260 : :
261 [ - + ]: 146734 : Assert(ScanDirectionIsForward(scan->rs_dir));
262 [ - + ]: 146734 : Assert(scan->rs_base.rs_parallel);
263 : :
264 [ + + ]: 146734 : if (unlikely(!scan->rs_inited))
265 : : {
266 : : /* parallel scan */
267 : 2903 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
268 : 2903 : scan->rs_parallelworkerdata,
366 drowley@postgresql.o 269 : 2903 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel,
270 : : scan->rs_startblock,
271 : : scan->rs_numblocks);
272 : :
273 : : /* may return InvalidBlockNumber if there are no more blocks */
964 tmunro@postgresql.or 274 : 5806 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
275 : 2903 : scan->rs_parallelworkerdata,
276 : 2903 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
277 : 2903 : scan->rs_inited = true;
278 : : }
279 : : else
280 : : {
281 : 143831 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
282 : 143831 : scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
283 : 143831 : scan->rs_base.rs_parallel);
284 : : }
285 : :
286 : 146734 : return scan->rs_prefetch_block;
287 : : }
288 : :
289 : : /*
290 : : * Streaming read API callback for serial sequential and TID range scans.
291 : : * Returns the next block the caller wants from the read stream or
292 : : * InvalidBlockNumber when done.
293 : : */
294 : : static BlockNumber
295 : 4058821 : heap_scan_stream_read_next_serial(ReadStream *stream,
296 : : void *callback_private_data,
297 : : void *per_buffer_data)
298 : : {
299 : 4058821 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
300 : :
301 [ + + ]: 4058821 : if (unlikely(!scan->rs_inited))
302 : : {
303 : 1129403 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
304 : 1129403 : scan->rs_inited = true;
305 : : }
306 : : else
307 : 2929418 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
308 : : scan->rs_prefetch_block,
309 : : scan->rs_dir);
310 : :
311 : 4058821 : return scan->rs_prefetch_block;
312 : : }
313 : :
314 : : /*
315 : : * Read stream API callback for bitmap heap scans.
316 : : * Returns the next block the caller wants from the read stream or
317 : : * InvalidBlockNumber when done.
318 : : */
319 : : static BlockNumber
623 melanieplageman@gmai 320 : 259286 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
321 : : void *per_buffer_data)
322 : : {
323 : 259286 : TBMIterateResult *tbmres = per_buffer_data;
324 : 259286 : BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
325 : 259286 : HeapScanDesc hscan = (HeapScanDesc) bscan;
326 : 259286 : TableScanDesc sscan = &hscan->rs_base;
327 : :
328 : : for (;;)
329 : : {
330 [ - + ]: 259286 : CHECK_FOR_INTERRUPTS();
331 : :
332 : : /* no more entries in the bitmap */
333 [ + + ]: 259286 : if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
334 : 14711 : return InvalidBlockNumber;
335 : :
336 : : /*
337 : : * Ignore any claimed entries past what we think is the end of the
338 : : * relation. It may have been extended after the start of our scan (we
339 : : * only hold an AccessShareLock, and it could be inserts from this
340 : : * backend). We don't take this optimization in SERIALIZABLE
341 : : * isolation though, as we need to examine all invisible tuples
342 : : * reachable by the index.
343 : : */
344 [ + + ]: 244575 : if (!IsolationIsSerializable() &&
345 [ - + ]: 244466 : tbmres->blockno >= hscan->rs_nblocks)
623 melanieplageman@gmai 346 :UBC 0 : continue;
347 : :
623 melanieplageman@gmai 348 :CBC 244575 : return tbmres->blockno;
349 : : }
350 : :
351 : : /* not reachable */
352 : : Assert(false);
353 : : }
354 : :
355 : : /* ----------------
356 : : * initscan - scan code common to heap_beginscan and heap_rescan
357 : : * ----------------
358 : : */
359 : : static void
4144 tgl@sss.pgh.pa.us 360 : 1169037 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
361 : : {
2819 andres@anarazel.de 362 : 1169037 : ParallelBlockTableScanDesc bpscan = NULL;
363 : : BlockNumber nblocks;
10 melanieplageman@gmai 364 : 1169037 : bool had_strat = scan->rs_strategy != NULL;
365 : : bool use_strat;
366 : : bool allow_sync;
367 : : bool rebuild_stream;
368 : :
369 : : /*
370 : : * Determine the number of blocks we have to scan.
371 : : *
372 : : * It is sufficient to do this once at scan start, since any tuples added
373 : : * while the scan is in progress will be invisible to my snapshot anyway.
374 : : * (That is not true when using a non-MVCC snapshot. However, we couldn't
375 : : * guarantee to return tuples added after scan start anyway, since they
376 : : * might go into pages we already scanned. To guarantee consistent
377 : : * results for a non-MVCC snapshot, the caller must hold some higher-level
378 : : * lock that ensures the interesting tuple(s) won't change.)
379 : : */
2819 andres@anarazel.de 380 [ + + ]: 1169037 : if (scan->rs_base.rs_parallel != NULL)
381 : : {
382 : 4758 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
10 melanieplageman@gmai 383 : 4758 : nblocks = bpscan->phs_nblocks;
384 : : }
385 : : else
386 : 1164279 : nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
387 : :
388 : : /*
389 : : * If the table is large relative to NBuffers, use a bulk-read access
390 : : * strategy and enable synchronized scanning (see syncscan.c). Although
391 : : * the thresholds for these features could be different, we make them the
392 : : * same so that there are only two behaviors to tune rather than four.
393 : : * (However, some callers need to be able to disable one or both of these
394 : : * behaviors, independently of the size of the table; also there is a GUC
395 : : * variable that can disable synchronized scanning.)
396 : : *
397 : : * Note that table_block_parallelscan_initialize has a very similar test;
398 : : * if you change this, consider changing that one, too.
399 : : */
2819 andres@anarazel.de 400 [ + + ]: 1169035 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
10 melanieplageman@gmai 401 [ + + ]: 1151180 : nblocks > NBuffers / 4)
402 : : {
403 : 14996 : use_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
2750 andres@anarazel.de 404 : 14996 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
405 : : }
406 : : else
10 melanieplageman@gmai 407 : 1154039 : use_strat = allow_sync = false;
408 : :
409 : : /*
410 : : * Reset the stream before reinitializing state used by its callback. A
411 : : * stream keeps the strategy passed at creation and sizes its buffer queue
412 : : * accordingly, so end it instead when strategy use changes.
413 : : */
414 [ + + + + ]: 1169035 : rebuild_stream = scan->rs_read_stream && had_strat != use_strat;
415 [ + + ]: 1169035 : if (scan->rs_read_stream)
416 : : {
417 [ + + ]: 719549 : if (rebuild_stream)
418 : : {
419 : 1 : read_stream_end(scan->rs_read_stream);
420 : 1 : scan->rs_read_stream = NULL;
421 : : }
422 : : else
423 : 719548 : read_stream_reset(scan->rs_read_stream);
424 : : }
425 : :
426 [ + + ]: 1169035 : if (use_strat)
427 : : {
428 : : /* During a rescan, keep the previous strategy object. */
429 [ + + ]: 13597 : if (!had_strat)
7122 tgl@sss.pgh.pa.us 430 : 13375 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
431 : : }
432 : : else
433 : : {
10 melanieplageman@gmai 434 [ - + ]: 1155438 : if (had_strat)
7122 tgl@sss.pgh.pa.us 435 :UBC 0 : FreeAccessStrategy(scan->rs_strategy);
7122 tgl@sss.pgh.pa.us 436 :CBC 1155438 : scan->rs_strategy = NULL;
437 : : }
438 : :
439 : : /* Publish the new size only after the old stream has been reset. */
10 melanieplageman@gmai 440 : 1169035 : scan->rs_nblocks = nblocks;
441 : :
2819 andres@anarazel.de 442 [ + + ]: 1169035 : if (scan->rs_base.rs_parallel != NULL)
443 : : {
444 : : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
2750 445 [ + + ]: 4758 : if (scan->rs_base.rs_parallel->phs_syncscan)
446 : 5 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
447 : : else
448 : 4753 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
449 : :
450 : : /*
451 : : * If not rescanning, initialize the startblock. Finding the actual
452 : : * start location is done in table_block_parallelscan_startblock_init,
453 : : * based on whether an alternative start location has been set with
454 : : * heap_setscanlimits, or using the syncscan location, when syncscan
455 : : * is enabled.
456 : : */
365 drowley@postgresql.o 457 [ + + ]: 4758 : if (!keep_startblock)
458 : 4546 : scan->rs_startblock = InvalidBlockNumber;
459 : : }
460 : : else
461 : : {
462 [ + + ]: 1164277 : if (keep_startblock)
463 : : {
464 : : /*
465 : : * When rescanning, we want to keep the previous startblock
466 : : * setting, so that rewinding a cursor doesn't generate surprising
467 : : * results. Reset the active syncscan setting, though.
468 : : */
469 [ + + + + ]: 727043 : if (allow_sync && synchronize_seqscans)
470 : 84 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
471 : : else
472 : 726959 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
473 : : }
474 [ + + + + ]: 437234 : else if (allow_sync && synchronize_seqscans)
475 : : {
476 : 141 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
477 : 141 : scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
478 : : }
479 : : else
480 : : {
481 : 437093 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
482 : 437093 : scan->rs_startblock = 0;
483 : : }
484 : : }
485 : :
4404 alvherre@alvh.no-ip. 486 : 1169035 : scan->rs_numblocks = InvalidBlockNumber;
7672 tgl@sss.pgh.pa.us 487 : 1169035 : scan->rs_inited = false;
9303 488 : 1169035 : scan->rs_ctup.t_data = NULL;
7672 489 : 1169035 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
9303 490 : 1169035 : scan->rs_cbuf = InvalidBuffer;
7672 491 : 1169035 : scan->rs_cblock = InvalidBlockNumber;
710 melanieplageman@gmai 492 : 1169035 : scan->rs_ntuples = 0;
493 : 1169035 : scan->rs_cindex = 0;
494 : :
495 : : /*
496 : : * Initialize to ForwardScanDirection because it is most common and
497 : : * because heap scans go forward before going backward (e.g. CURSORs).
498 : : */
964 tmunro@postgresql.or 499 : 1169035 : scan->rs_dir = ForwardScanDirection;
500 : 1169035 : scan->rs_prefetch_block = InvalidBlockNumber;
501 : :
502 : : /* page-at-a-time fields are always invalid when not rs_inited */
503 : :
504 : : /*
505 : : * copy the scan key, if appropriate
506 : : */
1731 tgl@sss.pgh.pa.us 507 [ + + + + ]: 1169035 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
2819 andres@anarazel.de 508 : 226874 : memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
509 : :
510 : : /*
511 : : * Currently, we only have a stats counter for sequential heap scans (but
512 : : * e.g for bitmap scans the underlying bitmap index scans will be counted,
513 : : * and for sample scans we update stats for tuple fetches).
514 : : */
2750 515 [ + + ]: 1169035 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
2819 516 [ + + + + : 1132747 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
+ + - + ]
517 : :
10 melanieplageman@gmai 518 [ + + ]: 1169035 : if (scan->rs_read_stream == NULL)
519 : : {
520 [ + + ]: 449487 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
521 [ + + ]: 33859 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
522 : 416973 : {
523 : : ReadStreamBlockNumberCB cb;
524 : :
525 [ + + ]: 416978 : if (scan->rs_base.rs_parallel)
526 : 4546 : cb = heap_scan_stream_read_next_parallel;
527 : : else
528 : 412432 : cb = heap_scan_stream_read_next_serial;
529 : :
530 : : /* ---
531 : : * It is safe to use batchmode as the only locks taken by `cb`
532 : : * are never taken while waiting for IO:
533 : : * - SyncScanLock is used in the non-parallel case
534 : : * - in the parallel case, only spinlocks and atomics are used
535 : : * ---
536 : : */
537 : 416973 : scan->rs_read_stream =
538 : 416978 : read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
539 : : READ_STREAM_USE_BATCHING,
540 : : scan->rs_strategy,
541 : : scan->rs_base.rs_rd,
542 : : MAIN_FORKNUM,
543 : : cb,
544 : : scan,
545 : : 0);
546 : : }
547 [ + + ]: 32509 : else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
548 : : {
549 : 12510 : scan->rs_read_stream =
550 : 12510 : read_stream_begin_relation(READ_STREAM_DEFAULT |
551 : : READ_STREAM_USE_BATCHING,
552 : : scan->rs_strategy,
553 : : scan->rs_base.rs_rd,
554 : : MAIN_FORKNUM,
555 : : bitmapheap_stream_read_next,
556 : : scan,
557 : : sizeof(TBMIterateResult));
558 : : }
559 : :
560 [ + + + + ]: 449482 : if (scan->rs_read_stream && scan->rs_base.rs_instrument)
561 : 8 : read_stream_enable_stats(scan->rs_read_stream,
562 : 8 : &scan->rs_base.rs_instrument->io);
563 : : }
11099 scrappy@hub.org 564 : 1169030 : }
565 : :
566 : : /*
567 : : * heap_setscanlimits - restrict range of a heapscan
568 : : *
569 : : * startBlk is the page to start at
570 : : * numBlks is number of pages to scan (InvalidBlockNumber means "all")
571 : : */
572 : : void
2819 andres@anarazel.de 573 : 3355 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
574 : : {
575 : 3355 : HeapScanDesc scan = (HeapScanDesc) sscan;
576 : :
4148 tgl@sss.pgh.pa.us 577 [ - + ]: 3355 : Assert(!scan->rs_inited); /* else too late to change */
578 : : /* else rs_startblock is significant */
2750 andres@anarazel.de 579 [ - + ]: 3355 : Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
580 : :
581 : : /* Check startBlk is valid (but allow case of zero blocks...) */
4148 tgl@sss.pgh.pa.us 582 [ + + - + ]: 3355 : Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
583 : :
4404 alvherre@alvh.no-ip. 584 : 3355 : scan->rs_startblock = startBlk;
585 : 3355 : scan->rs_numblocks = numBlks;
586 : 3355 : }
587 : :
588 : : /*
589 : : * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
590 : : * multiple times, with constant arguments for all_visible,
591 : : * check_serializable.
592 : : */
593 : : pg_always_inline
594 : : static int
965 andres@anarazel.de 595 : 2943329 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
596 : : Page page, Buffer buffer,
597 : : BlockNumber block, int lines,
598 : : bool all_visible, bool check_serializable)
599 : : {
320 600 : 2943329 : Oid relid = RelationGetRelid(scan->rs_base.rs_rd);
966 601 : 2943329 : int ntup = 0;
320 602 : 2943329 : int nvis = 0;
603 : : BatchMVCCState batchmvcc;
604 : :
605 : : /* page at a time should have been disabled otherwise */
606 [ - + ]: 2943329 : Assert(IsMVCCSnapshot(snapshot));
607 : :
608 : : /* first find all tuples on the page */
609 [ + + ]: 156880478 : for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
610 : : {
966 611 : 153937149 : ItemId lpp = PageGetItemId(page, lineoff);
612 : : HeapTuple tup;
613 : :
320 614 [ + + ]: 153937149 : if (unlikely(!ItemIdIsNormal(lpp)))
966 615 : 23346692 : continue;
616 : :
617 : : /*
618 : : * If the page is not all-visible or we need to check serializability,
619 : : * maintain enough state to be able to refind the tuple efficiently,
620 : : * without again first needing to fetch the item and then via that the
621 : : * tuple.
622 : : */
320 623 [ + + - + ]: 130590457 : if (!all_visible || check_serializable)
624 : : {
625 : 66612014 : tup = &batchmvcc.tuples[ntup];
626 : :
627 : 66612014 : tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
628 : 66612014 : tup->t_len = ItemIdGetLength(lpp);
629 : 66612014 : tup->t_tableOid = relid;
630 : 66612014 : ItemPointerSet(&(tup->t_self), block, lineoff);
631 : : }
632 : :
633 : : /*
634 : : * If the page is all visible, these fields otherwise won't be
635 : : * populated in loop below.
636 : : */
637 [ + + ]: 130590457 : if (all_visible)
638 : : {
639 [ - + ]: 63978443 : if (check_serializable)
640 : : {
320 andres@anarazel.de 641 :UBC 0 : batchmvcc.visible[ntup] = true;
642 : : }
966 andres@anarazel.de 643 :CBC 63978443 : scan->rs_vistuples[ntup] = lineoff;
644 : : }
645 : :
320 646 : 130590457 : ntup++;
647 : : }
648 : :
966 649 [ - + ]: 2943329 : Assert(ntup <= MaxHeapTuplesPerPage);
650 : :
651 : : /*
652 : : * Unless the page is all visible, test visibility for all tuples one go.
653 : : * That is considerably more efficient than calling
654 : : * HeapTupleSatisfiesMVCC() one-by-one.
655 : : */
320 656 [ + + ]: 2943329 : if (all_visible)
657 : 1338684 : nvis = ntup;
658 : : else
659 : 1604645 : nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
660 : : ntup,
661 : : &batchmvcc,
662 : 1604645 : scan->rs_vistuples);
663 : :
664 : : /*
665 : : * So far we don't have batch API for testing serializabilty, so do so
666 : : * one-by-one.
667 : : */
668 [ + + ]: 2943329 : if (check_serializable)
669 : : {
670 [ + + ]: 2069 : for (int i = 0; i < ntup; i++)
671 : : {
672 : 1454 : HeapCheckForSerializableConflictOut(batchmvcc.visible[i],
673 : : scan->rs_base.rs_rd,
674 : : &batchmvcc.tuples[i],
675 : : buffer, snapshot);
676 : : }
677 : : }
678 : :
679 : 2943321 : return nvis;
680 : : }
681 : :
682 : : /*
683 : : * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
684 : : *
685 : : * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
686 : : * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
687 : : */
688 : : void
968 drowley@postgresql.o 689 : 2943329 : heap_prepare_pagescan(TableScanDesc sscan)
690 : : {
2819 andres@anarazel.de 691 : 2943329 : HeapScanDesc scan = (HeapScanDesc) sscan;
968 drowley@postgresql.o 692 : 2943329 : Buffer buffer = scan->rs_cbuf;
693 : 2943329 : BlockNumber block = scan->rs_cblock;
694 : : Snapshot snapshot;
695 : : Page page;
696 : : int lines;
697 : : bool all_visible;
698 : : bool check_serializable;
699 : :
700 [ - + ]: 2943329 : Assert(BufferGetBlockNumber(buffer) == block);
701 : :
702 : : /* ensure we're not accidentally being used when not in pagemode */
703 [ - + ]: 2943329 : Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
2819 andres@anarazel.de 704 : 2943329 : snapshot = scan->rs_base.rs_snapshot;
705 : :
706 : : /*
707 : : * Prune and repair fragmentation for the whole page, if possible.
708 : : */
243 melanieplageman@gmai 709 : 2943329 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer, &scan->rs_vmbuffer,
710 : 2943329 : sscan->rs_flags & SO_HINT_REL_READ_ONLY);
711 : :
712 : : /*
713 : : * We must hold share lock on the buffer content while examining tuple
714 : : * visibility. Afterwards, however, the tuples we have found to be
715 : : * visible are guaranteed good as long as we hold the buffer pin.
716 : : */
7672 tgl@sss.pgh.pa.us 717 : 2943329 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
718 : :
1473 peter@eisentraut.org 719 : 2943329 : page = BufferGetPage(buffer);
720 : 2943329 : lines = PageGetMaxOffsetNumber(page);
721 : :
722 : : /*
723 : : * If the all-visible flag indicates that all tuples on the page are
724 : : * visible to everyone, we can skip the per-tuple visibility tests.
725 : : *
726 : : * Note: In hot standby, a tuple that's already visible to all
727 : : * transactions on the primary might still be invisible to a read-only
728 : : * transaction in the standby. We partly handle this problem by tracking
729 : : * the minimum xmin of visible tuples as the cut-off XID while marking a
730 : : * page all-visible on the primary and WAL log that along with the
731 : : * visibility map SET operation. In hot standby, we wait for (or abort)
732 : : * all transactions that can potentially may not see one or more tuples on
733 : : * the page. That's how index-only scans work fine in hot standby. A
734 : : * crucial difference between index-only scans and heap scans is that the
735 : : * index-only scan completely relies on the visibility map where as heap
736 : : * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
737 : : * the page-level flag can be trusted in the same way, because it might
738 : : * get propagated somehow without being explicitly WAL-logged, e.g. via a
739 : : * full page write. Until we can prove that beyond doubt, let's check each
740 : : * tuple for visibility the hard way.
741 : : */
742 [ + + + + ]: 2943329 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
743 : : check_serializable =
966 andres@anarazel.de 744 : 2943329 : CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
745 : :
746 : : /*
747 : : * We call page_collect_tuples() with constant arguments, to get the
748 : : * compiler to constant fold the constant arguments. Separate calls with
749 : : * constant arguments, rather than variables, are needed on several
750 : : * compilers to actually perform constant folding.
751 : : */
752 [ + + ]: 2943329 : if (likely(all_visible))
753 : : {
754 [ + - ]: 1338684 : if (likely(!check_serializable))
965 755 : 1338684 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
756 : : block, lines, true, false);
757 : : else
965 andres@anarazel.de 758 :UBC 0 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
759 : : block, lines, true, true);
760 : : }
761 : : else
762 : : {
966 andres@anarazel.de 763 [ + + ]:CBC 1604645 : if (likely(!check_serializable))
965 764 : 1604022 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
765 : : block, lines, false, false);
766 : : else
767 : 623 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
768 : : block, lines, false, true);
769 : : }
770 : :
7672 tgl@sss.pgh.pa.us 771 : 2943321 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
772 : 2943321 : }
773 : :
774 : : /*
775 : : * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
776 : : *
777 : : * Read the next block of the scan relation from the read stream and save it
778 : : * in the scan descriptor. It is already pinned.
779 : : */
780 : : static inline void
968 drowley@postgresql.o 781 : 3991616 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
782 : : {
964 tmunro@postgresql.or 783 [ - + ]: 3991616 : Assert(scan->rs_read_stream);
784 : :
785 : : /* release previous scan buffer, if any */
968 drowley@postgresql.o 786 [ + + ]: 3991616 : if (BufferIsValid(scan->rs_cbuf))
787 : : {
788 : 2859305 : ReleaseBuffer(scan->rs_cbuf);
789 : 2859305 : scan->rs_cbuf = InvalidBuffer;
790 : : }
791 : :
792 : : /*
793 : : * Be sure to check for interrupts at least once per page. Checks at
794 : : * higher code levels won't be able to stop a seqscan that encounters many
795 : : * pages' worth of consecutive dead tuples.
796 : : */
797 [ + + ]: 3991616 : CHECK_FOR_INTERRUPTS();
798 : :
799 : : /*
800 : : * If the scan direction is changing, reset the prefetch block to the
801 : : * current block. Otherwise, we will incorrectly prefetch the blocks
802 : : * between the prefetch block and the current block again before
803 : : * prefetching blocks in the new, correct scan direction.
804 : : */
964 tmunro@postgresql.or 805 [ + + ]: 3991609 : if (unlikely(scan->rs_dir != dir))
806 : : {
807 : 109 : scan->rs_prefetch_block = scan->rs_cblock;
808 : 109 : read_stream_reset(scan->rs_read_stream);
809 : : }
810 : :
811 : 3991609 : scan->rs_dir = dir;
812 : :
813 : 3991609 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
814 [ + + ]: 3991581 : if (BufferIsValid(scan->rs_cbuf))
815 : 3053769 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
968 drowley@postgresql.o 816 : 3991581 : }
817 : :
818 : : /*
819 : : * heapgettup_initial_block - return the first BlockNumber to scan
820 : : *
821 : : * Returns InvalidBlockNumber when there are no blocks to scan. This can
822 : : * occur with empty tables and in parallel scans when parallel workers get all
823 : : * of the pages before we can get a chance to get our first page.
824 : : */
825 : : static pg_noinline BlockNumber
1395 826 : 1129403 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
827 : : {
828 [ - + ]: 1129403 : Assert(!scan->rs_inited);
964 tmunro@postgresql.or 829 [ - + ]: 1129403 : Assert(scan->rs_base.rs_parallel == NULL);
830 : :
831 : : /* When there are no pages to scan, return InvalidBlockNumber */
1395 drowley@postgresql.o 832 [ + + + + ]: 1129403 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
833 : 571826 : return InvalidBlockNumber;
834 : :
835 [ + + ]: 557577 : if (ScanDirectionIsForward(dir))
836 : : {
964 tmunro@postgresql.or 837 : 557532 : return scan->rs_startblock;
838 : : }
839 : : else
840 : : {
841 : : /*
842 : : * Disable reporting to syncscan logic in a backwards scan; it's not
843 : : * very likely anyone else is doing the same thing at the same time,
844 : : * and much more likely that we'll just bollix things for forward
845 : : * scanners.
846 : : */
1395 drowley@postgresql.o 847 : 45 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
848 : :
849 : : /*
850 : : * Start from last page of the scan. Ensure we take into account
851 : : * rs_numblocks if it's been adjusted by heap_setscanlimits().
852 : : */
853 [ + + ]: 45 : if (scan->rs_numblocks != InvalidBlockNumber)
854 : 8 : return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
855 : :
856 [ - + ]: 37 : if (scan->rs_startblock > 0)
1395 drowley@postgresql.o 857 :UBC 0 : return scan->rs_startblock - 1;
858 : :
1395 drowley@postgresql.o 859 :CBC 37 : return scan->rs_nblocks - 1;
860 : : }
861 : : }
862 : :
863 : :
864 : : /*
865 : : * heapgettup_start_page - helper function for heapgettup()
866 : : *
867 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
868 : : * to the number of tuples on this page. Also set *lineoff to the first
869 : : * offset to scan with forward scans getting the first offset and backward
870 : : * getting the final offset on the page.
871 : : */
872 : : static Page
1394 873 : 117507 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
874 : : OffsetNumber *lineoff)
875 : : {
876 : : Page page;
877 : :
878 [ - + ]: 117507 : Assert(scan->rs_inited);
879 [ - + ]: 117507 : Assert(BufferIsValid(scan->rs_cbuf));
880 : :
881 : : /* Caller is responsible for ensuring buffer is locked if needed */
882 : 117507 : page = BufferGetPage(scan->rs_cbuf);
883 : :
1390 884 : 117507 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
885 : :
1394 886 [ + - ]: 117507 : if (ScanDirectionIsForward(dir))
887 : 117507 : *lineoff = FirstOffsetNumber;
888 : : else
1394 drowley@postgresql.o 889 :UBC 0 : *lineoff = (OffsetNumber) (*linesleft);
890 : :
891 : : /* lineoff now references the physically previous or next tid */
1394 drowley@postgresql.o 892 :CBC 117507 : return page;
893 : : }
894 : :
895 : :
896 : : /*
897 : : * heapgettup_continue_page - helper function for heapgettup()
898 : : *
899 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
900 : : * to the number of tuples left to scan on this page. Also set *lineoff to
901 : : * the next offset to scan according to the ScanDirection in 'dir'.
902 : : */
903 : : static inline Page
904 : 9492651 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
905 : : OffsetNumber *lineoff)
906 : : {
907 : : Page page;
908 : :
909 [ - + ]: 9492651 : Assert(scan->rs_inited);
910 [ - + ]: 9492651 : Assert(BufferIsValid(scan->rs_cbuf));
911 : :
912 : : /* Caller is responsible for ensuring buffer is locked if needed */
913 : 9492651 : page = BufferGetPage(scan->rs_cbuf);
914 : :
915 [ + - ]: 9492651 : if (ScanDirectionIsForward(dir))
916 : : {
917 : 9492651 : *lineoff = OffsetNumberNext(scan->rs_coffset);
918 : 9492651 : *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
919 : : }
920 : : else
921 : : {
922 : : /*
923 : : * The previous returned tuple may have been vacuumed since the
924 : : * previous scan when we use a non-MVCC snapshot, so we must
925 : : * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
926 : : */
1394 drowley@postgresql.o 927 [ # # ]:UBC 0 : *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
928 : 0 : *linesleft = *lineoff;
929 : : }
930 : :
931 : : /* lineoff now references the physically previous or next tid */
1394 drowley@postgresql.o 932 :CBC 9492651 : return page;
933 : : }
934 : :
935 : : /*
936 : : * heapgettup_advance_block - helper for heap_fetch_next_buffer()
937 : : *
938 : : * Given the current block number, the scan direction, and various information
939 : : * contained in the scan descriptor, calculate the BlockNumber to scan next
940 : : * and return it. If there are no further blocks to scan, return
941 : : * InvalidBlockNumber to indicate this fact to the caller.
942 : : *
943 : : * This should not be called to determine the initial block number -- only for
944 : : * subsequent blocks.
945 : : *
946 : : * This also adjusts rs_numblocks when a limit has been imposed by
947 : : * heap_setscanlimits().
948 : : */
949 : : static inline BlockNumber
950 : 2929418 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
951 : : {
964 tmunro@postgresql.or 952 [ - + ]: 2929418 : Assert(scan->rs_base.rs_parallel == NULL);
953 : :
954 [ + + ]: 2929418 : if (likely(ScanDirectionIsForward(dir)))
955 : : {
956 : 2929329 : block++;
957 : :
958 : : /* wrap back to the start of the heap */
959 [ + + ]: 2929329 : if (block >= scan->rs_nblocks)
960 : 437618 : block = 0;
961 : :
962 : : /*
963 : : * Report our new scan position for synchronization purposes. We don't
964 : : * do that when moving backwards, however. That would just mess up any
965 : : * other forward-moving scanners.
966 : : *
967 : : * Note: we do this before checking for end of scan so that the final
968 : : * state of the position hint is back at the start of the rel. That's
969 : : * not strictly necessary, but otherwise when you run the same query
970 : : * multiple times the starting position would shift a little bit
971 : : * backwards on every invocation, which is confusing. We don't
972 : : * guarantee any specific ordering in general, though.
973 : : */
974 [ + + ]: 2929329 : if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
975 : 44272 : ss_report_location(scan->rs_base.rs_rd, block);
976 : :
977 : : /* we're done if we're back at where we started */
978 [ + + ]: 2929329 : if (block == scan->rs_startblock)
979 : 437568 : return InvalidBlockNumber;
980 : :
981 : : /* check if the limit imposed by heap_setscanlimits() is met */
982 [ + + ]: 2491761 : if (scan->rs_numblocks != InvalidBlockNumber)
983 : : {
984 : : BlockNumber endblock;
985 : :
65 drowley@postgresql.o 986 : 2823 : endblock = (scan->rs_startblock + scan->rs_numblocks) %
987 : 2823 : scan->rs_nblocks;
988 [ + + ]: 2823 : if (block == endblock)
964 tmunro@postgresql.or 989 : 1602 : return InvalidBlockNumber;
990 : : }
991 : :
992 : 2490159 : return block;
993 : : }
994 : : else
995 : : {
996 : : /*
997 : : * We're done if the last block is the start position. No need to
998 : : * check if rs_numblocks was set by heap_setscanlimits() as that only
999 : : * changes the end block. The start block is the same with or without
1000 : : * scan limits.
1001 : : */
1394 drowley@postgresql.o 1002 [ + + ]: 89 : if (block == scan->rs_startblock)
1003 : 77 : return InvalidBlockNumber;
1004 : :
1005 : : /* wrap to the end of the heap when the last page was page 0 */
1006 [ - + ]: 12 : if (block == 0)
1394 drowley@postgresql.o 1007 :UBC 0 : block = scan->rs_nblocks;
1008 : :
1394 drowley@postgresql.o 1009 :CBC 12 : block--;
1010 : :
1011 : 12 : return block;
1012 : : }
1013 : : }
1014 : :
1015 : : /* ----------------
1016 : : * heapgettup - fetch next heap tuple
1017 : : *
1018 : : * Initialize the scan if not already done; then advance to the next
1019 : : * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
1020 : : * or set scan->rs_ctup.t_data = NULL if no more tuples.
1021 : : *
1022 : : * Note: the reason nkeys/key are passed separately, even though they are
1023 : : * kept in the scan descriptor, is that the caller may not want us to check
1024 : : * the scankeys.
1025 : : *
1026 : : * Note: when we fall off the end of the scan in either direction, we
1027 : : * reset rs_inited. This means that a further request with the same
1028 : : * scan direction will restart the scan, which is a bit odd, but a
1029 : : * request with the opposite scan direction will start a fresh scan
1030 : : * in the proper direction. The latter is required behavior for cursors,
1031 : : * while the former case is generally undefined behavior in Postgres
1032 : : * so we don't care too much.
1033 : : * ----------------
1034 : : */
1035 : : static void
7672 tgl@sss.pgh.pa.us 1036 : 9520314 : heapgettup(HeapScanDesc scan,
1037 : : ScanDirection dir,
1038 : : int nkeys,
1039 : : ScanKey key)
1040 : : {
1041 : 9520314 : HeapTuple tuple = &(scan->rs_ctup);
1042 : : Page page;
1043 : : OffsetNumber lineoff;
1044 : : int linesleft;
1045 : :
968 drowley@postgresql.o 1046 [ + + ]: 9520314 : if (likely(scan->rs_inited))
1047 : : {
1048 : : /* continue from previously returned page/tuple */
1394 1049 : 9492651 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
1050 : 9492651 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
1390 1051 : 9492651 : goto continue_page;
1052 : : }
1053 : :
1054 : : /*
1055 : : * advance the scan until we find a qualifying tuple or run out of stuff
1056 : : * to scan
1057 : : */
1058 : : while (true)
1059 : : {
968 1060 : 144246 : heap_fetch_next_buffer(scan, dir);
1061 : :
1062 : : /* did we run out of blocks to scan? */
1063 [ + + ]: 144246 : if (!BufferIsValid(scan->rs_cbuf))
1064 : 26739 : break;
1065 : :
1066 [ - + ]: 117507 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1067 : :
1390 1068 : 117507 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
1069 : 117507 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
1070 : 9610158 : continue_page:
1071 : :
1072 : : /*
1073 : : * Only continue scanning the page while we have lines left.
1074 : : *
1075 : : * Note that this protects us from accessing line pointers past
1076 : : * PageGetMaxOffsetNumber(); both for forward scans when we resume the
1077 : : * table scan, and for when we start scanning a new page.
1078 : : */
1079 [ + + ]: 9667304 : for (; linesleft > 0; linesleft--, lineoff += dir)
1080 : : {
1081 : : bool visible;
1082 : 9550721 : ItemId lpp = PageGetItemId(page, lineoff);
1083 : :
1084 [ + + ]: 9550721 : if (!ItemIdIsNormal(lpp))
1085 : 36080 : continue;
1086 : :
1087 : 9514641 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1088 : 9514641 : tuple->t_len = ItemIdGetLength(lpp);
968 1089 : 9514641 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1090 : :
1390 1091 : 9514641 : visible = HeapTupleSatisfiesVisibility(tuple,
1092 : : scan->rs_base.rs_snapshot,
1093 : : scan->rs_cbuf);
1094 : :
1095 : 9514641 : HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
1096 : : tuple, scan->rs_cbuf,
1097 : : scan->rs_base.rs_snapshot);
1098 : :
1099 : : /* skip tuples not visible to this snapshot */
1100 [ + + ]: 9514641 : if (!visible)
1101 : 6985 : continue;
1102 : :
1103 : : /* skip any tuples that don't match the scan key */
1104 [ + + ]: 9507656 : if (key != NULL &&
1105 [ + + ]: 14854 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1106 : : nkeys, key))
1107 : 14081 : continue;
1108 : :
1109 : 9493575 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1110 : 9493575 : scan->rs_coffset = lineoff;
1111 : 9493575 : return;
1112 : : }
1113 : :
1114 : : /*
1115 : : * if we get here, it means we've exhausted the items on this page and
1116 : : * it's time to move to the next.
1117 : : */
7672 tgl@sss.pgh.pa.us 1118 : 116583 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1119 : : }
1120 : :
1121 : : /* end of scan */
1390 drowley@postgresql.o 1122 [ - + ]: 26739 : if (BufferIsValid(scan->rs_cbuf))
1390 drowley@postgresql.o 1123 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1124 : :
1390 drowley@postgresql.o 1125 :CBC 26739 : scan->rs_cbuf = InvalidBuffer;
1126 : 26739 : scan->rs_cblock = InvalidBlockNumber;
964 tmunro@postgresql.or 1127 : 26739 : scan->rs_prefetch_block = InvalidBlockNumber;
1390 drowley@postgresql.o 1128 : 26739 : tuple->t_data = NULL;
1129 : 26739 : scan->rs_inited = false;
1130 : : }
1131 : :
1132 : : /* ----------------
1133 : : * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
1134 : : *
1135 : : * Same API as heapgettup, but used in page-at-a-time mode
1136 : : *
1137 : : * The internal logic is much the same as heapgettup's too, but there are some
1138 : : * differences: we do not take the buffer content lock (that only needs to
1139 : : * happen inside heap_prepare_pagescan), and we iterate through just the
1140 : : * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
1141 : : * that lineindex is 0-based, where the corresponding loop variable lineoff in
1142 : : * heapgettup is 1-based.
1143 : : * ----------------
1144 : : */
1145 : : static void
7672 tgl@sss.pgh.pa.us 1146 : 66304128 : heapgettup_pagemode(HeapScanDesc scan,
1147 : : ScanDirection dir,
1148 : : int nkeys,
1149 : : ScanKey key)
1150 : : {
1151 : 66304128 : HeapTuple tuple = &(scan->rs_ctup);
1152 : : Page page;
1153 : : uint32 lineindex;
1154 : : uint32 linesleft;
1155 : :
968 drowley@postgresql.o 1156 [ + + ]: 66304128 : if (likely(scan->rs_inited))
1157 : : {
1158 : : /* continue from previously returned page/tuple */
1394 1159 : 65199480 : page = BufferGetPage(scan->rs_cbuf);
1160 : :
1161 : 65199480 : lineindex = scan->rs_cindex + dir;
1162 [ + + ]: 65199480 : if (ScanDirectionIsForward(dir))
1163 : 65199023 : linesleft = scan->rs_ntuples - lineindex;
1164 : : else
1165 : 457 : linesleft = scan->rs_cindex;
1166 : : /* lineindex now references the next or previous visible tid */
1167 : :
1390 1168 : 65199480 : goto continue_page;
1169 : : }
1170 : :
1171 : : /*
1172 : : * advance the scan until we find a qualifying tuple or run out of stuff
1173 : : * to scan
1174 : : */
1175 : : while (true)
1176 : : {
968 1177 : 3847370 : heap_fetch_next_buffer(scan, dir);
1178 : :
1179 : : /* did we run out of blocks to scan? */
1180 [ + + ]: 3847335 : if (!BufferIsValid(scan->rs_cbuf))
1181 : 911073 : break;
1182 : :
1183 [ - + ]: 2936262 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1184 : :
1185 : : /* prune the page and determine visible tuple offsets */
1186 : 2936262 : heap_prepare_pagescan((TableScanDesc) scan);
1390 1187 : 2936254 : page = BufferGetPage(scan->rs_cbuf);
1188 : 2936254 : linesleft = scan->rs_ntuples;
1189 [ + + ]: 2936254 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1190 : :
1191 : : /* block is the same for all tuples, set it once outside the loop */
606 heikki.linnakangas@i 1192 : 2936254 : ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1193 : :
1194 : : /* lineindex now references the next or previous visible tid */
1390 drowley@postgresql.o 1195 : 68135734 : continue_page:
1196 : :
1197 [ + + ]: 122744823 : for (; linesleft > 0; linesleft--, lineindex += dir)
1198 : : {
1199 : : ItemId lpp;
1200 : : OffsetNumber lineoff;
1201 : :
327 heikki.linnakangas@i 1202 [ - + ]: 120002101 : Assert(lineindex < scan->rs_ntuples);
7672 tgl@sss.pgh.pa.us 1203 : 120002101 : lineoff = scan->rs_vistuples[lineindex];
1473 peter@eisentraut.org 1204 : 120002101 : lpp = PageGetItemId(page, lineoff);
7017 tgl@sss.pgh.pa.us 1205 [ - + ]: 120002101 : Assert(ItemIdIsNormal(lpp));
1206 : :
1473 peter@eisentraut.org 1207 : 120002101 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
7672 tgl@sss.pgh.pa.us 1208 : 120002101 : tuple->t_len = ItemIdGetLength(lpp);
606 heikki.linnakangas@i 1209 : 120002101 : ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1210 : :
1211 : : /* skip any tuples that don't match the scan key */
1390 drowley@postgresql.o 1212 [ + + ]: 120002101 : if (key != NULL &&
1213 [ + + ]: 55005612 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1214 : : nkeys, key))
1215 : 54609089 : continue;
1216 : :
1217 : 65393012 : scan->rs_cindex = lineindex;
1218 : 65393012 : return;
1219 : : }
1220 : : }
1221 : :
1222 : : /* end of scan */
1223 [ - + ]: 911073 : if (BufferIsValid(scan->rs_cbuf))
1390 drowley@postgresql.o 1224 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1390 drowley@postgresql.o 1225 :CBC 911073 : scan->rs_cbuf = InvalidBuffer;
1226 : 911073 : scan->rs_cblock = InvalidBlockNumber;
964 tmunro@postgresql.or 1227 : 911073 : scan->rs_prefetch_block = InvalidBlockNumber;
1390 drowley@postgresql.o 1228 : 911073 : tuple->t_data = NULL;
1229 : 911073 : scan->rs_inited = false;
1230 : : }
1231 : :
1232 : :
1233 : : /* ----------------------------------------------------------------
1234 : : * heap access method interface
1235 : : * ----------------------------------------------------------------
1236 : : */
1237 : :
1238 : :
1239 : : TableScanDesc
8958 tgl@sss.pgh.pa.us 1240 : 441782 : heap_beginscan(Relation relation, Snapshot snapshot,
1241 : : int nkeys, ScanKey key,
1242 : : ParallelTableScanDesc parallel_scan,
1243 : : uint32 flags)
1244 : : {
1245 : : HeapScanDesc scan;
1246 : :
1247 : : /*
1248 : : * increment relation ref count while scanning relation
1249 : : *
1250 : : * This is just to make really sure the relcache entry won't go away while
1251 : : * the scan has a pointer to it. Caller should be holding the rel open
1252 : : * anyway, so this is redundant in all normal scenarios...
1253 : : */
9516 1254 : 441782 : RelationIncrementReferenceCount(relation);
1255 : :
1256 : : /*
1257 : : * allocate and initialize scan descriptor
1258 : : */
681 melanieplageman@gmai 1259 [ + + ]: 441782 : if (flags & SO_TYPE_BITMAPSCAN)
1260 : : {
353 michael@paquier.xyz 1261 : 12510 : BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
1262 : :
1263 : : /*
1264 : : * Bitmap Heap scans do not have any fields that a normal Heap Scan
1265 : : * does not have, so no special initializations required here.
1266 : : */
681 melanieplageman@gmai 1267 : 12510 : scan = (HeapScanDesc) bscan;
1268 : : }
1269 : : else
353 michael@paquier.xyz 1270 : 429272 : scan = (HeapScanDesc) palloc_object(HeapScanDescData);
1271 : :
2819 andres@anarazel.de 1272 : 441782 : scan->rs_base.rs_rd = relation;
1273 : 441782 : scan->rs_base.rs_snapshot = snapshot;
1274 : 441782 : scan->rs_base.rs_nkeys = nkeys;
2750 1275 : 441782 : scan->rs_base.rs_flags = flags;
2819 1276 : 441782 : scan->rs_base.rs_parallel = parallel_scan;
10 melanieplageman@gmai 1277 [ + + ]: 441782 : if (flags & SO_SCAN_INSTRUMENT)
1278 : 8 : scan->rs_base.rs_instrument = palloc0_object(TableScanInstrumentation);
1279 : : else
1280 : 441774 : scan->rs_base.rs_instrument = NULL;
2750 andres@anarazel.de 1281 : 441782 : scan->rs_strategy = NULL; /* set in initscan */
623 melanieplageman@gmai 1282 : 441782 : scan->rs_cbuf = InvalidBuffer;
1283 : :
1284 : : /*
1285 : : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1286 : : */
2750 andres@anarazel.de 1287 [ + + + + ]: 441782 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
1288 : 39367 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1289 : :
1290 : : /* Check that a historic snapshot is not used for non-catalog tables */
463 heikki.linnakangas@i 1291 [ + + ]: 441782 : if (snapshot &&
1292 [ + + ]: 430078 : IsHistoricMVCCSnapshot(snapshot) &&
1293 [ + + + - : 773 : !RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - - +
- - - - -
- - - -
- ]
1294 : : {
463 heikki.linnakangas@i 1295 [ # # ]:UBC 0 : ereport(ERROR,
1296 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1297 : : errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1298 : : RelationGetRelationName(relation))));
1299 : : }
1300 : :
1301 : : /*
1302 : : * For seqscan and sample scans in a serializable transaction, acquire a
1303 : : * predicate lock on the entire relation. This is required not only to
1304 : : * lock all the matching tuples, but also to conflict with new insertions
1305 : : * into the table. In an indexscan, we take page locks on the index pages
1306 : : * covering the range specified in the scan qual, but in a heap scan there
1307 : : * is nothing more fine-grained to lock. A bitmap scan is a different
1308 : : * story, there we have already scanned the index and locked the index
1309 : : * pages covering the predicate. But in that case we still have to lock
1310 : : * any matching heap tuples. For sample scan we could optimize the locking
1311 : : * to be at least page-level granularity, but we'd need to add per-tuple
1312 : : * locking for that.
1313 : : */
2750 andres@anarazel.de 1314 [ + + ]:CBC 441782 : if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
1315 : : {
1316 : : /*
1317 : : * Ensure a missing snapshot is noticed reliably, even if the
1318 : : * isolation mode means predicate locking isn't performed (and
1319 : : * therefore the snapshot isn't used here).
1320 : : */
1321 [ - + ]: 415732 : Assert(snapshot);
5631 heikki.linnakangas@i 1322 : 415732 : PredicateLockRelation(relation, snapshot);
1323 : : }
1324 : :
1325 : : /* we only need to set this up once */
7672 tgl@sss.pgh.pa.us 1326 : 441782 : scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1327 : :
1328 : : /*
1329 : : * Allocate memory to keep track of page allocation for parallel workers
1330 : : * when doing a parallel scan.
1331 : : */
2069 drowley@postgresql.o 1332 [ + + ]: 441782 : if (parallel_scan != NULL)
353 michael@paquier.xyz 1333 : 4546 : scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
1334 : : else
2069 drowley@postgresql.o 1335 : 437236 : scan->rs_parallelworkerdata = NULL;
1336 : :
1337 : : /*
1338 : : * we do this here instead of in initscan() because heap_rescan also calls
1339 : : * initscan() and we don't want to allocate memory again
1340 : : */
8958 tgl@sss.pgh.pa.us 1341 [ + + ]: 441782 : if (nkeys > 0)
353 michael@paquier.xyz 1342 : 226874 : scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
1343 : : else
2819 andres@anarazel.de 1344 : 214908 : scan->rs_base.rs_key = NULL;
1345 : :
964 tmunro@postgresql.or 1346 : 441782 : scan->rs_read_stream = NULL;
10 melanieplageman@gmai 1347 : 441782 : initscan(scan, key, false);
1348 : :
258 1349 : 441775 : scan->rs_vmbuffer = InvalidBuffer;
1350 : :
2819 andres@anarazel.de 1351 : 441775 : return (TableScanDesc) scan;
1352 : : }
1353 : :
1354 : : void
1355 : 727255 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1356 : : bool allow_strat, bool allow_sync, bool allow_pagemode)
1357 : : {
1358 : 727255 : HeapScanDesc scan = (HeapScanDesc) sscan;
1359 : :
1360 [ + + ]: 727255 : if (set_params)
1361 : : {
2750 1362 [ + + ]: 39 : if (allow_strat)
1363 : 23 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1364 : : else
1365 : 16 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1366 : :
1367 [ + + ]: 39 : if (allow_sync)
1368 : 12 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1369 : : else
1370 : 27 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1371 : :
1372 [ + - + - ]: 39 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1373 [ + - ]: 39 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1374 : 39 : scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
1375 : : else
2750 andres@anarazel.de 1376 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1377 : : }
1378 : :
1379 : : /*
1380 : : * unpin scan buffers
1381 : : */
9303 tgl@sss.pgh.pa.us 1382 [ + + ]:CBC 727255 : if (BufferIsValid(scan->rs_cbuf))
1383 : : {
1384 : 2070 : ReleaseBuffer(scan->rs_cbuf);
623 melanieplageman@gmai 1385 : 2070 : scan->rs_cbuf = InvalidBuffer;
1386 : : }
1387 : :
258 1388 [ + + ]: 727255 : if (BufferIsValid(scan->rs_vmbuffer))
1389 : : {
1390 : 20 : ReleaseBuffer(scan->rs_vmbuffer);
1391 : 20 : scan->rs_vmbuffer = InvalidBuffer;
1392 : : }
1393 : :
1394 : : /*
1395 : : * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1396 : : * additional data vs a normal HeapScan
1397 : : */
1398 : :
1399 : : /*
1400 : : * reinitialize scan descriptor
1401 : : */
6380 tgl@sss.pgh.pa.us 1402 : 727255 : initscan(scan, key, true);
11099 scrappy@hub.org 1403 : 727255 : }
1404 : :
1405 : : void
2819 andres@anarazel.de 1406 : 438225 : heap_endscan(TableScanDesc sscan)
1407 : : {
1408 : 438225 : HeapScanDesc scan = (HeapScanDesc) sscan;
1409 : :
1410 : : /* Note: no locking manipulations needed */
1411 : :
1412 : : /*
1413 : : * unpin scan buffers
1414 : : */
9303 tgl@sss.pgh.pa.us 1415 [ + + ]: 438225 : if (BufferIsValid(scan->rs_cbuf))
1416 : 190002 : ReleaseBuffer(scan->rs_cbuf);
1417 : :
258 melanieplageman@gmai 1418 [ + + ]: 438225 : if (BufferIsValid(scan->rs_vmbuffer))
1419 : 2830 : ReleaseBuffer(scan->rs_vmbuffer);
1420 : :
1421 : : /*
1422 : : * Must free the read stream before freeing the BufferAccessStrategy.
1423 : : */
964 tmunro@postgresql.or 1424 [ + + ]: 438225 : if (scan->rs_read_stream)
1425 : 425999 : read_stream_end(scan->rs_read_stream);
1426 : :
1427 : : /*
1428 : : * decrement relation reference count and free scan descriptor storage
1429 : : */
2819 andres@anarazel.de 1430 : 438225 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1431 : :
1432 [ + + ]: 438225 : if (scan->rs_base.rs_key)
1433 : 226838 : pfree(scan->rs_base.rs_key);
1434 : :
7122 tgl@sss.pgh.pa.us 1435 [ + + ]: 438225 : if (scan->rs_strategy != NULL)
1436 : 13366 : FreeAccessStrategy(scan->rs_strategy);
1437 : :
2069 drowley@postgresql.o 1438 [ + + ]: 438225 : if (scan->rs_parallelworkerdata != NULL)
1439 : 4537 : pfree(scan->rs_parallelworkerdata);
1440 : :
2750 andres@anarazel.de 1441 [ + + ]: 438225 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
2819 1442 : 13473 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1443 : :
235 tomas.vondra@postgre 1444 [ + + ]: 438225 : if (scan->rs_base.rs_instrument)
1445 : 8 : pfree(scan->rs_base.rs_instrument);
1446 : :
9933 tgl@sss.pgh.pa.us 1447 : 438225 : pfree(scan);
11099 scrappy@hub.org 1448 : 438225 : }
1449 : :
1450 : : HeapTuple
2819 andres@anarazel.de 1451 : 11971493 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1452 : : {
1453 : 11971493 : HeapScanDesc scan = (HeapScanDesc) sscan;
1454 : :
1455 : : /*
1456 : : * This is still widely used directly, without going through table AM, so
1457 : : * add a safety check. It's possible we should, at a later point,
1458 : : * downgrade this to an assert. The reason for checking the AM routine,
1459 : : * rather than the AM oid, is that this allows to write regression tests
1460 : : * that create another AM reusing the heap handler.
1461 : : */
1462 [ - + ]: 11971493 : if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
2819 andres@anarazel.de 1463 [ # # ]:UBC 0 : ereport(ERROR,
1464 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1465 : : errmsg_internal("only heap AM is supported")));
1466 : :
1467 : : /* Note: no locking manipulations needed */
1468 : :
2750 andres@anarazel.de 1469 [ + + ]:CBC 11971493 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
7585 neilc@samurai.com 1470 : 3044019 : heapgettup_pagemode(scan, direction,
2819 andres@anarazel.de 1471 : 3044019 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1472 : : else
1473 : 8927474 : heapgettup(scan, direction,
1474 : 8927474 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1475 : :
7672 tgl@sss.pgh.pa.us 1476 [ + + ]: 11971493 : if (scan->rs_ctup.t_data == NULL)
8958 1477 : 45169 : return NULL;
1478 : :
1479 : : /*
1480 : : * if we get here it means we have a new current scan tuple, so point to
1481 : : * the proper return buffer and return the tuple.
1482 : : */
1483 : :
2819 andres@anarazel.de 1484 [ - + - - : 11926324 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - - + ]
1485 : :
1486 : 11926324 : return &scan->rs_ctup;
1487 : : }
1488 : :
1489 : : bool
1490 : 63844425 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1491 : : {
1492 : 63844425 : HeapScanDesc scan = (HeapScanDesc) sscan;
1493 : :
1494 : : /* Note: no locking manipulations needed */
1495 : :
2750 1496 [ + + ]: 63844425 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1497 : 63251585 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1498 : : else
1499 : 592840 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1500 : :
2819 1501 [ + + ]: 63844392 : if (scan->rs_ctup.t_data == NULL)
1502 : : {
1503 : 892441 : ExecClearTuple(slot);
1504 : 892441 : return false;
1505 : : }
1506 : :
1507 : : /*
1508 : : * if we get here it means we have a new current scan tuple, so point to
1509 : : * the proper return buffer and return the tuple.
1510 : : */
1511 : :
1512 [ + + - + : 62951951 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ + - + ]
1513 : :
1514 : 62951951 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1515 : : scan->rs_cbuf);
1516 : 62951951 : return true;
1517 : : }
1518 : :
1519 : : void
2100 drowley@postgresql.o 1520 : 1426 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
1521 : : ItemPointer maxtid)
1522 : : {
1523 : 1426 : HeapScanDesc scan = (HeapScanDesc) sscan;
1524 : : BlockNumber startBlk;
1525 : : BlockNumber numBlks;
1526 : : ItemPointerData highestItem;
1527 : : ItemPointerData lowestItem;
1528 : :
1529 : : /*
1530 : : * For relations without any pages, we can simply leave the TID range
1531 : : * unset. There will be no tuples to scan, therefore no tuples outside
1532 : : * the given TID range.
1533 : : */
1534 [ + + ]: 1426 : if (scan->rs_nblocks == 0)
1535 : 32 : return;
1536 : :
1537 : : /*
1538 : : * Set up some ItemPointers which point to the first and last possible
1539 : : * tuples in the heap.
1540 : : */
1541 : 1418 : ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1542 : 1418 : ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1543 : :
1544 : : /*
1545 : : * If the given maximum TID is below the highest possible TID in the
1546 : : * relation, then restrict the range to that, otherwise we scan to the end
1547 : : * of the relation.
1548 : : */
1549 [ + + ]: 1418 : if (ItemPointerCompare(maxtid, &highestItem) < 0)
1550 : 184 : ItemPointerCopy(maxtid, &highestItem);
1551 : :
1552 : : /*
1553 : : * If the given minimum TID is above the lowest possible TID in the
1554 : : * relation, then restrict the range to only scan for TIDs above that.
1555 : : */
1556 [ + + ]: 1418 : if (ItemPointerCompare(mintid, &lowestItem) > 0)
1557 : 1230 : ItemPointerCopy(mintid, &lowestItem);
1558 : :
1559 : : /*
1560 : : * Check for an empty range and protect from would be negative results
1561 : : * from the numBlks calculation below.
1562 : : */
1563 [ + + ]: 1418 : if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1564 : : {
1565 : : /* Set an empty range of blocks to scan */
1566 : 24 : heap_setscanlimits(sscan, 0, 0);
1567 : 24 : return;
1568 : : }
1569 : :
1570 : : /*
1571 : : * Calculate the first block and the number of blocks we must scan. We
1572 : : * could be more aggressive here and perform some more validation to try
1573 : : * and further narrow the scope of blocks to scan by checking if the
1574 : : * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1575 : : * advance startBlk by one. Likewise, if highestItem has an offset of 0
1576 : : * we could scan one fewer blocks. However, such an optimization does not
1577 : : * seem worth troubling over, currently.
1578 : : */
1579 : 1394 : startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1580 : :
1581 : 1394 : numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1582 : 1394 : ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1583 : :
1584 : : /* Set the start block and number of blocks to scan */
1585 : 1394 : heap_setscanlimits(sscan, startBlk, numBlks);
1586 : :
1587 : : /* Finally, set the TID range in sscan */
764 melanieplageman@gmai 1588 : 1394 : ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1589 : 1394 : ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1590 : : }
1591 : :
1592 : : bool
2100 drowley@postgresql.o 1593 : 8400 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1594 : : TupleTableSlot *slot)
1595 : : {
1596 : 8400 : HeapScanDesc scan = (HeapScanDesc) sscan;
764 melanieplageman@gmai 1597 : 8400 : ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
1598 : 8400 : ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
1599 : :
1600 : : /* Note: no locking manipulations needed */
1601 : : for (;;)
1602 : : {
2100 drowley@postgresql.o 1603 [ + - ]: 8524 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1604 : 8524 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1605 : : else
2100 drowley@postgresql.o 1606 :UBC 0 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1607 : :
2100 drowley@postgresql.o 1608 [ + + ]:CBC 8514 : if (scan->rs_ctup.t_data == NULL)
1609 : : {
1610 : 202 : ExecClearTuple(slot);
1611 : 202 : return false;
1612 : : }
1613 : :
1614 : : /*
1615 : : * heap_set_tidrange will have used heap_setscanlimits to limit the
1616 : : * range of pages we scan to only ones that can contain the TID range
1617 : : * we're scanning for. Here we must filter out any tuples from these
1618 : : * pages that are outside of that range.
1619 : : */
1620 [ + + ]: 8312 : if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1621 : : {
1622 : 124 : ExecClearTuple(slot);
1623 : :
1624 : : /*
1625 : : * When scanning backwards, the TIDs will be in descending order.
1626 : : * Future tuples in this direction will be lower still, so we can
1627 : : * just return false to indicate there will be no more tuples.
1628 : : */
1629 [ - + ]: 124 : if (ScanDirectionIsBackward(direction))
2100 drowley@postgresql.o 1630 :UBC 0 : return false;
1631 : :
2100 drowley@postgresql.o 1632 :CBC 124 : continue;
1633 : : }
1634 : :
1635 : : /*
1636 : : * Likewise for the final page, we must filter out TIDs greater than
1637 : : * maxtid.
1638 : : */
1639 [ + + ]: 8188 : if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1640 : : {
1641 : 74 : ExecClearTuple(slot);
1642 : :
1643 : : /*
1644 : : * When scanning forward, the TIDs will be in ascending order.
1645 : : * Future tuples in this direction will be higher still, so we can
1646 : : * just return false to indicate there will be no more tuples.
1647 : : */
1648 [ + - ]: 74 : if (ScanDirectionIsForward(direction))
1649 : 74 : return false;
2100 drowley@postgresql.o 1650 :UBC 0 : continue;
1651 : : }
1652 : :
2100 drowley@postgresql.o 1653 :CBC 8114 : break;
1654 : : }
1655 : :
1656 : : /*
1657 : : * if we get here it means we have a new current scan tuple, so point to
1658 : : * the proper return buffer and return the tuple.
1659 : : */
1660 [ - + - - : 8114 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - - + ]
1661 : :
1662 : 8114 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1663 : 8114 : return true;
1664 : : }
1665 : :
1666 : : /*
1667 : : * heap_fetch - retrieve tuple with given tid
1668 : : *
1669 : : * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1670 : : * the tuple, fill in the remaining fields of *tuple, and check the tuple
1671 : : * against the specified snapshot.
1672 : : *
1673 : : * If successful (tuple found and passes snapshot time qual), then *userbuf
1674 : : * is set to the buffer holding the tuple and true is returned. The caller
1675 : : * must unpin the buffer when done with the tuple.
1676 : : *
1677 : : * If the tuple is not found (ie, item number references a deleted slot),
1678 : : * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1679 : : * and false is returned.
1680 : : *
1681 : : * If the tuple is found but fails the time qual check, then the behavior
1682 : : * depends on the keep_buf parameter. If keep_buf is false, the results
1683 : : * are the same as for the tuple-not-found case. If keep_buf is true,
1684 : : * then tuple->t_data and *userbuf are returned as for the success case,
1685 : : * and again the caller must unpin the buffer; but false is returned.
1686 : : *
1687 : : * heap_fetch does not follow HOT chains: only the exact TID requested will
1688 : : * be fetched.
1689 : : *
1690 : : * It is somewhat inconsistent that we ereport() on invalid block number but
1691 : : * return false on invalid item number. There are a couple of reasons though.
1692 : : * One is that the caller can relatively easily check the block number for
1693 : : * validity, but cannot check the item number without reading the page
1694 : : * himself. Another is that when we are following a t_ctid link, we can be
1695 : : * reasonably confident that the page number is valid (since VACUUM shouldn't
1696 : : * truncate off the destination page without having killed the referencing
1697 : : * tuple first), but the item number might well not be good.
1698 : : */
1699 : : bool
11099 scrappy@hub.org 1700 : 2865014 : heap_fetch(Relation relation,
1701 : : Snapshot snapshot,
1702 : : HeapTuple tuple,
1703 : : Buffer *userbuf,
1704 : : bool keep_buf)
1705 : : {
8954 tgl@sss.pgh.pa.us 1706 : 2865014 : ItemPointer tid = &(tuple->t_self);
1707 : : ItemId lp;
1708 : : Buffer buffer;
1709 : : Page page;
1710 : : OffsetNumber offnum;
1711 : : bool valid;
1712 : :
1713 : : /*
1714 : : * Fetch and pin the appropriate page of the relation.
1715 : : */
6813 1716 : 2865014 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1717 : :
1718 : : /*
1719 : : * Need share lock on buffer to examine tuple commit status.
1720 : : */
10210 vadim4o@yahoo.com 1721 : 2865006 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3874 kgrittn@postgresql.o 1722 : 2865006 : page = BufferGetPage(buffer);
1723 : :
1724 : : /*
1725 : : * We'd better check for out-of-range offnum in case of VACUUM since the
1726 : : * TID was obtained.
1727 : : */
10674 bruce@momjian.us 1728 : 2865006 : offnum = ItemPointerGetOffsetNumber(tid);
6712 tgl@sss.pgh.pa.us 1729 [ + - + + ]: 2865006 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1730 : : {
246 andres@anarazel.de 1731 : 4 : UnlockReleaseBuffer(buffer);
2807 1732 : 4 : *userbuf = InvalidBuffer;
7916 tgl@sss.pgh.pa.us 1733 : 4 : tuple->t_data = NULL;
1734 : 4 : return false;
1735 : : }
1736 : :
1737 : : /*
1738 : : * get the item line pointer corresponding to the requested tid
1739 : : */
6712 1740 : 2865002 : lp = PageGetItemId(page, offnum);
1741 : :
1742 : : /*
1743 : : * Must check for deleted tuple.
1744 : : */
7017 1745 [ + + ]: 2865002 : if (!ItemIdIsNormal(lp))
1746 : : {
246 andres@anarazel.de 1747 : 266 : UnlockReleaseBuffer(buffer);
2807 1748 : 266 : *userbuf = InvalidBuffer;
8954 tgl@sss.pgh.pa.us 1749 : 266 : tuple->t_data = NULL;
1750 : 266 : return false;
1751 : : }
1752 : :
1753 : : /*
1754 : : * fill in *tuple fields
1755 : : */
6712 1756 : 2864736 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10228 vadim4o@yahoo.com 1757 : 2864736 : tuple->t_len = ItemIdGetLength(lp);
7770 tgl@sss.pgh.pa.us 1758 : 2864736 : tuple->t_tableOid = RelationGetRelid(relation);
1759 : :
1760 : : /*
1761 : : * check tuple visibility, then release lock
1762 : : */
7672 1763 : 2864736 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1764 : :
5773 heikki.linnakangas@i 1765 [ + + ]: 2864736 : if (valid)
2496 tmunro@postgresql.or 1766 : 2864647 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1767 : 2864647 : HeapTupleHeaderGetXmin(tuple->t_data));
1768 : :
1769 : 2864736 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1770 : :
5748 heikki.linnakangas@i 1771 : 2864736 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1772 : :
8954 tgl@sss.pgh.pa.us 1773 [ + + ]: 2864736 : if (valid)
1774 : : {
1775 : : /*
1776 : : * All checks passed, so return the tuple as valid. Caller is now
1777 : : * responsible for releasing the buffer.
1778 : : */
9927 1779 : 2864647 : *userbuf = buffer;
1780 : :
8954 1781 : 2864647 : return true;
1782 : : }
1783 : :
1784 : : /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1690 1785 [ + + ]: 89 : if (keep_buf)
1786 : 43 : *userbuf = buffer;
1787 : : else
1788 : : {
1789 : 46 : ReleaseBuffer(buffer);
1790 : 46 : *userbuf = InvalidBuffer;
1791 : 46 : tuple->t_data = NULL;
1792 : : }
1793 : :
8954 1794 : 89 : return false;
1795 : : }
1796 : :
1797 : : /*
1798 : : * heap_get_latest_tid - get the latest tid of a specified tuple
1799 : : *
1800 : : * Actually, this gets the latest version that is visible according to the
1801 : : * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1802 : : * possibly uncommitted version.
1803 : : *
1804 : : * *tid is both an input and an output parameter: it is updated to
1805 : : * show the latest version of the row. Note that it will not be changed
1806 : : * if no version of the row passes the snapshot test.
1807 : : */
1808 : : void
2752 andres@anarazel.de 1809 : 207 : heap_get_latest_tid(TableScanDesc sscan,
1810 : : ItemPointer tid)
1811 : : {
2747 tgl@sss.pgh.pa.us 1812 : 207 : Relation relation = sscan->rs_rd;
1813 : 207 : Snapshot snapshot = sscan->rs_snapshot;
1814 : : ItemPointerData ctid;
1815 : : TransactionId priorXmax;
1816 : :
1817 : : /*
1818 : : * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1819 : : * Assume that t_ctid links are valid however - there shouldn't be invalid
1820 : : * ones in the table.
1821 : : */
2752 andres@anarazel.de 1822 [ - + ]: 207 : Assert(ItemPointerIsValid(tid));
1823 : :
1824 : : /*
1825 : : * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1826 : : * need to examine, and *tid is the TID we will return if ctid turns out
1827 : : * to be bogus.
1828 : : *
1829 : : * Note that we will loop until we reach the end of the t_ctid chain.
1830 : : * Depending on the snapshot passed, there might be at most one visible
1831 : : * version of the row, but we don't try to optimize for that.
1832 : : */
7770 tgl@sss.pgh.pa.us 1833 : 207 : ctid = *tid;
1834 : 207 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1835 : : for (;;)
1836 : 64 : {
1837 : : Buffer buffer;
1838 : : Page page;
1839 : : OffsetNumber offnum;
1840 : : ItemId lp;
1841 : : HeapTupleData tp;
1842 : : bool valid;
1843 : :
1844 : : /*
1845 : : * Read, pin, and lock the page.
1846 : : */
1847 : 271 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1848 : 271 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3874 kgrittn@postgresql.o 1849 : 271 : page = BufferGetPage(buffer);
1850 : :
1851 : : /*
1852 : : * Check for bogus item number. This is not treated as an error
1853 : : * condition because it can happen while following a t_ctid link. We
1854 : : * just assume that the prior tid is OK and return it unchanged.
1855 : : */
7770 tgl@sss.pgh.pa.us 1856 : 271 : offnum = ItemPointerGetOffsetNumber(&ctid);
6712 1857 [ + - - + ]: 271 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1858 : : {
7547 tgl@sss.pgh.pa.us 1859 :UBC 0 : UnlockReleaseBuffer(buffer);
7770 1860 : 0 : break;
1861 : : }
6712 tgl@sss.pgh.pa.us 1862 :CBC 271 : lp = PageGetItemId(page, offnum);
7017 1863 [ - + ]: 271 : if (!ItemIdIsNormal(lp))
1864 : : {
7547 tgl@sss.pgh.pa.us 1865 :UBC 0 : UnlockReleaseBuffer(buffer);
7770 1866 : 0 : break;
1867 : : }
1868 : :
1869 : : /* OK to access the tuple */
7770 tgl@sss.pgh.pa.us 1870 :CBC 271 : tp.t_self = ctid;
6712 1871 : 271 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
7770 1872 : 271 : tp.t_len = ItemIdGetLength(lp);
4877 rhaas@postgresql.org 1873 : 271 : tp.t_tableOid = RelationGetRelid(relation);
1874 : :
1875 : : /*
1876 : : * After following a t_ctid link, we might arrive at an unrelated
1877 : : * tuple. Check for XMIN match.
1878 : : */
7770 tgl@sss.pgh.pa.us 1879 [ + + - + ]: 335 : if (TransactionIdIsValid(priorXmax) &&
3313 alvherre@alvh.no-ip. 1880 : 64 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1881 : : {
7547 tgl@sss.pgh.pa.us 1882 :UBC 0 : UnlockReleaseBuffer(buffer);
7770 1883 : 0 : break;
1884 : : }
1885 : :
1886 : : /*
1887 : : * Check tuple visibility; if visible, set it as the new result
1888 : : * candidate.
1889 : : */
7672 tgl@sss.pgh.pa.us 1890 :CBC 271 : valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2496 tmunro@postgresql.or 1891 : 271 : HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
7770 tgl@sss.pgh.pa.us 1892 [ + + ]: 271 : if (valid)
1893 : 191 : *tid = ctid;
1894 : :
1895 : : /*
1896 : : * If there's a valid t_ctid link, follow it, else we're done.
1897 : : */
5057 alvherre@alvh.no-ip. 1898 [ + + + + ]: 391 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1899 [ + - ]: 200 : HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
3157 andres@anarazel.de 1900 [ + + ]: 160 : HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
7770 tgl@sss.pgh.pa.us 1901 : 80 : ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1902 : : {
7547 1903 : 207 : UnlockReleaseBuffer(buffer);
7770 1904 : 207 : break;
1905 : : }
1906 : :
1907 : 64 : ctid = tp.t_data->t_ctid;
5057 alvherre@alvh.no-ip. 1908 : 64 : priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
7547 tgl@sss.pgh.pa.us 1909 : 64 : UnlockReleaseBuffer(buffer);
1910 : : } /* end of loop */
9910 inoue@tpf.co.jp 1911 : 207 : }
1912 : :
1913 : :
1914 : : /*
1915 : : * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1916 : : *
1917 : : * This is called after we have waited for the XMAX transaction to terminate.
1918 : : * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1919 : : * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1920 : : * hint bit if possible --- but beware that that may not yet be possible,
1921 : : * if the transaction committed asynchronously.
1922 : : *
1923 : : * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1924 : : * even if it commits.
1925 : : *
1926 : : * Hence callers should look only at XMAX_INVALID.
1927 : : *
1928 : : * Note this is not allowed for tuples whose xmax is a multixact.
1929 : : */
1930 : : static void
7046 tgl@sss.pgh.pa.us 1931 : 257 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1932 : : {
5057 alvherre@alvh.no-ip. 1933 [ - + ]: 257 : Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1934 [ - + ]: 257 : Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1935 : :
7046 tgl@sss.pgh.pa.us 1936 [ + + ]: 257 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1937 : : {
5057 alvherre@alvh.no-ip. 1938 [ + + + + ]: 461 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1939 : 205 : TransactionIdDidCommit(xid))
7046 tgl@sss.pgh.pa.us 1940 : 178 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1941 : : xid);
1942 : : else
1943 : 78 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1944 : : InvalidTransactionId);
1945 : : }
1946 : 257 : }
1947 : :
1948 : :
1949 : : /*
1950 : : * GetBulkInsertState - prepare status object for a bulk insert
1951 : : */
1952 : : BulkInsertState
6596 1953 : 3433 : GetBulkInsertState(void)
1954 : : {
1955 : : BulkInsertState bistate;
1956 : :
353 michael@paquier.xyz 1957 : 3433 : bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
6596 tgl@sss.pgh.pa.us 1958 : 3433 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1959 : 3433 : bistate->current_buf = InvalidBuffer;
1332 andres@anarazel.de 1960 : 3433 : bistate->next_free = InvalidBlockNumber;
1961 : 3433 : bistate->last_free = InvalidBlockNumber;
1202 1962 : 3433 : bistate->already_extended_by = 0;
6596 tgl@sss.pgh.pa.us 1963 : 3433 : return bistate;
1964 : : }
1965 : :
1966 : : /*
1967 : : * FreeBulkInsertState - clean up after finishing a bulk insert
1968 : : */
1969 : : void
1970 : 3169 : FreeBulkInsertState(BulkInsertState bistate)
1971 : : {
1972 [ + + ]: 3169 : if (bistate->current_buf != InvalidBuffer)
6379 bruce@momjian.us 1973 : 2454 : ReleaseBuffer(bistate->current_buf);
6596 tgl@sss.pgh.pa.us 1974 : 3169 : FreeAccessStrategy(bistate->strategy);
1975 : 3169 : pfree(bistate);
1976 : 3169 : }
1977 : :
1978 : : /*
1979 : : * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
1980 : : */
1981 : : void
3595 rhaas@postgresql.org 1982 : 90786 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
1983 : : {
1984 [ + + ]: 90786 : if (bistate->current_buf != InvalidBuffer)
1985 : 40028 : ReleaseBuffer(bistate->current_buf);
1986 : 90786 : bistate->current_buf = InvalidBuffer;
1987 : :
1988 : : /*
1989 : : * Despite the name, we also reset bulk relation extension state.
1990 : : * Otherwise we can end up erroring out due to looking for free space in
1991 : : * ->next_free of one partition, even though ->next_free was set when
1992 : : * extending another partition. It could obviously also be bad for
1993 : : * efficiency to look at existing blocks at offsets from another
1994 : : * partition, even if we don't error out.
1995 : : */
1142 andres@anarazel.de 1996 : 90786 : bistate->next_free = InvalidBlockNumber;
1997 : 90786 : bistate->last_free = InvalidBlockNumber;
3595 rhaas@postgresql.org 1998 : 90786 : }
1999 : :
2000 : :
2001 : : /*
2002 : : * heap_insert - insert tuple into a heap
2003 : : *
2004 : : * The new tuple is stamped with current transaction ID and the specified
2005 : : * command ID.
2006 : : *
2007 : : * See table_tuple_insert for comments about most of the input flags, except
2008 : : * that this routine directly takes a tuple rather than a slot.
2009 : : *
2010 : : * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
2011 : : * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
2012 : : * implement table_tuple_insert_speculative().
2013 : : *
2014 : : * On return the header fields of *tup are updated to match the stored tuple;
2015 : : * in particular tup->t_self receives the actual TID where the tuple was
2016 : : * stored. But note that any toasting of fields within the tuple data is NOT
2017 : : * reflected into *tup.
2018 : : */
2019 : : void
7831 tgl@sss.pgh.pa.us 2020 : 12090247 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2021 : : uint32 options, BulkInsertState bistate)
2022 : : {
8108 2023 : 12090247 : TransactionId xid = GetCurrentTransactionId();
2024 : : HeapTuple heaptup;
2025 : : Buffer buffer;
2026 : : Page page;
5639 rhaas@postgresql.org 2027 : 12090247 : Buffer vmbuffer = InvalidBuffer;
136 melanieplageman@gmai 2028 : 12090247 : bool clear_all_visible = false;
2029 : 12090247 : bool vmbuffer_modified = false;
2030 : :
2031 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2028 tgl@sss.pgh.pa.us 2032 [ - + ]: 12090247 : Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
2033 : : RelationGetNumberOfAttributes(relation));
2034 : :
547 nathan@postgresql.or 2035 : 12090247 : AssertHasSnapshotForToast(relation);
2036 : :
2037 : : /*
2038 : : * Fill in tuple header fields and toast the tuple if necessary.
2039 : : *
2040 : : * Note: below this point, heaptup is the data we actually intend to store
2041 : : * into the relation; tup is the caller's original untoasted data.
2042 : : */
5498 heikki.linnakangas@i 2043 : 12090247 : heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2044 : :
2045 : : /*
2046 : : * Find buffer to insert this tuple into. If the page is all visible,
2047 : : * this will also pin the requisite visibility map page.
2048 : : */
4046 kgrittn@postgresql.o 2049 : 12090247 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2050 : : InvalidBuffer, options, bistate,
2051 : : &vmbuffer, NULL,
2052 : : 0);
2053 : :
243 melanieplageman@gmai 2054 : 12090245 : page = BufferGetPage(buffer);
2055 : :
2056 : : /*
2057 : : * We're about to do the actual insert -- but check for conflict first, to
2058 : : * avoid possibly having to roll back work we've just done.
2059 : : *
2060 : : * This is safe without a recheck as long as there is no possibility of
2061 : : * another process scanning the page between this check and the insert
2062 : : * being visible to the scan (i.e., an exclusive buffer content lock is
2063 : : * continuously held from this point until the tuple insert is visible).
2064 : : *
2065 : : * For a heap insert, we only need to check for table-level SSI locks. Our
2066 : : * new tuple can't possibly conflict with existing tuple locks, and heap
2067 : : * page locks are only consolidated versions of tuple locks; they do not
2068 : : * lock "gaps" as index page locks do. So we don't need to specify a
2069 : : * buffer when making the call, which makes for a faster check.
2070 : : */
2496 tmunro@postgresql.or 2071 : 12090245 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2072 : :
2073 : : /* Lock the vmbuffer before the critical section */
136 melanieplageman@gmai 2074 [ + + ]: 12090228 : if (PageIsAllVisible(page))
2075 : : {
2076 : 10170 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2077 : 10170 : clear_all_visible = true;
2078 : : }
2079 : :
2080 : : /* NO EREPORT(ERROR) from here till changes are logged */
9451 tgl@sss.pgh.pa.us 2081 : 12090228 : START_CRIT_SECTION();
2082 : :
4222 andres@anarazel.de 2083 : 12090228 : RelationPutHeapTuple(relation, buffer, heaptup,
2084 : 12090228 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2085 : :
136 melanieplageman@gmai 2086 [ + + ]: 12090228 : if (clear_all_visible)
2087 : : {
2088 : : /* It's possible the VM bits were already clear */
136 melanieplageman@gmai 2089 [ + - ]:GNC 10170 : if (visibilitymap_clear(relation->rd_locator,
136 melanieplageman@gmai 2090 :CBC 10170 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2091 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
2092 : 10170 : vmbuffer_modified = true;
2093 : :
243 2094 : 10170 : PageClearAllVisible(page);
2095 : : }
2096 : :
2097 : : /*
2098 : : * Set pd_prune_xid to trigger heap_page_prune_and_freeze() once the page
2099 : : * is full so that we can set the page all-visible in the VM on the next
2100 : : * page access.
2101 : : *
2102 : : * Setting pd_prune_xid is also handy if the inserting transaction
2103 : : * eventually aborts making this tuple DEAD and hence available for
2104 : : * pruning. If no other tuple in this page is UPDATEd/DELETEd, the aborted
2105 : : * tuple would never otherwise be pruned until next vacuum is triggered.
2106 : : *
2107 : : * Don't set it if we are in bootstrap mode or we are inserting a frozen
2108 : : * tuple, as there is no further pruning/freezing needed in those cases.
2109 : : */
2110 [ + + + + ]: 12090228 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
2111 [ - + + + : 11403410 : PageSetPrunable(page, xid);
+ + ]
2112 : :
7547 tgl@sss.pgh.pa.us 2113 : 12090228 : MarkBufferDirty(buffer);
2114 : :
2115 : : /* XLOG stuff */
2429 noah@leadboat.com 2116 [ + + + + : 12090228 : if (RelationNeedsWAL(relation))
+ + + + ]
2117 : : {
2118 : : xl_heap_insert xlrec;
2119 : : xl_heap_header xlhdr;
2120 : : XLogRecPtr recptr;
9382 bruce@momjian.us 2121 : 10812439 : uint8 info = XLOG_HEAP_INSERT;
4391 heikki.linnakangas@i 2122 : 10812439 : int bufflags = 0;
2123 : :
2124 : : /*
2125 : : * If this is a catalog, we need to transmit combo CIDs to properly
2126 : : * decode, so log that as well.
2127 : : */
4736 rhaas@postgresql.org 2128 [ + + + + : 10812439 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
2129 : 4315 : log_heap_new_cid(relation, heaptup);
2130 : :
2131 : : /*
2132 : : * If this is the single and first tuple on page, we can reinit the
2133 : : * page instead of restoring the whole thing. Set flag, and hide
2134 : : * buffer references from XLogInsert.
2135 : : */
4391 heikki.linnakangas@i 2136 [ + + + + ]: 10939511 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2137 : 127072 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2138 : : {
2139 : 125344 : info |= XLOG_HEAP_INIT_PAGE;
2140 : 125344 : bufflags |= REGBUF_WILL_INIT;
2141 : : }
2142 : :
2143 : 10812439 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
4222 andres@anarazel.de 2144 : 10812439 : xlrec.flags = 0;
136 melanieplageman@gmai 2145 [ + + ]: 10812439 : if (clear_all_visible)
4222 andres@anarazel.de 2146 : 10087 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2147 [ + + ]: 10812439 : if (options & HEAP_INSERT_SPECULATIVE)
2148 : 2255 : xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
4391 heikki.linnakangas@i 2149 [ - + ]: 10812439 : Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2150 : :
2151 : : /*
2152 : : * For logical decoding, we need the tuple even if we're doing a full
2153 : : * page write, so make sure it's included even if we take a full-page
2154 : : * image. (XXX We could alternatively store a pointer into the FPW).
2155 : : */
2971 andres@anarazel.de 2156 [ + + + + : 10812439 : if (RelationIsLogicallyLogged(relation) &&
+ - - + -
- - - + -
+ + + + ]
2157 [ + + ]: 298750 : !(options & HEAP_INSERT_NO_LOGICAL))
2158 : : {
4222 2159 : 298512 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
4391 heikki.linnakangas@i 2160 : 298512 : bufflags |= REGBUF_KEEP_DATA;
2161 : :
2303 akapila@postgresql.o 2162 [ + + ]: 298512 : if (IsToastRelation(relation))
2163 : 1970 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2164 : : }
2165 : :
4391 heikki.linnakangas@i 2166 : 10812439 : XLogBeginInsert();
655 peter@eisentraut.org 2167 : 10812439 : XLogRegisterData(&xlrec, SizeOfHeapInsert);
2168 : :
4391 heikki.linnakangas@i 2169 : 10812439 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2170 : 10812439 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2171 : 10812439 : xlhdr.t_hoff = heaptup->t_data->t_hoff;
2172 : :
2173 : : /*
2174 : : * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2175 : : * write the whole page to the xlog, we don't need to store
2176 : : * xl_heap_header in the xlog.
2177 : : */
136 melanieplageman@gmai 2178 : 10812439 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_HEAP, buffer,
2179 : 10812439 : REGBUF_STANDARD | bufflags);
2180 : 10812439 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP, &xlhdr,
2181 : : SizeOfHeapHeader);
2182 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2183 : 10812439 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP,
4298 tgl@sss.pgh.pa.us 2184 : 10812439 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2185 : 10812439 : heaptup->t_len - SizeofHeapTupleHeader);
2186 : :
2187 : : /* filtering by origin on a row level is much more efficient */
3628 andres@anarazel.de 2188 : 10812439 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2189 : :
136 melanieplageman@gmai 2190 [ + + ]: 10812439 : if (vmbuffer_modified)
2191 : 10087 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_VM, vmbuffer, 0);
2192 : :
4391 heikki.linnakangas@i 2193 : 10812439 : recptr = XLogInsert(RM_HEAP_ID, info);
2194 : :
9466 vadim4o@yahoo.com 2195 : 10812439 : PageSetLSN(page, recptr);
2196 : :
136 melanieplageman@gmai 2197 [ + + ]: 10812439 : if (vmbuffer_modified)
2198 : 10087 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2199 : : }
2200 : :
9451 tgl@sss.pgh.pa.us 2201 [ - + ]: 12090228 : END_CRIT_SECTION();
2202 : :
7547 2203 : 12090228 : UnlockReleaseBuffer(buffer);
2204 : :
2205 : : /*
2206 : : * We locked vmbuffer if clear_all_visible was true regardless of whether
2207 : : * or not we ended up modifying the vmbuffer.
2208 : : */
136 melanieplageman@gmai 2209 [ + + ]: 12090228 : if (clear_all_visible)
2210 : 10170 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2211 [ + + ]: 12090228 : if (BufferIsValid(vmbuffer))
5639 rhaas@postgresql.org 2212 : 10533 : ReleaseBuffer(vmbuffer);
2213 : :
2214 : : /*
2215 : : * If tuple is cacheable, mark it for invalidation from the caches in case
2216 : : * we abort. Note it is OK to do this after releasing the buffer, because
2217 : : * the heaptup data structure is all in local memory, not in the shared
2218 : : * buffer.
2219 : : */
5583 tgl@sss.pgh.pa.us 2220 : 12090228 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2221 : :
2222 : : /* Note: speculative insertions are counted too, even if aborted later */
5498 heikki.linnakangas@i 2223 : 12090228 : pgstat_count_heap_insert(relation, 1);
2224 : :
2225 : : /*
2226 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
2227 : : * back to the caller's image, too.
2228 : : */
7678 tgl@sss.pgh.pa.us 2229 [ + + ]: 12090228 : if (heaptup != tup)
2230 : : {
2231 : 22843 : tup->t_self = heaptup->t_self;
2232 : 22843 : heap_freetuple(heaptup);
2233 : : }
11099 scrappy@hub.org 2234 : 12090228 : }
2235 : :
2236 : : /*
2237 : : * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2238 : : * tuple header fields and toasts the tuple if necessary. Returns a toasted
2239 : : * version of the tuple if it was toasted, or the original tuple if not. Note
2240 : : * that in any case, the header fields are also set in the original tuple.
2241 : : */
2242 : : static HeapTuple
5498 heikki.linnakangas@i 2243 : 13931477 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2244 : : CommandId cid, uint32 options)
2245 : : {
2246 : : /*
2247 : : * To allow parallel inserts, we need to ensure that they are safe to be
2248 : : * performed in workers. We have the infrastructure to allow parallel
2249 : : * inserts in general except for the cases where inserts generate a new
2250 : : * CommandId (eg. inserts into a table having a foreign key column).
2251 : : */
3341 rhaas@postgresql.org 2252 [ - + ]: 13931477 : if (IsParallelWorker())
4230 rhaas@postgresql.org 2253 [ # # ]:UBC 0 : ereport(ERROR,
2254 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2255 : : errmsg("cannot insert tuples in a parallel worker")));
2256 : :
2257 : : /* don't need to unset HEAP_IS_DATUM, it's part of HEAP_XACT_MASK */
2258 : :
5498 heikki.linnakangas@i 2259 :CBC 13931477 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2260 : 13931477 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2261 : 13931477 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
4724 rhaas@postgresql.org 2262 : 13931477 : HeapTupleHeaderSetXmin(tup->t_data, xid);
5109 simon@2ndQuadrant.co 2263 [ + + ]: 13931477 : if (options & HEAP_INSERT_FROZEN)
4724 rhaas@postgresql.org 2264 : 102656 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2265 : :
5498 heikki.linnakangas@i 2266 : 13931477 : HeapTupleHeaderSetCmin(tup->t_data, cid);
3447 tgl@sss.pgh.pa.us 2267 : 13931477 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
5498 heikki.linnakangas@i 2268 : 13931477 : tup->t_tableOid = RelationGetRelid(relation);
2269 : :
2270 : : /*
2271 : : * If the new tuple is too big for storage or contains already toasted
2272 : : * out-of-line attributes from some other relation, invoke the toaster.
2273 : : */
5018 kgrittn@postgresql.o 2274 [ + + ]: 13931477 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2275 [ + + ]: 42069 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2276 : : {
2277 : : /* toast table entries should never be recursively toasted */
5498 heikki.linnakangas@i 2278 [ - + ]: 42008 : Assert(!HeapTupleHasExternal(tup));
2279 : 42008 : return tup;
2280 : : }
2281 [ + + + + ]: 13889469 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2612 rhaas@postgresql.org 2282 : 22930 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2283 : : else
5498 heikki.linnakangas@i 2284 : 13866539 : return tup;
2285 : : }
2286 : :
2287 : : /*
2288 : : * Helper for heap_multi_insert() that computes the number of entire pages
2289 : : * that inserting the remaining heaptuples requires. Used to determine how
2290 : : * much the relation needs to be extended by.
2291 : : */
2292 : : static int
1332 andres@anarazel.de 2293 : 491848 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2294 : : {
2295 : 491848 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2296 : 491848 : int npages = 1;
2297 : :
2298 [ + + ]: 3017057 : for (int i = done; i < ntuples; i++)
2299 : : {
2300 : 2525209 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2301 : :
2302 [ + + ]: 2525209 : if (page_avail < tup_sz)
2303 : : {
2304 : 17590 : npages++;
2305 : 17590 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2306 : : }
2307 : 2525209 : page_avail -= tup_sz;
2308 : : }
2309 : :
2310 : 491848 : return npages;
2311 : : }
2312 : :
2313 : : /*
2314 : : * heap_multi_insert - insert multiple tuples into a heap
2315 : : *
2316 : : * This is like heap_insert(), but inserts multiple tuples in one operation.
2317 : : * That's faster than calling heap_insert() in a loop, because when multiple
2318 : : * tuples can be inserted on a single page, we can write just a single WAL
2319 : : * record covering all of them, and only need to lock/unlock the page once.
2320 : : *
2321 : : * Note: this leaks memory into the current memory context. You can create a
2322 : : * temporary context before calling this, if that's a problem.
2323 : : */
2324 : : void
2795 2325 : 482609 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2326 : : CommandId cid, uint32 options, BulkInsertState bistate)
2327 : : {
5498 heikki.linnakangas@i 2328 : 482609 : TransactionId xid = GetCurrentTransactionId();
2329 : : HeapTuple *heaptuples;
2330 : : int i;
2331 : : int ndone;
2332 : : PGAlignedBlock scratch;
2333 : : Page page;
2141 tomas.vondra@postgre 2334 : 482609 : Buffer vmbuffer = InvalidBuffer;
2335 : : bool needwal;
2336 : : Size saveFreeSpace;
4736 rhaas@postgresql.org 2337 [ + + + + : 482609 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
+ - - + -
- - - + -
+ + + - ]
2338 [ + + + + : 482609 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
+ - - + -
- - - + +
- + - - -
- - - ]
1332 andres@anarazel.de 2339 : 482609 : bool starting_with_empty_page = false;
2340 : 482609 : int npages = 0;
2341 : 482609 : int npages_used = 0;
2342 : :
2343 : : /* currently not needed (thus unsupported) for heap_multi_insert() */
1492 peter@eisentraut.org 2344 [ - + ]: 482609 : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2345 : :
547 nathan@postgresql.or 2346 : 482609 : AssertHasSnapshotForToast(relation);
2347 : :
2429 noah@leadboat.com 2348 [ + + + + : 482609 : needwal = RelationNeedsWAL(relation);
+ - + + ]
961 akorotkov@postgresql 2349 [ + + ]: 482609 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2350 : : HEAP_DEFAULT_FILLFACTOR);
2351 : :
2352 : : /* Toast and set header data in all the slots */
103 michael@paquier.xyz 2353 :GNC 482609 : heaptuples = palloc_array(HeapTuple, ntuples);
5498 heikki.linnakangas@i 2354 [ + + ]:CBC 2323839 : for (i = 0; i < ntuples; i++)
2355 : : {
2356 : : HeapTuple tuple;
2357 : :
2795 andres@anarazel.de 2358 : 1841230 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2359 : 1841230 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2360 : 1841230 : tuple->t_tableOid = slots[i]->tts_tableOid;
2361 : 1841230 : heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2362 : : options);
2363 : : }
2364 : :
2365 : : /*
2366 : : * We're about to do the actual inserts -- but check for conflict first,
2367 : : * to minimize the possibility of having to roll back work we've just
2368 : : * done.
2369 : : *
2370 : : * A check here does not definitively prevent a serialization anomaly;
2371 : : * that check MUST be done at least past the point of acquiring an
2372 : : * exclusive buffer content lock on every buffer that will be affected,
2373 : : * and MAY be done after all inserts are reflected in the buffers and
2374 : : * those locks are released; otherwise there is a race condition. Since
2375 : : * multiple buffers can be locked and unlocked in the loop below, and it
2376 : : * would not be feasible to identify and lock all of those buffers before
2377 : : * the loop, we must do a final check at the end.
2378 : : *
2379 : : * The check here could be omitted with no loss of correctness; it is
2380 : : * present strictly as an optimization.
2381 : : *
2382 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2383 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2384 : : * page locks are only consolidated versions of tuple locks; they do not
2385 : : * lock "gaps" as index page locks do. So we don't need to specify a
2386 : : * buffer when making the call, which makes for a faster check.
2387 : : */
2496 tmunro@postgresql.or 2388 : 482609 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2389 : :
5498 heikki.linnakangas@i 2390 : 482609 : ndone = 0;
2391 [ + + ]: 983777 : while (ndone < ntuples)
2392 : : {
2393 : : Buffer buffer;
136 melanieplageman@gmai 2394 : 501168 : bool clear_all_visible = false;
2141 tomas.vondra@postgre 2395 : 501168 : bool all_frozen_set = false;
136 melanieplageman@gmai 2396 : 501168 : bool vmbuffer_modified = false;
2397 : : int nthispage;
2398 : :
4541 rhaas@postgresql.org 2399 [ + + ]: 501168 : CHECK_FOR_INTERRUPTS();
2400 : :
2401 : : /*
2402 : : * Compute number of pages needed to fit the to-be-inserted tuples in
2403 : : * the worst case. This will be used to determine how much to extend
2404 : : * the relation by in RelationGetBufferForTuple(), if needed. If we
2405 : : * filled a prior page from scratch, we can just update our last
2406 : : * computation, but if we started with a partially filled page,
2407 : : * recompute from scratch, the number of potentially required pages
2408 : : * can vary due to tuples needing to fit onto the page, page headers
2409 : : * etc.
2410 : : */
1332 andres@anarazel.de 2411 [ + + + + ]: 501168 : if (ndone == 0 || !starting_with_empty_page)
2412 : : {
2413 : 491848 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2414 : : saveFreeSpace);
2415 : 491848 : npages_used = 0;
2416 : : }
2417 : : else
2418 : 9320 : npages_used++;
2419 : :
2420 : : /*
2421 : : * Find buffer where at least the next tuple will fit. If the page is
2422 : : * all-visible, this will also pin the requisite visibility map page.
2423 : : *
2424 : : * Also pin visibility map page if COPY FREEZE inserts tuples into an
2425 : : * empty page. See all_frozen_set below.
2426 : : */
5498 heikki.linnakangas@i 2427 : 501168 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2428 : : InvalidBuffer, options, bistate,
2429 : : &vmbuffer, NULL,
2430 : : npages - npages_used);
3874 kgrittn@postgresql.o 2431 : 501168 : page = BufferGetPage(buffer);
2432 : :
2141 tomas.vondra@postgre 2433 : 501168 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2434 : :
2435 [ + + + + ]: 501168 : if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2436 : : {
2437 : 1666 : all_frozen_set = true;
2438 : : /* Lock the vmbuffer before entering the critical section */
415 melanieplageman@gmai 2439 : 1666 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2440 : : }
136 2441 [ + + + + ]: 499502 : else if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2442 : : {
2443 : 7439 : clear_all_visible = true;
2444 : : /* Lock the vmbuffer before entering the critical section */
2445 : 7439 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2446 : : }
2447 : :
2448 : : /* NO EREPORT(ERROR) from here till changes are logged */
5498 heikki.linnakangas@i 2449 : 501168 : START_CRIT_SECTION();
2450 : :
2451 : : /*
2452 : : * RelationGetBufferForTuple has ensured that the first tuple fits.
2453 : : * Put that on the page, and then as many other tuples as fit.
2454 : : */
4222 andres@anarazel.de 2455 : 501168 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2456 : :
2457 : : /*
2458 : : * For logical decoding we need combo CIDs to properly decode the
2459 : : * catalog.
2460 : : */
2468 michael@paquier.xyz 2461 [ + + + + ]: 501168 : if (needwal && need_cids)
2462 : 6299 : log_heap_new_cid(relation, heaptuples[ndone]);
2463 : :
5099 heikki.linnakangas@i 2464 [ + + ]: 1841230 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2465 : : {
5498 2466 : 1358621 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2467 : :
5309 2468 [ + + ]: 1358621 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
5498 2469 : 18559 : break;
2470 : :
4222 andres@anarazel.de 2471 : 1340062 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2472 : :
2473 : : /*
2474 : : * For logical decoding we need combo CIDs to properly decode the
2475 : : * catalog.
2476 : : */
4391 heikki.linnakangas@i 2477 [ + + + + ]: 1340062 : if (needwal && need_cids)
2478 : 5801 : log_heap_new_cid(relation, heaptup);
2479 : : }
2480 : :
2481 : : /*
2482 : : * If the page is all visible, need to clear that, unless we're only
2483 : : * going to add further frozen rows to it.
2484 : : *
2485 : : * If we're only adding already frozen rows to a previously empty
2486 : : * page, mark it as all-frozen and update the visibility map. We're
2487 : : * already holding a pin on the vmbuffer.
2488 : : */
136 melanieplageman@gmai 2489 [ + + ]: 501168 : if (clear_all_visible)
2490 : : {
2491 [ - + ]: 7439 : Assert(!(options & HEAP_INSERT_FROZEN));
2492 : : /* It's possible the VM bits were already clear */
136 melanieplageman@gmai 2493 [ + - ]:GNC 7439 : if (visibilitymap_clear(relation->rd_locator,
2494 : : BufferGetBlockNumber(buffer),
2495 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
136 melanieplageman@gmai 2496 :CBC 7439 : vmbuffer_modified = true;
2497 : :
5287 rhaas@postgresql.org 2498 : 7439 : PageClearAllVisible(page);
2499 : : }
2141 tomas.vondra@postgre 2500 [ + + ]: 493729 : else if (all_frozen_set)
2501 : : {
2502 : 1666 : PageSetAllVisible(page);
271 melanieplageman@gmai 2503 : 1666 : PageClearPrunable(page);
75 2504 : 1666 : (void) visibilitymap_set(BufferGetBlockNumber(buffer),
2505 : : vmbuffer,
2506 : : VISIBILITYMAP_ALL_VISIBLE |
2507 : : VISIBILITYMAP_ALL_FROZEN,
2508 : : relation->rd_locator);
2509 : : }
2510 : :
2511 : : /*
2512 : : * Set pd_prune_xid. See heap_insert() for more on why we do this when
2513 : : * inserting tuples. This only makes sense if the tuples aren't frozen
2514 : : * and we're not in bootstrap mode.
2515 : : */
2516 [ + + + + ]: 501168 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
243 2517 [ - + + + : 477322 : PageSetPrunable(page, xid);
+ + ]
2518 : :
5498 heikki.linnakangas@i 2519 : 501168 : MarkBufferDirty(buffer);
2520 : :
2521 : : /* XLOG stuff */
2522 [ + + ]: 501168 : if (needwal)
2523 : : {
2524 : : XLogRecPtr recptr;
2525 : : xl_heap_multi_insert *xlrec;
2526 : 497268 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2527 : : char *tupledata;
2528 : : int totaldatalen;
3010 tgl@sss.pgh.pa.us 2529 : 497268 : char *scratchptr = scratch.data;
2530 : : bool init;
4391 heikki.linnakangas@i 2531 : 497268 : int bufflags = 0;
2532 : :
2533 : : /*
2534 : : * If the page was previously empty, we can reinit the page
2535 : : * instead of restoring the whole thing.
2536 : : */
2141 tomas.vondra@postgre 2537 : 497268 : init = starting_with_empty_page;
2538 : :
2539 : : /* allocate xl_heap_multi_insert struct from the scratch area */
5498 heikki.linnakangas@i 2540 : 497268 : xlrec = (xl_heap_multi_insert *) scratchptr;
2541 : 497268 : scratchptr += SizeOfHeapMultiInsert;
2542 : :
2543 : : /*
2544 : : * Allocate offsets array. Unless we're reinitializing the page,
2545 : : * in that case the tuples are stored in order starting at
2546 : : * FirstOffsetNumber and we don't need to store the offsets
2547 : : * explicitly.
2548 : : */
2549 [ + + ]: 497268 : if (!init)
2550 : 482381 : scratchptr += nthispage * sizeof(OffsetNumber);
2551 : :
2552 : : /* the rest of the scratch space is used for tuple data */
2553 : 497268 : tupledata = scratchptr;
2554 : :
2555 : : /* check that the mutually exclusive flags are not both set */
136 melanieplageman@gmai 2556 [ + + - + ]: 497268 : Assert(!(clear_all_visible && all_frozen_set));
2557 : :
2141 tomas.vondra@postgre 2558 : 497268 : xlrec->flags = 0;
136 melanieplageman@gmai 2559 [ + + ]: 497268 : if (clear_all_visible)
2141 tomas.vondra@postgre 2560 : 7439 : xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
2561 : :
2562 : : /*
2563 : : * We don't have to worry about including a conflict xid in the
2564 : : * WAL record, as HEAP_INSERT_FROZEN intentionally violates
2565 : : * visibility rules.
2566 : : */
2567 [ + + ]: 497268 : if (all_frozen_set)
2568 : 21 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2569 : :
5498 heikki.linnakangas@i 2570 : 497268 : xlrec->ntuples = nthispage;
2571 : :
2572 : : /*
2573 : : * Write out an xl_multi_insert_tuple and the tuple data itself
2574 : : * for each tuple.
2575 : : */
2576 [ + + ]: 2131322 : for (i = 0; i < nthispage; i++)
2577 : : {
2578 : 1634054 : HeapTuple heaptup = heaptuples[ndone + i];
2579 : : xl_multi_insert_tuple *tuphdr;
2580 : : int datalen;
2581 : :
2582 [ + + ]: 1634054 : if (!init)
2583 : 1000243 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2584 : : /* xl_multi_insert_tuple needs two-byte alignment. */
2585 : 1634054 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2586 : 1634054 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2587 : :
2588 : 1634054 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2589 : 1634054 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2590 : 1634054 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2591 : :
2592 : : /* write bitmap [+ padding] [+ oid] + data */
4298 tgl@sss.pgh.pa.us 2593 : 1634054 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
5498 heikki.linnakangas@i 2594 : 1634054 : memcpy(scratchptr,
4298 tgl@sss.pgh.pa.us 2595 : 1634054 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2596 : : datalen);
5498 heikki.linnakangas@i 2597 : 1634054 : tuphdr->datalen = datalen;
2598 : 1634054 : scratchptr += datalen;
2599 : : }
2600 : 497268 : totaldatalen = scratchptr - tupledata;
3010 tgl@sss.pgh.pa.us 2601 [ - + ]: 497268 : Assert((scratchptr - scratch.data) < BLCKSZ);
2602 : :
4736 rhaas@postgresql.org 2603 [ + + ]: 497268 : if (need_tuple_data)
4222 andres@anarazel.de 2604 : 75 : xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2605 : :
2606 : : /*
2607 : : * Signal that this is the last xl_heap_multi_insert record
2608 : : * emitted by this call to heap_multi_insert(). Needed for logical
2609 : : * decoding so it knows when to cleanup temporary data.
2610 : : */
4391 heikki.linnakangas@i 2611 [ + + ]: 497268 : if (ndone + nthispage == ntuples)
4222 andres@anarazel.de 2612 : 482154 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2613 : :
5498 heikki.linnakangas@i 2614 [ + + ]: 497268 : if (init)
2615 : : {
2616 : 14887 : info |= XLOG_HEAP_INIT_PAGE;
4391 2617 : 14887 : bufflags |= REGBUF_WILL_INIT;
2618 : : }
2619 : :
2620 : : /*
2621 : : * If we're doing logical decoding, include the new tuple data
2622 : : * even if we take a full-page image of the page.
2623 : : */
2624 [ + + ]: 497268 : if (need_tuple_data)
2625 : 75 : bufflags |= REGBUF_KEEP_DATA;
2626 : :
2627 : 497268 : XLogBeginInsert();
655 peter@eisentraut.org 2628 : 497268 : XLogRegisterData(xlrec, tupledata - scratch.data);
136 melanieplageman@gmai 2629 : 497268 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_HEAP, buffer,
2630 : 497268 : REGBUF_STANDARD | bufflags);
2631 [ + + + + ]: 497268 : if (all_frozen_set || vmbuffer_modified)
2632 : 7460 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_VM, vmbuffer, 0);
2633 : :
2634 : 497268 : XLogRegisterBufData(HEAP_MULTI_INSERT_BLKREF_HEAP, tupledata,
2635 : : totaldatalen);
2636 : :
2637 : : /* filtering by origin on a row level is much more efficient */
3628 andres@anarazel.de 2638 : 497268 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2639 : :
4391 heikki.linnakangas@i 2640 : 497268 : recptr = XLogInsert(RM_HEAP2_ID, info);
2641 : :
5498 2642 : 497268 : PageSetLSN(page, recptr);
136 melanieplageman@gmai 2643 [ + + + + ]: 497268 : if (all_frozen_set || vmbuffer_modified)
2644 : : {
415 2645 [ - + ]: 7460 : Assert(BufferIsDirty(vmbuffer));
2646 : 7460 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2647 : : }
2648 : : }
2649 : :
5498 heikki.linnakangas@i 2650 [ - + ]: 501168 : END_CRIT_SECTION();
2651 : :
2652 : : /*
2653 : : * We locked vmbuffer if clear_all_visible was true regardless of
2654 : : * whether or not we ended up modifying the vmbuffer.
2655 : : */
136 melanieplageman@gmai 2656 [ + + + + ]: 501168 : if (all_frozen_set || clear_all_visible)
415 2657 : 9105 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2658 : :
2141 tomas.vondra@postgre 2659 : 501168 : UnlockReleaseBuffer(buffer);
5498 heikki.linnakangas@i 2660 : 501168 : ndone += nthispage;
2661 : :
2662 : : /*
2663 : : * NB: Only release vmbuffer after inserting all tuples - it's fairly
2664 : : * likely that we'll insert into subsequent heap pages that are likely
2665 : : * to use the same vm page.
2666 : : */
2667 : : }
2668 : :
2669 : : /* We're done with inserting all tuples, so release the last vmbuffer. */
2141 tomas.vondra@postgre 2670 [ + + ]: 482609 : if (vmbuffer != InvalidBuffer)
2671 : 7440 : ReleaseBuffer(vmbuffer);
2672 : :
2673 : : /*
2674 : : * We're done with the actual inserts. Check for conflicts again, to
2675 : : * ensure that all rw-conflicts in to these inserts are detected. Without
2676 : : * this final check, a sequential scan of the heap may have locked the
2677 : : * table after the "before" check, missing one opportunity to detect the
2678 : : * conflict, and then scanned the table before the new tuples were there,
2679 : : * missing the other chance to detect the conflict.
2680 : : *
2681 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2682 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2683 : : * page locks are only consolidated versions of tuple locks; they do not
2684 : : * lock "gaps" as index page locks do. So we don't need to specify a
2685 : : * buffer when making the call.
2686 : : */
2496 tmunro@postgresql.or 2687 : 482609 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2688 : :
2689 : : /*
2690 : : * If tuples are cacheable, mark them for invalidation from the caches in
2691 : : * case we abort. Note it is OK to do this after releasing the buffer,
2692 : : * because the heaptuples data structure is all in local memory, not in
2693 : : * the shared buffer.
2694 : : */
4748 rhaas@postgresql.org 2695 [ + + ]: 482609 : if (IsCatalogRelation(relation))
2696 : : {
5498 heikki.linnakangas@i 2697 [ + + ]: 1607367 : for (i = 0; i < ntuples; i++)
2698 : 1126263 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2699 : : }
2700 : :
2701 : : /* copy t_self fields back to the caller's slots */
5402 2702 [ + + ]: 2323839 : for (i = 0; i < ntuples; i++)
2795 andres@anarazel.de 2703 : 1841230 : slots[i]->tts_tid = heaptuples[i]->t_self;
2704 : :
5498 heikki.linnakangas@i 2705 : 482609 : pgstat_count_heap_insert(relation, ntuples);
2706 : 482609 : }
2707 : :
2708 : : /*
2709 : : * simple_heap_insert - insert a tuple
2710 : : *
2711 : : * Currently, this routine differs from heap_insert only in supplying
2712 : : * a default command ID and not allowing access to the speedup options.
2713 : : *
2714 : : * This should be used rather than using heap_insert directly in most places
2715 : : * where we are modifying system catalogs.
2716 : : */
2717 : : void
8957 tgl@sss.pgh.pa.us 2718 : 1127128 : simple_heap_insert(Relation relation, HeapTuple tup)
2719 : : {
2930 andres@anarazel.de 2720 : 1127128 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
8957 tgl@sss.pgh.pa.us 2721 : 1127128 : }
2722 : :
2723 : : /*
2724 : : * Given infomask/infomask2, compute the bits that must be saved in the
2725 : : * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2726 : : * xl_heap_lock_updated WAL records.
2727 : : *
2728 : : * See fix_infomask_from_infobits.
2729 : : */
2730 : : static uint8
5057 alvherre@alvh.no-ip. 2731 : 6549757 : compute_infobits(uint16 infomask, uint16 infomask2)
2732 : : {
2733 : : return
2734 : 6549757 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2735 : 6549757 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2736 : 6549757 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2737 : : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2738 : 13099514 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2739 : : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2740 : 6549757 : XLHL_KEYS_UPDATED : 0);
2741 : : }
2742 : :
2743 : : /*
2744 : : * Given two versions of the same t_infomask for a tuple, compare them and
2745 : : * return whether the relevant status for a tuple Xmax has changed. This is
2746 : : * used after a buffer lock has been released and reacquired: we want to ensure
2747 : : * that the tuple state continues to be the same it was when we previously
2748 : : * examined it.
2749 : : *
2750 : : * Note the Xmax field itself must be compared separately.
2751 : : */
2752 : : static inline bool
4601 2753 : 5432 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2754 : : {
4589 bruce@momjian.us 2755 : 5432 : const uint16 interesting =
2756 : : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2757 : :
4601 alvherre@alvh.no-ip. 2758 [ + + ]: 5432 : if ((new_infomask & interesting) != (old_infomask & interesting))
2759 : 15 : return true;
2760 : :
2761 : 5417 : return false;
2762 : : }
2763 : :
2764 : : /*
2765 : : * heap_delete - delete a tuple
2766 : : *
2767 : : * See table_tuple_delete() for an explanation of the parameters, except that
2768 : : * this routine directly takes a tuple rather than a slot.
2769 : : *
2770 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2771 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2772 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2773 : : * generated by another transaction).
2774 : : */
2775 : : TM_Result
394 peter@eisentraut.org 2776 : 1893077 : heap_delete(Relation relation, const ItemPointerData *tid,
2777 : : CommandId cid, uint32 options, Snapshot crosscheck,
2778 : : bool wait, TM_FailureData *tmfd)
2779 : : {
2780 : : TM_Result result;
8108 tgl@sss.pgh.pa.us 2781 : 1893077 : TransactionId xid = GetCurrentTransactionId();
2782 : : ItemId lp;
2783 : : HeapTupleData tp;
2784 : : Page page;
2785 : : BlockNumber block;
2786 : : Buffer buffer;
5639 rhaas@postgresql.org 2787 : 1893077 : Buffer vmbuffer = InvalidBuffer;
136 melanieplageman@gmai 2788 : 1893077 : bool vmbuffer_modified = false;
2789 : : TransactionId new_xmax;
2790 : : uint16 new_infomask,
2791 : : new_infomask2;
241 alvherre@kurilemu.de 2792 : 1893077 : bool changingPart = (options & TABLE_DELETE_CHANGING_PARTITION) != 0;
236 2793 : 1893077 : bool walLogical = (options & TABLE_DELETE_NO_LOGICAL) == 0;
7882 tgl@sss.pgh.pa.us 2794 : 1893077 : bool have_tuple_lock = false;
2795 : : bool iscombo;
136 melanieplageman@gmai 2796 : 1893077 : bool clear_all_visible = false;
4589 bruce@momjian.us 2797 : 1893077 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
4736 rhaas@postgresql.org 2798 : 1893077 : bool old_key_copied = false;
2799 : :
10674 bruce@momjian.us 2800 [ - + ]: 1893077 : Assert(ItemPointerIsValid(tid));
2801 : :
547 nathan@postgresql.or 2802 : 1893077 : AssertHasSnapshotForToast(relation);
2803 : :
2804 : : /*
2805 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
2806 : : * Other workers might need that combo CID for visibility checks, and we
2807 : : * have no provision for broadcasting it to them.
2808 : : */
4230 rhaas@postgresql.org 2809 [ - + ]: 1893077 : if (IsInParallelMode())
4230 rhaas@postgresql.org 2810 [ # # ]:UBC 0 : ereport(ERROR,
2811 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2812 : : errmsg("cannot delete tuples during a parallel operation")));
2813 : :
5639 rhaas@postgresql.org 2814 :CBC 1893077 : block = ItemPointerGetBlockNumber(tid);
2815 : 1893077 : buffer = ReadBuffer(relation, block);
3874 kgrittn@postgresql.o 2816 : 1893077 : page = BufferGetPage(buffer);
2817 : :
2818 : : /*
2819 : : * Before locking the buffer, pin the visibility map page if it appears to
2820 : : * be necessary. Since we haven't got the lock yet, someone else might be
2821 : : * in the middle of changing this, so we'll need to recheck after we have
2822 : : * the lock.
2823 : : */
5639 rhaas@postgresql.org 2824 [ + + ]: 1893077 : if (PageIsAllVisible(page))
2825 : 3149 : visibilitymap_pin(relation, block, &vmbuffer);
2826 : :
10210 vadim4o@yahoo.com 2827 : 1893077 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2828 : :
1528 jdavis@postgresql.or 2829 : 1893077 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2830 [ - + ]: 1893077 : Assert(ItemIdIsNormal(lp));
2831 : :
2832 : 1893077 : tp.t_tableOid = RelationGetRelid(relation);
2833 : 1893077 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2834 : 1893077 : tp.t_len = ItemIdGetLength(lp);
2835 : 1893077 : tp.t_self = *tid;
2836 : :
2837 : 1 : l1:
2838 : :
2839 : : /*
2840 : : * If we didn't pin the visibility map page and the page has become all
2841 : : * visible while we were busy locking the buffer, we'll have to unlock and
2842 : : * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2843 : : * unfortunate, but hopefully shouldn't happen often.
2844 : : */
5639 rhaas@postgresql.org 2845 [ + + - + ]: 1893078 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2846 : : {
5639 rhaas@postgresql.org 2847 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2848 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
2849 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2850 : : }
2851 : :
4877 rhaas@postgresql.org 2852 :CBC 1893078 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2853 : :
2807 andres@anarazel.de 2854 [ - + ]: 1893078 : if (result == TM_Invisible)
2855 : : {
7547 tgl@sss.pgh.pa.us 2856 :UBC 0 : UnlockReleaseBuffer(buffer);
4136 2857 [ # # ]: 0 : ereport(ERROR,
2858 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2859 : : errmsg("attempted to delete invisible tuple")));
2860 : : }
961 akorotkov@postgresql 2861 [ + + + - ]:CBC 1893078 : else if (result == TM_BeingModified && wait)
2862 : : {
2863 : : TransactionId xwait;
2864 : : uint16 infomask;
2865 : :
2866 : : /* must copy state data before unlocking buffer */
5057 alvherre@alvh.no-ip. 2867 : 40732 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
7882 tgl@sss.pgh.pa.us 2868 : 40732 : infomask = tp.t_data->t_infomask;
2869 : :
2870 : : /*
2871 : : * Sleep until concurrent transaction ends -- except when there's a
2872 : : * single locker and it's our own transaction. Note we don't care
2873 : : * which lock mode the locker has, because we need the strongest one.
2874 : : *
2875 : : * Before sleeping, we need to acquire tuple lock to establish our
2876 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
2877 : : * release us when we are next-in-line for the tuple.
2878 : : *
2879 : : * If we are forced to "start over" below, we keep the tuple lock;
2880 : : * this arranges that we stay at the head of the line while rechecking
2881 : : * tuple state.
2882 : : */
7884 2883 [ + + ]: 40732 : if (infomask & HEAP_XMAX_IS_MULTI)
2884 : : {
2720 alvherre@alvh.no-ip. 2885 : 9 : bool current_is_member = false;
2886 : :
4250 2887 [ + - ]: 9 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2888 : : LockTupleExclusive, ¤t_is_member))
2889 : : {
2890 : 9 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2891 : :
2892 : : /*
2893 : : * Acquire the lock, if necessary (but skip it when we're
2894 : : * requesting a lock and already have one; avoids deadlock).
2895 : : */
2720 2896 [ + + ]: 9 : if (!current_is_member)
2897 : 7 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2898 : : LockWaitBlock, &have_tuple_lock);
2899 : :
2900 : : /* wait for multixact */
4250 2901 : 9 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2902 : : relation, &(tp.t_self), XLTW_Delete,
2903 : : NULL);
2904 : 9 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2905 : :
2906 : : /*
2907 : : * If xwait had just locked the tuple then some other xact
2908 : : * could update this tuple before we get to this point. Check
2909 : : * for xmax change, and start over if so.
2910 : : *
2911 : : * We also must start over if we didn't pin the VM page, and
2912 : : * the page has become all visible.
2913 : : */
1528 jdavis@postgresql.or 2914 [ + - + - : 18 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ - ]
2915 [ - + ]: 18 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4250 alvherre@alvh.no-ip. 2916 : 9 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2917 : : xwait))
4250 alvherre@alvh.no-ip. 2918 :UBC 0 : goto l1;
2919 : : }
2920 : :
2921 : : /*
2922 : : * You might think the multixact is necessarily done here, but not
2923 : : * so: it could have surviving members, namely our own xact or
2924 : : * other subxacts of this backend. It is legal for us to delete
2925 : : * the tuple in either case, however (the latter case is
2926 : : * essentially a situation of upgrading our former shared lock to
2927 : : * exclusive). We don't bother changing the on-disk hint bits
2928 : : * since we are about to overwrite the xmax altogether.
2929 : : */
2930 : : }
4250 alvherre@alvh.no-ip. 2931 [ + + ]:CBC 40723 : else if (!TransactionIdIsCurrentTransactionId(xwait))
2932 : : {
2933 : : /*
2934 : : * Wait for regular transaction to end; but first, acquire tuple
2935 : : * lock.
2936 : : */
2937 : 57 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2938 : 57 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2939 : : LockWaitBlock, &have_tuple_lock);
4315 heikki.linnakangas@i 2940 : 57 : XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
7884 tgl@sss.pgh.pa.us 2941 : 53 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2942 : :
2943 : : /*
2944 : : * xwait is done, but if xwait had just locked the tuple then some
2945 : : * other xact could update this tuple before we get to this point.
2946 : : * Check for xmax change, and start over if so.
2947 : : *
2948 : : * We also must start over if we didn't pin the VM page, and the
2949 : : * page has become all visible.
2950 : : */
1528 jdavis@postgresql.or 2951 [ + - + - : 106 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ + ]
2952 [ - + ]: 105 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
5057 alvherre@alvh.no-ip. 2953 : 52 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2954 : : xwait))
7884 tgl@sss.pgh.pa.us 2955 : 1 : goto l1;
2956 : :
2957 : : /* Otherwise check if it committed or aborted */
7046 2958 : 52 : UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2959 : : }
2960 : :
2961 : : /*
2962 : : * We may overwrite if previous xmax aborted, or if it committed but
2963 : : * only locked the tuple without updating it.
2964 : : */
5057 alvherre@alvh.no-ip. 2965 [ + + + + ]: 81434 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2966 [ + + ]: 40744 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2967 : 37 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2807 andres@anarazel.de 2968 : 40695 : result = TM_Ok;
2105 alvherre@alvh.no-ip. 2969 [ + + ]: 32 : else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2807 andres@anarazel.de 2970 : 27 : result = TM_Updated;
2971 : : else
2972 : 5 : result = TM_Deleted;
2973 : : }
2974 : :
2975 : : /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2976 [ + + ]: 1893073 : if (result != TM_Ok)
2977 : : {
2978 [ + + + + : 73 : Assert(result == TM_SelfModified ||
- + - - ]
2979 : : result == TM_Updated ||
2980 : : result == TM_Deleted ||
2981 : : result == TM_BeingModified);
7770 tgl@sss.pgh.pa.us 2982 [ - + ]: 73 : Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2807 andres@anarazel.de 2983 [ + + - + ]: 73 : Assert(result != TM_Updated ||
2984 : : !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2985 : : }
2986 : :
1096 heikki.linnakangas@i 2987 [ + + + - ]: 1893073 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
2988 : : {
2989 : : /* Perform additional check for transaction-snapshot mode RI updates */
2990 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2991 : 1 : result = TM_Updated;
2992 : : }
2993 : :
2994 [ + + ]: 1893073 : if (result != TM_Ok)
2995 : : {
2807 andres@anarazel.de 2996 : 74 : tmfd->ctid = tp.t_data->t_ctid;
2997 : 74 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2998 [ + + ]: 74 : if (result == TM_SelfModified)
2999 : 28 : tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
3000 : : else
3001 : 46 : tmfd->cmax = InvalidCommandId;
961 akorotkov@postgresql 3002 : 74 : UnlockReleaseBuffer(buffer);
7882 tgl@sss.pgh.pa.us 3003 [ + + ]: 74 : if (have_tuple_lock)
5057 alvherre@alvh.no-ip. 3004 : 32 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
5639 rhaas@postgresql.org 3005 [ - + ]: 74 : if (vmbuffer != InvalidBuffer)
5639 rhaas@postgresql.org 3006 :UBC 0 : ReleaseBuffer(vmbuffer);
10210 vadim4o@yahoo.com 3007 :CBC 74 : return result;
3008 : : }
3009 : :
3010 : : /*
3011 : : * We're about to do the actual delete -- check for conflict first, to
3012 : : * avoid possibly having to roll back work we've just done.
3013 : : *
3014 : : * This is safe without a recheck as long as there is no possibility of
3015 : : * another process scanning the page between this check and the delete
3016 : : * being visible to the scan (i.e., an exclusive buffer content lock is
3017 : : * continuously held from this point until the tuple delete is visible).
3018 : : */
2496 tmunro@postgresql.or 3019 : 1892999 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
3020 : :
3021 : : /* replace cid with a combo CID if necessary */
7232 tgl@sss.pgh.pa.us 3022 : 1892985 : HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
3023 : :
3024 : : /*
3025 : : * Compute replica identity tuple before entering the critical section so
3026 : : * we don't PANIC upon a memory allocation failure.
3027 : : */
236 alvherre@kurilemu.de 3028 : 1892985 : old_key_tuple = walLogical ?
3029 [ + + ]: 1892985 : ExtractReplicaIdentity(relation, &tp, true, &old_key_copied) : NULL;
3030 : :
3031 : : /*
3032 : : * If this is the first possibly-multixact-able operation in the current
3033 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
3034 : : * certain that the transaction will never become a member of any older
3035 : : * MultiXactIds than that. (We have to do this even if we end up just
3036 : : * using our own TransactionId below, since some other backend could
3037 : : * incorporate our XID into a MultiXact immediately afterwards.)
3038 : : */
4621 heikki.linnakangas@i 3039 : 1892985 : MultiXactIdSetOldestMember();
3040 : :
3041 : 1892985 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
3042 : 1892985 : tp.t_data->t_infomask, tp.t_data->t_infomask2,
3043 : : xid, LockTupleExclusive, true,
3044 : : &new_xmax, &new_infomask, &new_infomask2);
3045 : :
3046 : : /* Lock the VM before entering the critical section */
136 melanieplageman@gmai 3047 [ + + ]: 1892985 : if (PageIsAllVisible(page))
3048 : : {
3049 : 3149 : clear_all_visible = true;
3050 : 3149 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3051 : : }
3052 : :
9451 tgl@sss.pgh.pa.us 3053 : 1892985 : START_CRIT_SECTION();
3054 : :
3055 : : /*
3056 : : * If this transaction commits, the tuple will become DEAD sooner or
3057 : : * later. Set flag that this page is a candidate for pruning once our xid
3058 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
3059 : : * the subsequent page pruning will be a no-op and the hint will be
3060 : : * cleared.
3061 : : */
6712 3062 [ - + + + : 1892985 : PageSetPrunable(page, xid);
+ + ]
3063 : :
136 melanieplageman@gmai 3064 [ + + ]: 1892985 : if (clear_all_visible)
3065 : : {
3066 : : /* It's possible the VM bits were already clear */
136 melanieplageman@gmai 3067 [ + - ]:GNC 3149 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(buffer),
3068 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
136 melanieplageman@gmai 3069 :CBC 3149 : vmbuffer_modified = true;
3070 : :
6569 heikki.linnakangas@i 3071 : 3149 : PageClearAllVisible(page);
3072 : : }
3073 : :
3074 : : /* store transaction information of xact deleting the tuple */
5057 alvherre@alvh.no-ip. 3075 : 1892985 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3076 : 1892985 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3077 : 1892985 : tp.t_data->t_infomask |= new_infomask;
3078 : 1892985 : tp.t_data->t_infomask2 |= new_infomask2;
7009 tgl@sss.pgh.pa.us 3079 : 1892985 : HeapTupleHeaderClearHotUpdated(tp.t_data);
5057 alvherre@alvh.no-ip. 3080 : 1892985 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
7232 tgl@sss.pgh.pa.us 3081 : 1892985 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3082 : : /* Make sure there is no forward chain link in t_ctid */
8873 3083 : 1892985 : tp.t_data->t_ctid = tp.t_self;
3084 : :
3085 : : /* Signal that this is actually a move into another partition */
3157 andres@anarazel.de 3086 [ + + ]: 1892985 : if (changingPart)
3087 : 651 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
3088 : :
7547 tgl@sss.pgh.pa.us 3089 : 1892985 : MarkBufferDirty(buffer);
3090 : :
3091 : : /*
3092 : : * XLOG stuff
3093 : : *
3094 : : * NB: heap_abort_speculative() uses the same xlog record and replay
3095 : : * routines.
3096 : : */
5829 rhaas@postgresql.org 3097 [ + + + + : 1892985 : if (RelationNeedsWAL(relation))
+ - + + ]
3098 : : {
3099 : : xl_heap_delete xlrec;
3100 : : xl_heap_header xlhdr;
3101 : : XLogRecPtr recptr;
3102 : :
3103 : : /*
3104 : : * For logical decode we need combo CIDs to properly decode the
3105 : : * catalog
3106 : : */
4736 3107 [ + + + + : 1784573 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- - + ]
3108 : 9097 : log_heap_new_cid(relation, &tp);
3109 : :
3157 andres@anarazel.de 3110 : 1784573 : xlrec.flags = 0;
136 melanieplageman@gmai 3111 [ + + ]: 1784573 : if (clear_all_visible)
3157 andres@anarazel.de 3112 : 2099 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3113 [ + + ]: 1784573 : if (changingPart)
3114 : 651 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
5057 alvherre@alvh.no-ip. 3115 : 3569146 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3116 : 1784573 : tp.t_data->t_infomask2);
4391 heikki.linnakangas@i 3117 : 1784573 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
5057 alvherre@alvh.no-ip. 3118 : 1784573 : xlrec.xmax = new_xmax;
3119 : :
4391 heikki.linnakangas@i 3120 [ + + ]: 1784573 : if (old_key_tuple != NULL)
3121 : : {
3122 [ + + ]: 47037 : if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4222 andres@anarazel.de 3123 : 132 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
3124 : : else
3125 : 46905 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
3126 : : }
3127 : :
3128 : : /*
3129 : : * Mark the change as not-for-logical-decoding if caller requested so.
3130 : : *
3131 : : * (This is used for changes that affect relations not visible to
3132 : : * other transactions, such as the transient table during concurrent
3133 : : * repack.)
3134 : : */
236 alvherre@kurilemu.de 3135 [ + + ]: 1784573 : if (!walLogical)
3136 : 4 : xlrec.flags |= XLH_DELETE_NO_LOGICAL;
3137 : :
4391 heikki.linnakangas@i 3138 : 1784573 : XLogBeginInsert();
655 peter@eisentraut.org 3139 : 1784573 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3140 : :
136 melanieplageman@gmai 3141 : 1784573 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3142 : :
3143 : : /*
3144 : : * Log replica identity of the deleted tuple if there is one
3145 : : */
4736 rhaas@postgresql.org 3146 [ + + ]: 1784573 : if (old_key_tuple != NULL)
3147 : : {
3148 : 47037 : xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3149 : 47037 : xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3150 : 47037 : xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3151 : :
655 peter@eisentraut.org 3152 : 47037 : XLogRegisterData(&xlhdr, SizeOfHeapHeader);
4391 heikki.linnakangas@i 3153 : 47037 : XLogRegisterData((char *) old_key_tuple->t_data
3154 : : + SizeofHeapTupleHeader,
3155 : 47037 : old_key_tuple->t_len
3156 : : - SizeofHeapTupleHeader);
3157 : : }
3158 : :
3159 : : /* filtering by origin on a row level is much more efficient */
3628 andres@anarazel.de 3160 : 1784573 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3161 : :
136 melanieplageman@gmai 3162 [ + + ]: 1784573 : if (vmbuffer_modified)
3163 : 2099 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_VM, vmbuffer, 0);
3164 : :
4391 heikki.linnakangas@i 3165 : 1784573 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3166 : :
6712 tgl@sss.pgh.pa.us 3167 : 1784573 : PageSetLSN(page, recptr);
3168 : :
136 melanieplageman@gmai 3169 [ + + ]: 1784573 : if (vmbuffer_modified)
3170 : 2099 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3171 : : }
3172 : :
9451 tgl@sss.pgh.pa.us 3173 [ - + ]: 1892985 : END_CRIT_SECTION();
3174 : :
3175 : : /*
3176 : : * Release VM lock first, since it covers many heap blocks. We locked
3177 : : * vmbuffer if clear_all_visible was true regardless of whether or not we
3178 : : * ended up modifying the vmbuffer.
3179 : : */
136 melanieplageman@gmai 3180 [ + + ]: 1892985 : if (clear_all_visible)
3181 : 3149 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3182 : :
9448 tgl@sss.pgh.pa.us 3183 : 1892985 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3184 : :
5639 rhaas@postgresql.org 3185 [ + + ]: 1892985 : if (vmbuffer != InvalidBuffer)
3186 : 3149 : ReleaseBuffer(vmbuffer);
3187 : :
3188 : : /*
3189 : : * If the tuple has toasted out-of-line attributes, we need to delete
3190 : : * those items too. We have to do this before releasing the buffer
3191 : : * because we need to look at the contents of the tuple, but it's OK to
3192 : : * release the content lock on the buffer first.
3193 : : */
5018 kgrittn@postgresql.o 3194 [ + + ]: 1892985 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3195 [ + + ]: 4643 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3196 : : {
3197 : : /* toast table entries should never be recursively toasted */
7179 tgl@sss.pgh.pa.us 3198 [ - + ]: 4630 : Assert(!HeapTupleHasExternal(&tp));
3199 : : }
3200 [ + + ]: 1888355 : else if (HeapTupleHasExternal(&tp))
2612 rhaas@postgresql.org 3201 : 541 : heap_toast_delete(relation, &tp, false);
3202 : :
3203 : : /*
3204 : : * Mark tuple for invalidation from system caches at next command
3205 : : * boundary. We have to do this before releasing the buffer because we
3206 : : * need to look at the contents of the tuple.
3207 : : */
5583 tgl@sss.pgh.pa.us 3208 : 1892985 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3209 : :
3210 : : /* Now we can release the buffer */
961 akorotkov@postgresql 3211 : 1892985 : ReleaseBuffer(buffer);
3212 : :
3213 : : /*
3214 : : * Release the lmgr tuple lock, if we had it.
3215 : : */
7882 tgl@sss.pgh.pa.us 3216 [ + + ]: 1892985 : if (have_tuple_lock)
5057 alvherre@alvh.no-ip. 3217 : 27 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3218 : :
7125 tgl@sss.pgh.pa.us 3219 : 1892985 : pgstat_count_heap_delete(relation);
3220 : :
4736 rhaas@postgresql.org 3221 [ + + + + ]: 1892985 : if (old_key_tuple != NULL && old_key_copied)
3222 : 46906 : heap_freetuple(old_key_tuple);
3223 : :
2807 andres@anarazel.de 3224 : 1892985 : return TM_Ok;
3225 : : }
3226 : :
3227 : : /*
3228 : : * simple_heap_delete - delete a tuple
3229 : : *
3230 : : * This routine may be used to delete a tuple when concurrent updates of
3231 : : * the target tuple are not expected (for example, because we have a lock
3232 : : * on the relation associated with the tuple). Any failure is reported
3233 : : * via ereport().
3234 : : */
3235 : : void
394 peter@eisentraut.org 3236 : 840342 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
3237 : : {
3238 : : TM_Result result;
3239 : : TM_FailureData tmfd;
3240 : :
8475 tgl@sss.pgh.pa.us 3241 : 840342 : result = heap_delete(relation, tid,
3242 : : GetCurrentCommandId(true),
3243 : : 0,
3244 : : InvalidSnapshot,
3245 : : true /* wait for commit */ ,
3246 : : &tmfd);
9440 3247 [ - + - - : 840342 : switch (result)
- ]
3248 : : {
2807 andres@anarazel.de 3249 :UBC 0 : case TM_SelfModified:
3250 : : /* Tuple was already updated in current command? */
8531 tgl@sss.pgh.pa.us 3251 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
3252 : : break;
3253 : :
2807 andres@anarazel.de 3254 :CBC 840342 : case TM_Ok:
3255 : : /* done successfully */
9440 tgl@sss.pgh.pa.us 3256 : 840342 : break;
3257 : :
2807 andres@anarazel.de 3258 :UBC 0 : case TM_Updated:
8531 tgl@sss.pgh.pa.us 3259 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
3260 : : break;
3261 : :
2807 andres@anarazel.de 3262 : 0 : case TM_Deleted:
3263 [ # # ]: 0 : elog(ERROR, "tuple concurrently deleted");
3264 : : break;
3265 : :
9440 tgl@sss.pgh.pa.us 3266 : 0 : default:
8531 3267 [ # # ]: 0 : elog(ERROR, "unrecognized heap_delete status: %u", result);
3268 : : break;
3269 : : }
9440 tgl@sss.pgh.pa.us 3270 :CBC 840342 : }
3271 : :
3272 : : /*
3273 : : * heap_update - replace a tuple
3274 : : *
3275 : : * See table_tuple_update() for an explanation of the parameters, except that
3276 : : * this routine directly takes a tuple rather than a slot.
3277 : : *
3278 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3279 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3280 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3281 : : * generated by another transaction).
3282 : : */
3283 : : TM_Result
394 peter@eisentraut.org 3284 : 2408938 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
3285 : : CommandId cid, uint32 options, Snapshot crosscheck, bool wait,
3286 : : TM_FailureData *tmfd, LockTupleMode *lockmode,
3287 : : TU_UpdateIndexes *update_indexes)
3288 : : {
3289 : : TM_Result result;
8108 tgl@sss.pgh.pa.us 3290 : 2408938 : TransactionId xid = GetCurrentTransactionId();
3291 : : Bitmapset *hot_attrs;
3292 : : Bitmapset *sum_attrs;
3293 : : Bitmapset *key_attrs;
3294 : : Bitmapset *id_attrs;
3295 : : Bitmapset *interesting_attrs;
3296 : : Bitmapset *modified_attrs;
3297 : : ItemId lp;
3298 : : HeapTupleData oldtup;
3299 : : HeapTuple heaptup;
4736 rhaas@postgresql.org 3300 : 2408938 : HeapTuple old_key_tuple = NULL;
3301 : 2408938 : bool old_key_copied = false;
236 alvherre@kurilemu.de 3302 : 2408938 : bool walLogical = (options & TABLE_UPDATE_NO_LOGICAL) == 0;
3303 : : Page page,
3304 : : newpage;
3305 : : BlockNumber block;
3306 : : MultiXactStatus mxact_status;
3307 : : Buffer buffer,
3308 : : newbuf,
5639 rhaas@postgresql.org 3309 : 2408938 : vmbuffer = InvalidBuffer,
3310 : 2408938 : vmbuffer_new = InvalidBuffer;
136 melanieplageman@gmai 3311 : 2408938 : bool unlock_vmbuffer = false;
3312 : 2408938 : bool unlock_vmbuffer_new = false;
3313 : : bool need_toast;
3314 : : Size newtupsize,
3315 : : pagefree;
7882 tgl@sss.pgh.pa.us 3316 : 2408938 : bool have_tuple_lock = false;
3317 : : bool iscombo;
7009 3318 : 2408938 : bool use_hot_update = false;
1349 tomas.vondra@postgre 3319 : 2408938 : bool summarized_update = false;
3320 : : bool key_intact;
136 melanieplageman@gmai 3321 : 2408938 : bool clear_all_visible = false;
3322 : 2408938 : bool clear_all_visible_new = false;
3323 : 2408938 : bool vmbuffer_modified = false;
3324 : 2408938 : bool vmbuffer_new_modified = false;
3325 : : bool checked_lockers;
3326 : : bool locker_remains;
1748 akapila@postgresql.o 3327 : 2408938 : bool id_has_external = false;
3328 : : TransactionId xmax_new_tuple,
3329 : : xmax_old_tuple;
3330 : : uint16 infomask_old_tuple,
3331 : : infomask2_old_tuple,
3332 : : infomask_new_tuple,
3333 : : infomask2_new_tuple;
3334 : :
10674 bruce@momjian.us 3335 [ - + ]: 2408938 : Assert(ItemPointerIsValid(otid));
3336 : :
3337 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2028 tgl@sss.pgh.pa.us 3338 [ - + ]: 2408938 : Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
3339 : : RelationGetNumberOfAttributes(relation));
3340 : :
547 nathan@postgresql.or 3341 : 2408938 : AssertHasSnapshotForToast(relation);
3342 : :
3343 : : /*
3344 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
3345 : : * Other workers might need that combo CID for visibility checks, and we
3346 : : * have no provision for broadcasting it to them.
3347 : : */
4230 rhaas@postgresql.org 3348 [ - + ]: 2408938 : if (IsInParallelMode())
4230 rhaas@postgresql.org 3349 [ # # ]:UBC 0 : ereport(ERROR,
3350 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3351 : : errmsg("cannot update tuples during a parallel operation")));
3352 : :
3353 : : #ifdef USE_ASSERT_CHECKING
795 noah@leadboat.com 3354 :CBC 2408938 : check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3355 : : #endif
3356 : :
3357 : : /*
3358 : : * Fetch the list of attributes to be checked for various operations.
3359 : : *
3360 : : * For HOT considerations, this is wasted effort if we fail to update or
3361 : : * have to put the new tuple on a different page. But we must compute the
3362 : : * list before obtaining buffer lock --- in the worst case, if we are
3363 : : * doing an update on one of the relevant system catalogs, we could
3364 : : * deadlock if we try to fetch the list later. In any case, the relcache
3365 : : * caches the data so this is usually pretty cheap.
3366 : : *
3367 : : * We also need columns used by the replica identity and columns that are
3368 : : * considered the "key" of rows in the table.
3369 : : *
3370 : : * Note that we get copies of each bitmap, so we need not worry about
3371 : : * relcache flush happening midway through.
3372 : : */
1349 tomas.vondra@postgre 3373 : 2408938 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3374 : : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3375 : 2408938 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3376 : : INDEX_ATTR_BITMAP_SUMMARIZED);
4736 rhaas@postgresql.org 3377 : 2408938 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3378 : 2408938 : id_attrs = RelationGetIndexAttrBitmap(relation,
3379 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
1828 pg@bowt.ie 3380 : 2408938 : interesting_attrs = NULL;
3381 : 2408938 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
1349 tomas.vondra@postgre 3382 : 2408938 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
1828 pg@bowt.ie 3383 : 2408938 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3384 : 2408938 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3385 : :
5639 rhaas@postgresql.org 3386 : 2408938 : block = ItemPointerGetBlockNumber(otid);
567 michael@paquier.xyz 3387 : 2408938 : INJECTION_POINT("heap_update-before-pin", NULL);
5639 rhaas@postgresql.org 3388 : 2408938 : buffer = ReadBuffer(relation, block);
3874 kgrittn@postgresql.o 3389 : 2408938 : page = BufferGetPage(buffer);
3390 : :
3391 : : /*
3392 : : * Before locking the buffer, pin the visibility map page if it appears to
3393 : : * be necessary. Since we haven't got the lock yet, someone else might be
3394 : : * in the middle of changing this, so we'll need to recheck after we have
3395 : : * the lock.
3396 : : */
5639 rhaas@postgresql.org 3397 [ + + ]: 2408938 : if (PageIsAllVisible(page))
3398 : 2741 : visibilitymap_pin(relation, block, &vmbuffer);
3399 : :
10210 vadim4o@yahoo.com 3400 : 2408938 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3401 : :
6712 tgl@sss.pgh.pa.us 3402 : 2408938 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3403 : :
3404 : : /*
3405 : : * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3406 : : * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3407 : : * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3408 : : * of which indicates concurrent pruning.
3409 : : *
3410 : : * Failing with TM_Updated would be most accurate. However, unlike other
3411 : : * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3412 : : * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3413 : : * does matter to SQL statements UPDATE and MERGE, those SQL statements
3414 : : * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3415 : : * TM_Updated and TM_Deleted affects only the wording of error messages.
3416 : : * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3417 : : * the specification of when tmfd->ctid is valid. Second, it creates
3418 : : * error log evidence that we took this branch.
3419 : : *
3420 : : * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3421 : : * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3422 : : * unrelated row, we'll fail with "duplicate key value violates unique".
3423 : : * XXX if otid is the live, newer version of the newtup row, we'll discard
3424 : : * changes originating in versions of this catalog row after the version
3425 : : * the caller got from syscache. See syscache-update-pruned.spec.
3426 : : */
672 noah@leadboat.com 3427 [ + + ]: 2408938 : if (!ItemIdIsNormal(lp))
3428 : : {
3429 [ - + ]: 1 : Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
3430 : :
3431 : 1 : UnlockReleaseBuffer(buffer);
3432 [ - + ]: 1 : Assert(!have_tuple_lock);
3433 [ + - ]: 1 : if (vmbuffer != InvalidBuffer)
3434 : 1 : ReleaseBuffer(vmbuffer);
3435 : 1 : tmfd->ctid = *otid;
3436 : 1 : tmfd->xmax = InvalidTransactionId;
3437 : 1 : tmfd->cmax = InvalidCommandId;
3438 : 1 : *update_indexes = TU_None;
3439 : :
3440 : 1 : bms_free(hot_attrs);
3441 : 1 : bms_free(sum_attrs);
3442 : 1 : bms_free(key_attrs);
3443 : 1 : bms_free(id_attrs);
3444 : : /* modified_attrs not yet initialized */
3445 : 1 : bms_free(interesting_attrs);
3446 : 1 : return TM_Deleted;
3447 : : }
3448 : :
3449 : : /*
3450 : : * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3451 : : * properly.
3452 : : */
5048 alvherre@alvh.no-ip. 3453 : 2408937 : oldtup.t_tableOid = RelationGetRelid(relation);
6712 tgl@sss.pgh.pa.us 3454 : 2408937 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
10228 vadim4o@yahoo.com 3455 : 2408937 : oldtup.t_len = ItemIdGetLength(lp);
3456 : 2408937 : oldtup.t_self = *otid;
3457 : :
3458 : : /* the new tuple is ready, except for this: */
5048 alvherre@alvh.no-ip. 3459 : 2408937 : newtup->t_tableOid = RelationGetRelid(relation);
3460 : :
3461 : : /*
3462 : : * Determine columns modified by the update. Additionally, identify
3463 : : * whether any of the unmodified replica identity key attributes in the
3464 : : * old tuple is externally stored or not. This is required because for
3465 : : * such attributes the flattened value won't be WAL logged as part of the
3466 : : * new tuple so we must include it as part of the old_key_tuple. See
3467 : : * ExtractReplicaIdentity.
3468 : : */
1748 akapila@postgresql.o 3469 : 2408937 : modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3470 : : id_attrs, &oldtup,
3471 : : newtup, &id_has_external);
3472 : :
3473 : : /*
3474 : : * If we're not updating any "key" column, we can grab a weaker lock type.
3475 : : * This allows for more concurrency when we are running simultaneously
3476 : : * with foreign key checks.
3477 : : *
3478 : : * Note that if a column gets detoasted while executing the update, but
3479 : : * the value ends up being the same, this test will fail and we will use
3480 : : * the stronger lock. This is acceptable; the important case to optimize
3481 : : * is updates that don't manipulate key columns, not those that
3482 : : * serendipitously arrive at the same key values.
3483 : : */
3531 alvherre@alvh.no-ip. 3484 [ + + ]: 2408937 : if (!bms_overlap(modified_attrs, key_attrs))
3485 : : {
3152 simon@2ndQuadrant.co 3486 : 2403063 : *lockmode = LockTupleNoKeyExclusive;
5057 alvherre@alvh.no-ip. 3487 : 2403063 : mxact_status = MultiXactStatusNoKeyUpdate;
3488 : 2403063 : key_intact = true;
3489 : :
3490 : : /*
3491 : : * If this is the first possibly-multixact-able operation in the
3492 : : * current transaction, set my per-backend OldestMemberMXactId
3493 : : * setting. We can be certain that the transaction will never become a
3494 : : * member of any older MultiXactIds than that. (We have to do this
3495 : : * even if we end up just using our own TransactionId below, since
3496 : : * some other backend could incorporate our XID into a MultiXact
3497 : : * immediately afterwards.)
3498 : : */
3499 : 2403063 : MultiXactIdSetOldestMember();
3500 : : }
3501 : : else
3502 : : {
3152 simon@2ndQuadrant.co 3503 : 5874 : *lockmode = LockTupleExclusive;
5057 alvherre@alvh.no-ip. 3504 : 5874 : mxact_status = MultiXactStatusUpdate;
3505 : 5874 : key_intact = false;
3506 : : }
3507 : :
3508 : : /*
3509 : : * Note: beyond this point, use oldtup not otid to refer to old tuple.
3510 : : * otid may very well point at newtup->t_self, which we will overwrite
3511 : : * with the new tuple's location, so there's great risk of confusion if we
3512 : : * use otid anymore.
3513 : : */
3514 : :
10210 vadim4o@yahoo.com 3515 : 1 : l2:
5057 alvherre@alvh.no-ip. 3516 : 2408938 : checked_lockers = false;
3517 : 2408938 : locker_remains = false;
4877 rhaas@postgresql.org 3518 : 2408938 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3519 : :
3520 : : /* see below about the "no wait" case */
961 akorotkov@postgresql 3521 [ + + - + ]: 2408938 : Assert(result != TM_BeingModified || wait);
3522 : :
2807 andres@anarazel.de 3523 [ - + ]: 2408938 : if (result == TM_Invisible)
3524 : : {
7547 tgl@sss.pgh.pa.us 3525 :UBC 0 : UnlockReleaseBuffer(buffer);
4136 3526 [ # # ]: 0 : ereport(ERROR,
3527 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3528 : : errmsg("attempted to update invisible tuple")));
3529 : : }
961 akorotkov@postgresql 3530 [ + + + - ]:CBC 2408938 : else if (result == TM_BeingModified && wait)
3531 : : {
3532 : : TransactionId xwait;
3533 : : uint16 infomask;
5057 alvherre@alvh.no-ip. 3534 : 36547 : bool can_continue = false;
3535 : :
3536 : : /*
3537 : : * XXX note that we don't consider the "no wait" case here. This
3538 : : * isn't a problem currently because no caller uses that case, but it
3539 : : * should be fixed if such a caller is introduced. It wasn't a
3540 : : * problem previously because this code would always wait, but now
3541 : : * that some tuple locks do not conflict with one of the lock modes we
3542 : : * use, it is possible that this case is interesting to handle
3543 : : * specially.
3544 : : *
3545 : : * This may cause failures with third-party code that calls
3546 : : * heap_update directly.
3547 : : */
3548 : :
3549 : : /* must copy state data before unlocking buffer */
3550 : 36547 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
7882 tgl@sss.pgh.pa.us 3551 : 36547 : infomask = oldtup.t_data->t_infomask;
3552 : :
3553 : : /*
3554 : : * Now we have to do something about the existing locker. If it's a
3555 : : * multi, sleep on it; we might be awakened before it is completely
3556 : : * gone (or even not sleep at all in some cases); we need to preserve
3557 : : * it as locker, unless it is gone completely.
3558 : : *
3559 : : * If it's not a multi, we need to check for sleeping conditions
3560 : : * before actually going to sleep. If the update doesn't conflict
3561 : : * with the locks, we just continue without sleeping (but making sure
3562 : : * it is preserved).
3563 : : *
3564 : : * Before sleeping, we need to acquire tuple lock to establish our
3565 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
3566 : : * release us when we are next-in-line for the tuple. Note we must
3567 : : * not acquire the tuple lock until we're sure we're going to sleep;
3568 : : * otherwise we're open for race conditions with other transactions
3569 : : * holding the tuple lock which sleep on us.
3570 : : *
3571 : : * If we are forced to "start over" below, we keep the tuple lock;
3572 : : * this arranges that we stay at the head of the line while rechecking
3573 : : * tuple state.
3574 : : */
7884 3575 [ + + ]: 36547 : if (infomask & HEAP_XMAX_IS_MULTI)
3576 : : {
3577 : : TransactionId update_xact;
3578 : : int remain;
2720 alvherre@alvh.no-ip. 3579 : 186 : bool current_is_member = false;
3580 : :
4250 3581 [ + + ]: 186 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3582 : : *lockmode, ¤t_is_member))
3583 : : {
3584 : 10 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3585 : :
3586 : : /*
3587 : : * Acquire the lock, if necessary (but skip it when we're
3588 : : * requesting a lock and already have one; avoids deadlock).
3589 : : */
2720 3590 [ + + ]: 10 : if (!current_is_member)
3591 : 2 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3592 : : LockWaitBlock, &have_tuple_lock);
3593 : :
3594 : : /* wait for multixact */
4250 3595 : 10 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3596 : : relation, &oldtup.t_self, XLTW_Update,
3597 : : &remain);
3598 : 10 : checked_lockers = true;
3599 : 10 : locker_remains = remain != 0;
3600 : 10 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3601 : :
3602 : : /*
3603 : : * If xwait had just locked the tuple then some other xact
3604 : : * could update this tuple before we get to this point. Check
3605 : : * for xmax change, and start over if so.
3606 : : */
3607 [ + - ]: 10 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3608 [ - + ]: 10 : infomask) ||
3447 tgl@sss.pgh.pa.us 3609 : 10 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3610 : : xwait))
4250 alvherre@alvh.no-ip. 3611 :UBC 0 : goto l2;
3612 : : }
3613 : :
3614 : : /*
3615 : : * Note that the multixact may not be done by now. It could have
3616 : : * surviving members; our own xact or other subxacts of this
3617 : : * backend, and also any other concurrent transaction that locked
3618 : : * the tuple with LockTupleKeyShare if we only got
3619 : : * LockTupleNoKeyExclusive. If this is the case, we have to be
3620 : : * careful to mark the updated tuple with the surviving members in
3621 : : * Xmax.
3622 : : *
3623 : : * Note that there could have been another update in the
3624 : : * MultiXact. In that case, we need to check whether it committed
3625 : : * or aborted. If it aborted we are safe to update it again;
3626 : : * otherwise there is an update conflict, and we have to return
3627 : : * TableTuple{Deleted, Updated} below.
3628 : : *
3629 : : * In the LockTupleExclusive case, we still need to preserve the
3630 : : * surviving members: those would include the tuple locks we had
3631 : : * before this one, which are important to keep in case this
3632 : : * subxact aborts.
3633 : : */
5057 alvherre@alvh.no-ip. 3634 [ + + ]:CBC 186 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3635 : 15 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3636 : : else
4250 3637 : 171 : update_xact = InvalidTransactionId;
3638 : :
44 heikki.linnakangas@i 3639 [ + + ]: 186 : if (!TransactionIdIsValid(update_xact))
3640 : : {
3641 : : /* no UPDATE in the MultiXact */
5057 alvherre@alvh.no-ip. 3642 : 171 : can_continue = true;
3643 : : }
3644 : : else
3645 : : {
3646 : : /*
3647 : : * There was another UPDATE. Did it abort?
3648 : : *
3649 : : * Note: We check !TransactionIdDidCommit() instead of
3650 : : * TransactionIdDidAbort(), to treat crashed transactions as
3651 : : * aborted. No TransactionIdIsInProgress() call is needed
3652 : : * here, because the MultiXactIdWait() call above already
3653 : : * waited for it to finish.
3654 : : */
44 heikki.linnakangas@i 3655 [ + + ]: 15 : if (!TransactionIdDidCommit(update_xact))
3656 : 8 : can_continue = true;
3657 : : }
3658 : : }
4250 alvherre@alvh.no-ip. 3659 [ + + ]: 36361 : else if (TransactionIdIsCurrentTransactionId(xwait))
3660 : : {
3661 : : /*
3662 : : * The only locker is ourselves; we can avoid grabbing the tuple
3663 : : * lock here, but must preserve our locking information.
3664 : : */
3665 : 36238 : checked_lockers = true;
3666 : 36238 : locker_remains = true;
3667 : 36238 : can_continue = true;
3668 : : }
3669 [ + + + + ]: 123 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3670 : : {
3671 : : /*
3672 : : * If it's just a key-share locker, and we're not changing the key
3673 : : * columns, we don't need to wait for it to end; but we need to
3674 : : * preserve it as locker.
3675 : : */
3676 : 30 : checked_lockers = true;
3677 : 30 : locker_remains = true;
3678 : 30 : can_continue = true;
3679 : : }
3680 : : else
3681 : : {
3682 : : /*
3683 : : * Wait for regular transaction to end; but first, acquire tuple
3684 : : * lock.
3685 : : */
3686 : 93 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3152 simon@2ndQuadrant.co 3687 : 93 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3688 : : LockWaitBlock, &have_tuple_lock);
4250 alvherre@alvh.no-ip. 3689 : 93 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3690 : : XLTW_Update);
3691 : 93 : checked_lockers = true;
3692 : 93 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3693 : :
3694 : : /*
3695 : : * xwait is done, but if xwait had just locked the tuple then some
3696 : : * other xact could update this tuple before we get to this point.
3697 : : * Check for xmax change, and start over if so.
3698 : : */
3699 [ + + - + ]: 185 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3700 : 92 : !TransactionIdEquals(xwait,
3701 : : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3702 : 1 : goto l2;
3703 : :
3704 : : /* Otherwise check if it committed or aborted */
3705 : 92 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3706 [ + + ]: 92 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
5057 3707 : 23 : can_continue = true;
3708 : : }
3709 : :
2807 andres@anarazel.de 3710 [ + + ]: 36546 : if (can_continue)
3711 : 36470 : result = TM_Ok;
2105 alvherre@alvh.no-ip. 3712 [ + + ]: 76 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
2807 andres@anarazel.de 3713 : 70 : result = TM_Updated;
3714 : : else
3715 : 6 : result = TM_Deleted;
3716 : : }
3717 : :
3718 : : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3719 [ + + ]: 2408937 : if (result != TM_Ok)
3720 : : {
3721 [ + + + + : 191 : Assert(result == TM_SelfModified ||
- + - - ]
3722 : : result == TM_Updated ||
3723 : : result == TM_Deleted ||
3724 : : result == TM_BeingModified);
7770 tgl@sss.pgh.pa.us 3725 [ - + ]: 191 : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
2807 andres@anarazel.de 3726 [ + + - + ]: 191 : Assert(result != TM_Updated ||
3727 : : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3728 : : }
3729 : :
1096 heikki.linnakangas@i 3730 [ + + + - ]: 2408937 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3731 : : {
3732 : : /* Perform additional check for transaction-snapshot mode RI updates */
3733 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3734 : 1 : result = TM_Updated;
3735 : : }
3736 : :
3737 [ + + ]: 2408937 : if (result != TM_Ok)
3738 : : {
2807 andres@anarazel.de 3739 : 192 : tmfd->ctid = oldtup.t_data->t_ctid;
3740 : 192 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3741 [ + + ]: 192 : if (result == TM_SelfModified)
3742 : 69 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3743 : : else
3744 : 123 : tmfd->cmax = InvalidCommandId;
961 akorotkov@postgresql 3745 : 192 : UnlockReleaseBuffer(buffer);
7882 tgl@sss.pgh.pa.us 3746 [ + + ]: 192 : if (have_tuple_lock)
3152 simon@2ndQuadrant.co 3747 : 69 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
5639 rhaas@postgresql.org 3748 [ - + ]: 192 : if (vmbuffer != InvalidBuffer)
5639 rhaas@postgresql.org 3749 :UBC 0 : ReleaseBuffer(vmbuffer);
1349 tomas.vondra@postgre 3750 :CBC 192 : *update_indexes = TU_None;
3751 : :
7009 tgl@sss.pgh.pa.us 3752 : 192 : bms_free(hot_attrs);
1349 tomas.vondra@postgre 3753 : 192 : bms_free(sum_attrs);
5057 alvherre@alvh.no-ip. 3754 : 192 : bms_free(key_attrs);
3748 tgl@sss.pgh.pa.us 3755 : 192 : bms_free(id_attrs);
3531 alvherre@alvh.no-ip. 3756 : 192 : bms_free(modified_attrs);
3757 : 192 : bms_free(interesting_attrs);
10210 vadim4o@yahoo.com 3758 : 192 : return result;
3759 : : }
3760 : :
3761 : : /*
3762 : : * If we didn't pin the visibility map page and the page has become all
3763 : : * visible while we were busy locking the buffer, or during some
3764 : : * subsequent window during which we had it unlocked, we'll have to unlock
3765 : : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3766 : : * bit unfortunate, especially since we'll now have to recheck whether the
3767 : : * tuple has been locked or updated under us, but hopefully it won't
3768 : : * happen very often.
3769 : : */
5633 rhaas@postgresql.org 3770 [ + + - + ]: 2408745 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3771 : : {
5633 rhaas@postgresql.org 3772 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3773 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
3774 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5541 3775 : 0 : goto l2;
3776 : : }
3777 : :
3778 : : /* Fill in transaction status data */
3779 : :
3780 : : /*
3781 : : * If the tuple we're updating is locked, we need to preserve the locking
3782 : : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3783 : : */
5057 alvherre@alvh.no-ip. 3784 :CBC 2408745 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3785 : 2408745 : oldtup.t_data->t_infomask,
3786 : 2408745 : oldtup.t_data->t_infomask2,
3787 : : xid, *lockmode, true,
3788 : : &xmax_old_tuple, &infomask_old_tuple,
3789 : : &infomask2_old_tuple);
3790 : :
3791 : : /*
3792 : : * And also prepare an Xmax value for the new copy of the tuple. If there
3793 : : * was no xmax previously, or there was one but all lockers are now gone,
3794 : : * then use InvalidTransactionId; otherwise, get the xmax from the old
3795 : : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3796 : : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3797 : : */
3798 [ + + + - ]: 2445192 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3809 3799 [ + + ]: 72894 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
5057 3800 [ + + ]: 36271 : (checked_lockers && !locker_remains))
3801 : 2372300 : xmax_new_tuple = InvalidTransactionId;
3802 : : else
3803 : 36445 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3804 : :
3805 [ + + ]: 2408745 : if (!TransactionIdIsValid(xmax_new_tuple))
3806 : : {
3807 : 2372300 : infomask_new_tuple = HEAP_XMAX_INVALID;
3808 : 2372300 : infomask2_new_tuple = 0;
3809 : : }
3810 : : else
3811 : : {
3812 : : /*
3813 : : * If we found a valid Xmax for the new tuple, then the infomask bits
3814 : : * to use on the new tuple depend on what was there on the old one.
3815 : : * Note that since we're doing an update, the only possibility is that
3816 : : * the lockers had FOR KEY SHARE lock.
3817 : : */
3818 [ + + ]: 36445 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3819 : : {
3820 : 177 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3821 : : &infomask2_new_tuple);
3822 : : }
3823 : : else
3824 : : {
3825 : 36268 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3826 : 36268 : infomask2_new_tuple = 0;
3827 : : }
3828 : : }
3829 : :
3830 : : /*
3831 : : * Prepare the new tuple with the appropriate initial values of Xmin and
3832 : : * Xmax, as well as initial infomask bits as computed above.
3833 : : *
3834 : : * Don't need to unset HEAP_IS_DATUM, it's part of HEAP_XACT_MASK.
3835 : : */
10228 vadim4o@yahoo.com 3836 : 2408745 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
7009 tgl@sss.pgh.pa.us 3837 : 2408745 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
8108 3838 : 2408745 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
8932 bruce@momjian.us 3839 : 2408745 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
5057 alvherre@alvh.no-ip. 3840 : 2408745 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3841 : 2408745 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3842 : 2408745 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3843 : :
3844 : : /*
3845 : : * Replace cid with a combo CID if necessary. Note that we already put
3846 : : * the plain cid into the new tuple.
3847 : : */
7232 tgl@sss.pgh.pa.us 3848 : 2408745 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3849 : :
3850 : : /*
3851 : : * If the toaster needs to be activated, OR if the new tuple will not fit
3852 : : * on the same page as the old, then we need to release the content lock
3853 : : * (but not the pin!) on the old tuple's buffer while we are off doing
3854 : : * TOAST and/or table-file-extension work. We must mark the old tuple to
3855 : : * show that it's locked, else other processes may try to update it
3856 : : * themselves.
3857 : : *
3858 : : * We need to invoke the toaster if there are already any out-of-line
3859 : : * toasted values present, or if the new tuple is over-threshold.
3860 : : */
5018 kgrittn@postgresql.o 3861 [ - + ]: 2408745 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
5018 kgrittn@postgresql.o 3862 [ # # ]:UBC 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3863 : : {
3864 : : /* toast table entries should never be recursively toasted */
7179 tgl@sss.pgh.pa.us 3865 [ # # ]: 0 : Assert(!HeapTupleHasExternal(&oldtup));
3866 [ # # ]: 0 : Assert(!HeapTupleHasExternal(newtup));
3867 : 0 : need_toast = false;
3868 : : }
3869 : : else
7179 tgl@sss.pgh.pa.us 3870 [ + + ]:CBC 7225515 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3871 [ + + ]: 4816770 : HeapTupleHasExternal(newtup) ||
3872 [ + + ]: 2407993 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3873 : :
6712 3874 : 2408745 : pagefree = PageGetHeapFreeSpace(page);
3875 : :
7237 3876 : 2408745 : newtupsize = MAXALIGN(newtup->t_len);
3877 : :
9327 3878 [ + + + + ]: 2408745 : if (need_toast || newtupsize > pagefree)
9578 vadim4o@yahoo.com 3879 : 2215443 : {
3880 : : TransactionId xmax_lock_old_tuple;
3881 : : uint16 infomask_lock_old_tuple,
3882 : : infomask2_lock_old_tuple;
3785 andres@anarazel.de 3883 : 2215443 : bool cleared_all_frozen = false;
3884 : :
3885 : : /*
3886 : : * To prevent concurrent sessions from updating the tuple, we have to
3887 : : * temporarily mark it locked, while we release the page-level lock.
3888 : : *
3889 : : * To satisfy the rule that any xid potentially appearing in a buffer
3890 : : * written out to disk, we unfortunately have to WAL log this
3891 : : * temporary modification. We can reuse xl_heap_lock for this
3892 : : * purpose. If we crash/error before following through with the
3893 : : * actual update, xmax will be of an aborted transaction, allowing
3894 : : * other sessions to proceed.
3895 : : */
3896 : :
3897 : : /*
3898 : : * Compute xmax / infomask appropriate for locking the tuple. This has
3899 : : * to be done separately from the combo that's going to be used for
3900 : : * updating, because the potentially created multixact would otherwise
3901 : : * be wrong.
3902 : : */
3788 3903 : 2215443 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3904 : 2215443 : oldtup.t_data->t_infomask,
3905 : 2215443 : oldtup.t_data->t_infomask2,
3906 : : xid, *lockmode, false,
3907 : : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3908 : : &infomask2_lock_old_tuple);
3909 : :
3910 [ - + ]: 2215443 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3911 : :
136 melanieplageman@gmai 3912 [ + + ]: 2215443 : if (PageIsAllVisible(page))
3913 : : {
3914 : 1707 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3915 : 1707 : unlock_vmbuffer = true;
3916 : : }
3917 : :
3788 andres@anarazel.de 3918 : 2215443 : START_CRIT_SECTION();
3919 : :
3920 : : /* Clear obsolete visibility flags ... */
5057 alvherre@alvh.no-ip. 3921 : 2215443 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3922 : 2215443 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7009 tgl@sss.pgh.pa.us 3923 : 2215443 : HeapTupleClearHotUpdated(&oldtup);
3924 : : /* ... and store info about transaction updating this tuple */
3788 andres@anarazel.de 3925 [ - + ]: 2215443 : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3926 : 2215443 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3927 : 2215443 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3928 : 2215443 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
7232 tgl@sss.pgh.pa.us 3929 : 2215443 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3930 : :
3931 : : /* temporarily make it look not-updated, but locked */
7678 3932 : 2215443 : oldtup.t_data->t_ctid = oldtup.t_self;
3933 : :
3934 : : /*
3935 : : * Clear all-frozen bit on visibility map if needed. We could
3936 : : * immediately reset ALL_VISIBLE, but given that the WAL logging
3937 : : * overhead would be unchanged, that doesn't seem necessarily
3938 : : * worthwhile.
3939 : : */
136 melanieplageman@gmai 3940 [ + + ]: 2215443 : if (PageIsAllVisible(page))
3941 : : {
3942 : : /* It's possible all-frozen was already clear */
136 melanieplageman@gmai 3943 [ + + ]:GNC 1707 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
3944 : : VISIBILITYMAP_ALL_FROZEN))
136 melanieplageman@gmai 3945 :CBC 930 : cleared_all_frozen = true;
3946 : : }
3947 : :
3788 andres@anarazel.de 3948 : 2215443 : MarkBufferDirty(buffer);
3949 : :
3950 [ + + + + : 2215443 : if (RelationNeedsWAL(relation))
+ - + + ]
3951 : : {
3952 : : xl_heap_lock xlrec;
3953 : : XLogRecPtr recptr;
3954 : :
3955 : 2205304 : XLogBeginInsert();
136 melanieplageman@gmai 3956 : 2205304 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3957 : :
3788 andres@anarazel.de 3958 : 2205304 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
1327 pg@bowt.ie 3959 : 2205304 : xlrec.xmax = xmax_lock_old_tuple;
3788 andres@anarazel.de 3960 : 4410608 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3961 : 2205304 : oldtup.t_data->t_infomask2);
3785 3962 : 2205304 : xlrec.flags =
3963 : 2205304 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
655 peter@eisentraut.org 3964 : 2205304 : XLogRegisterData(&xlrec, SizeOfHeapLock);
3965 : :
136 melanieplageman@gmai 3966 [ + + ]: 2205304 : if (cleared_all_frozen)
3967 : 930 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
3968 : :
3788 andres@anarazel.de 3969 : 2205304 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3970 : 2205304 : PageSetLSN(page, recptr);
3971 : :
136 melanieplageman@gmai 3972 [ + + ]: 2205304 : if (cleared_all_frozen)
3973 : 930 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3974 : : }
3975 : :
3788 andres@anarazel.de 3976 [ - + ]: 2215443 : END_CRIT_SECTION();
3977 : :
3978 : : /* release VM lock first, since it covers many heap blocks */
136 melanieplageman@gmai 3979 [ + + ]: 2215443 : if (unlock_vmbuffer)
3980 : 1707 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3981 : 2215443 : unlock_vmbuffer = false;
3982 : :
9578 vadim4o@yahoo.com 3983 : 2215443 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3984 : :
3985 : : /*
3986 : : * Let the toaster do its thing, if needed.
3987 : : *
3988 : : * Note: below this point, heaptup is the data we actually intend to
3989 : : * store into the relation; newtup is the caller's original untoasted
3990 : : * data.
3991 : : */
9448 tgl@sss.pgh.pa.us 3992 [ + + ]: 2215443 : if (need_toast)
3993 : : {
3994 : : /*
3995 : : * If logical decoding is not needed, suppress it for the TOAST
3996 : : * tuples too. We never skip the FSM here.
3997 : : */
78 msawada@postgresql.o 3998 [ + + ]: 2422 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
3999 : : walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
7678 tgl@sss.pgh.pa.us 4000 : 2422 : newtupsize = MAXALIGN(heaptup->t_len);
4001 : : }
4002 : : else
4003 : 2213021 : heaptup = newtup;
4004 : :
4005 : : /*
4006 : : * Now, do we need a new page for the tuple, or not? This is a bit
4007 : : * tricky since someone else could have added tuples to the page while
4008 : : * we weren't looking. We have to recheck the available space after
4009 : : * reacquiring the buffer lock. But don't bother to do that if the
4010 : : * former amount of free space is still not enough; it's unlikely
4011 : : * there's more free now than before.
4012 : : *
4013 : : * What's more, if we need to get a new page, we will need to acquire
4014 : : * buffer locks on both old and new pages. To avoid deadlock against
4015 : : * some other backend trying to get the same two locks in the other
4016 : : * order, we must be consistent about the order we get the locks in.
4017 : : * We use the rule "lock the lower-numbered page of the relation
4018 : : * first". To implement this, we must do RelationGetBufferForTuple
4019 : : * while not holding the lock on the old page, and we must rely on it
4020 : : * to get the locks on both pages in the correct order.
4021 : : *
4022 : : * Another consideration is that we need visibility map page pin(s) if
4023 : : * we will have to clear the all-visible flag on either page. If we
4024 : : * call RelationGetBufferForTuple, we rely on it to acquire any such
4025 : : * pins; but if we don't, we have to handle that here. Hence we need
4026 : : * a loop.
4027 : : */
4028 : : for (;;)
4029 : : {
2055 4030 [ + + ]: 2215443 : if (newtupsize > pagefree)
4031 : : {
4032 : : /* It doesn't fit, must use RelationGetBufferForTuple. */
4033 : 2214500 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
4034 : : buffer, 0, NULL,
4035 : : &vmbuffer_new, &vmbuffer,
4036 : : 0);
4037 : : /* We're all done. */
4038 : 2214500 : break;
4039 : : }
4040 : : /* Acquire VM page pin if needed and we don't have it. */
4041 [ + + - + ]: 943 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2055 tgl@sss.pgh.pa.us 4042 :UBC 0 : visibilitymap_pin(relation, block, &vmbuffer);
4043 : : /* Re-acquire the lock on the old tuple's page. */
9327 tgl@sss.pgh.pa.us 4044 :CBC 943 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4045 : : /* Re-check using the up-to-date free space */
6712 4046 : 943 : pagefree = PageGetHeapFreeSpace(page);
2055 4047 [ + - ]: 943 : if (newtupsize > pagefree ||
4048 [ + + - + ]: 943 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
4049 : : {
4050 : : /*
4051 : : * Rats, it doesn't fit anymore, or somebody just now set the
4052 : : * all-visible flag. We must now unlock and loop to avoid
4053 : : * deadlock. Fortunately, this path should seldom be taken.
4054 : : */
9327 tgl@sss.pgh.pa.us 4055 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4056 : : }
4057 : : else
4058 : : {
4059 : : /* We're all done. */
9327 tgl@sss.pgh.pa.us 4060 :CBC 943 : newbuf = buffer;
2055 4061 : 943 : break;
4062 : : }
4063 : : }
4064 : : }
4065 : : else
4066 : : {
4067 : : /* No TOAST work needed, and it'll fit on same page */
9448 4068 : 193302 : newbuf = buffer;
7678 4069 : 193302 : heaptup = newtup;
4070 : : }
4071 : :
258 melanieplageman@gmai 4072 : 2408745 : newpage = BufferGetPage(newbuf);
4073 : :
4074 : : /*
4075 : : * We're about to do the actual update -- check for conflict first, to
4076 : : * avoid possibly having to roll back work we've just done.
4077 : : *
4078 : : * This is safe without a recheck as long as there is no possibility of
4079 : : * another process scanning the pages between this check and the update
4080 : : * being visible to the scan (i.e., exclusive buffer content lock(s) are
4081 : : * continuously held from this point until the tuple update is visible).
4082 : : *
4083 : : * For the new tuple the only check needed is at the relation level, but
4084 : : * since both tuples are in the same relation and the check for oldtup
4085 : : * will include checking the relation level, there is no benefit to a
4086 : : * separate check for the new tuple.
4087 : : */
2055 tmunro@postgresql.or 4088 : 2408745 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
4089 : : BufferGetBlockNumber(buffer));
4090 : :
4091 : : /*
4092 : : * At this point newbuf and buffer are both pinned and locked, and newbuf
4093 : : * has enough space for the new tuple. If they are the same buffer, only
4094 : : * one pin is held.
4095 : : */
4096 : :
7009 tgl@sss.pgh.pa.us 4097 [ + + ]: 2408732 : if (newbuf == buffer)
4098 : : {
4099 : : /*
4100 : : * Since the new tuple is going into the same page, we might be able
4101 : : * to do a HOT update. Check if any of the index columns have been
4102 : : * changed.
4103 : : */
1828 pg@bowt.ie 4104 [ + + ]: 194232 : if (!bms_overlap(modified_attrs, hot_attrs))
4105 : : {
7009 tgl@sss.pgh.pa.us 4106 : 177162 : use_hot_update = true;
4107 : :
4108 : : /*
4109 : : * If none of the columns that are used in hot-blocking indexes
4110 : : * were updated, we can apply HOT, but we do still need to check
4111 : : * if we need to update the summarizing indexes, and update those
4112 : : * indexes if the columns were updated, or we may fail to detect
4113 : : * e.g. value bound changes in BRIN minmax indexes.
4114 : : */
1349 tomas.vondra@postgre 4115 [ + + ]: 177162 : if (bms_overlap(modified_attrs, sum_attrs))
4116 : 2188 : summarized_update = true;
4117 : : }
4118 : : }
4119 : : else
4120 : : {
4121 : : /* Set a hint that the old page could use prune/defrag */
6712 tgl@sss.pgh.pa.us 4122 : 2214500 : PageSetFull(page);
4123 : : }
4124 : :
4125 : : /*
4126 : : * Compute replica identity tuple before entering the critical section so
4127 : : * we don't PANIC upon a memory allocation failure.
4128 : : * ExtractReplicaIdentity() will return NULL if nothing needs to be
4129 : : * logged. Pass old key required as true only if the replica identity key
4130 : : * columns are modified or it has external data.
4131 : : */
3531 alvherre@alvh.no-ip. 4132 : 2408732 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
1748 akapila@postgresql.o 4133 [ + + + + ]: 2408732 : bms_overlap(modified_attrs, id_attrs) ||
4134 : : id_has_external,
3531 alvherre@alvh.no-ip. 4135 : 2408732 : &old_key_copied);
4136 : :
136 melanieplageman@gmai 4137 : 2408732 : clear_all_visible = PageIsAllVisible(page);
4138 [ + + + + ]: 2408732 : clear_all_visible_new = newbuf != buffer && PageIsAllVisible(newpage);
4139 : :
4140 : : /*
4141 : : * Clear PD_ALL_VISIBLE flags and reset visibility map bits for any heap
4142 : : * pages that were all-visible. If there are two heap pages, we may need
4143 : : * to clear VM bits for both.
4144 : : */
4145 [ + + + + ]: 2408732 : if (clear_all_visible && clear_all_visible_new &&
4146 [ + - ]: 171 : vmbuffer_new == vmbuffer)
4147 : : {
4148 : : /*
4149 : : * This is the more complicated case: both the new and old heap pages
4150 : : * are all-visible and both their VM bits are on the same page of the
4151 : : * VM, so we register a single VM buffer as HEAP_UPDATE_BLKREF_VM_NEW
4152 : : * in the WAL record. We must be careful to only lock and register one
4153 : : * buffer, even though we modify it twice -- once for each heap
4154 : : * block's VM bits.
4155 : : */
4156 : 171 : LockBuffer(vmbuffer_new, BUFFER_LOCK_EXCLUSIVE);
4157 : 171 : unlock_vmbuffer_new = true;
4158 : :
4159 : : /* We will not lock or attempt to modify old VM buffer */
4160 : : }
4161 : : else
4162 : : {
4163 : : /*
4164 : : * In all the remaining cases, we will clear at most one heap block's
4165 : : * VM bits per VM page.
4166 : : */
4167 : 4817122 : Buffer vmbuffers[2] = {
4168 [ + + ]: 2408561 : clear_all_visible ? vmbuffer : InvalidBuffer,
4169 [ + + ]: 2408561 : clear_all_visible_new ? vmbuffer_new : InvalidBuffer
4170 : : };
4171 : :
4172 : : /*
4173 : : * When both pages need different VM pages cleared, acquire the VM
4174 : : * buffer locks in VM block order to avoid deadlocks between backends
4175 : : * updating tuples in opposite directions across VM pages.
4176 : : */
4177 [ + + - + : 2408561 : if (clear_all_visible && clear_all_visible_new &&
- - ]
136 melanieplageman@gmai 4178 :UBC 0 : BufferGetBlockNumber(vmbuffers[0]) > BufferGetBlockNumber(vmbuffers[1]))
4179 : : {
4180 : 0 : Buffer swap = vmbuffers[0];
4181 : :
4182 : 0 : vmbuffers[0] = vmbuffers[1];
4183 : 0 : vmbuffers[1] = swap;
4184 : : }
4185 : :
136 melanieplageman@gmai 4186 [ + + + + :CBC 2408561 : Assert((!BufferIsValid(vmbuffers[0]) && !BufferIsValid(vmbuffers[1])) ||
- + ]
4187 : : vmbuffers[0] != vmbuffers[1]);
4188 : :
4189 [ + + ]: 2408561 : if (BufferIsValid(vmbuffers[0]))
4190 : 2569 : LockBuffer(vmbuffers[0], BUFFER_LOCK_EXCLUSIVE);
4191 [ + + ]: 2408561 : if (BufferIsValid(vmbuffers[1]))
4192 : 1482 : LockBuffer(vmbuffers[1], BUFFER_LOCK_EXCLUSIVE);
4193 : :
4194 [ + + ]: 2408561 : if (clear_all_visible)
4195 : 2569 : unlock_vmbuffer = true;
4196 [ + + ]: 2408561 : if (clear_all_visible_new)
4197 : 1482 : unlock_vmbuffer_new = true;
4198 : : }
4199 : :
4200 : : /* NO EREPORT(ERROR) from here till changes are logged */
9451 tgl@sss.pgh.pa.us 4201 : 2408732 : START_CRIT_SECTION();
4202 : :
4203 : : /*
4204 : : * If this transaction commits, the old tuple will become DEAD sooner or
4205 : : * later. Set flag that this page is a candidate for pruning once our xid
4206 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
4207 : : * the subsequent page pruning will be a no-op and the hint will be
4208 : : * cleared.
4209 : : *
4210 : : * We set the new page prunable as well. See heap_insert() for more on why
4211 : : * we do this when inserting tuples.
4212 : : */
6712 4213 [ - + + + : 2408732 : PageSetPrunable(page, xid);
+ + ]
243 melanieplageman@gmai 4214 [ + + ]: 2408732 : if (newbuf != buffer)
4215 [ - + + + : 2214500 : PageSetPrunable(newpage, xid);
+ + ]
4216 : :
7009 tgl@sss.pgh.pa.us 4217 [ + + ]: 2408732 : if (use_hot_update)
4218 : : {
4219 : : /* Mark the old tuple as HOT-updated */
4220 : 177162 : HeapTupleSetHotUpdated(&oldtup);
4221 : : /* And mark the new tuple as heap-only */
4222 : 177162 : HeapTupleSetHeapOnly(heaptup);
4223 : : /* Mark the caller's copy too, in case different from heaptup */
4224 : 177162 : HeapTupleSetHeapOnly(newtup);
4225 : : }
4226 : : else
4227 : : {
4228 : : /* Make sure tuples are correctly marked as not-HOT */
4229 : 2231570 : HeapTupleClearHotUpdated(&oldtup);
4230 : 2231570 : HeapTupleClearHeapOnly(heaptup);
4231 : 2231570 : HeapTupleClearHeapOnly(newtup);
4232 : : }
4233 : :
3447 4234 : 2408732 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4235 : :
4236 : :
4237 : : /* Clear obsolete visibility flags, possibly set by ourselves above... */
3788 andres@anarazel.de 4238 : 2408732 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4239 : 2408732 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4240 : : /* ... and store info about transaction updating this tuple */
4241 [ - + ]: 2408732 : Assert(TransactionIdIsValid(xmax_old_tuple));
4242 : 2408732 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4243 : 2408732 : oldtup.t_data->t_infomask |= infomask_old_tuple;
4244 : 2408732 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4245 : 2408732 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4246 : :
4247 : : /* record address of new tuple in t_ctid of old one */
7678 tgl@sss.pgh.pa.us 4248 : 2408732 : oldtup.t_data->t_ctid = heaptup->t_self;
4249 : :
4250 : : /*
4251 : : * Clear PD_ALL_VISIBLE flags and reset all visibilitymap bits. In all
4252 : : * cases, it's possible that PD_ALL_VISIBLE was set but the corresponding
4253 : : * visibility map bits were already clear.
4254 : : */
136 melanieplageman@gmai 4255 [ + + ]: 2408732 : if (clear_all_visible)
4256 : : {
136 melanieplageman@gmai 4257 [ + - ]:GNC 2740 : if (visibilitymap_clear(relation->rd_locator, block,
4258 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
4259 : : {
4260 : : /*
4261 : : * When old and new heap blocks' VM bits are on the same VM page,
4262 : : * that page is registered in the WAL record only once. If both
4263 : : * heap pages were PD_ALL_VISIBLE and either VM bit needs
4264 : : * clearing, we register the VM buffer as
4265 : : * HEAP_UPDATE_BLKREF_VM_NEW.
4266 : : */
136 melanieplageman@gmai 4267 [ + + + - ]:CBC 2740 : if (clear_all_visible_new && vmbuffer == vmbuffer_new)
4268 : 171 : vmbuffer_new_modified = true;
4269 : : else
4270 : 2569 : vmbuffer_modified = true;
4271 : : }
4272 : :
258 4273 : 2740 : PageClearAllVisible(page);
4274 : : }
136 4275 [ + + ]: 2408732 : if (clear_all_visible_new)
4276 : : {
4277 : : /*
4278 : : * If both heap blocks' VM bits are on the same VM buffer, this will
4279 : : * clear the new heap block's VM bits from the shared vmbuffer.
4280 : : */
136 melanieplageman@gmai 4281 [ + - ]:GNC 1653 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(newbuf),
4282 : : vmbuffer_new, VISIBILITYMAP_VALID_BITS))
136 melanieplageman@gmai 4283 :CBC 1653 : vmbuffer_new_modified = true;
4284 : :
258 4285 : 1653 : PageClearAllVisible(newpage);
4286 : : }
4287 : :
7547 tgl@sss.pgh.pa.us 4288 [ + + ]: 2408732 : if (newbuf != buffer)
4289 : 2214500 : MarkBufferDirty(newbuf);
4290 : 2408732 : MarkBufferDirty(buffer);
4291 : :
4292 : : /* XLOG stuff */
5829 rhaas@postgresql.org 4293 [ + + + + : 2408732 : if (RelationNeedsWAL(relation))
+ - + + ]
4294 : : {
4295 : : XLogRecPtr recptr;
4296 : :
4297 : : /*
4298 : : * For logical decoding we need combo CIDs to properly decode the
4299 : : * catalog.
4300 : : */
4736 4301 [ + + + + : 2396887 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
4302 : : {
4303 : 2860 : log_heap_new_cid(relation, &oldtup);
4304 : 2860 : log_heap_new_cid(relation, heaptup);
4305 : : }
4306 : :
4307 [ + + + + ]: 2396887 : recptr = log_heap_update(relation, buffer,
4308 : : vmbuffer_modified ? vmbuffer : InvalidBuffer,
4309 : : newbuf,
4310 : : vmbuffer_new_modified ? vmbuffer_new : InvalidBuffer,
4311 : : &oldtup, heaptup,
4312 : : old_key_tuple,
4313 : : clear_all_visible,
4314 : : clear_all_visible_new,
4315 : : walLogical);
9644 vadim4o@yahoo.com 4316 [ + + ]: 2396887 : if (newbuf != buffer)
4317 : : {
258 melanieplageman@gmai 4318 : 2204369 : PageSetLSN(newpage, recptr);
4319 : : }
4320 : 2396887 : PageSetLSN(page, recptr);
4321 : :
136 4322 [ + + ]: 2396887 : if (vmbuffer_modified)
4323 : 2458 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
4324 [ + + ]: 2396887 : if (vmbuffer_new_modified)
4325 : 1653 : PageSetLSN(BufferGetPage(vmbuffer_new), recptr);
4326 : : }
4327 : :
9451 tgl@sss.pgh.pa.us 4328 [ - + ]: 2408732 : END_CRIT_SECTION();
4329 : :
136 melanieplageman@gmai 4330 [ + + ]: 2408732 : if (unlock_vmbuffer)
4331 : 2569 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
4332 [ + + ]: 2408732 : if (unlock_vmbuffer_new)
4333 : 1653 : LockBuffer(vmbuffer_new, BUFFER_LOCK_UNLOCK);
4334 : :
9644 vadim4o@yahoo.com 4335 [ + + ]: 2408732 : if (newbuf != buffer)
4336 : 2214500 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
10210 4337 : 2408732 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4338 : :
4339 : : /*
4340 : : * Mark old tuple for invalidation from system caches at next command
4341 : : * boundary, and mark the new tuple for invalidation in case we abort. We
4342 : : * have to do this before releasing the buffer because oldtup is in the
4343 : : * buffer. (heaptup is all in local memory, but it's necessary to process
4344 : : * both tuple versions in one call to inval.c so we can avoid redundant
4345 : : * sinval messages.)
4346 : : */
5583 tgl@sss.pgh.pa.us 4347 : 2408732 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4348 : :
4349 : : /* Now we can release the buffer(s) */
9456 4350 [ + + ]: 2408732 : if (newbuf != buffer)
7547 4351 : 2214500 : ReleaseBuffer(newbuf);
961 akorotkov@postgresql 4352 : 2408732 : ReleaseBuffer(buffer);
5639 rhaas@postgresql.org 4353 [ + + ]: 2408732 : if (BufferIsValid(vmbuffer_new))
4354 : 1657 : ReleaseBuffer(vmbuffer_new);
4355 [ + + ]: 2408732 : if (BufferIsValid(vmbuffer))
4356 : 2740 : ReleaseBuffer(vmbuffer);
4357 : :
4358 : : /*
4359 : : * Release the lmgr tuple lock, if we had it.
4360 : : */
7882 tgl@sss.pgh.pa.us 4361 [ + + ]: 2408732 : if (have_tuple_lock)
3152 simon@2ndQuadrant.co 4362 : 24 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4363 : :
1346 pg@bowt.ie 4364 : 2408732 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4365 : :
4366 : : /*
4367 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
4368 : : * back to the caller's image, too.
4369 : : */
7678 tgl@sss.pgh.pa.us 4370 [ + + ]: 2408732 : if (heaptup != newtup)
4371 : : {
4372 : 2347 : newtup->t_self = heaptup->t_self;
4373 : 2347 : heap_freetuple(heaptup);
4374 : : }
4375 : :
4376 : : /*
4377 : : * If it is a HOT update, the update may still need to update summarized
4378 : : * indexes, lest we fail to update those summaries and get incorrect
4379 : : * results (for example, minmax bounds of the block may change with this
4380 : : * update).
4381 : : */
1349 tomas.vondra@postgre 4382 [ + + ]: 2408732 : if (use_hot_update)
4383 : : {
4384 [ + + ]: 177162 : if (summarized_update)
4385 : 2188 : *update_indexes = TU_Summarizing;
4386 : : else
4387 : 174974 : *update_indexes = TU_None;
4388 : : }
4389 : : else
4390 : 2231570 : *update_indexes = TU_All;
4391 : :
4736 rhaas@postgresql.org 4392 [ + + + + ]: 2408732 : if (old_key_tuple != NULL && old_key_copied)
4393 : 95 : heap_freetuple(old_key_tuple);
4394 : :
7009 tgl@sss.pgh.pa.us 4395 : 2408732 : bms_free(hot_attrs);
1349 tomas.vondra@postgre 4396 : 2408732 : bms_free(sum_attrs);
5057 alvherre@alvh.no-ip. 4397 : 2408732 : bms_free(key_attrs);
3748 tgl@sss.pgh.pa.us 4398 : 2408732 : bms_free(id_attrs);
3531 alvherre@alvh.no-ip. 4399 : 2408732 : bms_free(modified_attrs);
4400 : 2408732 : bms_free(interesting_attrs);
4401 : :
2807 andres@anarazel.de 4402 : 2408732 : return TM_Ok;
4403 : : }
4404 : :
4405 : : #ifdef USE_ASSERT_CHECKING
4406 : : /*
4407 : : * Confirm adequate lock held during heap_update(), per rules from
4408 : : * README.tuplock section "Locking to write inplace-updated tables".
4409 : : */
4410 : : static void
795 noah@leadboat.com 4411 : 2408938 : check_lock_if_inplace_updateable_rel(Relation relation,
4412 : : const ItemPointerData *otid,
4413 : : HeapTuple newtup)
4414 : : {
4415 : : /* LOCKTAG_TUPLE acceptable for any catalog */
4416 [ + + ]: 2408938 : switch (RelationGetRelid(relation))
4417 : : {
4418 : 91707 : case RelationRelationId:
4419 : : case DatabaseRelationId:
4420 : : {
4421 : : LOCKTAG tuptag;
4422 : :
4423 : 91707 : SET_LOCKTAG_TUPLE(tuptag,
4424 : : relation->rd_lockInfo.lockRelId.dbId,
4425 : : relation->rd_lockInfo.lockRelId.relId,
4426 : : ItemPointerGetBlockNumber(otid),
4427 : : ItemPointerGetOffsetNumber(otid));
4428 [ + + ]: 91707 : if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
4429 : 38033 : return;
4430 : : }
4431 : 53674 : break;
4432 : 2317231 : default:
4433 [ - + ]: 2317231 : Assert(!IsInplaceUpdateRelation(relation));
4434 : 2317231 : return;
4435 : : }
4436 : :
4437 [ + - - ]: 53674 : switch (RelationGetRelid(relation))
4438 : : {
4439 : 53674 : case RelationRelationId:
4440 : : {
4441 : : /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4442 : 53674 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
4443 : 53674 : Oid relid = classForm->oid;
4444 : : Oid dbid;
4445 : : LOCKTAG tag;
4446 : :
4447 [ + + ]: 53674 : if (IsSharedRelation(relid))
4448 : 47 : dbid = InvalidOid;
4449 : : else
4450 : 53627 : dbid = MyDatabaseId;
4451 : :
4452 [ + + ]: 53674 : if (classForm->relkind == RELKIND_INDEX)
4453 : : {
4454 : 1410 : Relation irel = index_open(relid, AccessShareLock);
4455 : :
4456 : 1410 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4457 : 1410 : index_close(irel, AccessShareLock);
4458 : : }
4459 : : else
4460 : 52264 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4461 : :
4462 [ + + ]: 53674 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4463 [ - + ]: 49092 : !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
795 noah@leadboat.com 4464 [ # # ]:UBC 0 : elog(WARNING,
4465 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4466 : : NameStr(classForm->relname),
4467 : : relid,
4468 : : classForm->relkind,
4469 : : ItemPointerGetBlockNumber(otid),
4470 : : ItemPointerGetOffsetNumber(otid));
4471 : : }
795 noah@leadboat.com 4472 :CBC 53674 : break;
795 noah@leadboat.com 4473 :UBC 0 : case DatabaseRelationId:
4474 : : {
4475 : : /* LOCKTAG_TUPLE required */
4476 : 0 : Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
4477 : :
4478 [ # # ]: 0 : elog(WARNING,
4479 : : "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4480 : : NameStr(dbForm->datname),
4481 : : dbForm->oid,
4482 : : ItemPointerGetBlockNumber(otid),
4483 : : ItemPointerGetOffsetNumber(otid));
4484 : : }
4485 : 0 : break;
4486 : : }
4487 : : }
4488 : :
4489 : : /*
4490 : : * Confirm adequate relation lock held, per rules from README.tuplock section
4491 : : * "Locking to write inplace-updated tables".
4492 : : */
4493 : : static void
795 noah@leadboat.com 4494 :CBC 118092 : check_inplace_rel_lock(HeapTuple oldtup)
4495 : : {
4496 : 118092 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
4497 : 118092 : Oid relid = classForm->oid;
4498 : : Oid dbid;
4499 : : LOCKTAG tag;
4500 : :
4501 [ + + ]: 118092 : if (IsSharedRelation(relid))
4502 : 10483 : dbid = InvalidOid;
4503 : : else
4504 : 107609 : dbid = MyDatabaseId;
4505 : :
4506 [ + + ]: 118092 : if (classForm->relkind == RELKIND_INDEX)
4507 : : {
4508 : 51927 : Relation irel = index_open(relid, AccessShareLock);
4509 : :
4510 : 51927 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4511 : 51927 : index_close(irel, AccessShareLock);
4512 : : }
4513 : : else
4514 : 66165 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4515 : :
4516 [ - + ]: 118092 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
795 noah@leadboat.com 4517 [ # # ]:UBC 0 : elog(WARNING,
4518 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4519 : : NameStr(classForm->relname),
4520 : : relid,
4521 : : classForm->relkind,
4522 : : ItemPointerGetBlockNumber(&oldtup->t_self),
4523 : : ItemPointerGetOffsetNumber(&oldtup->t_self));
795 noah@leadboat.com 4524 :CBC 118092 : }
4525 : : #endif
4526 : :
4527 : : /*
4528 : : * Check if the specified attribute's values are the same. Subroutine for
4529 : : * HeapDetermineColumnsInfo.
4530 : : */
4531 : : static bool
1748 akapila@postgresql.o 4532 : 1053489 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4533 : : bool isnull1, bool isnull2)
4534 : : {
4535 : : /*
4536 : : * If one value is NULL and other is not, then they are certainly not
4537 : : * equal
4538 : : */
7009 tgl@sss.pgh.pa.us 4539 [ + + ]: 1053489 : if (isnull1 != isnull2)
4540 : 62 : return false;
4541 : :
4542 : : /*
4543 : : * If both are NULL, they can be considered equal.
4544 : : */
4545 [ + + ]: 1053427 : if (isnull1)
4546 : 6641 : return true;
4547 : :
4548 : : /*
4549 : : * We do simple binary comparison of the two datums. This may be overly
4550 : : * strict because there can be multiple binary representations for the
4551 : : * same logical value. But we should be OK as long as there are no false
4552 : : * positives. Using a type-specific equality operator is messy because
4553 : : * there could be multiple notions of equality in different operator
4554 : : * classes; furthermore, we cannot safely invoke user-defined functions
4555 : : * while holding exclusive buffer lock.
4556 : : */
4557 [ - + ]: 1046786 : if (attrnum <= 0)
4558 : : {
4559 : : /* The only allowed system columns are OIDs, so do this */
7009 tgl@sss.pgh.pa.us 4560 :UBC 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4561 : : }
4562 : : else
4563 : : {
4564 : : CompactAttribute *att;
4565 : :
7009 tgl@sss.pgh.pa.us 4566 [ - + ]:CBC 1046786 : Assert(attrnum <= tupdesc->natts);
708 drowley@postgresql.o 4567 : 1046786 : att = TupleDescCompactAttr(tupdesc, attrnum - 1);
7009 tgl@sss.pgh.pa.us 4568 : 1046786 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4569 : : }
4570 : : }
4571 : :
4572 : : /*
4573 : : * Check which columns are being updated.
4574 : : *
4575 : : * Given an updated tuple, determine (and return into the output bitmapset),
4576 : : * from those listed as interesting, the set of columns that changed.
4577 : : *
4578 : : * has_external indicates if any of the unmodified attributes (from those
4579 : : * listed as interesting) of the old tuple is a member of external_cols and is
4580 : : * stored externally.
4581 : : */
4582 : : static Bitmapset *
1748 akapila@postgresql.o 4583 : 2408937 : HeapDetermineColumnsInfo(Relation relation,
4584 : : Bitmapset *interesting_cols,
4585 : : Bitmapset *external_cols,
4586 : : HeapTuple oldtup, HeapTuple newtup,
4587 : : bool *has_external)
4588 : : {
4589 : : int attidx;
3482 bruce@momjian.us 4590 : 2408937 : Bitmapset *modified = NULL;
1748 akapila@postgresql.o 4591 : 2408937 : TupleDesc tupdesc = RelationGetDescr(relation);
4592 : :
1367 tgl@sss.pgh.pa.us 4593 : 2408937 : attidx = -1;
4594 [ + + ]: 3462426 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4595 : : {
4596 : : /* attidx is zero-based, attrnum is the normal attribute number */
4597 : 1053489 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4598 : : Datum value1,
4599 : : value2;
4600 : : bool isnull1,
4601 : : isnull2;
4602 : :
4603 : : /*
4604 : : * If it's a whole-tuple reference, say "not equal". It's not really
4605 : : * worth supporting this case, since it could only succeed after a
4606 : : * no-op update, which is hardly a case worth optimizing for.
4607 : : */
1748 akapila@postgresql.o 4608 [ - + ]: 1053489 : if (attrnum == 0)
4609 : : {
1367 tgl@sss.pgh.pa.us 4610 :UBC 0 : modified = bms_add_member(modified, attidx);
1748 akapila@postgresql.o 4611 :CBC 1021212 : continue;
4612 : : }
4613 : :
4614 : : /*
4615 : : * Likewise, automatically say "not equal" for any system attribute
4616 : : * other than tableOID; we cannot expect these to be consistent in a
4617 : : * HOT chain, or even to be set correctly yet in the new tuple.
4618 : : */
4619 [ - + ]: 1053489 : if (attrnum < 0)
4620 : : {
1748 akapila@postgresql.o 4621 [ # # ]:UBC 0 : if (attrnum != TableOidAttributeNumber)
4622 : : {
1367 tgl@sss.pgh.pa.us 4623 : 0 : modified = bms_add_member(modified, attidx);
1748 akapila@postgresql.o 4624 : 0 : continue;
4625 : : }
4626 : : }
4627 : :
4628 : : /*
4629 : : * Extract the corresponding values. XXX this is pretty inefficient
4630 : : * if there are many indexed columns. Should we do a single
4631 : : * heap_deform_tuple call on each tuple, instead? But that doesn't
4632 : : * work for system columns ...
4633 : : */
1748 akapila@postgresql.o 4634 :CBC 1053489 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4635 : 1053489 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4636 : :
4637 [ + + ]: 1053489 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4638 : : value2, isnull1, isnull2))
4639 : : {
1367 tgl@sss.pgh.pa.us 4640 : 65265 : modified = bms_add_member(modified, attidx);
1748 akapila@postgresql.o 4641 : 65265 : continue;
4642 : : }
4643 : :
4644 : : /*
4645 : : * No need to check attributes that can't be stored externally. Note
4646 : : * that system attributes can't be stored externally.
4647 : : */
4648 [ + - + + ]: 988224 : if (attrnum < 0 || isnull1 ||
708 drowley@postgresql.o 4649 [ + + ]: 981583 : TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
1748 akapila@postgresql.o 4650 : 955947 : continue;
4651 : :
4652 : : /*
4653 : : * Check if the old tuple's attribute is stored externally and is a
4654 : : * member of external_cols.
4655 : : */
290 michael@paquier.xyz 4656 [ + + + + ]: 32282 : if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
1367 tgl@sss.pgh.pa.us 4657 : 5 : bms_is_member(attidx, external_cols))
1748 akapila@postgresql.o 4658 : 2 : *has_external = true;
4659 : : }
4660 : :
3531 alvherre@alvh.no-ip. 4661 : 2408937 : return modified;
4662 : : }
4663 : :
4664 : : /*
4665 : : * simple_heap_update - replace a tuple
4666 : : *
4667 : : * This routine may be used to update a tuple when concurrent updates of
4668 : : * the target tuple are not expected (for example, because we have a lock
4669 : : * on the relation associated with the tuple). Any failure is reported
4670 : : * via ereport().
4671 : : */
4672 : : void
394 peter@eisentraut.org 4673 : 146797 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
4674 : : TU_UpdateIndexes *update_indexes)
4675 : : {
4676 : : TM_Result result;
4677 : : TM_FailureData tmfd;
4678 : : LockTupleMode lockmode;
4679 : :
8475 tgl@sss.pgh.pa.us 4680 : 146797 : result = heap_update(relation, otid, tup,
4681 : : GetCurrentCommandId(true), 0,
4682 : : InvalidSnapshot,
4683 : : true /* wait for commit */ ,
4684 : : &tmfd, &lockmode, update_indexes);
9440 4685 [ - + - + : 146797 : switch (result)
- ]
4686 : : {
2807 andres@anarazel.de 4687 :UBC 0 : case TM_SelfModified:
4688 : : /* Tuple was already updated in current command? */
8531 tgl@sss.pgh.pa.us 4689 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
4690 : : break;
4691 : :
2807 andres@anarazel.de 4692 :CBC 146796 : case TM_Ok:
4693 : : /* done successfully */
9440 tgl@sss.pgh.pa.us 4694 : 146796 : break;
4695 : :
2807 andres@anarazel.de 4696 :UBC 0 : case TM_Updated:
8531 tgl@sss.pgh.pa.us 4697 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
4698 : : break;
4699 : :
2807 andres@anarazel.de 4700 :CBC 1 : case TM_Deleted:
4701 [ + - ]: 1 : elog(ERROR, "tuple concurrently deleted");
4702 : : break;
4703 : :
9440 tgl@sss.pgh.pa.us 4704 :UBC 0 : default:
8531 4705 [ # # ]: 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4706 : : break;
4707 : : }
9440 tgl@sss.pgh.pa.us 4708 :CBC 146796 : }
4709 : :
4710 : :
4711 : : /*
4712 : : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4713 : : */
4714 : : static MultiXactStatus
5057 alvherre@alvh.no-ip. 4715 : 115480 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4716 : : {
4717 : : int retval;
4718 : :
4719 [ + + ]: 115480 : if (is_update)
4720 : 226 : retval = tupleLockExtraInfo[mode].updstatus;
4721 : : else
4722 : 115254 : retval = tupleLockExtraInfo[mode].lockstatus;
4723 : :
4724 [ - + ]: 115480 : if (retval == -1)
5057 alvherre@alvh.no-ip. 4725 [ # # # # ]:UBC 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4726 : : is_update ? "true" : "false");
4727 : :
4904 alvherre@alvh.no-ip. 4728 :CBC 115480 : return (MultiXactStatus) retval;
4729 : : }
4730 : :
4731 : : /*
4732 : : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4733 : : *
4734 : : * Note that this acquires a buffer pin, which the caller must release.
4735 : : *
4736 : : * Input parameters:
4737 : : * relation: relation containing tuple (caller must hold suitable lock)
4738 : : * cid: current command ID (used for visibility test, and stored into
4739 : : * tuple's cmax if lock is successful)
4740 : : * mode: indicates if shared or exclusive tuple lock is desired
4741 : : * wait_policy: what to do if tuple lock is not available
4742 : : * follow_updates: if true, follow the update chain to also lock descendant
4743 : : * tuples.
4744 : : *
4745 : : * Output parameters:
4746 : : * *tuple: all fields filled in
4747 : : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4748 : : * *tmfd: filled in failure cases (see below)
4749 : : *
4750 : : * Function results are the same as the ones for table_tuple_lock().
4751 : : *
4752 : : * In the failure cases other than TM_Invisible, the routine fills
4753 : : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4754 : : * if necessary), and t_cmax (the last only for TM_SelfModified,
4755 : : * since we cannot obtain cmax from a combo CID generated by another
4756 : : * transaction).
4757 : : * See comments for struct TM_FailureData for additional info.
4758 : : *
4759 : : * See README.tuplock for a thorough explanation of this mechanism.
4760 : : */
4761 : : TM_Result
961 akorotkov@postgresql 4762 : 762850 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4763 : : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4764 : : bool follow_updates,
4765 : : Buffer *buffer, TM_FailureData *tmfd)
4766 : : {
4767 : : TM_Result result;
4768 : 762850 : ItemPointer tid = &(tuple->t_self);
4769 : : ItemId lp;
4770 : : Page page;
3785 andres@anarazel.de 4771 : 762850 : Buffer vmbuffer = InvalidBuffer;
136 melanieplageman@gmai 4772 : 762850 : bool unlock_vmbuffer = false;
4773 : : BlockNumber block;
4774 : : TransactionId xid,
4775 : : xmax;
4776 : : uint16 old_infomask,
4777 : : new_infomask,
4778 : : new_infomask2;
4250 alvherre@alvh.no-ip. 4779 : 762850 : bool first_time = true;
2720 4780 : 762850 : bool skip_tuple_lock = false;
7882 tgl@sss.pgh.pa.us 4781 : 762850 : bool have_tuple_lock = false;
3785 andres@anarazel.de 4782 : 762850 : bool cleared_all_frozen = false;
4783 : :
961 akorotkov@postgresql 4784 : 762850 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3785 andres@anarazel.de 4785 : 762850 : block = ItemPointerGetBlockNumber(tid);
136 melanieplageman@gmai 4786 : 762850 : page = BufferGetPage(*buffer);
4787 : :
4788 : : /*
4789 : : * Before locking the buffer, pin the visibility map page if it appears to
4790 : : * be necessary. Since we haven't got the lock yet, someone else might be
4791 : : * in the middle of changing this, so we'll need to recheck after we have
4792 : : * the lock.
4793 : : */
4794 [ + + ]: 762850 : if (PageIsAllVisible(page))
3785 andres@anarazel.de 4795 : 604033 : visibilitymap_pin(relation, block, &vmbuffer);
4796 : :
961 akorotkov@postgresql 4797 : 762850 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4798 : :
6712 tgl@sss.pgh.pa.us 4799 : 762850 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
7017 4800 [ - + ]: 762850 : Assert(ItemIdIsNormal(lp));
4801 : :
6712 4802 : 762850 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10210 vadim4o@yahoo.com 4803 : 762850 : tuple->t_len = ItemIdGetLength(lp);
7770 tgl@sss.pgh.pa.us 4804 : 762850 : tuple->t_tableOid = RelationGetRelid(relation);
4805 : :
10210 vadim4o@yahoo.com 4806 : 14 : l3:
961 akorotkov@postgresql 4807 : 762864 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4808 : :
2807 andres@anarazel.de 4809 [ + + ]: 762864 : if (result == TM_Invisible)
4810 : : {
4811 : : /*
4812 : : * This is possible, but only when locking a tuple for ON CONFLICT DO
4813 : : * SELECT/UPDATE. We return this value here rather than throwing an
4814 : : * error in order to give that case the opportunity to throw a more
4815 : : * specific error.
4816 : : */
4817 : 28 : result = TM_Invisible;
3785 4818 : 28 : goto out_locked;
4819 : : }
2807 4820 [ + + + + ]: 762836 : else if (result == TM_BeingModified ||
4821 [ + + ]: 81803 : result == TM_Updated ||
4822 : : result == TM_Deleted)
4823 : : {
4824 : : TransactionId xwait;
4825 : : uint16 infomask;
4826 : : uint16 infomask2;
4827 : : bool require_sleep;
4828 : : ItemPointerData t_ctid;
4829 : :
4830 : : /* must copy state data before unlocking buffer */
5057 alvherre@alvh.no-ip. 4831 : 681035 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
7882 tgl@sss.pgh.pa.us 4832 : 681035 : infomask = tuple->t_data->t_infomask;
5057 alvherre@alvh.no-ip. 4833 : 681035 : infomask2 = tuple->t_data->t_infomask2;
4834 : 681035 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4835 : :
961 akorotkov@postgresql 4836 : 681035 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4837 : :
4838 : : /*
4839 : : * If any subtransaction of the current top transaction already holds
4840 : : * a lock as strong as or stronger than what we're requesting, we
4841 : : * effectively hold the desired lock already. We *must* succeed
4842 : : * without trying to take the tuple lock, else we will deadlock
4843 : : * against anyone wanting to acquire a stronger lock.
4844 : : *
4845 : : * Note we only do this the first time we loop on the HTSU result;
4846 : : * there is no point in testing in subsequent passes, because
4847 : : * evidently our own transaction cannot have acquired a new lock after
4848 : : * the first time we checked.
4849 : : */
4250 alvherre@alvh.no-ip. 4850 [ + + ]: 681035 : if (first_time)
4851 : : {
4852 : 681024 : first_time = false;
4853 : :
4854 [ + + ]: 681024 : if (infomask & HEAP_XMAX_IS_MULTI)
4855 : : {
4856 : : int i;
4857 : : int nmembers;
4858 : : MultiXactMember *members;
4859 : :
4860 : : /*
4861 : : * We don't need to allow old multixacts here; if that had
4862 : : * been the case, HeapTupleSatisfiesUpdate would have returned
4863 : : * MayBeUpdated and we wouldn't be here.
4864 : : */
4865 : : nmembers =
4866 : 73302 : GetMultiXactIdMembers(xwait, &members, false,
4867 : 73302 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4868 : :
4869 [ + + ]: 1422679 : for (i = 0; i < nmembers; i++)
4870 : : {
4871 : : /* only consider members of our own transaction */
4872 [ + + ]: 1349391 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4873 : 1349341 : continue;
4874 : :
4875 [ + + ]: 50 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4876 : : {
5057 4877 : 14 : pfree(members);
2807 andres@anarazel.de 4878 : 14 : result = TM_Ok;
3785 4879 : 14 : goto out_unlocked;
4880 : : }
4881 : : else
4882 : : {
4883 : : /*
4884 : : * Disable acquisition of the heavyweight tuple lock.
4885 : : * Otherwise, when promoting a weaker lock, we might
4886 : : * deadlock with another locker that has acquired the
4887 : : * heavyweight tuple lock and is waiting for our
4888 : : * transaction to finish.
4889 : : *
4890 : : * Note that in this case we still need to wait for
4891 : : * the multixact if required, to avoid acquiring
4892 : : * conflicting locks.
4893 : : */
2720 alvherre@alvh.no-ip. 4894 : 36 : skip_tuple_lock = true;
4895 : : }
4896 : : }
4897 : :
4250 4898 [ + - ]: 73288 : if (members)
4899 : 73288 : pfree(members);
4900 : : }
4901 [ + + ]: 607722 : else if (TransactionIdIsCurrentTransactionId(xwait))
4902 : : {
4903 [ + + + + : 606348 : switch (mode)
- ]
4904 : : {
4905 : 599885 : case LockTupleKeyShare:
4906 [ - + - - : 599885 : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
- - ]
4907 : : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4908 : : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
2807 andres@anarazel.de 4909 : 599885 : result = TM_Ok;
3785 4910 : 599885 : goto out_unlocked;
4250 alvherre@alvh.no-ip. 4911 : 56 : case LockTupleShare:
4912 [ + + - + ]: 62 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4913 : 6 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4914 : : {
2807 andres@anarazel.de 4915 : 50 : result = TM_Ok;
3785 4916 : 50 : goto out_unlocked;
4917 : : }
4250 alvherre@alvh.no-ip. 4918 : 6 : break;
4919 : 87 : case LockTupleNoKeyExclusive:
4920 [ + + ]: 87 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4921 : : {
2807 andres@anarazel.de 4922 : 74 : result = TM_Ok;
3785 4923 : 74 : goto out_unlocked;
4924 : : }
4250 alvherre@alvh.no-ip. 4925 : 13 : break;
4926 : 6320 : case LockTupleExclusive:
4927 [ + + ]: 6320 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4928 [ + + ]: 1277 : infomask2 & HEAP_KEYS_UPDATED)
4929 : : {
2807 andres@anarazel.de 4930 : 1248 : result = TM_Ok;
3785 4931 : 1248 : goto out_unlocked;
4932 : : }
4250 alvherre@alvh.no-ip. 4933 : 5072 : break;
4934 : : }
4935 : : }
4936 : : }
4937 : :
4938 : : /*
4939 : : * Initially assume that we will have to wait for the locking
4940 : : * transaction(s) to finish. We check various cases below in which
4941 : : * this can be turned off.
4942 : : */
5057 4943 : 79764 : require_sleep = true;
4944 [ + + ]: 79764 : if (mode == LockTupleKeyShare)
4945 : : {
4946 : : /*
4947 : : * If we're requesting KeyShare, and there's no update present, we
4948 : : * don't need to wait. Even if there is an update, we can still
4949 : : * continue if the key hasn't been modified.
4950 : : *
4951 : : * However, if there are updates, we need to walk the update chain
4952 : : * to mark future versions of the row as locked, too. That way,
4953 : : * if somebody deletes that future version, we're protected
4954 : : * against the key going away. This locking of future versions
4955 : : * could block momentarily, if a concurrent transaction is
4956 : : * deleting a key; or it could return a value to the effect that
4957 : : * the transaction deleting the key has already committed. So we
4958 : : * do this before re-locking the buffer; otherwise this would be
4959 : : * prone to deadlocks.
4960 : : *
4961 : : * Note that the TID we're locking was grabbed before we unlocked
4962 : : * the buffer. For it to change while we're not looking, the
4963 : : * other properties we're testing for below after re-locking the
4964 : : * buffer would also change, in which case we would restart this
4965 : : * loop above.
4966 : : */
4967 [ + + ]: 73877 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4968 : : {
4969 : : bool updated;
4970 : :
4971 : 73825 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4972 : :
4973 : : /*
4974 : : * If there are updates, follow the update chain; bail out if
4975 : : * that cannot be done.
4976 : : */
340 heikki.linnakangas@i 4977 [ + + + + ]: 73825 : if (follow_updates && updated &&
4978 [ + - ]: 2175 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
4979 : : {
4980 : : TM_Result res;
4981 : :
4982 : 2175 : res = heap_lock_updated_tuple(relation,
4983 : : infomask, xwait, &t_ctid,
4984 : : GetCurrentTransactionId(),
4985 : : mode);
2807 andres@anarazel.de 4986 [ + + ]: 2175 : if (res != TM_Ok)
4987 : : {
5057 alvherre@alvh.no-ip. 4988 : 6 : result = res;
4989 : : /* recovery code expects to have buffer lock held */
961 akorotkov@postgresql 4990 : 6 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5057 alvherre@alvh.no-ip. 4991 : 217 : goto failed;
4992 : : }
4993 : : }
4994 : :
961 akorotkov@postgresql 4995 : 73819 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4996 : :
4997 : : /*
4998 : : * Make sure it's still an appropriate lock, else start over.
4999 : : * Also, if it wasn't updated before we released the lock, but
5000 : : * is updated now, we start over too; the reason is that we
5001 : : * now need to follow the update chain to lock the new
5002 : : * versions.
5003 : : */
5057 alvherre@alvh.no-ip. 5004 [ + + ]: 73819 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
5005 [ + - ]: 2158 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
5006 [ - + ]: 2158 : !updated))
5007 : 14 : goto l3;
5008 : :
5009 : : /* Things look okay, so we can skip sleeping */
5010 : 73819 : require_sleep = false;
5011 : :
5012 : : /*
5013 : : * Note we allow Xmax to change here; other updaters/lockers
5014 : : * could have modified it before we grabbed the buffer lock.
5015 : : * However, this is not a problem, because with the recheck we
5016 : : * just did we ensure that they still don't conflict with the
5017 : : * lock we want.
5018 : : */
5019 : : }
5020 : : }
5021 [ + + ]: 5887 : else if (mode == LockTupleShare)
5022 : : {
5023 : : /*
5024 : : * If we're requesting Share, we can similarly avoid sleeping if
5025 : : * there's no update and no exclusive lock present.
5026 : : */
5027 [ + - ]: 452 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5028 [ + + ]: 452 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
5029 : : {
961 akorotkov@postgresql 5030 : 446 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5031 : :
5032 : : /*
5033 : : * Make sure it's still an appropriate lock, else start over.
5034 : : * See above about allowing xmax to change.
5035 : : */
5057 alvherre@alvh.no-ip. 5036 [ + - - + ]: 892 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5037 : 446 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
5057 alvherre@alvh.no-ip. 5038 :UBC 0 : goto l3;
5057 alvherre@alvh.no-ip. 5039 :CBC 446 : require_sleep = false;
5040 : : }
5041 : : }
5042 [ + + ]: 5435 : else if (mode == LockTupleNoKeyExclusive)
5043 : : {
5044 : : /*
5045 : : * If we're requesting NoKeyExclusive, we might also be able to
5046 : : * avoid sleeping; just ensure that there no conflicting lock
5047 : : * already acquired.
5048 : : */
5049 [ + + ]: 185 : if (infomask & HEAP_XMAX_IS_MULTI)
5050 : : {
4355 5051 [ + + ]: 27 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
5052 : : mode, NULL))
5053 : : {
5054 : : /*
5055 : : * No conflict, but if the xmax changed under us in the
5056 : : * meantime, start over.
5057 : : */
961 akorotkov@postgresql 5058 : 13 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4355 alvherre@alvh.no-ip. 5059 [ + - - + ]: 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5060 : 13 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5061 : : xwait))
4355 alvherre@alvh.no-ip. 5062 :UBC 0 : goto l3;
5063 : :
5064 : : /* otherwise, we're good */
4355 alvherre@alvh.no-ip. 5065 :CBC 13 : require_sleep = false;
5066 : : }
5067 : : }
5057 5068 [ + + ]: 158 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
5069 : : {
961 akorotkov@postgresql 5070 : 19 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5071 : :
5072 : : /* if the xmax changed in the meantime, start over */
4601 alvherre@alvh.no-ip. 5073 [ + - - + ]: 38 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
2494 5074 : 19 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5075 : : xwait))
5057 alvherre@alvh.no-ip. 5076 :UBC 0 : goto l3;
5077 : : /* otherwise, we're good */
5057 alvherre@alvh.no-ip. 5078 :CBC 19 : require_sleep = false;
5079 : : }
5080 : : }
5081 : :
5082 : : /*
5083 : : * As a check independent from those above, we can also avoid sleeping
5084 : : * if the current transaction is the sole locker of the tuple. Note
5085 : : * that the strength of the lock already held is irrelevant; this is
5086 : : * not about recording the lock in Xmax (which will be done regardless
5087 : : * of this optimization, below). Also, note that the cases where we
5088 : : * hold a lock stronger than we are requesting are already handled
5089 : : * above by not doing anything.
5090 : : *
5091 : : * Note we only deal with the non-multixact case here; MultiXactIdWait
5092 : : * is well equipped to deal with this situation on its own.
5093 : : */
4250 5094 [ + + + + : 85174 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
+ + ]
5095 : 5416 : TransactionIdIsCurrentTransactionId(xwait))
5096 : : {
5097 : : /* ... but if the xmax changed in the meantime, start over */
961 akorotkov@postgresql 5098 : 5072 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4250 alvherre@alvh.no-ip. 5099 [ + - - + ]: 10144 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5100 : 5072 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5101 : : xwait))
4250 alvherre@alvh.no-ip. 5102 :UBC 0 : goto l3;
4250 alvherre@alvh.no-ip. 5103 [ - + ]:CBC 5072 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
5104 : 5072 : require_sleep = false;
5105 : : }
5106 : :
5107 : : /*
5108 : : * Time to sleep on the other transaction/multixact, if necessary.
5109 : : *
5110 : : * If the other transaction is an update/delete that's already
5111 : : * committed, then sleeping cannot possibly do any good: if we're
5112 : : * required to sleep, get out to raise an error instead.
5113 : : *
5114 : : * By here, we either have already acquired the buffer exclusive lock,
5115 : : * or we must wait for the locking transaction or multixact; so below
5116 : : * we ensure that we grab buffer lock after the sleep.
5117 : : */
2807 andres@anarazel.de 5118 [ + + + + : 79758 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
+ + ]
5119 : : {
961 akorotkov@postgresql 5120 : 170 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3788 alvherre@alvh.no-ip. 5121 : 170 : goto failed;
5122 : : }
5123 [ + + ]: 79588 : else if (require_sleep)
5124 : : {
5125 : : /*
5126 : : * Acquire tuple lock to establish our priority for the tuple, or
5127 : : * die trying. LockTuple will release us when we are next-in-line
5128 : : * for the tuple. We must do this even if we are share-locking,
5129 : : * but not if we already have a weaker lock on the tuple.
5130 : : *
5131 : : * If we are forced to "start over" below, we keep the tuple lock;
5132 : : * this arranges that we stay at the head of the line while
5133 : : * rechecking tuple state.
5134 : : */
2720 5135 [ + + ]: 219 : if (!skip_tuple_lock &&
5136 [ + + ]: 202 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
5137 : : &have_tuple_lock))
5138 : : {
5139 : : /*
5140 : : * This can only happen if wait_policy is Skip and the lock
5141 : : * couldn't be obtained.
5142 : : */
2807 andres@anarazel.de 5143 : 1 : result = TM_WouldBlock;
5144 : : /* recovery code expects to have buffer lock held */
961 akorotkov@postgresql 5145 : 1 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4355 alvherre@alvh.no-ip. 5146 : 1 : goto failed;
5147 : : }
5148 : :
5057 5149 [ + + ]: 217 : if (infomask & HEAP_XMAX_IS_MULTI)
5150 : : {
5151 : 45 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
5152 : :
5153 : : /* We only ever lock tuples, never update them */
5154 [ - + ]: 45 : if (status >= MultiXactStatusNoKeyUpdate)
5057 alvherre@alvh.no-ip. 5155 [ # # ]:UBC 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
5156 : :
5157 : : /* wait for multixact to end, or die trying */
4435 alvherre@alvh.no-ip. 5158 [ + + + - ]:CBC 45 : switch (wait_policy)
5159 : : {
5160 : 37 : case LockWaitBlock:
5161 : 37 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
3447 tgl@sss.pgh.pa.us 5162 : 37 : relation, &tuple->t_self, XLTW_Lock, NULL);
4435 alvherre@alvh.no-ip. 5163 : 37 : break;
5164 : 2 : case LockWaitSkip:
5165 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5166 : : status, infomask, relation,
5167 : : NULL, false))
5168 : : {
2807 andres@anarazel.de 5169 : 2 : result = TM_WouldBlock;
5170 : : /* recovery code expects to have buffer lock held */
961 akorotkov@postgresql 5171 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4435 alvherre@alvh.no-ip. 5172 : 2 : goto failed;
5173 : : }
4435 alvherre@alvh.no-ip. 5174 :UBC 0 : break;
4435 alvherre@alvh.no-ip. 5175 :CBC 6 : case LockWaitError:
5176 [ + - ]: 6 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5177 : : status, infomask, relation,
5178 : : NULL, log_lock_failures))
5179 [ + - ]: 6 : ereport(ERROR,
5180 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5181 : : errmsg("could not obtain lock on row in relation \"%s\"",
5182 : : RelationGetRelationName(relation))));
5183 : :
4435 alvherre@alvh.no-ip. 5184 :UBC 0 : break;
5185 : : }
5186 : :
5187 : : /*
5188 : : * Of course, the multixact might not be done here: if we're
5189 : : * requesting a light lock mode, other transactions with light
5190 : : * locks could still be alive, as well as locks owned by our
5191 : : * own xact or other subxacts of this backend. We need to
5192 : : * preserve the surviving MultiXact members. Note that it
5193 : : * isn't absolutely necessary in the latter case, but doing so
5194 : : * is simpler.
5195 : : */
5196 : : }
5197 : : else
5198 : : {
5199 : : /* wait for regular transaction to end, or die trying */
4435 alvherre@alvh.no-ip. 5200 [ + + + - ]:CBC 172 : switch (wait_policy)
5201 : : {
5202 : 131 : case LockWaitBlock:
4315 heikki.linnakangas@i 5203 : 131 : XactLockTableWait(xwait, relation, &tuple->t_self,
5204 : : XLTW_Lock);
4435 alvherre@alvh.no-ip. 5205 : 131 : break;
5206 : 33 : case LockWaitSkip:
624 fujii@postgresql.org 5207 [ + - ]: 33 : if (!ConditionalXactLockTableWait(xwait, false))
5208 : : {
2807 andres@anarazel.de 5209 : 33 : result = TM_WouldBlock;
5210 : : /* recovery code expects to have buffer lock held */
961 akorotkov@postgresql 5211 : 33 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4435 alvherre@alvh.no-ip. 5212 : 33 : goto failed;
5213 : : }
4435 alvherre@alvh.no-ip. 5214 :UBC 0 : break;
4435 alvherre@alvh.no-ip. 5215 :CBC 8 : case LockWaitError:
543 fujii@postgresql.org 5216 [ + - ]: 8 : if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
4435 alvherre@alvh.no-ip. 5217 [ + - ]: 8 : ereport(ERROR,
5218 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5219 : : errmsg("could not obtain lock on row in relation \"%s\"",
5220 : : RelationGetRelationName(relation))));
4435 alvherre@alvh.no-ip. 5221 :UBC 0 : break;
5222 : : }
5223 : : }
5224 : :
5225 : : /* if there are updates, follow the update chain */
340 heikki.linnakangas@i 5226 [ + + + + ]:CBC 168 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5227 [ + + ]: 73 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
5228 : : {
5229 : : TM_Result res;
5230 : :
5231 : 57 : res = heap_lock_updated_tuple(relation,
5232 : : infomask, xwait, &t_ctid,
5233 : : GetCurrentTransactionId(),
5234 : : mode);
2807 andres@anarazel.de 5235 [ + + ]: 57 : if (res != TM_Ok)
5236 : : {
4250 alvherre@alvh.no-ip. 5237 : 5 : result = res;
5238 : : /* recovery code expects to have buffer lock held */
961 akorotkov@postgresql 5239 : 5 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4250 alvherre@alvh.no-ip. 5240 : 5 : goto failed;
5241 : : }
5242 : : }
5243 : :
961 akorotkov@postgresql 5244 : 163 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5245 : :
5246 : : /*
5247 : : * xwait is done, but if xwait had just locked the tuple then some
5248 : : * other xact could update this tuple before we get to this point.
5249 : : * Check for xmax change, and start over if so.
5250 : : */
4250 alvherre@alvh.no-ip. 5251 [ + + + + ]: 313 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5252 : 150 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5253 : : xwait))
5254 : 14 : goto l3;
5255 : :
5256 [ + + ]: 149 : if (!(infomask & HEAP_XMAX_IS_MULTI))
5257 : : {
5258 : : /*
5259 : : * Otherwise check if it committed or aborted. Note we cannot
5260 : : * be here if the tuple was only locked by somebody who didn't
5261 : : * conflict with us; that would have been handled above. So
5262 : : * that transaction must necessarily be gone by now. But
5263 : : * don't check for this in the multixact case, because some
5264 : : * locker transactions might still be running.
5265 : : */
961 akorotkov@postgresql 5266 : 113 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5267 : : }
5268 : : }
5269 : :
5270 : : /* By here, we're certain that we hold buffer exclusive lock again */
5271 : :
5272 : : /*
5273 : : * We may lock if previous xmax aborted, or if it committed but only
5274 : : * locked the tuple without updating it; or if we didn't have to wait
5275 : : * at all for whatever reason.
5276 : : */
5057 alvherre@alvh.no-ip. 5277 [ + + ]: 79518 : if (!require_sleep ||
5278 [ + + + + ]: 262 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5279 [ + + ]: 210 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5280 : 97 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
2807 andres@anarazel.de 5281 : 79430 : result = TM_Ok;
2105 alvherre@alvh.no-ip. 5282 [ + + ]: 88 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
2807 andres@anarazel.de 5283 : 67 : result = TM_Updated;
5284 : : else
5285 : 21 : result = TM_Deleted;
5286 : : }
5287 : :
5057 alvherre@alvh.no-ip. 5288 : 81801 : failed:
2807 andres@anarazel.de 5289 [ + + ]: 161536 : if (result != TM_Ok)
5290 : : {
5291 [ + + + + : 317 : Assert(result == TM_SelfModified || result == TM_Updated ||
+ + - + ]
5292 : : result == TM_Deleted || result == TM_WouldBlock);
5293 : :
5294 : : /*
5295 : : * When locking a tuple under LockWaitSkip semantics and we fail with
5296 : : * TM_WouldBlock above, it's possible for concurrent transactions to
5297 : : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5298 : : * this assert is slightly different from the equivalent one in
5299 : : * heap_delete and heap_update.
5300 : : */
1789 alvherre@alvh.no-ip. 5301 [ + + - + ]: 317 : Assert((result == TM_WouldBlock) ||
5302 : : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
2807 andres@anarazel.de 5303 [ + + - + ]: 317 : Assert(result != TM_Updated ||
5304 : : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5305 : 317 : tmfd->ctid = tuple->t_data->t_ctid;
5306 : 317 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5307 [ + + ]: 317 : if (result == TM_SelfModified)
5308 : 12 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5309 : : else
5310 : 305 : tmfd->cmax = InvalidCommandId;
3785 5311 : 317 : goto out_locked;
5312 : : }
5313 : :
5314 : : /*
5315 : : * If we didn't pin the visibility map page and the page has become all
5316 : : * visible while we were busy locking the buffer, or during some
5317 : : * subsequent window during which we had it unlocked, we'll have to unlock
5318 : : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5319 : : * unfortunate, especially since we'll now have to recheck whether the
5320 : : * tuple has been locked or updated under us, but hopefully it won't
5321 : : * happen very often.
5322 : : */
3768 5323 [ + + - + ]: 161219 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5324 : : {
961 akorotkov@postgresql 5325 :UBC 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3768 andres@anarazel.de 5326 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
961 akorotkov@postgresql 5327 : 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3768 andres@anarazel.de 5328 : 0 : goto l3;
5329 : : }
5330 : :
5057 alvherre@alvh.no-ip. 5331 :CBC 161219 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5332 : 161219 : old_infomask = tuple->t_data->t_infomask;
5333 : :
5334 : : /*
5335 : : * If this is the first possibly-multixact-able operation in the current
5336 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
5337 : : * certain that the transaction will never become a member of any older
5338 : : * MultiXactIds than that. (We have to do this even if we end up just
5339 : : * using our own TransactionId below, since some other backend could
5340 : : * incorporate our XID into a MultiXact immediately afterwards.)
5341 : : */
5342 : 161219 : MultiXactIdSetOldestMember();
5343 : :
5344 : : /*
5345 : : * Compute the new xmax and infomask to store into the tuple. Note we do
5346 : : * not modify the tuple just yet, because that would leave it in the wrong
5347 : : * state if multixact.c elogs.
5348 : : */
5349 : 161219 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5350 : : GetCurrentTransactionId(), mode, false,
5351 : : &xid, &new_infomask, &new_infomask2);
5352 : :
5353 : : /* Lock VM buffer before entering critical section */
136 melanieplageman@gmai 5354 [ + + ]: 161219 : if (PageIsAllVisible(page))
5355 : : {
5356 : 3514 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
5357 : 3514 : unlock_vmbuffer = true;
5358 : : }
5359 : :
7884 tgl@sss.pgh.pa.us 5360 : 161219 : START_CRIT_SECTION();
5361 : :
5362 : : /*
5363 : : * Store transaction information of xact locking the tuple.
5364 : : *
5365 : : * Note: Cmax is meaningless in this context, so don't set it; this avoids
5366 : : * possibly generating a useless combo CID. Moreover, if we're locking a
5367 : : * previously updated tuple, it's important to preserve the Cmax.
5368 : : *
5369 : : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5370 : : * we would break the HOT chain.
5371 : : */
5057 alvherre@alvh.no-ip. 5372 : 161219 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5373 : 161219 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5374 : 161219 : tuple->t_data->t_infomask |= new_infomask;
5375 : 161219 : tuple->t_data->t_infomask2 |= new_infomask2;
5376 [ + + ]: 161219 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5377 : 159065 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
8108 tgl@sss.pgh.pa.us 5378 : 161219 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
5379 : :
5380 : : /*
5381 : : * Make sure there is no forward chain link in t_ctid. Note that in the
5382 : : * cases where the tuple has been updated, we must not overwrite t_ctid,
5383 : : * because it was set by the updater. Moreover, if the tuple has been
5384 : : * updated, we need to follow the update chain to lock the new versions of
5385 : : * the tuple as well.
5386 : : */
5057 alvherre@alvh.no-ip. 5387 [ + + ]: 161219 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5388 : 159065 : tuple->t_data->t_ctid = *tid;
5389 : :
5390 : : /* Clear only the all-frozen bit on visibility map if needed */
136 melanieplageman@gmai 5391 [ + + ]: 161219 : if (PageIsAllVisible(page))
5392 : : {
136 melanieplageman@gmai 5393 [ + + ]:GNC 3514 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
5394 : : VISIBILITYMAP_ALL_FROZEN))
136 melanieplageman@gmai 5395 :CBC 16 : cleared_all_frozen = true;
5396 : : }
5397 : :
5398 : :
961 akorotkov@postgresql 5399 : 161219 : MarkBufferDirty(*buffer);
5400 : :
5401 : : /*
5402 : : * XLOG stuff. You might think that we don't need an XLOG record because
5403 : : * there is no state change worth restoring after a crash. You would be
5404 : : * wrong however: we have just written either a TransactionId or a
5405 : : * MultiXactId that may never have been seen on disk before, and we need
5406 : : * to make sure that there are XLOG entries covering those ID numbers.
5407 : : * Else the same IDs might be re-used after a crash, which would be
5408 : : * disastrous if this page made it to disk before the crash. Essentially
5409 : : * we have to enforce the WAL log-before-data rule even in this case.
5410 : : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5411 : : * entries for everything anyway.)
5412 : : */
5829 rhaas@postgresql.org 5413 [ + + + + : 161219 : if (RelationNeedsWAL(relation))
+ - + - ]
5414 : : {
5415 : : xl_heap_lock xlrec;
5416 : : XLogRecPtr recptr;
5417 : :
4391 heikki.linnakangas@i 5418 : 160786 : XLogBeginInsert();
136 melanieplageman@gmai 5419 : 160786 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, *buffer, REGBUF_STANDARD);
5420 : :
4391 heikki.linnakangas@i 5421 : 160786 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
1327 pg@bowt.ie 5422 : 160786 : xlrec.xmax = xid;
5057 alvherre@alvh.no-ip. 5423 : 321572 : xlrec.infobits_set = compute_infobits(new_infomask,
5424 : 160786 : tuple->t_data->t_infomask2);
3785 andres@anarazel.de 5425 : 160786 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
655 peter@eisentraut.org 5426 : 160786 : XLogRegisterData(&xlrec, SizeOfHeapLock);
5427 : :
136 melanieplageman@gmai 5428 [ + + ]: 160786 : if (cleared_all_frozen)
5429 : 16 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
5430 : :
5431 : : /* we don't decode row locks atm, so no need to log the origin */
5432 : :
4391 heikki.linnakangas@i 5433 : 160786 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5434 : :
6712 tgl@sss.pgh.pa.us 5435 : 160786 : PageSetLSN(page, recptr);
5436 : :
136 melanieplageman@gmai 5437 [ + + ]: 160786 : if (cleared_all_frozen)
5438 : 16 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
5439 : : }
5440 : :
7884 tgl@sss.pgh.pa.us 5441 [ - + ]: 161219 : END_CRIT_SECTION();
5442 : :
5443 : : /* release VM lock first, since it covers many heap blocks */
136 melanieplageman@gmai 5444 [ + + ]: 161219 : if (unlock_vmbuffer)
5445 : : {
5446 : 3514 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
5447 : 3514 : unlock_vmbuffer = false;
5448 : : }
5449 : :
2807 andres@anarazel.de 5450 : 161219 : result = TM_Ok;
5451 : :
3785 5452 : 161564 : out_locked:
961 akorotkov@postgresql 5453 : 161564 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
136 melanieplageman@gmai 5454 [ - + ]: 161564 : Assert(!unlock_vmbuffer);
5455 : :
3785 andres@anarazel.de 5456 : 161564 : out_unlocked:
5457 [ + + ]: 762835 : if (BufferIsValid(vmbuffer))
5458 : 604033 : ReleaseBuffer(vmbuffer);
5459 : :
5460 : : /*
5461 : : * Don't update the visibility map here. Locking a tuple doesn't change
5462 : : * visibility info.
5463 : : */
5464 : :
5465 : : /*
5466 : : * Now that we have successfully marked the tuple as locked, we can
5467 : : * release the lmgr tuple lock, if we had it.
5468 : : */
7882 tgl@sss.pgh.pa.us 5469 [ + + ]: 762835 : if (have_tuple_lock)
5057 alvherre@alvh.no-ip. 5470 : 181 : UnlockTupleTuplock(relation, tid, mode);
5471 : :
3785 andres@anarazel.de 5472 : 762835 : return result;
5473 : : }
5474 : :
5475 : : /*
5476 : : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5477 : : * its normal, Xmax-based tuple lock.
5478 : : *
5479 : : * have_tuple_lock is an input and output parameter: on input, it indicates
5480 : : * whether the lock has previously been acquired (and this function does
5481 : : * nothing in that case). If this function returns success, have_tuple_lock
5482 : : * has been flipped to true.
5483 : : *
5484 : : * Returns false if it was unable to obtain the lock; this can only happen if
5485 : : * wait_policy is Skip.
5486 : : */
5487 : : static bool
394 peter@eisentraut.org 5488 : 361 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
5489 : : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5490 : : {
4355 alvherre@alvh.no-ip. 5491 [ + + ]: 361 : if (*have_tuple_lock)
5492 : 9 : return true;
5493 : :
5494 [ + + + - ]: 352 : switch (wait_policy)
5495 : : {
5496 : 305 : case LockWaitBlock:
5497 : 305 : LockTupleTuplock(relation, tid, mode);
5498 : 305 : break;
5499 : :
5500 : 34 : case LockWaitSkip:
624 fujii@postgresql.org 5501 [ + + ]: 34 : if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
4355 alvherre@alvh.no-ip. 5502 : 1 : return false;
5503 : 33 : break;
5504 : :
5505 : 13 : case LockWaitError:
543 fujii@postgresql.org 5506 [ + + ]: 13 : if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
4355 alvherre@alvh.no-ip. 5507 [ + - ]: 1 : ereport(ERROR,
5508 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5509 : : errmsg("could not obtain lock on row in relation \"%s\"",
5510 : : RelationGetRelationName(relation))));
5511 : 12 : break;
5512 : : }
5513 : 350 : *have_tuple_lock = true;
5514 : :
5515 : 350 : return true;
5516 : : }
5517 : :
5518 : : /*
5519 : : * Given an original set of Xmax and infomask, and a transaction (identified by
5520 : : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5521 : : * corresponding infomasks to use on the tuple.
5522 : : *
5523 : : * Note that this might have side effects such as creating a new MultiXactId.
5524 : : *
5525 : : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5526 : : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5527 : : * but it was not running anymore. There is a race condition, which is that the
5528 : : * MultiXactId may have finished since then, but that uncommon case is handled
5529 : : * either here, or within MultiXactIdExpand.
5530 : : *
5531 : : * There is a similar race condition possible when the old xmax was a regular
5532 : : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5533 : : * window, but it's still possible to end up creating an unnecessary
5534 : : * MultiXactId. Fortunately this is harmless.
5535 : : */
5536 : : static void
5057 5537 : 6680587 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5538 : : uint16 old_infomask2, TransactionId add_to_xmax,
5539 : : LockTupleMode mode, bool is_update,
5540 : : TransactionId *result_xmax, uint16 *result_infomask,
5541 : : uint16 *result_infomask2)
5542 : : {
5543 : : TransactionId new_xmax;
5544 : : uint16 new_infomask,
5545 : : new_infomask2;
5546 : :
4727 5547 [ + - ]: 6680587 : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5548 : :
5057 5549 : 6785229 : l5:
5550 : 6785229 : new_infomask = 0;
5551 : 6785229 : new_infomask2 = 0;
5552 [ + + ]: 6785229 : if (old_infomask & HEAP_XMAX_INVALID)
5553 : : {
5554 : : /*
5555 : : * No previous locker; we just insert our own TransactionId.
5556 : : *
5557 : : * Note that it's critical that this case be the first one checked,
5558 : : * because there are several blocks below that come back to this one
5559 : : * to implement certain optimizations; old_infomask might contain
5560 : : * other dirty bits in those cases, but we don't really care.
5561 : : */
5562 [ + + ]: 6603929 : if (is_update)
5563 : : {
5564 : 4301504 : new_xmax = add_to_xmax;
5565 [ + + ]: 4301504 : if (mode == LockTupleExclusive)
5566 : 1930943 : new_infomask2 |= HEAP_KEYS_UPDATED;
5567 : : }
5568 : : else
5569 : : {
5570 : 2302425 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5571 [ + + + + : 2302425 : switch (mode)
- ]
5572 : : {
5573 : 6335 : case LockTupleKeyShare:
5574 : 6335 : new_xmax = add_to_xmax;
5575 : 6335 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5576 : 6335 : break;
5577 : 805 : case LockTupleShare:
5578 : 805 : new_xmax = add_to_xmax;
5579 : 805 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5580 : 805 : break;
5581 : 2199036 : case LockTupleNoKeyExclusive:
5582 : 2199036 : new_xmax = add_to_xmax;
5583 : 2199036 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5584 : 2199036 : break;
5585 : 96249 : case LockTupleExclusive:
5586 : 96249 : new_xmax = add_to_xmax;
5587 : 96249 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5588 : 96249 : new_infomask2 |= HEAP_KEYS_UPDATED;
5589 : 96249 : break;
5057 alvherre@alvh.no-ip. 5590 :UBC 0 : default:
5591 : 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5592 [ # # ]: 0 : elog(ERROR, "invalid lock mode");
5593 : : }
5594 : : }
5595 : : }
5057 alvherre@alvh.no-ip. 5596 [ + + ]:CBC 181300 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5597 : : {
5598 : : MultiXactStatus new_status;
5599 : :
5600 : : /*
5601 : : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5602 : : * cross-check.
5603 : : */
5604 [ - + ]: 75576 : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5605 : :
5606 : : /*
5607 : : * A multixact together with LOCK_ONLY set but neither lock bit set
5608 : : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5609 : : * anymore. This check is critical for databases upgraded by
5610 : : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5611 : : * that such multis are never passed.
5612 : : */
3809 5613 [ - + ]: 75576 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5614 : : {
5057 alvherre@alvh.no-ip. 5615 :UBC 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5616 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5617 : 0 : goto l5;
5618 : : }
5619 : :
5620 : : /*
5621 : : * If the XMAX is already a MultiXactId, then we need to expand it to
5622 : : * include add_to_xmax; but if all the members were lockers and are
5623 : : * all gone, we can do away with the IS_MULTI bit and just set
5624 : : * add_to_xmax as the only locker/updater. If all lockers are gone
5625 : : * and we have an updater that aborted, we can also do without a
5626 : : * multi.
5627 : : *
5628 : : * The cost of doing GetMultiXactIdMembers would be paid by
5629 : : * MultiXactIdExpand if we weren't to do this, so this check is not
5630 : : * incurring extra work anyhow.
5631 : : */
4505 alvherre@alvh.no-ip. 5632 [ + + ]:CBC 75576 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5633 : : {
5057 5634 [ + + ]: 29 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4250 5635 [ + - ]: 13 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5636 : : old_infomask)))
5637 : : {
5638 : : /*
5639 : : * Reset these bits and restart; otherwise fall through to
5640 : : * create a new multi below.
5641 : : */
5057 5642 : 29 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5643 : 29 : old_infomask |= HEAP_XMAX_INVALID;
5644 : 29 : goto l5;
5645 : : }
5646 : : }
5647 : :
5648 : 75547 : new_status = get_mxact_status_for_lock(mode, is_update);
5649 : :
5650 : 75547 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5651 : : new_status);
5652 : 75547 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5653 : : }
5654 [ + + ]: 105724 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5655 : : {
5656 : : /*
5657 : : * It's a committed update, so we need to preserve him as updater of
5658 : : * the tuple.
5659 : : */
5660 : : MultiXactStatus status;
5661 : : MultiXactStatus new_status;
5662 : :
5663 [ - + ]: 14 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5057 alvherre@alvh.no-ip. 5664 :UBC 0 : status = MultiXactStatusUpdate;
5665 : : else
5057 alvherre@alvh.no-ip. 5666 :CBC 14 : status = MultiXactStatusNoKeyUpdate;
5667 : :
5668 : 14 : new_status = get_mxact_status_for_lock(mode, is_update);
5669 : :
5670 : : /*
5671 : : * since it's not running, it's obviously impossible for the old
5672 : : * updater to be identical to the current one, so we need not check
5673 : : * for that case as we do in the block above.
5674 : : */
5675 : 14 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5676 : 14 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5677 : : }
5678 [ + + ]: 105710 : else if (TransactionIdIsInProgress(xmax))
5679 : : {
5680 : : /*
5681 : : * If the XMAX is a valid, in-progress TransactionId, then we need to
5682 : : * create a new MultiXactId that includes both the old locker or
5683 : : * updater and our own TransactionId.
5684 : : */
5685 : : MultiXactStatus new_status;
5686 : : MultiXactStatus old_status;
5687 : : LockTupleMode old_mode;
5688 : :
5689 [ + + ]: 105701 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5690 : : {
5691 [ + + ]: 105669 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4727 5692 : 5693 : old_status = MultiXactStatusForKeyShare;
5057 5693 [ + + ]: 99976 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4727 5694 : 443 : old_status = MultiXactStatusForShare;
5057 5695 [ + - ]: 99533 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5696 : : {
5697 [ + + ]: 99533 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4727 5698 : 92966 : old_status = MultiXactStatusForUpdate;
5699 : : else
5700 : 6567 : old_status = MultiXactStatusForNoKeyUpdate;
5701 : : }
5702 : : else
5703 : : {
5704 : : /*
5705 : : * LOCK_ONLY can be present alone only when a page has been
5706 : : * upgraded by pg_upgrade. But in that case,
5707 : : * TransactionIdIsInProgress() should have returned false. We
5708 : : * assume it's no longer locked in this case.
5709 : : */
5057 alvherre@alvh.no-ip. 5710 [ # # ]:UBC 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5711 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5712 : 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5713 : 0 : goto l5;
5714 : : }
5715 : : }
5716 : : else
5717 : : {
5718 : : /* it's an update, but which kind? */
5057 alvherre@alvh.no-ip. 5719 [ - + ]:CBC 32 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4727 alvherre@alvh.no-ip. 5720 :UBC 0 : old_status = MultiXactStatusUpdate;
5721 : : else
4727 alvherre@alvh.no-ip. 5722 :CBC 32 : old_status = MultiXactStatusNoKeyUpdate;
5723 : : }
5724 : :
5725 : 105701 : old_mode = TUPLOCK_from_mxstatus(old_status);
5726 : :
5727 : : /*
5728 : : * If the lock to be acquired is for the same TransactionId as the
5729 : : * existing lock, there's an optimization possible: consider only the
5730 : : * strongest of both locks as the only one present, and restart.
5731 : : */
5057 5732 [ + + ]: 105701 : if (xmax == add_to_xmax)
5733 : : {
5734 : : /*
5735 : : * Note that it's not possible for the original tuple to be
5736 : : * updated: we wouldn't be here because the tuple would have been
5737 : : * invisible and we wouldn't try to update it. As a subtlety,
5738 : : * this code can also run when traversing an update chain to lock
5739 : : * future versions of a tuple. But we wouldn't be here either,
5740 : : * because the add_to_xmax would be different from the original
5741 : : * updater.
5742 : : */
4727 5743 [ - + ]: 104605 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5744 : :
5745 : : /* acquire the strongest of both */
5746 [ + + ]: 104605 : if (mode < old_mode)
5747 : 52238 : mode = old_mode;
5748 : : /* mustn't touch is_update */
5749 : :
5750 : 104605 : old_infomask |= HEAP_XMAX_INVALID;
5751 : 104605 : goto l5;
5752 : : }
5753 : :
5754 : : /* otherwise, just fall back to creating a new multixact */
5755 : 1096 : new_status = get_mxact_status_for_lock(mode, is_update);
5756 : 1096 : new_xmax = MultiXactIdCreate(xmax, old_status,
5757 : : add_to_xmax, new_status);
5057 5758 : 1096 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5759 : : }
5760 [ + + + + ]: 14 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5761 : 5 : TransactionIdDidCommit(xmax))
5762 : 1 : {
5763 : : /*
5764 : : * It's a committed update, so we gotta preserve him as updater of the
5765 : : * tuple.
5766 : : */
5767 : : MultiXactStatus status;
5768 : : MultiXactStatus new_status;
5769 : :
5770 [ - + ]: 1 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5057 alvherre@alvh.no-ip. 5771 :UBC 0 : status = MultiXactStatusUpdate;
5772 : : else
5057 alvherre@alvh.no-ip. 5773 :CBC 1 : status = MultiXactStatusNoKeyUpdate;
5774 : :
5775 : 1 : new_status = get_mxact_status_for_lock(mode, is_update);
5776 : :
5777 : : /*
5778 : : * since it's not running, it's obviously impossible for the old
5779 : : * updater to be identical to the current one, so we need not check
5780 : : * for that case as we do in the block above.
5781 : : */
5782 : 1 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5783 : 1 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5784 : : }
5785 : : else
5786 : : {
5787 : : /*
5788 : : * Can get here iff the locking/updating transaction was running when
5789 : : * the infomask was extracted from the tuple, but finished before
5790 : : * TransactionIdIsInProgress got to run. Deal with it as if there was
5791 : : * no locker at all in the first place.
5792 : : */
5793 : 8 : old_infomask |= HEAP_XMAX_INVALID;
5794 : 8 : goto l5;
5795 : : }
5796 : :
5797 : 6680587 : *result_infomask = new_infomask;
5798 : 6680587 : *result_infomask2 = new_infomask2;
5799 : 6680587 : *result_xmax = new_xmax;
5800 : 6680587 : }
5801 : :
5802 : : /*
5803 : : * Subroutine for heap_lock_updated_tuple_rec.
5804 : : *
5805 : : * Given a hypothetical multixact status held by the transaction identified
5806 : : * with the given xid, does the current transaction need to wait, fail, or can
5807 : : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5808 : : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5809 : : * returned. If the lock is already held by the current transaction, return
5810 : : * TM_SelfModified. In case of a conflict with another transaction, a
5811 : : * different HeapTupleSatisfiesUpdate return code is returned.
5812 : : *
5813 : : * The held status is said to be hypothetical because it might correspond to a
5814 : : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5815 : : * way for simplicity of API.
5816 : : */
5817 : : static TM_Result
4749 5818 : 38777 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5819 : : LockTupleMode mode, HeapTuple tup,
5820 : : bool *needwait)
5821 : : {
5822 : : MultiXactStatus wantedstatus;
5823 : :
5824 : 38777 : *needwait = false;
5825 : 38777 : wantedstatus = get_mxact_status_for_lock(mode, false);
5826 : :
5827 : : /*
5828 : : * Note: we *must* check TransactionIdIsInProgress before
5829 : : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5830 : : * for an explanation.
5831 : : */
5832 [ - + ]: 38777 : if (TransactionIdIsCurrentTransactionId(xid))
5833 : : {
5834 : : /*
5835 : : * The tuple has already been locked by our own transaction. This is
5836 : : * very rare but can happen if multiple transactions are trying to
5837 : : * lock an ancient version of the same tuple.
5838 : : */
2807 andres@anarazel.de 5839 :UBC 0 : return TM_SelfModified;
5840 : : }
4749 alvherre@alvh.no-ip. 5841 [ + + ]:CBC 38777 : else if (TransactionIdIsInProgress(xid))
5842 : : {
5843 : : /*
5844 : : * If the locking transaction is running, what we do depends on
5845 : : * whether the lock modes conflict: if they do, then we must wait for
5846 : : * it to finish; otherwise we can fall through to lock this tuple
5847 : : * version without waiting.
5848 : : */
5849 [ + + ]: 36539 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5850 : 36539 : LOCKMODE_from_mxstatus(wantedstatus)))
5851 : : {
5852 : 8 : *needwait = true;
5853 : : }
5854 : :
5855 : : /*
5856 : : * If we set needwait above, then this value doesn't matter;
5857 : : * otherwise, this value signals to caller that it's okay to proceed.
5858 : : */
2807 andres@anarazel.de 5859 : 36539 : return TM_Ok;
5860 : : }
4749 alvherre@alvh.no-ip. 5861 [ + + ]: 2238 : else if (TransactionIdDidAbort(xid))
2807 andres@anarazel.de 5862 : 206 : return TM_Ok;
4749 alvherre@alvh.no-ip. 5863 [ + - ]: 2032 : else if (TransactionIdDidCommit(xid))
5864 : : {
5865 : : /*
5866 : : * The other transaction committed. If it was only a locker, then the
5867 : : * lock is completely gone now and we can return success; but if it
5868 : : * was an update, then what we do depends on whether the two lock
5869 : : * modes conflict. If they conflict, then we must report error to
5870 : : * caller. But if they don't, we can fall through to allow the current
5871 : : * transaction to lock the tuple.
5872 : : *
5873 : : * Note: the reason we worry about ISUPDATE here is because as soon as
5874 : : * a transaction ends, all its locks are gone and meaningless, and
5875 : : * thus we can ignore them; whereas its updates persist. In the
5876 : : * TransactionIdIsInProgress case, above, we don't need to check
5877 : : * because we know the lock is still "alive" and thus a conflict needs
5878 : : * always be checked.
5879 : : */
4741 5880 [ + + ]: 2032 : if (!ISUPDATE_from_mxstatus(status))
2807 andres@anarazel.de 5881 : 2020 : return TM_Ok;
5882 : :
4749 alvherre@alvh.no-ip. 5883 [ + + ]: 12 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5884 : 12 : LOCKMODE_from_mxstatus(wantedstatus)))
5885 : : {
5886 : : /* bummer */
2105 5887 [ + + ]: 11 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
2807 andres@anarazel.de 5888 : 9 : return TM_Updated;
5889 : : else
5890 : 2 : return TM_Deleted;
5891 : : }
5892 : :
5893 : 1 : return TM_Ok;
5894 : : }
5895 : :
5896 : : /* Not in progress, not aborted, not committed -- must have crashed */
2807 andres@anarazel.de 5897 :UBC 0 : return TM_Ok;
5898 : : }
5899 : :
5900 : :
5901 : : /*
5902 : : * Recursive part of heap_lock_updated_tuple
5903 : : *
5904 : : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5905 : : * xid with the given mode; if this tuple is updated, recurse to lock the new
5906 : : * version as well.
5907 : : */
5908 : : static TM_Result
340 heikki.linnakangas@i 5909 :CBC 2230 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
5910 : : const ItemPointerData *tid, TransactionId xid,
5911 : : LockTupleMode mode)
5912 : : {
5913 : : TM_Result result;
5914 : : ItemPointerData tupid;
5915 : : HeapTupleData mytup;
5916 : : Buffer buf;
5917 : : Page page;
5918 : : uint16 new_infomask,
5919 : : new_infomask2,
5920 : : old_infomask,
5921 : : old_infomask2;
5922 : : TransactionId xmax,
5923 : : new_xmax;
3785 andres@anarazel.de 5924 : 2230 : bool cleared_all_frozen = false;
5925 : : bool pinned_desired_page;
5926 : 2230 : Buffer vmbuffer = InvalidBuffer;
136 melanieplageman@gmai 5927 : 2230 : bool unlock_vmbuffer = false;
5928 : : BlockNumber block;
5929 : :
5057 alvherre@alvh.no-ip. 5930 : 2230 : ItemPointerCopy(tid, &tupid);
5931 : :
5932 : : for (;;)
5933 : : {
5934 : 2233 : new_infomask = 0;
5935 : 2233 : new_xmax = InvalidTransactionId;
136 melanieplageman@gmai 5936 : 2233 : cleared_all_frozen = false;
3785 andres@anarazel.de 5937 : 2233 : block = ItemPointerGetBlockNumber(&tupid);
5057 alvherre@alvh.no-ip. 5938 : 2233 : ItemPointerCopy(&tupid, &(mytup.t_self));
5939 : :
1690 tgl@sss.pgh.pa.us 5940 [ + - ]: 2233 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5941 : : {
5942 : : /*
5943 : : * if we fail to find the updated version of the tuple, it's
5944 : : * because it was vacuumed/pruned away after its creator
5945 : : * transaction aborted. So behave as if we got to the end of the
5946 : : * chain, and there's no further tuple to lock: return success to
5947 : : * caller.
5948 : : */
2807 andres@anarazel.de 5949 :UBC 0 : result = TM_Ok;
3193 tgl@sss.pgh.pa.us 5950 : 0 : goto out_unlocked;
5951 : : }
5952 : :
5057 alvherre@alvh.no-ip. 5953 :CBC 2233 : l4:
5954 [ - + ]: 2241 : CHECK_FOR_INTERRUPTS();
5955 : :
136 melanieplageman@gmai 5956 : 2241 : page = BufferGetPage(buf);
5957 : :
5958 : : /*
5959 : : * Before locking the buffer, pin the visibility map page if it
5960 : : * appears to be necessary. Since we haven't got the lock yet,
5961 : : * someone else might be in the middle of changing this, so we'll need
5962 : : * to recheck after we have the lock.
5963 : : */
5964 [ - + ]: 2241 : if (PageIsAllVisible(page))
5965 : : {
3785 andres@anarazel.de 5966 :UBC 0 : visibilitymap_pin(rel, block, &vmbuffer);
3193 tgl@sss.pgh.pa.us 5967 : 0 : pinned_desired_page = true;
5968 : : }
5969 : : else
3193 tgl@sss.pgh.pa.us 5970 :CBC 2241 : pinned_desired_page = false;
5971 : :
5057 alvherre@alvh.no-ip. 5972 : 2241 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5973 : :
5974 : : /*
5975 : : * If we didn't pin the visibility map page and the page has become
5976 : : * all visible while we were busy locking the buffer, we'll have to
5977 : : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5978 : : * That's a bit unfortunate, but hopefully shouldn't happen often.
5979 : : *
5980 : : * Note: in some paths through this function, we will reach here
5981 : : * holding a pin on a vm page that may or may not be the one matching
5982 : : * this page. If this page isn't all-visible, we won't use the vm
5983 : : * page, but we hold onto such a pin till the end of the function.
5984 : : */
136 melanieplageman@gmai 5985 [ + - - + ]: 2241 : if (!pinned_desired_page && PageIsAllVisible(page))
5986 : : {
3768 andres@anarazel.de 5987 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5988 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5989 : 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5990 : : }
5991 : :
5992 : : /*
5993 : : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5994 : : * end of the chain, we're done, so return success.
5995 : : */
4749 alvherre@alvh.no-ip. 5996 [ + - + + ]:CBC 4482 : if (TransactionIdIsValid(priorXmax) &&
3313 5997 : 2241 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5998 : : priorXmax))
5999 : : {
2807 andres@anarazel.de 6000 : 2 : result = TM_Ok;
3785 6001 : 2 : goto out_locked;
6002 : : }
6003 : :
6004 : : /*
6005 : : * Also check Xmin: if this tuple was created by an aborted
6006 : : * (sub)transaction, then we already locked the last live one in the
6007 : : * chain, thus we're done, so return success.
6008 : : */
3732 alvherre@alvh.no-ip. 6009 [ + + ]: 2239 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
6010 : : {
2807 andres@anarazel.de 6011 : 25 : result = TM_Ok;
3193 tgl@sss.pgh.pa.us 6012 : 25 : goto out_locked;
6013 : : }
6014 : :
5057 alvherre@alvh.no-ip. 6015 : 2214 : old_infomask = mytup.t_data->t_infomask;
4749 6016 : 2214 : old_infomask2 = mytup.t_data->t_infomask2;
5057 6017 : 2214 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
6018 : :
6019 : : /*
6020 : : * If this tuple version has been updated or locked by some concurrent
6021 : : * transaction(s), what we do depends on whether our lock mode
6022 : : * conflicts with what those other transactions hold, and also on the
6023 : : * status of them.
6024 : : */
4749 6025 [ + + ]: 2214 : if (!(old_infomask & HEAP_XMAX_INVALID))
6026 : : {
6027 : : TransactionId rawxmax;
6028 : : bool needwait;
6029 : :
6030 : 2141 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
6031 [ + + ]: 2141 : if (old_infomask & HEAP_XMAX_IS_MULTI)
6032 : : {
6033 : : int nmembers;
6034 : : int i;
6035 : : MultiXactMember *members;
6036 : :
6037 : : /*
6038 : : * We don't need a test for pg_upgrade'd tuples: this is only
6039 : : * applied to tuples after the first in an update chain. Said
6040 : : * first tuple in the chain may well be locked-in-9.2-and-
6041 : : * pg_upgraded, but that one was already locked by our caller,
6042 : : * not us; and any subsequent ones cannot be because our
6043 : : * caller must necessarily have obtained a snapshot later than
6044 : : * the pg_upgrade itself.
6045 : : */
3809 6046 [ - + ]: 2109 : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
6047 : :
4505 6048 : 2109 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
3447 tgl@sss.pgh.pa.us 6049 : 2109 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4749 alvherre@alvh.no-ip. 6050 [ + + ]: 40854 : for (i = 0; i < nmembers; i++)
6051 : : {
3785 andres@anarazel.de 6052 : 38745 : result = test_lockmode_for_conflict(members[i].status,
6053 : 38745 : members[i].xid,
6054 : : mode,
6055 : : &mytup,
6056 : : &needwait);
6057 : :
6058 : : /*
6059 : : * If the tuple was already locked by ourselves in a
6060 : : * previous iteration of this (say heap_lock_tuple was
6061 : : * forced to restart the locking loop because of a change
6062 : : * in xmax), then we hold the lock already on this tuple
6063 : : * version and we don't need to do anything; and this is
6064 : : * not an error condition either. We just need to skip
6065 : : * this tuple and continue locking the next version in the
6066 : : * update chain.
6067 : : */
2807 6068 [ - + ]: 38745 : if (result == TM_SelfModified)
6069 : : {
3412 alvherre@alvh.no-ip. 6070 :UBC 0 : pfree(members);
6071 : 0 : goto next;
6072 : : }
6073 : :
4749 alvherre@alvh.no-ip. 6074 [ - + ]:CBC 38745 : if (needwait)
6075 : : {
4749 alvherre@alvh.no-ip. 6076 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4637 6077 : 0 : XactLockTableWait(members[i].xid, rel,
6078 : : &mytup.t_self,
6079 : : XLTW_LockUpdated);
4749 6080 : 0 : pfree(members);
6081 : 0 : goto l4;
6082 : : }
2807 andres@anarazel.de 6083 [ - + ]:CBC 38745 : if (result != TM_Ok)
6084 : : {
4749 alvherre@alvh.no-ip. 6085 :UBC 0 : pfree(members);
3785 andres@anarazel.de 6086 : 0 : goto out_locked;
6087 : : }
6088 : : }
4749 alvherre@alvh.no-ip. 6089 [ + - ]:CBC 2109 : if (members)
6090 : 2109 : pfree(members);
6091 : : }
6092 : : else
6093 : : {
6094 : : MultiXactStatus status;
6095 : :
6096 : : /*
6097 : : * For a non-multi Xmax, we first need to compute the
6098 : : * corresponding MultiXactStatus by using the infomask bits.
6099 : : */
6100 [ + + ]: 32 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
6101 : : {
6102 [ + - ]: 10 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
6103 : 10 : status = MultiXactStatusForKeyShare;
4749 alvherre@alvh.no-ip. 6104 [ # # ]:UBC 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
6105 : 0 : status = MultiXactStatusForShare;
6106 [ # # ]: 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
6107 : : {
6108 [ # # ]: 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6109 : 0 : status = MultiXactStatusForUpdate;
6110 : : else
6111 : 0 : status = MultiXactStatusForNoKeyUpdate;
6112 : : }
6113 : : else
6114 : : {
6115 : : /*
6116 : : * LOCK_ONLY present alone (a pg_upgraded tuple marked
6117 : : * as share-locked in the old cluster) shouldn't be
6118 : : * seen in the middle of an update chain.
6119 : : */
6120 [ # # ]: 0 : elog(ERROR, "invalid lock status in tuple");
6121 : : }
6122 : : }
6123 : : else
6124 : : {
6125 : : /* it's an update, but which kind? */
4749 alvherre@alvh.no-ip. 6126 [ + + ]:CBC 22 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6127 : 17 : status = MultiXactStatusUpdate;
6128 : : else
6129 : 5 : status = MultiXactStatusNoKeyUpdate;
6130 : : }
6131 : :
3785 andres@anarazel.de 6132 : 32 : result = test_lockmode_for_conflict(status, rawxmax, mode,
6133 : : &mytup, &needwait);
6134 : :
6135 : : /*
6136 : : * If the tuple was already locked by ourselves in a previous
6137 : : * iteration of this (say heap_lock_tuple was forced to
6138 : : * restart the locking loop because of a change in xmax), then
6139 : : * we hold the lock already on this tuple version and we don't
6140 : : * need to do anything; and this is not an error condition
6141 : : * either. We just need to skip this tuple and continue
6142 : : * locking the next version in the update chain.
6143 : : */
2807 6144 [ - + ]: 32 : if (result == TM_SelfModified)
3412 alvherre@alvh.no-ip. 6145 :UBC 0 : goto next;
6146 : :
4749 alvherre@alvh.no-ip. 6147 [ + + ]:CBC 32 : if (needwait)
6148 : : {
6149 : 8 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4315 heikki.linnakangas@i 6150 : 8 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
6151 : : XLTW_LockUpdated);
4749 alvherre@alvh.no-ip. 6152 : 8 : goto l4;
6153 : : }
2807 andres@anarazel.de 6154 [ + + ]: 24 : if (result != TM_Ok)
6155 : : {
3785 6156 : 11 : goto out_locked;
6157 : : }
6158 : : }
6159 : : }
6160 : :
6161 : : /* compute the new Xmax and infomask values for the tuple ... */
5057 alvherre@alvh.no-ip. 6162 : 2195 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
6163 : : xid, mode, false,
6164 : : &new_xmax, &new_infomask, &new_infomask2);
6165 : :
136 melanieplageman@gmai 6166 [ - + ]: 2195 : if (PageIsAllVisible(page))
6167 : : {
136 melanieplageman@gmai 6168 :UBC 0 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
6169 : 0 : unlock_vmbuffer = true;
6170 : : }
6171 : :
5057 alvherre@alvh.no-ip. 6172 :CBC 2195 : START_CRIT_SECTION();
6173 : :
6174 : : /* ... and set them */
6175 : 2195 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
6176 : 2195 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
6177 : 2195 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6178 : 2195 : mytup.t_data->t_infomask |= new_infomask;
6179 : 2195 : mytup.t_data->t_infomask2 |= new_infomask2;
6180 : :
6181 : 2195 : MarkBufferDirty(buf);
6182 : :
136 melanieplageman@gmai 6183 [ - + ]: 2195 : if (PageIsAllVisible(page))
6184 : : {
6185 : : /* It's possible all-frozen was already clear */
136 melanieplageman@gmai 6186 [ # # ]:UNC 0 : if (visibilitymap_clear(rel->rd_locator, block, vmbuffer,
6187 : : VISIBILITYMAP_ALL_FROZEN))
136 melanieplageman@gmai 6188 :UBC 0 : cleared_all_frozen = true;
6189 : : }
6190 : :
6191 : : /* XLOG stuff */
5057 alvherre@alvh.no-ip. 6192 [ + - + + :CBC 2195 : if (RelationNeedsWAL(rel))
+ - + - ]
6193 : : {
6194 : : xl_heap_lock_updated xlrec;
6195 : : XLogRecPtr recptr;
6196 : :
4391 heikki.linnakangas@i 6197 : 2195 : XLogBeginInsert();
136 melanieplageman@gmai 6198 : 2195 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buf, REGBUF_STANDARD);
6199 : :
4391 heikki.linnakangas@i 6200 : 2195 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5057 alvherre@alvh.no-ip. 6201 : 2195 : xlrec.xmax = new_xmax;
6202 : 2195 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
3785 andres@anarazel.de 6203 : 2195 : xlrec.flags =
6204 : 2195 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
6205 : :
655 peter@eisentraut.org 6206 : 2195 : XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
6207 : :
136 melanieplageman@gmai 6208 [ - + ]: 2195 : if (cleared_all_frozen)
136 melanieplageman@gmai 6209 :UBC 0 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
6210 : :
4391 heikki.linnakangas@i 6211 :CBC 2195 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
6212 : :
5057 alvherre@alvh.no-ip. 6213 : 2195 : PageSetLSN(page, recptr);
6214 : :
136 melanieplageman@gmai 6215 [ - + ]: 2195 : if (cleared_all_frozen)
136 melanieplageman@gmai 6216 :UBC 0 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
6217 : : }
6218 : :
5057 alvherre@alvh.no-ip. 6219 [ - + ]:CBC 2195 : END_CRIT_SECTION();
6220 : :
6221 : : /* release VM lock first, since it covers many heap blocks */
136 melanieplageman@gmai 6222 [ + - ]: 2195 : if (unlock_vmbuffer)
6223 : : {
136 melanieplageman@gmai 6224 :UBC 0 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
6225 : 0 : unlock_vmbuffer = false;
6226 : : }
6227 : :
3412 alvherre@alvh.no-ip. 6228 :CBC 2195 : next:
6229 : : /* if we find the end of update chain, we're done. */
5057 6230 [ + - + - ]: 4390 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
3157 andres@anarazel.de 6231 [ + + ]: 4390 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
4931 bruce@momjian.us 6232 [ + + ]: 2199 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5057 alvherre@alvh.no-ip. 6233 : 4 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
6234 : : {
2807 andres@anarazel.de 6235 : 2192 : result = TM_Ok;
3785 6236 : 2192 : goto out_locked;
6237 : : }
6238 : :
6239 : : /* tail recursion */
4749 alvherre@alvh.no-ip. 6240 : 3 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5057 6241 : 3 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6242 : 3 : UnlockReleaseBuffer(buf);
6243 : : }
6244 : :
6245 : : result = TM_Ok;
6246 : :
3785 andres@anarazel.de 6247 : 2230 : out_locked:
6248 : 2230 : UnlockReleaseBuffer(buf);
6249 : :
3193 tgl@sss.pgh.pa.us 6250 : 2230 : out_unlocked:
3785 andres@anarazel.de 6251 [ - + ]: 2230 : if (vmbuffer != InvalidBuffer)
3785 andres@anarazel.de 6252 :UBC 0 : ReleaseBuffer(vmbuffer);
136 melanieplageman@gmai 6253 [ - + ]:CBC 2230 : Assert(!unlock_vmbuffer);
6254 : :
3785 andres@anarazel.de 6255 : 2230 : return result;
6256 : : }
6257 : :
6258 : : /*
6259 : : * heap_lock_updated_tuple
6260 : : * Follow update chain when locking an updated tuple, acquiring locks (row
6261 : : * marks) on the updated versions.
6262 : : *
6263 : : * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
6264 : : * fields from the initial tuple. We will lock the tuples starting from the
6265 : : * one that 'prior_ctid' points to. Note: This function does not lock the
6266 : : * initial tuple itself.
6267 : : *
6268 : : * This function doesn't check visibility, it just unconditionally marks the
6269 : : * tuple(s) as locked. If any tuple in the updated chain is being deleted
6270 : : * concurrently (or updated with the key being modified), sleep until the
6271 : : * transaction doing it is finished.
6272 : : *
6273 : : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6274 : : * when we have to wait for other transactions to release them, as opposed to
6275 : : * what heap_lock_tuple does. The reason is that having more than one
6276 : : * transaction walking the chain is probably uncommon enough that risk of
6277 : : * starvation is not likely: one of the preconditions for being here is that
6278 : : * the snapshot in use predates the update that created this tuple (because we
6279 : : * started at an earlier version of the tuple), but at the same time such a
6280 : : * transaction cannot be using repeatable read or serializable isolation
6281 : : * levels, because that would lead to a serializability failure.
6282 : : */
6283 : : static TM_Result
340 heikki.linnakangas@i 6284 : 2232 : heap_lock_updated_tuple(Relation rel,
6285 : : uint16 prior_infomask,
6286 : : TransactionId prior_raw_xmax,
6287 : : const ItemPointerData *prior_ctid,
6288 : : TransactionId xid, LockTupleMode mode)
6289 : : {
6290 : 2232 : INJECTION_POINT("heap_lock_updated_tuple", NULL);
6291 : :
6292 : : /*
6293 : : * If the tuple has moved into another partition (effectively a delete)
6294 : : * stop here.
6295 : : */
6296 [ + + ]: 2232 : if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
6297 : : {
6298 : : TransactionId prior_xmax;
6299 : :
6300 : : /*
6301 : : * If this is the first possibly-multixact-able operation in the
6302 : : * current transaction, set my per-backend OldestMemberMXactId
6303 : : * setting. We can be certain that the transaction will never become a
6304 : : * member of any older MultiXactIds than that. (We have to do this
6305 : : * even if we end up just using our own TransactionId below, since
6306 : : * some other backend could incorporate our XID into a MultiXact
6307 : : * immediately afterwards.)
6308 : : */
5057 alvherre@alvh.no-ip. 6309 : 2230 : MultiXactIdSetOldestMember();
6310 : :
340 heikki.linnakangas@i 6311 : 4460 : prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
6312 [ + + ]: 2230 : MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
6313 : 2230 : return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
6314 : : }
6315 : :
6316 : : /* nothing to lock */
2807 andres@anarazel.de 6317 : 2 : return TM_Ok;
6318 : : }
6319 : :
6320 : : /*
6321 : : * heap_finish_speculative - mark speculative insertion as successful
6322 : : *
6323 : : * To successfully finish a speculative insertion we have to clear speculative
6324 : : * token from tuple. To do so the t_ctid field, which will contain a
6325 : : * speculative token value, is modified in place to point to the tuple itself,
6326 : : * which is characteristic of a newly inserted ordinary tuple.
6327 : : *
6328 : : * NB: It is not ok to commit without either finishing or aborting a
6329 : : * speculative insertion. We could treat speculative tuples of committed
6330 : : * transactions implicitly as completed, but then we would have to be prepared
6331 : : * to deal with speculative tokens on committed tuples. That wouldn't be
6332 : : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6333 : : * but clearing the token at completion isn't very expensive either.
6334 : : * An explicit confirmation WAL record also makes logical decoding simpler.
6335 : : */
6336 : : void
394 peter@eisentraut.org 6337 : 2235 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
6338 : : {
6339 : : Buffer buffer;
6340 : : Page page;
6341 : : OffsetNumber offnum;
6342 : : ItemId lp;
6343 : : HeapTupleHeader htup;
6344 : :
2807 andres@anarazel.de 6345 : 2235 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4222 6346 : 2235 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
456 peter@eisentraut.org 6347 : 2235 : page = BufferGetPage(buffer);
6348 : :
2807 andres@anarazel.de 6349 : 2235 : offnum = ItemPointerGetOffsetNumber(tid);
348 tgl@sss.pgh.pa.us 6350 [ + - - + ]: 2235 : if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
348 tgl@sss.pgh.pa.us 6351 [ # # ]:UBC 0 : elog(ERROR, "offnum out of range");
348 tgl@sss.pgh.pa.us 6352 :CBC 2235 : lp = PageGetItemId(page, offnum);
6353 [ - + ]: 2235 : if (!ItemIdIsNormal(lp))
4027 andres@anarazel.de 6354 [ # # ]:UBC 0 : elog(ERROR, "invalid lp");
6355 : :
4222 andres@anarazel.de 6356 :CBC 2235 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6357 : :
6358 : : /* NO EREPORT(ERROR) from here till changes are logged */
6359 : 2235 : START_CRIT_SECTION();
6360 : :
2807 6361 [ - + ]: 2235 : Assert(HeapTupleHeaderIsSpeculative(htup));
6362 : :
4222 6363 : 2235 : MarkBufferDirty(buffer);
6364 : :
6365 : : /*
6366 : : * Replace the speculative insertion token with a real t_ctid, pointing to
6367 : : * itself like it does on regular tuples.
6368 : : */
2807 6369 : 2235 : htup->t_ctid = *tid;
6370 : :
6371 : : /* XLOG stuff */
4222 6372 [ + + + + : 2235 : if (RelationNeedsWAL(relation))
+ - + - ]
6373 : : {
6374 : : xl_heap_confirm xlrec;
6375 : : XLogRecPtr recptr;
6376 : :
2807 6377 : 2216 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
6378 : :
4222 6379 : 2216 : XLogBeginInsert();
6380 : :
6381 : : /* We want the same filtering on this as on a plain insert */
3628 6382 : 2216 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6383 : :
655 peter@eisentraut.org 6384 : 2216 : XLogRegisterData(&xlrec, SizeOfHeapConfirm);
4222 andres@anarazel.de 6385 : 2216 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6386 : :
6387 : 2216 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6388 : :
6389 : 2216 : PageSetLSN(page, recptr);
6390 : : }
6391 : :
6392 [ - + ]: 2235 : END_CRIT_SECTION();
6393 : :
6394 : 2235 : UnlockReleaseBuffer(buffer);
6395 : 2235 : }
6396 : :
6397 : : /*
6398 : : * heap_abort_speculative - kill a speculatively inserted tuple
6399 : : *
6400 : : * Marks a tuple that was speculatively inserted in the same command as dead,
6401 : : * by setting its xmin as invalid. That makes it immediately appear as dead
6402 : : * to all transactions, including our own. In particular, it makes
6403 : : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6404 : : * inserting a duplicate key value won't unnecessarily wait for our whole
6405 : : * transaction to finish (it'll just wait for our speculative insertion to
6406 : : * finish).
6407 : : *
6408 : : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6409 : : * that arise due to a mutual dependency that is not user visible. By
6410 : : * definition, unprincipled deadlocks cannot be prevented by the user
6411 : : * reordering lock acquisition in client code, because the implementation level
6412 : : * lock acquisitions are not under the user's direct control. If speculative
6413 : : * inserters did not take this precaution, then under high concurrency they
6414 : : * could deadlock with each other, which would not be acceptable.
6415 : : *
6416 : : * This is somewhat redundant with heap_delete, but we prefer to have a
6417 : : * dedicated routine with stripped down requirements. Note that this is also
6418 : : * used to delete the TOAST tuples created during speculative insertion.
6419 : : *
6420 : : * This routine does not affect logical decoding as it only looks at
6421 : : * confirmation records.
6422 : : */
6423 : : void
394 peter@eisentraut.org 6424 : 16 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
6425 : : {
4222 andres@anarazel.de 6426 : 16 : TransactionId xid = GetCurrentTransactionId();
6427 : : ItemId lp;
6428 : : HeapTupleData tp;
6429 : : Page page;
6430 : : BlockNumber block;
6431 : : Buffer buffer;
6432 : :
6433 [ - + ]: 16 : Assert(ItemPointerIsValid(tid));
6434 : :
6435 : 16 : block = ItemPointerGetBlockNumber(tid);
6436 : 16 : buffer = ReadBuffer(relation, block);
3874 kgrittn@postgresql.o 6437 : 16 : page = BufferGetPage(buffer);
6438 : :
4222 andres@anarazel.de 6439 : 16 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6440 : :
6441 : : /*
6442 : : * Page can't be all visible, we just inserted into it, and are still
6443 : : * running.
6444 : : */
6445 [ - + ]: 16 : Assert(!PageIsAllVisible(page));
6446 : :
6447 : 16 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6448 [ - + ]: 16 : Assert(ItemIdIsNormal(lp));
6449 : :
6450 : 16 : tp.t_tableOid = RelationGetRelid(relation);
6451 : 16 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6452 : 16 : tp.t_len = ItemIdGetLength(lp);
6453 : 16 : tp.t_self = *tid;
6454 : :
6455 : : /*
6456 : : * Sanity check that the tuple really is a speculatively inserted tuple,
6457 : : * inserted by us.
6458 : : */
6459 [ - + ]: 16 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
4222 andres@anarazel.de 6460 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
3755 andres@anarazel.de 6461 [ + + - + ]:CBC 16 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
4222 andres@anarazel.de 6462 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
4222 andres@anarazel.de 6463 [ - + ]:CBC 16 : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
6464 : :
6465 : : /*
6466 : : * No need to check for serializable conflicts here. There is never a
6467 : : * need for a combo CID, either. No need to extract replica identity, or
6468 : : * do anything special with infomask bits.
6469 : : */
6470 : :
6471 : 16 : START_CRIT_SECTION();
6472 : :
6473 : : /*
6474 : : * The tuple will become DEAD immediately. Flag that this page is a
6475 : : * candidate for pruning by setting xmin to TransactionXmin. While not
6476 : : * immediately prunable, it is the oldest xid we can cheaply determine
6477 : : * that's safe against wraparound / being older than the table's
6478 : : * relfrozenxid. To defend against the unlikely case of a new relation
6479 : : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6480 : : * if so (vacuum can't subsequently move relfrozenxid to beyond
6481 : : * TransactionXmin, so there's no race here).
6482 : : */
2428 6483 [ - + ]: 16 : Assert(TransactionIdIsValid(TransactionXmin));
6484 : : {
943 noah@leadboat.com 6485 : 16 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6486 : : TransactionId prune_xid;
6487 : :
6488 [ - + ]: 16 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
943 noah@leadboat.com 6489 :UBC 0 : prune_xid = relfrozenxid;
6490 : : else
943 noah@leadboat.com 6491 :CBC 16 : prune_xid = TransactionXmin;
6492 [ - + + - : 16 : PageSetPrunable(page, prune_xid);
+ + ]
6493 : : }
6494 : :
6495 : : /* store transaction information of xact deleting the tuple */
4222 andres@anarazel.de 6496 : 16 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
6497 : 16 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6498 : :
6499 : : /*
6500 : : * Set the tuple header xmin to InvalidTransactionId. This makes the
6501 : : * tuple immediately invisible everyone. (In particular, to any
6502 : : * transactions waiting on the speculative token, woken up later.)
6503 : : */
6504 : 16 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
6505 : :
6506 : : /* Clear the speculative insertion token too */
6507 : 16 : tp.t_data->t_ctid = tp.t_self;
6508 : :
6509 : 16 : MarkBufferDirty(buffer);
6510 : :
6511 : : /*
6512 : : * XLOG stuff
6513 : : *
6514 : : * The WAL records generated here match heap_delete(). The same recovery
6515 : : * routines are used.
6516 : : */
6517 [ + + + + : 16 : if (RelationNeedsWAL(relation))
+ - + - ]
6518 : : {
6519 : : xl_heap_delete xlrec;
6520 : : XLogRecPtr recptr;
6521 : :
6522 : 12 : xlrec.flags = XLH_DELETE_IS_SUPER;
6523 : 24 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6524 : 12 : tp.t_data->t_infomask2);
6525 : 12 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6526 : 12 : xlrec.xmax = xid;
6527 : :
6528 : 12 : XLogBeginInsert();
655 peter@eisentraut.org 6529 : 12 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
4222 andres@anarazel.de 6530 : 12 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6531 : :
6532 : : /* No replica identity & replication origin logged */
6533 : :
6534 : 12 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6535 : :
6536 : 12 : PageSetLSN(page, recptr);
6537 : : }
6538 : :
6539 [ - + ]: 16 : END_CRIT_SECTION();
6540 : :
6541 : 16 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6542 : :
6543 [ + + ]: 16 : if (HeapTupleHasExternal(&tp))
6544 : : {
3755 6545 [ - + ]: 1 : Assert(!IsToastRelation(relation));
2612 rhaas@postgresql.org 6546 : 1 : heap_toast_delete(relation, &tp, true);
6547 : : }
6548 : :
6549 : : /*
6550 : : * Never need to mark tuple for invalidation, since catalogs don't support
6551 : : * speculative insertion
6552 : : */
6553 : :
6554 : : /* Now we can release the buffer */
4222 andres@anarazel.de 6555 : 16 : ReleaseBuffer(buffer);
6556 : :
6557 : : /* count deletion, as we counted the insertion too */
6558 : 16 : pgstat_count_heap_delete(relation);
6559 : 16 : }
6560 : :
6561 : : /*
6562 : : * heap_inplace_lock - protect inplace update from concurrent heap_update()
6563 : : *
6564 : : * Evaluate whether the tuple's state is compatible with a no-key update.
6565 : : * Current transaction rowmarks are fine, as is KEY SHARE from any
6566 : : * transaction. If compatible, return true with the buffer exclusive-locked,
6567 : : * and the caller must release that by calling
6568 : : * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6569 : : * an error. Otherwise, call release_callback(arg), wait for blocking
6570 : : * transactions to end, and return false.
6571 : : *
6572 : : * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6573 : : * DDL, this doesn't guarantee any particular predicate locking.
6574 : : *
6575 : : * heap_delete() is a rarer source of blocking transactions (xwait). We'll
6576 : : * wait for such a transaction just like for the normal heap_update() case.
6577 : : * Normal concurrent DROP commands won't cause that, because all inplace
6578 : : * updaters take some lock that conflicts with DROP. An explicit SQL "DELETE
6579 : : * FROM pg_class" can cause it. By waiting, if the concurrent transaction
6580 : : * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
6581 : : * can find the successor tuple.
6582 : : *
6583 : : * Readers of inplace-updated fields expect changes to those fields are
6584 : : * durable. For example, vac_truncate_clog() reads datfrozenxid from
6585 : : * pg_database tuples via catalog snapshots. A future snapshot must not
6586 : : * return a lower datfrozenxid for the same database OID (lower in the
6587 : : * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6588 : : * tuple can start while we hold a lock on its buffer. In cases like
6589 : : * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6590 : : * to this transaction. ROLLBACK then is one case where it's okay to lose
6591 : : * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6592 : : * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6593 : : * committed tuple.)
6594 : : *
6595 : : * In principle, we could avoid waiting by overwriting every tuple in the
6596 : : * updated tuple chain. Reader expectations permit updating a tuple only if
6597 : : * it's aborted, is the tail of the chain, or we already updated the tuple
6598 : : * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6599 : : * order from tail to head. That would imply either (a) mutating all tuples
6600 : : * in one critical section or (b) accepting a chance of partial completion.
6601 : : * Partial completion of a relfrozenxid update would have the weird
6602 : : * consequence that the table's next VACUUM could see the table's relfrozenxid
6603 : : * move forward between vacuum_get_cutoffs() and finishing.
6604 : : */
6605 : : pg_attribute_no_sanitize_function()
6606 : : bool
795 noah@leadboat.com 6607 : 119542 : heap_inplace_lock(Relation relation,
6608 : : HeapTuple oldtup_ptr, Buffer buffer,
6609 : : void (*release_callback) (void *), void *arg)
6610 : : {
6611 : 119542 : HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6612 : : TM_Result result;
6613 : : bool ret;
6614 : :
6615 : : #ifdef USE_ASSERT_CHECKING
6616 [ + + ]: 119542 : if (RelationGetRelid(relation) == RelationRelationId)
6617 : 118092 : check_inplace_rel_lock(oldtup_ptr);
6618 : : #endif
6619 : :
6620 [ - + ]: 119542 : Assert(BufferIsValid(buffer));
6621 : :
6622 : : /*
6623 : : * Register shared cache invals if necessary. Other sessions may finish
6624 : : * inplace updates of this tuple between this step and LockTuple(). Since
6625 : : * inplace updates don't change cache keys, that's harmless.
6626 : : *
6627 : : * While it's tempting to register invals only after confirming we can
6628 : : * return true, the following obstacle precludes reordering steps that
6629 : : * way. Registering invals might reach a CatalogCacheInitializeCache()
6630 : : * that locks "buffer". That would hang indefinitely if running after our
6631 : : * own LockBuffer(). Hence, we must register invals before LockBuffer().
6632 : : */
348 6633 : 119542 : CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
6634 : :
795 6635 : 119542 : LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6636 : 119542 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6637 : :
6638 : : /*----------
6639 : : * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6640 : : *
6641 : : * - wait unconditionally
6642 : : * - already locked tuple above, since inplace needs that unconditionally
6643 : : * - don't recheck header after wait: simpler to defer to next iteration
6644 : : * - don't try to continue even if the updater aborts: likewise
6645 : : * - no crosscheck
6646 : : */
6647 : 119542 : result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6648 : : buffer);
6649 : :
6650 [ - + ]: 119542 : if (result == TM_Invisible)
6651 : : {
6652 : : /* no known way this can happen */
4230 rhaas@postgresql.org 6653 [ # # ]:UBC 0 : ereport(ERROR,
6654 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6655 : : errmsg_internal("attempted to overwrite invisible tuple")));
6656 : : }
795 noah@leadboat.com 6657 [ - + ]:CBC 119542 : else if (result == TM_SelfModified)
6658 : : {
6659 : : /*
6660 : : * CREATE INDEX might reach this if an expression is silly enough to
6661 : : * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6662 : : * statements might get here after a heap_update() of the same row, in
6663 : : * the absence of an intervening CommandCounterIncrement().
6664 : : */
795 noah@leadboat.com 6665 [ # # ]:UBC 0 : ereport(ERROR,
6666 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6667 : : errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6668 : : }
795 noah@leadboat.com 6669 [ + + ]:CBC 119542 : else if (result == TM_BeingModified)
6670 : : {
6671 : : TransactionId xwait;
6672 : : uint16 infomask;
6673 : :
6674 : 55 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6675 : 55 : infomask = oldtup.t_data->t_infomask;
6676 : :
6677 [ + + ]: 55 : if (infomask & HEAP_XMAX_IS_MULTI)
6678 : : {
6679 : 5 : LockTupleMode lockmode = LockTupleNoKeyExclusive;
6680 : 5 : MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
6681 : : int remain;
6682 : :
6683 [ + + ]: 5 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6684 : : lockmode, NULL))
6685 : : {
6686 : 2 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
760 6687 : 2 : release_callback(arg);
795 6688 : 2 : ret = false;
6689 : 2 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6690 : : relation, &oldtup.t_self, XLTW_Update,
6691 : : &remain);
6692 : : }
6693 : : else
6694 : 3 : ret = true;
6695 : : }
6696 [ + + ]: 50 : else if (TransactionIdIsCurrentTransactionId(xwait))
6697 : 1 : ret = true;
6698 [ + + ]: 49 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6699 : 1 : ret = true;
6700 : : else
6701 : : {
6702 : 48 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
760 6703 : 48 : release_callback(arg);
795 6704 : 48 : ret = false;
6705 : 48 : XactLockTableWait(xwait, relation, &oldtup.t_self,
6706 : : XLTW_Update);
6707 : : }
6708 : : }
6709 : : else
6710 : : {
6711 : 119487 : ret = (result == TM_Ok);
6712 [ + + ]: 119487 : if (!ret)
6713 : : {
6714 : 1 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
760 6715 : 1 : release_callback(arg);
6716 : : }
6717 : : }
6718 : :
6719 : : /*
6720 : : * GetCatalogSnapshot() relies on invalidation messages to know when to
6721 : : * take a new snapshot. COMMIT of xwait is responsible for sending the
6722 : : * invalidation. We're not acquiring heavyweight locks sufficient to
6723 : : * block if not yet sent, so we must take a new snapshot to ensure a later
6724 : : * attempt has a fair chance. While we don't need this if xwait aborted,
6725 : : * don't bother optimizing that.
6726 : : */
795 6727 [ + + ]: 119542 : if (!ret)
6728 : : {
6729 : 51 : UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
756 6730 : 51 : ForgetInplace_Inval();
795 6731 : 51 : InvalidateCatalogSnapshot();
6732 : : }
6733 : 119542 : return ret;
6734 : : }
6735 : :
6736 : : /*
6737 : : * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6738 : : *
6739 : : * The tuple cannot change size, and therefore its header fields and null
6740 : : * bitmap (if any) don't change either.
6741 : : *
6742 : : * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6743 : : */
6744 : : void
6745 : 83134 : heap_inplace_update_and_unlock(Relation relation,
6746 : : HeapTuple oldtup, HeapTuple tuple,
6747 : : Buffer buffer)
6748 : : {
6749 : 83134 : HeapTupleHeader htup = oldtup->t_data;
6750 : : uint32 oldlen;
6751 : : uint32 newlen;
6752 : : char *dst;
6753 : : char *src;
764 6754 : 83134 : int nmsgs = 0;
6755 : 83134 : SharedInvalidationMessage *invalMessages = NULL;
6756 : 83134 : bool RelcacheInitFileInval = false;
6757 : :
795 6758 [ - + ]: 83134 : Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6759 : 83134 : oldlen = oldtup->t_len - htup->t_hoff;
7507 tgl@sss.pgh.pa.us 6760 : 83134 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6761 [ + - - + ]: 83134 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
4027 andres@anarazel.de 6762 [ # # ]:UBC 0 : elog(ERROR, "wrong tuple length");
6763 : :
764 noah@leadboat.com 6764 :CBC 83134 : dst = (char *) htup + htup->t_hoff;
6765 : 83134 : src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6766 : :
6767 : : /* Like RecordTransactionCommit(), log only if needed */
6768 [ + + ]: 83134 : if (XLogStandbyInfoActive())
6769 : 75305 : nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6770 : : &RelcacheInitFileInval);
6771 : :
6772 : : /*
6773 : : * Unlink relcache init files as needed. If unlinking, acquire
6774 : : * RelCacheInitLock until after associated invalidations. By doing this
6775 : : * in advance, if we checkpoint and then crash between inplace
6776 : : * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6777 : : * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6778 : : * neglect to PANIC on EIO.
6779 : : */
6780 : 83134 : PreInplace_Inval();
6781 : :
6782 : : /*----------
6783 : : * NO EREPORT(ERROR) from here till changes are complete
6784 : : *
6785 : : * Our exclusive buffer lock won't stop a reader having already pinned and
6786 : : * checked visibility for this tuple. With the usual order of changes
6787 : : * (i.e. updating the buffer contents before WAL logging), a reader could
6788 : : * observe our not-yet-persistent update to relfrozenxid and update
6789 : : * datfrozenxid based on that. A crash in that moment could allow
6790 : : * datfrozenxid to overtake relfrozenxid:
6791 : : *
6792 : : * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6793 : : * ["R" is a VACUUM tbl]
6794 : : * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6795 : : * D: systable_getnext() returns pg_class tuple of tbl
6796 : : * R: memcpy() into pg_class tuple of tbl
6797 : : * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6798 : : * [crash]
6799 : : * [recovery restores datfrozenxid w/o relfrozenxid]
6800 : : *
6801 : : * We avoid that by using a temporary copy of the buffer to hide our
6802 : : * change from other backends until the change has been WAL-logged. We
6803 : : * apply our change to the temporary copy and WAL-log it, before modifying
6804 : : * the real page. That way any action a reader of the in-place-updated
6805 : : * value takes will be WAL logged after this change.
6806 : : */
6807 : 83134 : START_CRIT_SECTION();
6808 : :
263 andres@anarazel.de 6809 : 83134 : MarkBufferDirty(buffer);
6810 : :
6811 : : /* XLOG stuff */
5829 rhaas@postgresql.org 6812 [ + - + + : 83134 : if (RelationNeedsWAL(relation))
+ - + + ]
6813 : : {
6814 : : xl_heap_inplace xlrec;
6815 : : PGAlignedBlock copied_buffer;
764 noah@leadboat.com 6816 : 83130 : char *origdata = (char *) BufferGetBlock(buffer);
6817 : 83130 : Page page = BufferGetPage(buffer);
6818 : 83130 : uint16 lower = ((PageHeader) page)->pd_lower;
6819 : 83130 : uint16 upper = ((PageHeader) page)->pd_upper;
6820 : : uintptr_t dst_offset_in_block;
6821 : : RelFileLocator rlocator;
6822 : : ForkNumber forkno;
6823 : : BlockNumber blkno;
6824 : : XLogRecPtr recptr;
6825 : :
4391 heikki.linnakangas@i 6826 : 83130 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
764 noah@leadboat.com 6827 : 83130 : xlrec.dbId = MyDatabaseId;
6828 : 83130 : xlrec.tsId = MyDatabaseTableSpace;
6829 : 83130 : xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6830 : 83130 : xlrec.nmsgs = nmsgs;
6831 : :
4391 heikki.linnakangas@i 6832 : 83130 : XLogBeginInsert();
655 peter@eisentraut.org 6833 : 83130 : XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
764 noah@leadboat.com 6834 [ + + ]: 83130 : if (nmsgs != 0)
655 peter@eisentraut.org 6835 : 57665 : XLogRegisterData(invalMessages,
6836 : : nmsgs * sizeof(SharedInvalidationMessage));
6837 : :
6838 : : /* register block matching what buffer will look like after changes */
764 noah@leadboat.com 6839 : 83130 : memcpy(copied_buffer.data, origdata, lower);
6840 : 83130 : memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6841 : 83130 : dst_offset_in_block = dst - origdata;
6842 : 83130 : memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6843 : 83130 : BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6844 [ - + ]: 83130 : Assert(forkno == MAIN_FORKNUM);
6845 : 83130 : XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6846 : : REGBUF_STANDARD);
6847 : 83130 : XLogRegisterBufData(0, src, newlen);
6848 : :
6849 : : /* inplace updates aren't decoded atm, don't log the origin */
6850 : :
4391 heikki.linnakangas@i 6851 : 83130 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6852 : :
764 noah@leadboat.com 6853 : 83130 : PageSetLSN(page, recptr);
6854 : : }
6855 : :
6856 : 83134 : memcpy(dst, src, newlen);
6857 : :
6858 : 83134 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6859 : :
6860 : : /*
6861 : : * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6862 : : * do this before UnlockTuple().
6863 : : */
6864 : 83134 : AtInplace_Inval();
6865 : :
7507 tgl@sss.pgh.pa.us 6866 [ - + ]: 83134 : END_CRIT_SECTION();
764 noah@leadboat.com 6867 : 83134 : UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6868 : :
6869 : 83134 : AcceptInvalidationMessages(); /* local processing of just-sent inval */
6870 : :
6871 : : /*
6872 : : * Queue a transactional inval, for logical decoding and for third-party
6873 : : * code that might have been relying on it since long before inplace
6874 : : * update adopted immediate invalidation. See README.tuplock section
6875 : : * "Reading inplace-updated columns" for logical decoding details.
6876 : : */
7507 tgl@sss.pgh.pa.us 6877 [ + + ]: 83134 : if (!IsBootstrapProcessingMode())
5583 6878 : 65494 : CacheInvalidateHeapTuple(relation, tuple, NULL);
7507 6879 : 83134 : }
6880 : :
6881 : : /*
6882 : : * heap_inplace_unlock - reverse of heap_inplace_lock
6883 : : */
6884 : : void
795 noah@leadboat.com 6885 : 36357 : heap_inplace_unlock(Relation relation,
6886 : : HeapTuple oldtup, Buffer buffer)
6887 : : {
6888 : 36357 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6889 : 36357 : UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
756 6890 : 36357 : ForgetInplace_Inval();
795 6891 : 36357 : }
6892 : :
6893 : : #define FRM_NOOP 0x0001
6894 : : #define FRM_INVALIDATE_XMAX 0x0002
6895 : : #define FRM_RETURN_IS_XID 0x0004
6896 : : #define FRM_RETURN_IS_MULTI 0x0008
6897 : : #define FRM_MARK_COMMITTED 0x0010
6898 : :
6899 : : /*
6900 : : * FreezeMultiXactId
6901 : : * Determine what to do during freezing when a tuple is marked by a
6902 : : * MultiXactId.
6903 : : *
6904 : : * "flags" is an output value; it's used to tell caller what to do on return.
6905 : : * "pagefrz" is an input/output value, used to manage page level freezing.
6906 : : *
6907 : : * Possible values that we can set in "flags":
6908 : : * FRM_NOOP
6909 : : * don't do anything -- keep existing Xmax
6910 : : * FRM_INVALIDATE_XMAX
6911 : : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6912 : : * FRM_RETURN_IS_XID
6913 : : * The Xid return value is a single update Xid to set as xmax.
6914 : : * FRM_MARK_COMMITTED
6915 : : * Xmax can be marked as HEAP_XMAX_COMMITTED
6916 : : * FRM_RETURN_IS_MULTI
6917 : : * The return value is a new MultiXactId to set as new Xmax.
6918 : : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6919 : : *
6920 : : * Caller delegates control of page freezing to us. In practice we always
6921 : : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6922 : : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6923 : : * can never be left behind. We freely choose when and how to process each
6924 : : * Multi, without ever violating the cutoff postconditions for freezing.
6925 : : *
6926 : : * It's useful to remove Multis on a proactive timeline (relative to freezing
6927 : : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6928 : : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6929 : : * misses through eager processing.
6930 : : *
6931 : : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6932 : : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6933 : : * This can usually be put off, which is usually enough to avoid it altogether.
6934 : : * Allocating new multis during VACUUM should be avoided on general principle;
6935 : : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6936 : : * its own special risks.
6937 : : *
6938 : : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6939 : : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6940 : : *
6941 : : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6942 : : * have already forced page-level freezing, since that might incur the same
6943 : : * SLRU buffer misses that we specifically intended to avoid by freezing.
6944 : : */
6945 : : static TransactionId
4730 alvherre@alvh.no-ip. 6946 : 7 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6947 : : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6948 : : HeapPageFreeze *pagefrz)
6949 : : {
6950 : : TransactionId newxmax;
6951 : : MultiXactMember *members;
6952 : : int nmembers;
6953 : : bool need_replace;
6954 : : int nnewmembers;
6955 : : MultiXactMember *newmembers;
6956 : : bool has_lockers;
6957 : : TransactionId update_xid;
6958 : : bool update_committed;
6959 : : TransactionId FreezePageRelfrozenXid;
6960 : :
6961 : 7 : *flags = 0;
6962 : :
6963 : : /* We should only be called in Multis */
6964 [ - + ]: 7 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6965 : :
3809 6966 [ + - - + ]: 14 : if (!MultiXactIdIsValid(multi) ||
6967 : 7 : HEAP_LOCKED_UPGRADED(t_infomask))
6968 : : {
4730 alvherre@alvh.no-ip. 6969 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1431 pg@bowt.ie 6970 : 0 : pagefrz->freeze_required = true;
4730 alvherre@alvh.no-ip. 6971 : 0 : return InvalidTransactionId;
6972 : : }
1437 pg@bowt.ie 6973 [ - + ]:CBC 7 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
3302 andres@anarazel.de 6974 [ # # ]:UBC 0 : ereport(ERROR,
6975 : : (errcode(ERRCODE_DATA_CORRUPTED),
6976 : : errmsg_internal("found multixact %u from before relminmxid %u",
6977 : : multi, cutoffs->relminmxid)));
1431 pg@bowt.ie 6978 [ + + ]:CBC 7 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6979 : : {
6980 : : TransactionId update_xact;
6981 : :
6982 : : /*
6983 : : * This old multi cannot possibly have members still running, but
6984 : : * verify just in case. If it was a locker only, it can be removed
6985 : : * without any further consideration; but if it contained an update,
6986 : : * we might need to preserve it.
6987 : : */
3302 andres@anarazel.de 6988 [ - + ]: 5 : if (MultiXactIdIsRunning(multi,
6989 : 5 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
3302 andres@anarazel.de 6990 [ # # ]:UBC 0 : ereport(ERROR,
6991 : : (errcode(ERRCODE_DATA_CORRUPTED),
6992 : : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6993 : : multi, cutoffs->OldestMxact)));
6994 : :
4730 alvherre@alvh.no-ip. 6995 [ + - ]:CBC 5 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6996 : : {
6997 : 5 : *flags |= FRM_INVALIDATE_XMAX;
1431 pg@bowt.ie 6998 : 5 : pagefrz->freeze_required = true;
6999 : 5 : return InvalidTransactionId;
7000 : : }
7001 : :
7002 : : /* replace multi with single XID for its updater? */
1431 pg@bowt.ie 7003 :UBC 0 : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
7004 [ # # ]: 0 : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
7005 [ # # ]: 0 : ereport(ERROR,
7006 : : (errcode(ERRCODE_DATA_CORRUPTED),
7007 : : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
7008 : : multi, update_xact,
7009 : : cutoffs->relfrozenxid)));
7010 [ # # ]: 0 : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
7011 : : {
7012 : : /*
7013 : : * Updater XID has to have aborted (otherwise the tuple would have
7014 : : * been pruned away instead, since updater XID is < OldestXmin).
7015 : : * Just remove xmax.
7016 : : */
1425 7017 [ # # ]: 0 : if (TransactionIdDidCommit(update_xact))
1431 7018 [ # # ]: 0 : ereport(ERROR,
7019 : : (errcode(ERRCODE_DATA_CORRUPTED),
7020 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
7021 : : multi, update_xact,
7022 : : cutoffs->OldestXmin)));
7023 : 0 : *flags |= FRM_INVALIDATE_XMAX;
7024 : 0 : pagefrz->freeze_required = true;
7025 : 0 : return InvalidTransactionId;
7026 : : }
7027 : :
7028 : : /* Have to keep updater XID as new xmax */
7029 : 0 : *flags |= FRM_RETURN_IS_XID;
7030 : 0 : pagefrz->freeze_required = true;
7031 : 0 : return update_xact;
7032 : : }
7033 : :
7034 : : /*
7035 : : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
7036 : : * need to walk the whole members array to figure out what to do, if
7037 : : * anything.
7038 : : */
7039 : : nmembers =
3809 alvherre@alvh.no-ip. 7040 :CBC 2 : GetMultiXactIdMembers(multi, &members, false,
4505 7041 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
4730 7042 [ - + ]: 2 : if (nmembers <= 0)
7043 : : {
7044 : : /* Nothing worth keeping */
4730 alvherre@alvh.no-ip. 7045 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1431 pg@bowt.ie 7046 : 0 : pagefrz->freeze_required = true;
4730 alvherre@alvh.no-ip. 7047 : 0 : return InvalidTransactionId;
7048 : : }
7049 : :
7050 : : /*
7051 : : * The FRM_NOOP case is the only case where we might need to ratchet back
7052 : : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
7053 : : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
7054 : : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
7055 : : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
7056 : : * trackers managed by VACUUM being ratcheting back by xmax to the degree
7057 : : * required to make it safe to leave xmax undisturbed, independent of
7058 : : * whether or not page freezing is triggered somewhere else.
7059 : : *
7060 : : * Our policy is to force freezing in every case other than FRM_NOOP,
7061 : : * which obviates the need to maintain either set of trackers, anywhere.
7062 : : * Every other case will reliably execute a freeze plan for xmax that
7063 : : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
7064 : : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
7065 : : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
7066 : : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
7067 : : */
4730 alvherre@alvh.no-ip. 7068 :CBC 2 : need_replace = false;
1431 pg@bowt.ie 7069 : 2 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
1437 7070 [ + + ]: 4 : for (int i = 0; i < nmembers; i++)
7071 : : {
7072 : 3 : TransactionId xid = members[i].xid;
7073 : :
7074 [ - + ]: 3 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7075 : :
7076 [ + + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7077 : : {
7078 : : /* Can't violate the FreezeLimit postcondition */
4730 alvherre@alvh.no-ip. 7079 : 1 : need_replace = true;
7080 : 1 : break;
7081 : : }
1431 pg@bowt.ie 7082 [ - + ]: 2 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
1431 pg@bowt.ie 7083 :UBC 0 : FreezePageRelfrozenXid = xid;
7084 : : }
7085 : :
7086 : : /* Can't violate the MultiXactCutoff postcondition, either */
1431 pg@bowt.ie 7087 [ + + ]:CBC 2 : if (!need_replace)
7088 : 1 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
7089 : :
4730 alvherre@alvh.no-ip. 7090 [ + + ]: 2 : if (!need_replace)
7091 : : {
7092 : : /*
7093 : : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
7094 : : * both together to make it safe to retain this particular multi after
7095 : : * freezing its page
7096 : : */
7097 : 1 : *flags |= FRM_NOOP;
1431 pg@bowt.ie 7098 : 1 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
7099 [ - + ]: 1 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
1431 pg@bowt.ie 7100 :UBC 0 : pagefrz->FreezePageRelminMxid = multi;
4730 alvherre@alvh.no-ip. 7101 :CBC 1 : pfree(members);
1700 pg@bowt.ie 7102 : 1 : return multi;
7103 : : }
7104 : :
7105 : : /*
7106 : : * Do a more thorough second pass over the multi to figure out which
7107 : : * member XIDs actually need to be kept. Checking the precise status of
7108 : : * individual members might even show that we don't need to keep anything.
7109 : : * That is quite possible even though the Multi must be >= OldestMxact,
7110 : : * since our second pass only keeps member XIDs when it's truly necessary;
7111 : : * even member XIDs >= OldestXmin often won't be kept by second pass.
7112 : : */
4730 alvherre@alvh.no-ip. 7113 : 1 : nnewmembers = 0;
353 michael@paquier.xyz 7114 : 1 : newmembers = palloc_array(MultiXactMember, nmembers);
4730 alvherre@alvh.no-ip. 7115 : 1 : has_lockers = false;
7116 : 1 : update_xid = InvalidTransactionId;
7117 : 1 : update_committed = false;
7118 : :
7119 : : /*
7120 : : * Determine whether to keep each member xid, or to ignore it instead
7121 : : */
1437 pg@bowt.ie 7122 [ + + ]: 3 : for (int i = 0; i < nmembers; i++)
7123 : : {
7124 : 2 : TransactionId xid = members[i].xid;
7125 : 2 : MultiXactStatus mstatus = members[i].status;
7126 : :
7127 [ - + ]: 2 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7128 : :
7129 [ + - ]: 2 : if (!ISUPDATE_from_mxstatus(mstatus))
7130 : : {
7131 : : /*
7132 : : * Locker XID (not updater XID). We only keep lockers that are
7133 : : * still running.
7134 : : */
7135 [ + - + + ]: 4 : if (TransactionIdIsCurrentTransactionId(xid) ||
7136 : 2 : TransactionIdIsInProgress(xid))
7137 : : {
1431 7138 [ - + ]: 1 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
1431 pg@bowt.ie 7139 [ # # ]:UBC 0 : ereport(ERROR,
7140 : : (errcode(ERRCODE_DATA_CORRUPTED),
7141 : : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
7142 : : multi, xid,
7143 : : cutoffs->OldestXmin)));
1437 pg@bowt.ie 7144 :CBC 1 : newmembers[nnewmembers++] = members[i];
7145 : 1 : has_lockers = true;
7146 : : }
7147 : :
7148 : 2 : continue;
7149 : : }
7150 : :
7151 : : /*
7152 : : * Updater XID (not locker XID). Should we keep it?
7153 : : *
7154 : : * Since the tuple wasn't totally removed when vacuum pruned, the
7155 : : * update Xid cannot possibly be older than OldestXmin cutoff unless
7156 : : * the updater XID aborted. If the updater transaction is known
7157 : : * aborted or crashed then it's okay to ignore it, otherwise not.
7158 : : *
7159 : : * In any case the Multi should never contain two updaters, whatever
7160 : : * their individual commit status. Check for that first, in passing.
7161 : : */
1437 pg@bowt.ie 7162 [ # # ]:UBC 0 : if (TransactionIdIsValid(update_xid))
7163 [ # # ]: 0 : ereport(ERROR,
7164 : : (errcode(ERRCODE_DATA_CORRUPTED),
7165 : : errmsg_internal("multixact %u has two or more updating members",
7166 : : multi),
7167 : : errdetail_internal("First updater XID=%u second updater XID=%u.",
7168 : : update_xid, xid)));
7169 : :
7170 : : /*
7171 : : * As with all tuple visibility routines, it's critical to test
7172 : : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
7173 : : * race conditions explained in detail in heapam_visibility.c.
7174 : : */
7175 [ # # # # ]: 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
7176 : 0 : TransactionIdIsInProgress(xid))
7177 : 0 : update_xid = xid;
7178 [ # # ]: 0 : else if (TransactionIdDidCommit(xid))
7179 : : {
7180 : : /*
7181 : : * The transaction committed, so we can tell caller to set
7182 : : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
7183 : : * transaction is not running.)
7184 : : */
7185 : 0 : update_committed = true;
7186 : 0 : update_xid = xid;
7187 : : }
7188 : : else
7189 : : {
7190 : : /*
7191 : : * Not in progress, not committed -- must be aborted or crashed;
7192 : : * we can ignore it.
7193 : : */
7194 : 0 : continue;
7195 : : }
7196 : :
7197 : : /*
7198 : : * We determined that updater must be kept -- add it to pending new
7199 : : * members list
7200 : : */
1431 7201 [ # # ]: 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
7202 [ # # ]: 0 : ereport(ERROR,
7203 : : (errcode(ERRCODE_DATA_CORRUPTED),
7204 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
7205 : : multi, xid, cutoffs->OldestXmin)));
1437 7206 : 0 : newmembers[nnewmembers++] = members[i];
7207 : : }
7208 : :
4730 alvherre@alvh.no-ip. 7209 :CBC 1 : pfree(members);
7210 : :
7211 : : /*
7212 : : * Determine what to do with caller's multi based on information gathered
7213 : : * during our second pass
7214 : : */
7215 [ - + ]: 1 : if (nnewmembers == 0)
7216 : : {
7217 : : /* Nothing worth keeping */
4730 alvherre@alvh.no-ip. 7218 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1437 pg@bowt.ie 7219 : 0 : newxmax = InvalidTransactionId;
7220 : : }
4730 alvherre@alvh.no-ip. 7221 [ - + - - ]:CBC 1 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
7222 : : {
7223 : : /*
7224 : : * If there's a single member and it's an update, pass it back alone
7225 : : * without creating a new Multi. (XXX we could do this when there's a
7226 : : * single remaining locker, too, but that would complicate the API too
7227 : : * much; moreover, the case with the single updater is more
7228 : : * interesting, because those are longer-lived.)
7229 : : */
4730 alvherre@alvh.no-ip. 7230 [ # # ]:UBC 0 : Assert(nnewmembers == 1);
7231 : 0 : *flags |= FRM_RETURN_IS_XID;
7232 [ # # ]: 0 : if (update_committed)
7233 : 0 : *flags |= FRM_MARK_COMMITTED;
1437 pg@bowt.ie 7234 : 0 : newxmax = update_xid;
7235 : : }
7236 : : else
7237 : : {
7238 : : /*
7239 : : * Create a new multixact with the surviving members of the previous
7240 : : * one, to set as new Xmax in the tuple
7241 : : */
1437 pg@bowt.ie 7242 :CBC 1 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
4730 alvherre@alvh.no-ip. 7243 : 1 : *flags |= FRM_RETURN_IS_MULTI;
7244 : : }
7245 : :
7246 : 1 : pfree(newmembers);
7247 : :
1431 pg@bowt.ie 7248 : 1 : pagefrz->freeze_required = true;
1437 7249 : 1 : return newxmax;
7250 : : }
7251 : :
7252 : : /*
7253 : : * heap_prepare_freeze_tuple
7254 : : *
7255 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7256 : : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
7257 : : * setup enough state (in the *frz output argument) to enable caller to
7258 : : * process this tuple as part of freezing its page, and return true. Return
7259 : : * false if nothing can be changed about the tuple right now.
7260 : : *
7261 : : * FreezePageConflictXid is advanced only for xmin/xvac freezing, not for xmax
7262 : : * changes. We only remove xmax state here when it is lock-only, or when the
7263 : : * updater XID (including an updater member of a MultiXact) must be aborted;
7264 : : * otherwise, the tuple would already be removable. Neither case affects
7265 : : * visibility on a standby.
7266 : : *
7267 : : * Also sets *totally_frozen to true if the tuple will be totally frozen once
7268 : : * caller executes returned freeze plan (or if the tuple was already totally
7269 : : * frozen by an earlier VACUUM). This indicates that there are no remaining
7270 : : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
7271 : : *
7272 : : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
7273 : : * tuple that we returned true for, and then execute freezing. Caller must
7274 : : * initialize pagefrz fields for page as a whole before first call here for
7275 : : * each heap page.
7276 : : *
7277 : : * VACUUM caller decides on whether or not to freeze the page as a whole.
7278 : : * We'll often prepare freeze plans for a page that caller just discards.
7279 : : * However, VACUUM doesn't always get to make a choice; it must freeze when
7280 : : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7281 : : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7282 : : * that VACUUM always follows that rule.
7283 : : *
7284 : : * We sometimes force freezing of xmax MultiXactId values long before it is
7285 : : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7286 : : * It's worth processing MultiXactIds proactively when it is cheap to do so,
7287 : : * and it's convenient to make that happen by piggy-backing it on the "force
7288 : : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7289 : : * because it is expensive right now (though only when it's still possible to
7290 : : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7291 : : *
7292 : : * It is assumed that the caller has checked the tuple with
7293 : : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7294 : : * (else we should be removing the tuple, not freezing it).
7295 : : *
7296 : : * NB: This function has side effects: it might allocate a new MultiXactId.
7297 : : * It will be set as tuple's new xmax when our *frz output is processed within
7298 : : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7299 : : * then caller had better have an exclusive lock on it already.
7300 : : */
7301 : : bool
3302 andres@anarazel.de 7302 : 5625106 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
7303 : : const struct VacuumCutoffs *cutoffs,
7304 : : HeapPageFreeze *pagefrz,
7305 : : HeapTupleFreeze *frz, bool *totally_frozen)
7306 : : {
1437 pg@bowt.ie 7307 : 5625106 : bool xmin_already_frozen = false,
7308 : 5625106 : xmax_already_frozen = false;
7309 : 5625106 : bool freeze_xmin = false,
7310 : 5625106 : replace_xvac = false,
7311 : 5625106 : replace_xmax = false,
7312 : 5625106 : freeze_xmax = false;
7313 : : TransactionId xid;
7314 : :
1425 7315 : 5625106 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
4730 alvherre@alvh.no-ip. 7316 : 5625106 : frz->t_infomask2 = tuple->t_infomask2;
7317 : 5625106 : frz->t_infomask = tuple->t_infomask;
1425 pg@bowt.ie 7318 : 5625106 : frz->frzflags = 0;
7319 : 5625106 : frz->checkflags = 0;
7320 : :
7321 : : /*
7322 : : * Process xmin, while keeping track of whether it's already frozen, or
7323 : : * will become frozen iff our freeze plan is executed by caller (could be
7324 : : * neither).
7325 : : */
7328 tgl@sss.pgh.pa.us 7326 : 5625106 : xid = HeapTupleHeaderGetXmin(tuple);
2767 alvherre@alvh.no-ip. 7327 [ + + ]: 5625106 : if (!TransactionIdIsNormal(xid))
1437 pg@bowt.ie 7328 : 936094 : xmin_already_frozen = true;
7329 : : else
7330 : : {
7331 [ - + ]: 4689012 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3302 andres@anarazel.de 7332 [ # # ]:UBC 0 : ereport(ERROR,
7333 : : (errcode(ERRCODE_DATA_CORRUPTED),
7334 : : errmsg_internal("found xmin %u from before relfrozenxid %u",
7335 : : xid, cutoffs->relfrozenxid)));
7336 : :
7337 : : /* Will set freeze_xmin flags in freeze plan below */
1431 pg@bowt.ie 7338 :CBC 4689012 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7339 : :
7340 : : /* Verify that xmin committed if and when freeze plan is executed */
1425 7341 [ + + ]: 4689012 : if (freeze_xmin)
7342 : : {
7343 : 3831871 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
263 melanieplageman@gmai 7344 [ + + ]: 3831871 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7345 : 552376 : pagefrz->FreezePageConflictXid = xid;
7346 : : }
7347 : : }
7348 : :
7349 : : /*
7350 : : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7351 : : * as we support having MOVED_OFF/MOVED_IN tuples in the database
7352 : : */
1437 pg@bowt.ie 7353 : 5625106 : xid = HeapTupleHeaderGetXvac(tuple);
7354 [ - + ]: 5625106 : if (TransactionIdIsNormal(xid))
7355 : : {
1437 pg@bowt.ie 7356 [ # # ]:UBC 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7357 [ # # ]: 0 : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7358 : :
7359 : : /*
7360 : : * For Xvac, we always freeze proactively. This allows totally_frozen
7361 : : * tracking to ignore xvac.
7362 : : */
1431 7363 : 0 : replace_xvac = pagefrz->freeze_required = true;
7364 : :
263 melanieplageman@gmai 7365 [ # # ]: 0 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7366 : 0 : pagefrz->FreezePageConflictXid = xid;
7367 : :
7368 : : /* Will set replace_xvac flags in freeze plan below */
7369 : : }
7370 : :
7371 : : /* Now process xmax */
1425 pg@bowt.ie 7372 :CBC 5625106 : xid = frz->xmax;
4748 alvherre@alvh.no-ip. 7373 [ + + ]: 5625106 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7374 : : {
7375 : : /* Raw xmax is a MultiXactId */
7376 : : TransactionId newxmax;
7377 : : uint16 flags;
7378 : :
7379 : : /*
7380 : : * We will either remove xmax completely (in the "freeze_xmax" path),
7381 : : * process xmax by replacing it (in the "replace_xmax" path), or
7382 : : * perform no-op xmax processing. The only constraint is that the
7383 : : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7384 : : */
1437 pg@bowt.ie 7385 : 7 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7386 : : &flags, pagefrz);
7387 : :
1431 7388 [ + + ]: 7 : if (flags & FRM_NOOP)
7389 : : {
7390 : : /*
7391 : : * xmax is a MultiXactId, and nothing about it changes for now.
7392 : : * This is the only case where 'freeze_required' won't have been
7393 : : * set for us by FreezeMultiXactId, as well as the only case where
7394 : : * neither freeze_xmax nor replace_xmax are set (given a multi).
7395 : : *
7396 : : * This is a no-op, but the call to FreezeMultiXactId might have
7397 : : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7398 : : * for us (the "freeze page" variants, specifically). That'll
7399 : : * make it safe for our caller to freeze the page later on, while
7400 : : * leaving this particular xmax undisturbed.
7401 : : *
7402 : : * FreezeMultiXactId is _not_ responsible for the "no freeze"
7403 : : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7404 : : * job. A call to heap_tuple_should_freeze for this same tuple
7405 : : * will take place below if 'freeze_required' isn't set already.
7406 : : * (This repeats work from FreezeMultiXactId, but allows "no
7407 : : * freeze" tracker maintenance to happen in only one place.)
7408 : : */
7409 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7410 [ + - - + ]: 1 : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7411 : : }
7412 [ - + ]: 6 : else if (flags & FRM_RETURN_IS_XID)
7413 : : {
7414 : : /*
7415 : : * xmax will become an updater Xid (original MultiXact's updater
7416 : : * member Xid will be carried forward as a simple Xid in Xmax).
7417 : : */
1437 pg@bowt.ie 7418 [ # # ]:UBC 0 : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7419 : :
7420 : : /*
7421 : : * NB -- some of these transformations are only valid because we
7422 : : * know the return Xid is a tuple updater (i.e. not merely a
7423 : : * locker.) Also note that the only reason we don't explicitly
7424 : : * worry about HEAP_KEYS_UPDATED is because it lives in
7425 : : * t_infomask2 rather than t_infomask.
7426 : : */
4730 alvherre@alvh.no-ip. 7427 : 0 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7428 : 0 : frz->xmax = newxmax;
7429 [ # # ]: 0 : if (flags & FRM_MARK_COMMITTED)
3432 teodor@sigaev.ru 7430 : 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
1437 pg@bowt.ie 7431 : 0 : replace_xmax = true;
7432 : : }
4730 alvherre@alvh.no-ip. 7433 [ + + ]:CBC 6 : else if (flags & FRM_RETURN_IS_MULTI)
7434 : : {
7435 : : uint16 newbits;
7436 : : uint16 newbits2;
7437 : :
7438 : : /*
7439 : : * xmax is an old MultiXactId that we have to replace with a new
7440 : : * MultiXactId, to carry forward two or more original member XIDs.
7441 : : */
1437 pg@bowt.ie 7442 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7443 : :
7444 : : /*
7445 : : * We can't use GetMultiXactIdHintBits directly on the new multi
7446 : : * here; that routine initializes the masks to all zeroes, which
7447 : : * would lose other bits we need. Doing it this way ensures all
7448 : : * unrelated bits remain untouched.
7449 : : */
4730 alvherre@alvh.no-ip. 7450 : 1 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7451 : 1 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7452 : 1 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7453 : 1 : frz->t_infomask |= newbits;
7454 : 1 : frz->t_infomask2 |= newbits2;
7455 : 1 : frz->xmax = newxmax;
1437 pg@bowt.ie 7456 : 1 : replace_xmax = true;
7457 : : }
7458 : : else
7459 : : {
7460 : : /*
7461 : : * Freeze plan for tuple "freezes xmax" in the strictest sense:
7462 : : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7463 : : */
7464 [ - + ]: 5 : Assert(flags & FRM_INVALIDATE_XMAX);
1700 7465 [ - + ]: 5 : Assert(!TransactionIdIsValid(newxmax));
7466 : :
7467 : : /* Will set freeze_xmax flags in freeze plan below */
1437 7468 : 5 : freeze_xmax = true;
7469 : : }
7470 : :
7471 : : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
1431 7472 [ - + - - : 7 : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
- - ]
7473 : : }
3818 rhaas@postgresql.org 7474 [ + + ]: 5625099 : else if (TransactionIdIsNormal(xid))
7475 : : {
7476 : : /* Raw xmax is normal XID */
1437 pg@bowt.ie 7477 [ - + ]: 399901 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3302 andres@anarazel.de 7478 [ # # ]:UBC 0 : ereport(ERROR,
7479 : : (errcode(ERRCODE_DATA_CORRUPTED),
7480 : : errmsg_internal("found xmax %u from before relfrozenxid %u",
7481 : : xid, cutoffs->relfrozenxid)));
7482 : :
7483 : : /* Will set freeze_xmax flags in freeze plan below */
1425 pg@bowt.ie 7484 :CBC 399901 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7485 : :
7486 : : /*
7487 : : * Verify that xmax aborted if and when freeze plan is executed,
7488 : : * provided it's from an update. (A lock-only xmax can be removed
7489 : : * independent of this, since the lock is released at xact end.)
7490 : : */
7491 [ + + + + ]: 399901 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7492 : 5885 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7493 : : }
1466 7494 [ + - ]: 5225198 : else if (!TransactionIdIsValid(xid))
7495 : : {
7496 : : /* Raw xmax is InvalidTransactionId XID */
7497 [ - + ]: 5225198 : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
3130 alvherre@alvh.no-ip. 7498 : 5225198 : xmax_already_frozen = true;
7499 : : }
7500 : : else
3130 alvherre@alvh.no-ip. 7501 [ # # ]:UBC 0 : ereport(ERROR,
7502 : : (errcode(ERRCODE_DATA_CORRUPTED),
7503 : : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7504 : : xid, tuple->t_infomask)));
7505 : :
1437 pg@bowt.ie 7506 [ + + ]:CBC 5625106 : if (freeze_xmin)
7507 : : {
7508 [ - + ]: 3831871 : Assert(!xmin_already_frozen);
7509 : :
7510 : 3831871 : frz->t_infomask |= HEAP_XMIN_FROZEN;
7511 : : }
7512 [ - + ]: 5625106 : if (replace_xvac)
7513 : : {
7514 : : /*
7515 : : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7516 : : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7517 : : * transaction succeeded.
7518 : : */
1431 pg@bowt.ie 7519 [ # # ]:UBC 0 : Assert(pagefrz->freeze_required);
1437 7520 [ # # ]: 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
7521 : 0 : frz->frzflags |= XLH_INVALID_XVAC;
7522 : : else
7523 : 0 : frz->frzflags |= XLH_FREEZE_XVAC;
7524 : : }
1437 pg@bowt.ie 7525 [ + + ]:CBC 5625106 : if (replace_xmax)
7526 : : {
7527 [ + - - + ]: 1 : Assert(!xmax_already_frozen && !freeze_xmax);
1431 7528 [ - + ]: 1 : Assert(pagefrz->freeze_required);
7529 : :
7530 : : /* Already set replace_xmax flags in freeze plan earlier */
7531 : : }
4748 alvherre@alvh.no-ip. 7532 [ + + ]: 5625106 : if (freeze_xmax)
7533 : : {
1437 pg@bowt.ie 7534 [ + - - + ]: 7067 : Assert(!xmax_already_frozen && !replace_xmax);
7535 : :
4730 alvherre@alvh.no-ip. 7536 : 7067 : frz->xmax = InvalidTransactionId;
7537 : :
7538 : : /*
7539 : : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7540 : : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7541 : : * Also get rid of the HEAP_KEYS_UPDATED bit.
7542 : : */
7543 : 7067 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7544 : 7067 : frz->t_infomask |= HEAP_XMAX_INVALID;
7545 : 7067 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7546 : 7067 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7547 : : }
7548 : :
7549 : : /*
7550 : : * Determine if this tuple is already totally frozen, or will become
7551 : : * totally frozen (provided caller executes freeze plans for the page)
7552 : : */
1437 pg@bowt.ie 7553 [ + + + + : 10386004 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
+ + ]
7554 [ + + ]: 4760898 : (freeze_xmax || xmax_already_frozen));
7555 : :
1431 7556 [ + + + + : 5625106 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
+ + ]
7557 : : xmax_already_frozen))
7558 : : {
7559 : : /*
7560 : : * So far no previous tuple from the page made freezing mandatory.
7561 : : * Does this tuple force caller to freeze the entire page?
7562 : : */
7563 : 3312485 : pagefrz->freeze_required =
7564 : 3312485 : heap_tuple_should_freeze(tuple, cutoffs,
7565 : : &pagefrz->NoFreezePageRelfrozenXid,
7566 : : &pagefrz->NoFreezePageRelminMxid);
7567 : : }
7568 : :
7569 : : /* Tell caller if this tuple has a usable freeze plan set in *frz */
1437 7570 [ + + + - : 5625106 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
+ - + + ]
7571 : : }
7572 : :
7573 : : /*
7574 : : * Perform xmin/xmax XID status sanity checks before actually executing freeze
7575 : : * plans.
7576 : : *
7577 : : * heap_prepare_freeze_tuple doesn't perform these checks directly because
7578 : : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7579 : : * successive VACUUMs that each decide against freezing the same page.
7580 : : */
7581 : : void
969 heikki.linnakangas@i 7582 : 25757 : heap_pre_freeze_checks(Buffer buffer,
7583 : : HeapTupleFreeze *tuples, int ntuples)
7584 : : {
1474 pg@bowt.ie 7585 : 25757 : Page page = BufferGetPage(buffer);
7586 : :
1425 7587 [ + + ]: 1350211 : for (int i = 0; i < ntuples; i++)
7588 : : {
7589 : 1324454 : HeapTupleFreeze *frz = tuples + i;
7590 : 1324454 : ItemId itemid = PageGetItemId(page, frz->offset);
7591 : : HeapTupleHeader htup;
7592 : :
7593 : 1324454 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7594 : :
7595 : : /* Deliberately avoid relying on tuple hint bits here */
7596 [ + + ]: 1324454 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7597 : : {
7598 : 1324453 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
7599 : :
7600 [ - + ]: 1324453 : Assert(!HeapTupleHeaderXminFrozen(htup));
7601 [ - + ]: 1324453 : if (unlikely(!TransactionIdDidCommit(xmin)))
1425 pg@bowt.ie 7602 [ # # ]:UBC 0 : ereport(ERROR,
7603 : : (errcode(ERRCODE_DATA_CORRUPTED),
7604 : : errmsg_internal("uncommitted xmin %u needs to be frozen",
7605 : : xmin)));
7606 : : }
7607 : :
7608 : : /*
7609 : : * TransactionIdDidAbort won't work reliably in the presence of XIDs
7610 : : * left behind by transactions that were in progress during a crash,
7611 : : * so we can only check that xmax didn't commit
7612 : : */
1425 pg@bowt.ie 7613 [ + + ]:CBC 1324454 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7614 : : {
7615 : 957 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
7616 : :
7617 [ - + ]: 957 : Assert(TransactionIdIsNormal(xmax));
7618 [ - + ]: 957 : if (unlikely(TransactionIdDidCommit(xmax)))
1425 pg@bowt.ie 7619 [ # # ]:UBC 0 : ereport(ERROR,
7620 : : (errcode(ERRCODE_DATA_CORRUPTED),
7621 : : errmsg_internal("cannot freeze committed xmax %u",
7622 : : xmax)));
7623 : : }
7624 : : }
969 heikki.linnakangas@i 7625 :CBC 25757 : }
7626 : :
7627 : : /*
7628 : : * Helper which executes freezing of one or more heap tuples on a page on
7629 : : * behalf of caller. Caller passes an array of tuple plans from
7630 : : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7631 : : * Must be called in a critical section that also marks the buffer dirty and,
7632 : : * if needed, emits WAL.
7633 : : */
7634 : : void
7635 : 25757 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
7636 : : {
7637 : 25757 : Page page = BufferGetPage(buffer);
7638 : :
1474 pg@bowt.ie 7639 [ + + ]: 1350211 : for (int i = 0; i < ntuples; i++)
7640 : : {
1425 7641 : 1324454 : HeapTupleFreeze *frz = tuples + i;
7642 : 1324454 : ItemId itemid = PageGetItemId(page, frz->offset);
7643 : : HeapTupleHeader htup;
7644 : :
1474 7645 : 1324454 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
1425 7646 : 1324454 : heap_execute_freeze_tuple(htup, frz);
7647 : : }
1474 7648 : 25757 : }
7649 : :
7650 : : /*
7651 : : * heap_freeze_tuple
7652 : : * Freeze tuple in place, without WAL logging.
7653 : : *
7654 : : * Useful for callers like CLUSTER that perform their own WAL logging.
7655 : : */
7656 : : bool
3302 andres@anarazel.de 7657 : 465606 : heap_freeze_tuple(HeapTupleHeader tuple,
7658 : : TransactionId relfrozenxid, TransactionId relminmxid,
7659 : : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7660 : : {
7661 : : HeapTupleFreeze frz;
7662 : : bool do_freeze;
7663 : : bool totally_frozen;
7664 : : struct VacuumCutoffs cutoffs;
7665 : : HeapPageFreeze pagefrz;
7666 : :
1437 pg@bowt.ie 7667 : 465606 : cutoffs.relfrozenxid = relfrozenxid;
7668 : 465606 : cutoffs.relminmxid = relminmxid;
7669 : 465606 : cutoffs.OldestXmin = FreezeLimit;
7670 : 465606 : cutoffs.OldestMxact = MultiXactCutoff;
7671 : 465606 : cutoffs.FreezeLimit = FreezeLimit;
7672 : 465606 : cutoffs.MultiXactCutoff = MultiXactCutoff;
7673 : :
1431 7674 : 465606 : pagefrz.freeze_required = true;
7675 : 465606 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7676 : 465606 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
263 melanieplageman@gmai 7677 : 465606 : pagefrz.FreezePageConflictXid = InvalidTransactionId;
1431 pg@bowt.ie 7678 : 465606 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7679 : 465606 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7680 : :
1437 7681 : 465606 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7682 : : &pagefrz, &frz, &totally_frozen);
7683 : :
7684 : : /*
7685 : : * Note that because this is not a WAL-logged operation, we don't need to
7686 : : * fill in the offset in the freeze record.
7687 : : */
7688 : :
4730 alvherre@alvh.no-ip. 7689 [ + + ]: 465606 : if (do_freeze)
7690 : 376224 : heap_execute_freeze_tuple(tuple, &frz);
7691 : 465606 : return do_freeze;
7692 : : }
7693 : :
7694 : : /*
7695 : : * For a given MultiXactId, return the hint bits that should be set in the
7696 : : * tuple's infomask.
7697 : : *
7698 : : * Normally this should be called for a multixact that was just created, and
7699 : : * so is on our local cache, so the GetMembers call is fast.
7700 : : */
7701 : : static void
5057 7702 : 76836 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
7703 : : uint16 *new_infomask2)
7704 : : {
7705 : : int nmembers;
7706 : : MultiXactMember *members;
7707 : : int i;
4931 bruce@momjian.us 7708 : 76836 : uint16 bits = HEAP_XMAX_IS_MULTI;
7709 : 76836 : uint16 bits2 = 0;
7710 : 76836 : bool has_update = false;
7711 : 76836 : LockTupleMode strongest = LockTupleKeyShare;
7712 : :
7713 : : /*
7714 : : * We only use this in multis we just created, so they cannot be values
7715 : : * pre-pg_upgrade.
7716 : : */
4505 alvherre@alvh.no-ip. 7717 : 76836 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7718 : :
5057 7719 [ + + ]: 1472714 : for (i = 0; i < nmembers; i++)
7720 : : {
7721 : : LockTupleMode mode;
7722 : :
7723 : : /*
7724 : : * Remember the strongest lock mode held by any member of the
7725 : : * multixact.
7726 : : */
5049 7727 : 1395878 : mode = TUPLOCK_from_mxstatus(members[i].status);
7728 [ + + ]: 1395878 : if (mode > strongest)
7729 : 2925 : strongest = mode;
7730 : :
7731 : : /* See what other bits we need */
5057 7732 [ + + + + : 1395878 : switch (members[i].status)
- ]
7733 : : {
7734 : 1393436 : case MultiXactStatusForKeyShare:
7735 : : case MultiXactStatusForShare:
7736 : : case MultiXactStatusForNoKeyUpdate:
7737 : 1393436 : break;
7738 : :
7739 : 53 : case MultiXactStatusForUpdate:
7740 : 53 : bits2 |= HEAP_KEYS_UPDATED;
7741 : 53 : break;
7742 : :
7743 : 2379 : case MultiXactStatusNoKeyUpdate:
7744 : 2379 : has_update = true;
7745 : 2379 : break;
7746 : :
7747 : 10 : case MultiXactStatusUpdate:
7748 : 10 : bits2 |= HEAP_KEYS_UPDATED;
7749 : 10 : has_update = true;
7750 : 10 : break;
7751 : : }
7752 : : }
7753 : :
5049 7754 [ + + + + ]: 76836 : if (strongest == LockTupleExclusive ||
7755 : : strongest == LockTupleNoKeyExclusive)
7756 : 2474 : bits |= HEAP_XMAX_EXCL_LOCK;
7757 [ + + ]: 74362 : else if (strongest == LockTupleShare)
7758 : 448 : bits |= HEAP_XMAX_SHR_LOCK;
7759 [ + - ]: 73914 : else if (strongest == LockTupleKeyShare)
7760 : 73914 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7761 : :
5057 7762 [ + + ]: 76836 : if (!has_update)
7763 : 74447 : bits |= HEAP_XMAX_LOCK_ONLY;
7764 : :
7765 [ + - ]: 76836 : if (nmembers > 0)
7766 : 76836 : pfree(members);
7767 : :
7768 : 76836 : *new_infomask = bits;
7769 : 76836 : *new_infomask2 = bits2;
7770 : 76836 : }
7771 : :
7772 : : /*
7773 : : * MultiXactIdGetUpdateXid
7774 : : *
7775 : : * Given a multixact Xmax and corresponding infomask, which does not have the
7776 : : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7777 : : * transaction.
7778 : : *
7779 : : * Caller is expected to check the status of the updating transaction, if
7780 : : * necessary.
7781 : : */
7782 : : static TransactionId
7783 : 162159 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7784 : : {
4931 bruce@momjian.us 7785 : 162159 : TransactionId update_xact = InvalidTransactionId;
7786 : : MultiXactMember *members;
7787 : : int nmembers;
7788 : :
5057 alvherre@alvh.no-ip. 7789 [ - + ]: 162159 : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7790 [ - + ]: 162159 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7791 : :
7792 : : /*
7793 : : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7794 : : * pre-pg_upgrade.
7795 : : */
4505 7796 : 162159 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7797 : :
5057 7798 [ + - ]: 162159 : if (nmembers > 0)
7799 : : {
7800 : : int i;
7801 : :
7802 [ + + ]: 3235379 : for (i = 0; i < nmembers; i++)
7803 : : {
7804 : : /* Ignore lockers */
4747 7805 [ + + ]: 3073220 : if (!ISUPDATE_from_mxstatus(members[i].status))
5057 7806 : 2911061 : continue;
7807 : :
7808 : : /* there can be at most one updater */
7809 [ - + ]: 162159 : Assert(update_xact == InvalidTransactionId);
7810 : 162159 : update_xact = members[i].xid;
7811 : : #ifndef USE_ASSERT_CHECKING
7812 : :
7813 : : /*
7814 : : * in an assert-enabled build, walk the whole array to ensure
7815 : : * there's no other updater.
7816 : : */
7817 : : break;
7818 : : #endif
7819 : : }
7820 : :
7821 : 162159 : pfree(members);
7822 : : }
7823 : :
7824 : 162159 : return update_xact;
7825 : : }
7826 : :
7827 : : /*
7828 : : * HeapTupleGetUpdateXid
7829 : : * As above, but use a HeapTupleHeader
7830 : : *
7831 : : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7832 : : * checking the hint bits.
7833 : : */
7834 : : TransactionId
674 peter@eisentraut.org 7835 : 160015 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
7836 : : {
7837 : 160015 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
7838 : 160015 : tup->t_infomask);
7839 : : }
7840 : :
7841 : : /*
7842 : : * Does the given multixact conflict with the current transaction grabbing a
7843 : : * tuple lock of the given strength?
7844 : : *
7845 : : * The passed infomask pairs up with the given multixact in the tuple header.
7846 : : *
7847 : : * If current_is_member is not NULL, it is set to 'true' if the current
7848 : : * transaction is a member of the given multixact.
7849 : : */
7850 : : static bool
4355 alvherre@alvh.no-ip. 7851 : 227 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7852 : : LockTupleMode lockmode, bool *current_is_member)
7853 : : {
7854 : : int nmembers;
7855 : : MultiXactMember *members;
4207 bruce@momjian.us 7856 : 227 : bool result = false;
7857 : 227 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7858 : :
3809 alvherre@alvh.no-ip. 7859 [ - + ]: 227 : if (HEAP_LOCKED_UPGRADED(infomask))
3809 alvherre@alvh.no-ip. 7860 :UBC 0 : return false;
7861 : :
3809 alvherre@alvh.no-ip. 7862 :CBC 227 : nmembers = GetMultiXactIdMembers(multi, &members, false,
4355 7863 : 227 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7864 [ + - ]: 227 : if (nmembers >= 0)
7865 : : {
7866 : : int i;
7867 : :
7868 [ + + ]: 2708 : for (i = 0; i < nmembers; i++)
7869 : : {
7870 : : TransactionId memxid;
7871 : : LOCKMODE memlockmode;
7872 : :
2720 7873 [ + + + + : 2489 : if (result && (current_is_member == NULL || *current_is_member))
+ - ]
7874 : : break;
7875 : :
7876 : 2481 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7877 : :
7878 : : /* ignore members from current xact (but track their presence) */
2722 7879 : 2481 : memxid = members[i].xid;
7880 [ + + ]: 2481 : if (TransactionIdIsCurrentTransactionId(memxid))
7881 : : {
2720 7882 [ + + ]: 96 : if (current_is_member != NULL)
7883 : 82 : *current_is_member = true;
7884 : 96 : continue;
7885 : : }
7886 [ + + ]: 2385 : else if (result)
7887 : 11 : continue;
7888 : :
7889 : : /* ignore members that don't conflict with the lock we want */
7890 [ + + ]: 2374 : if (!DoLockModesConflict(memlockmode, wanted))
2722 7891 : 2326 : continue;
7892 : :
4355 7893 [ + + ]: 48 : if (ISUPDATE_from_mxstatus(members[i].status))
7894 : : {
7895 : : /* ignore aborted (or crashed) updaters */
44 heikki.linnakangas@i 7896 [ + + ]: 26 : if (!TransactionIdIsInProgress(memxid) &&
7897 [ + + ]: 13 : !TransactionIdDidCommit(memxid))
4355 alvherre@alvh.no-ip. 7898 : 6 : continue;
7899 : : }
7900 : : else
7901 : : {
7902 : : /* ignore lockers-only that are no longer in progress */
7903 [ + + ]: 22 : if (!TransactionIdIsInProgress(memxid))
7904 : 7 : continue;
7905 : : }
7906 : :
7907 : : /*
7908 : : * Whatever remains are either live lockers that conflict with our
7909 : : * wanted lock, and updaters that are not aborted. Those conflict
7910 : : * with what we want. Set up to return true, but keep going to
7911 : : * look for the current transaction among the multixact members,
7912 : : * if needed.
7913 : : */
7914 : 35 : result = true;
7915 : : }
7916 : 227 : pfree(members);
7917 : : }
7918 : :
7919 : 227 : return result;
7920 : : }
7921 : :
7922 : : /*
7923 : : * Do_MultiXactIdWait
7924 : : * Actual implementation for the two functions below.
7925 : : *
7926 : : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7927 : : * needed to ensure we only sleep on conflicting members, and the infomask is
7928 : : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7929 : : * indicates whether to use conditional lock acquisition, to allow callers to
7930 : : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7931 : : * context information for error messages. 'remaining', if not NULL, receives
7932 : : * the number of members that are still running, including any (non-aborted)
7933 : : * subtransactions of our own transaction. 'logLockFailure' indicates whether
7934 : : * to log details when a lock acquisition fails with 'nowait' enabled.
7935 : : *
7936 : : * We do this by sleeping on each member using XactLockTableWait. Any
7937 : : * members that belong to the current backend are *not* waited for, however;
7938 : : * this would not merely be useless but would lead to Assert failure inside
7939 : : * XactLockTableWait. By the time this returns, it is certain that all
7940 : : * transactions *of other backends* that were members of the MultiXactId
7941 : : * that conflict with the requested status are dead (and no new ones can have
7942 : : * been added, since it is not legal to add members to an existing
7943 : : * MultiXactId).
7944 : : *
7945 : : * But by the time we finish sleeping, someone else may have changed the Xmax
7946 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7947 : : *
7948 : : * Note that in case we return false, the number of remaining members is
7949 : : * not to be trusted.
7950 : : */
7951 : : static bool
5057 7952 : 66 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7953 : : uint16 infomask, bool nowait,
7954 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7955 : : int *remaining, bool logLockFailure)
7956 : : {
7957 : 66 : bool result = true;
7958 : : MultiXactMember *members;
7959 : : int nmembers;
7960 : 66 : int remain = 0;
7961 : :
7962 : : /* for pre-pg_upgrade tuples, no need to sleep at all */
3809 7963 [ + - ]: 66 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7964 : 66 : GetMultiXactIdMembers(multi, &members, false,
7965 : 66 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7966 : :
5057 7967 [ + - ]: 66 : if (nmembers >= 0)
7968 : : {
7969 : : int i;
7970 : :
7971 [ + + ]: 203 : for (i = 0; i < nmembers; i++)
7972 : : {
7973 : 145 : TransactionId memxid = members[i].xid;
7974 : 145 : MultiXactStatus memstatus = members[i].status;
7975 : :
7976 [ + + ]: 145 : if (TransactionIdIsCurrentTransactionId(memxid))
7977 : : {
7978 : 25 : remain++;
7979 : 25 : continue;
7980 : : }
7981 : :
7982 [ + + ]: 120 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7983 : 120 : LOCKMODE_from_mxstatus(status)))
7984 : : {
7985 [ + + + + ]: 23 : if (remaining && TransactionIdIsInProgress(memxid))
7986 : 8 : remain++;
7987 : 23 : continue;
7988 : : }
7989 : :
7990 : : /*
7991 : : * This member conflicts with our multi, so we have to sleep (or
7992 : : * return failure, if asked to avoid waiting.)
7993 : : *
7994 : : * Note that we don't set up an error context callback ourselves,
7995 : : * but instead we pass the info down to XactLockTableWait. This
7996 : : * might seem a bit wasteful because the context is set up and
7997 : : * tore down for each member of the multixact, but in reality it
7998 : : * should be barely noticeable, and it avoids duplicate code.
7999 : : */
8000 [ + + ]: 97 : if (nowait)
8001 : : {
624 fujii@postgresql.org 8002 : 9 : result = ConditionalXactLockTableWait(memxid, logLockFailure);
5057 alvherre@alvh.no-ip. 8003 [ + + ]: 9 : if (!result)
8004 : 8 : break;
8005 : : }
8006 : : else
4637 8007 : 88 : XactLockTableWait(memxid, rel, ctid, oper);
8008 : : }
8009 : :
5057 8010 : 66 : pfree(members);
8011 : : }
8012 : :
8013 [ + + ]: 66 : if (remaining)
8014 : 12 : *remaining = remain;
8015 : :
8016 : 66 : return result;
8017 : : }
8018 : :
8019 : : /*
8020 : : * MultiXactIdWait
8021 : : * Sleep on a MultiXactId.
8022 : : *
8023 : : * By the time we finish sleeping, someone else may have changed the Xmax
8024 : : * of the containing tuple, so the caller needs to iterate on us somehow.
8025 : : *
8026 : : * We return (in *remaining, if not NULL) the number of members that are still
8027 : : * running, including any (non-aborted) subtransactions of our own transaction.
8028 : : */
8029 : : static void
4637 8030 : 58 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
8031 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
8032 : : int *remaining)
8033 : : {
8034 : 58 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
8035 : : rel, ctid, oper, remaining, false);
5057 8036 : 58 : }
8037 : :
8038 : : /*
8039 : : * ConditionalMultiXactIdWait
8040 : : * As above, but only lock if we can get the lock without blocking.
8041 : : *
8042 : : * By the time we finish sleeping, someone else may have changed the Xmax
8043 : : * of the containing tuple, so the caller needs to iterate on us somehow.
8044 : : *
8045 : : * If the multixact is now all gone, return true. Returns false if some
8046 : : * transactions might still be running.
8047 : : *
8048 : : * We return (in *remaining, if not NULL) the number of members that are still
8049 : : * running, including any (non-aborted) subtransactions of our own transaction.
8050 : : */
8051 : : static bool
8052 : 8 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
8053 : : uint16 infomask, Relation rel, int *remaining,
8054 : : bool logLockFailure)
8055 : : {
4637 8056 : 8 : return Do_MultiXactIdWait(multi, status, infomask, true,
8057 : : rel, NULL, XLTW_None, remaining, logLockFailure);
8058 : : }
8059 : :
8060 : : /*
8061 : : * heap_tuple_needs_eventual_freeze
8062 : : *
8063 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
8064 : : * will eventually require freezing (if tuple isn't removed by pruning first).
8065 : : */
8066 : : bool
3924 rhaas@postgresql.org 8067 : 2245037 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
8068 : : {
8069 : : TransactionId xid;
8070 : :
8071 : : /*
8072 : : * If xmin is a normal transaction ID, this tuple is definitely not
8073 : : * frozen.
8074 : : */
8075 : 2245037 : xid = HeapTupleHeaderGetXmin(tuple);
8076 [ + + ]: 2245037 : if (TransactionIdIsNormal(xid))
8077 : 53387 : return true;
8078 : :
8079 : : /*
8080 : : * If xmax is a valid xact or multixact, this tuple is also not frozen.
8081 : : */
8082 [ + + ]: 2191650 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
8083 : : {
8084 : : MultiXactId multi;
8085 : :
8086 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8087 [ + - ]: 2 : if (MultiXactIdIsValid(multi))
8088 : 2 : return true;
8089 : : }
8090 : : else
8091 : : {
8092 : 2191648 : xid = HeapTupleHeaderGetRawXmax(tuple);
8093 [ + + ]: 2191648 : if (TransactionIdIsNormal(xid))
8094 : 42 : return true;
8095 : : }
8096 : :
8097 [ - + ]: 2191606 : if (tuple->t_infomask & HEAP_MOVED)
8098 : : {
3924 rhaas@postgresql.org 8099 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
8100 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8101 : 0 : return true;
8102 : : }
8103 : :
3924 rhaas@postgresql.org 8104 :CBC 2191606 : return false;
8105 : : }
8106 : :
8107 : : /*
8108 : : * heap_tuple_should_freeze
8109 : : *
8110 : : * Return value indicates if heap_prepare_freeze_tuple sibling function would
8111 : : * (or should) force freezing of the heap page that contains caller's tuple.
8112 : : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
8113 : : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
8114 : : *
8115 : : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
8116 : : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
8117 : : * Our working assumption is that caller won't decide to freeze this tuple.
8118 : : * It's up to caller to only ratchet back its own top-level trackers after the
8119 : : * point that it fully commits to not freezing the tuple/page in question.
8120 : : */
8121 : : bool
1431 pg@bowt.ie 8122 : 3313420 : heap_tuple_should_freeze(HeapTupleHeader tuple,
8123 : : const struct VacuumCutoffs *cutoffs,
8124 : : TransactionId *NoFreezePageRelfrozenXid,
8125 : : MultiXactId *NoFreezePageRelminMxid)
8126 : : {
8127 : : TransactionId xid;
8128 : : MultiXactId multi;
1437 8129 : 3313420 : bool freeze = false;
8130 : :
8131 : : /* First deal with xmin */
5500 rhaas@postgresql.org 8132 : 3313420 : xid = HeapTupleHeaderGetXmin(tuple);
1700 pg@bowt.ie 8133 [ + + ]: 3313420 : if (TransactionIdIsNormal(xid))
8134 : : {
1437 8135 [ - + ]: 3313003 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1431 8136 [ + + ]: 3313003 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8137 : 24853 : *NoFreezePageRelfrozenXid = xid;
1437 8138 [ + + ]: 3313003 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8139 : 21429 : freeze = true;
8140 : : }
8141 : :
8142 : : /* Now deal with xmax */
1700 8143 : 3313420 : xid = InvalidTransactionId;
8144 : 3313420 : multi = InvalidMultiXactId;
8145 [ + + ]: 3313420 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
4748 alvherre@alvh.no-ip. 8146 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8147 : : else
1700 pg@bowt.ie 8148 : 3313418 : xid = HeapTupleHeaderGetRawXmax(tuple);
8149 : :
8150 [ + + ]: 3313420 : if (TransactionIdIsNormal(xid))
8151 : : {
1437 8152 [ - + ]: 378648 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8153 : : /* xmax is a non-permanent XID */
1431 8154 [ + + ]: 378648 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8155 : 19 : *NoFreezePageRelfrozenXid = xid;
1437 8156 [ + + ]: 378648 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8157 : 13 : freeze = true;
8158 : : }
1700 8159 [ + + ]: 2934772 : else if (!MultiXactIdIsValid(multi))
8160 : : {
8161 : : /* xmax is a permanent XID or invalid MultiXactId/XID */
8162 : : }
8163 [ - + ]: 2 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
8164 : : {
8165 : : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
1431 pg@bowt.ie 8166 [ # # ]:UBC 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8167 : 0 : *NoFreezePageRelminMxid = multi;
8168 : : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
1437 8169 : 0 : freeze = true;
8170 : : }
8171 : : else
8172 : : {
8173 : : /* xmax is a MultiXactId that may have an updater XID */
8174 : : MultiXactMember *members;
8175 : : int nmembers;
8176 : :
1437 pg@bowt.ie 8177 [ - + ]:CBC 2 : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
1431 8178 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8179 : 2 : *NoFreezePageRelminMxid = multi;
1437 8180 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
8181 : 2 : freeze = true;
8182 : :
8183 : : /* need to check whether any member of the mxact is old */
1700 8184 : 2 : nmembers = GetMultiXactIdMembers(multi, &members, false,
8185 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
8186 : :
8187 [ + + ]: 5 : for (int i = 0; i < nmembers; i++)
8188 : : {
8189 : 3 : xid = members[i].xid;
1437 8190 [ - + ]: 3 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1431 8191 [ - + ]: 3 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
1431 pg@bowt.ie 8192 :UBC 0 : *NoFreezePageRelfrozenXid = xid;
1437 pg@bowt.ie 8193 [ - + ]:CBC 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
1437 pg@bowt.ie 8194 :UBC 0 : freeze = true;
8195 : : }
1700 pg@bowt.ie 8196 [ + + ]:CBC 2 : if (nmembers > 0)
8197 : 1 : pfree(members);
8198 : : }
8199 : :
5500 rhaas@postgresql.org 8200 [ - + ]: 3313420 : if (tuple->t_infomask & HEAP_MOVED)
8201 : : {
5500 rhaas@postgresql.org 8202 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
1700 pg@bowt.ie 8203 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8204 : : {
1437 8205 [ # # ]: 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1431 8206 [ # # ]: 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8207 : 0 : *NoFreezePageRelfrozenXid = xid;
8208 : : /* heap_prepare_freeze_tuple forces xvac freezing */
1437 8209 : 0 : freeze = true;
8210 : : }
8211 : : }
8212 : :
1437 pg@bowt.ie 8213 :CBC 3313420 : return freeze;
8214 : : }
8215 : :
8216 : : /*
8217 : : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
8218 : : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
8219 : : * that caller is in the process of physically removing, e.g. via HOT pruning
8220 : : * or index deletion.
8221 : : *
8222 : : * Caller must initialize its value to InvalidTransactionId, which is
8223 : : * generally interpreted as "definitely no need for a recovery conflict".
8224 : : * Final value must reflect all heap tuples that caller will physically remove
8225 : : * (or remove TID references to) via its ongoing pruning/deletion operation.
8226 : : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
8227 : : * caller's WAL record) by REDO routine when it replays caller's operation.
8228 : : */
8229 : : void
1472 8230 : 4149065 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
8231 : : TransactionId *snapshotConflictHorizon)
8232 : : {
6188 simon@2ndQuadrant.co 8233 : 4149065 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
5057 alvherre@alvh.no-ip. 8234 : 4149065 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
6188 simon@2ndQuadrant.co 8235 : 4149065 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
8236 : :
6137 tgl@sss.pgh.pa.us 8237 [ - + ]: 4149065 : if (tuple->t_infomask & HEAP_MOVED)
8238 : : {
1472 pg@bowt.ie 8239 [ # # ]:UBC 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
8240 : 0 : *snapshotConflictHorizon = xvac;
8241 : : }
8242 : :
8243 : : /*
8244 : : * Ignore tuples inserted by an aborted transaction or if the tuple was
8245 : : * updated/deleted by the inserting transaction.
8246 : : *
8247 : : * Look for a committed hint bit, or if no xmin bit is set, check clog.
8248 : : */
4724 rhaas@postgresql.org 8249 [ + + ]:CBC 4149065 : if (HeapTupleHeaderXminCommitted(tuple) ||
8250 [ + + + - ]: 160558 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
8251 : : {
5833 simon@2ndQuadrant.co 8252 [ + + + + ]: 7819851 : if (xmax != xmin &&
1472 pg@bowt.ie 8253 : 3804772 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
8254 : 139799 : *snapshotConflictHorizon = xmax;
8255 : : }
6188 simon@2ndQuadrant.co 8256 : 4149065 : }
8257 : :
8258 : : #ifdef USE_PREFETCH
8259 : : /*
8260 : : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
8261 : : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
8262 : : * we can prefetch, and which have already been prefetched; each call to this
8263 : : * function picks up where the previous call left off.
8264 : : *
8265 : : * Note: we expect the deltids array to be sorted in an order that groups TIDs
8266 : : * by heap block, with all TIDs for each block appearing together in exactly
8267 : : * one group.
8268 : : */
8269 : : static void
2145 pg@bowt.ie 8270 : 25160 : index_delete_prefetch_buffer(Relation rel,
8271 : : IndexDeletePrefetchState *prefetch_state,
8272 : : int prefetch_count)
8273 : : {
2804 andres@anarazel.de 8274 : 25160 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
8275 : 25160 : int count = 0;
8276 : : int i;
2145 pg@bowt.ie 8277 : 25160 : int ndeltids = prefetch_state->ndeltids;
8278 : 25160 : TM_IndexDelete *deltids = prefetch_state->deltids;
8279 : :
2804 andres@anarazel.de 8280 : 25160 : for (i = prefetch_state->next_item;
2145 pg@bowt.ie 8281 [ + + + + ]: 890578 : i < ndeltids && count < prefetch_count;
2804 andres@anarazel.de 8282 : 865418 : i++)
8283 : : {
2145 pg@bowt.ie 8284 : 865418 : ItemPointer htid = &deltids[i].tid;
8285 : :
2804 andres@anarazel.de 8286 [ + + + + ]: 1723105 : if (cur_hblkno == InvalidBlockNumber ||
8287 : 857687 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
8288 : : {
8289 : 22781 : cur_hblkno = ItemPointerGetBlockNumber(htid);
8290 : 22781 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
8291 : 22781 : count++;
8292 : : }
8293 : : }
8294 : :
8295 : : /*
8296 : : * Save the prefetch position so that next time we can continue from that
8297 : : * position.
8298 : : */
8299 : 25160 : prefetch_state->next_item = i;
8300 : 25160 : prefetch_state->cur_hblkno = cur_hblkno;
8301 : 25160 : }
8302 : : #endif
8303 : :
8304 : : /*
8305 : : * Helper function for heap_index_delete_tuples. Checks for index corruption
8306 : : * involving an invalid TID in index AM caller's index page.
8307 : : *
8308 : : * This is an ideal place for these checks. The index AM must hold a buffer
8309 : : * lock on the index page containing the TIDs we examine here, so we don't
8310 : : * have to worry about concurrent VACUUMs at all. We can be sure that the
8311 : : * index is corrupt when htid points directly to an LP_UNUSED item or
8312 : : * heap-only tuple, which is not the case during standard index scans.
8313 : : */
8314 : : static inline void
1850 pg@bowt.ie 8315 : 718704 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
8316 : : Page page, OffsetNumber maxoff,
8317 : : const ItemPointerData *htid, TM_IndexStatus *istatus)
8318 : : {
8319 : 718704 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8320 : : ItemId iid;
8321 : :
8322 [ + - + - : 718704 : Assert(OffsetNumberIsValid(istatus->idxoffnum));
- + ]
8323 : :
8324 [ - + ]: 718704 : if (unlikely(indexpagehoffnum > maxoff))
1850 pg@bowt.ie 8325 [ # # ]:UBC 0 : ereport(ERROR,
8326 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8327 : : 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\"",
8328 : : ItemPointerGetBlockNumber(htid),
8329 : : indexpagehoffnum,
8330 : : istatus->idxoffnum, delstate->iblknum,
8331 : : RelationGetRelationName(delstate->irel))));
8332 : :
1850 pg@bowt.ie 8333 :CBC 718704 : iid = PageGetItemId(page, indexpagehoffnum);
8334 [ - + ]: 718704 : if (unlikely(!ItemIdIsUsed(iid)))
1850 pg@bowt.ie 8335 [ # # ]:UBC 0 : ereport(ERROR,
8336 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8337 : : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8338 : : ItemPointerGetBlockNumber(htid),
8339 : : indexpagehoffnum,
8340 : : istatus->idxoffnum, delstate->iblknum,
8341 : : RelationGetRelationName(delstate->irel))));
8342 : :
1850 pg@bowt.ie 8343 [ + + ]:CBC 718704 : if (ItemIdHasStorage(iid))
8344 : : {
8345 : : HeapTupleHeader htup;
8346 : :
8347 [ - + ]: 462430 : Assert(ItemIdIsNormal(iid));
8348 : 462430 : htup = (HeapTupleHeader) PageGetItem(page, iid);
8349 : :
8350 [ - + ]: 462430 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
1850 pg@bowt.ie 8351 [ # # ]:UBC 0 : ereport(ERROR,
8352 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8353 : : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8354 : : ItemPointerGetBlockNumber(htid),
8355 : : indexpagehoffnum,
8356 : : istatus->idxoffnum, delstate->iblknum,
8357 : : RelationGetRelationName(delstate->irel))));
8358 : : }
1850 pg@bowt.ie 8359 :CBC 718704 : }
8360 : :
8361 : : /*
8362 : : * heapam implementation of tableam's index_delete_tuples interface.
8363 : : *
8364 : : * This helper function is called by index AMs during index tuple deletion.
8365 : : * See tableam header comments for an explanation of the interface implemented
8366 : : * here and a general theory of operation. Note that each call here is either
8367 : : * a simple index deletion call, or a bottom-up index deletion call.
8368 : : *
8369 : : * It's possible for this to generate a fair amount of I/O, since we may be
8370 : : * deleting hundreds of tuples from a single index block. To amortize that
8371 : : * cost to some degree, this uses prefetching and combines repeat accesses to
8372 : : * the same heap block.
8373 : : */
8374 : : TransactionId
2145 8375 : 7731 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
8376 : : {
8377 : : /* Initial assumption is that earlier pruning took care of conflict */
1472 8378 : 7731 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
2159 8379 : 7731 : BlockNumber blkno = InvalidBlockNumber;
2804 andres@anarazel.de 8380 : 7731 : Buffer buf = InvalidBuffer;
2159 pg@bowt.ie 8381 : 7731 : Page page = NULL;
8382 : 7731 : OffsetNumber maxoff = InvalidOffsetNumber;
8383 : : TransactionId priorXmax;
8384 : : #ifdef USE_PREFETCH
8385 : : IndexDeletePrefetchState prefetch_state;
8386 : : int prefetch_distance;
8387 : : #endif
8388 : : SnapshotData SnapshotNonVacuumable;
2145 8389 : 7731 : int finalndeltids = 0,
8390 : 7731 : nblocksaccessed = 0;
8391 : :
8392 : : /* State that's only used in bottom-up index deletion case */
8393 : 7731 : int nblocksfavorable = 0;
8394 : 7731 : int curtargetfreespace = delstate->bottomupfreespace,
8395 : 7731 : lastfreespace = 0,
8396 : 7731 : actualfreespace = 0;
8397 : 7731 : bool bottomup_final_block = false;
8398 : :
8399 : 7731 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8400 : :
8401 : : /* Sort caller's deltids array by TID for further processing */
8402 : 7731 : index_delete_sort(delstate);
8403 : :
8404 : : /*
8405 : : * Bottom-up case: resort deltids array in an order attuned to where the
8406 : : * greatest number of promising TIDs are to be found, and determine how
8407 : : * many blocks from the start of sorted array should be considered
8408 : : * favorable. This will also shrink the deltids array in order to
8409 : : * eliminate completely unfavorable blocks up front.
8410 : : */
8411 [ + + ]: 7731 : if (delstate->bottomup)
8412 : 2843 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
8413 : :
8414 : : #ifdef USE_PREFETCH
8415 : : /* Initialize prefetch state. */
2804 andres@anarazel.de 8416 : 7731 : prefetch_state.cur_hblkno = InvalidBlockNumber;
8417 : 7731 : prefetch_state.next_item = 0;
2145 pg@bowt.ie 8418 : 7731 : prefetch_state.ndeltids = delstate->ndeltids;
8419 : 7731 : prefetch_state.deltids = delstate->deltids;
8420 : :
8421 : : /*
8422 : : * Determine the prefetch distance that we will attempt to maintain.
8423 : : *
8424 : : * Since the caller holds a buffer lock somewhere in rel, we'd better make
8425 : : * sure that isn't a catalog relation before we call code that does
8426 : : * syscache lookups, to avoid risk of deadlock.
8427 : : */
2797 tmunro@postgresql.or 8428 [ + + ]: 7731 : if (IsCatalogRelation(rel))
2448 8429 : 5433 : prefetch_distance = maintenance_io_concurrency;
8430 : : else
8431 : : prefetch_distance =
8432 : 2298 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
8433 : :
8434 : : /* Cap initial prefetch distance for bottom-up deletion caller */
2145 pg@bowt.ie 8435 [ + + ]: 7731 : if (delstate->bottomup)
8436 : : {
8437 [ - + ]: 2843 : Assert(nblocksfavorable >= 1);
8438 [ - + ]: 2843 : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8439 : 2843 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8440 : : }
8441 : :
8442 : : /* Start prefetching. */
8443 : 7731 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8444 : : #endif
8445 : :
8446 : : /* Iterate over deltids, determine which to delete, check their horizon */
8447 [ - + ]: 7731 : Assert(delstate->ndeltids > 0);
8448 [ + + ]: 726435 : for (int i = 0; i < delstate->ndeltids; i++)
8449 : : {
8450 : 721547 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8451 : 721547 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8452 : 721547 : ItemPointer htid = &ideltid->tid;
8453 : : OffsetNumber offnum;
8454 : :
8455 : : /*
8456 : : * Read buffer, and perform required extra steps each time a new block
8457 : : * is encountered. Avoid refetching if it's the same block as the one
8458 : : * from the last htid.
8459 : : */
2159 8460 [ + + + + ]: 1435363 : if (blkno == InvalidBlockNumber ||
8461 : 713816 : ItemPointerGetBlockNumber(htid) != blkno)
8462 : : {
8463 : : /*
8464 : : * Consider giving up early for bottom-up index deletion caller
8465 : : * first. (Only prefetch next-next block afterwards, when it
8466 : : * becomes clear that we're at least going to access the next
8467 : : * block in line.)
8468 : : *
8469 : : * Sometimes the first block frees so much space for bottom-up
8470 : : * caller that the deletion process can end without accessing any
8471 : : * more blocks. It is usually necessary to access 2 or 3 blocks
8472 : : * per bottom-up deletion operation, though.
8473 : : */
2145 8474 [ + + ]: 20272 : if (delstate->bottomup)
8475 : : {
8476 : : /*
8477 : : * We often allow caller to delete a few additional items
8478 : : * whose entries we reached after the point that space target
8479 : : * from caller was satisfied. The cost of accessing the page
8480 : : * was already paid at that point, so it made sense to finish
8481 : : * it off. When that happened, we finalize everything here
8482 : : * (by finishing off the whole bottom-up deletion operation
8483 : : * without needlessly paying the cost of accessing any more
8484 : : * blocks).
8485 : : */
8486 [ + + ]: 6112 : if (bottomup_final_block)
8487 : 162 : break;
8488 : :
8489 : : /*
8490 : : * Give up when we didn't enable our caller to free any
8491 : : * additional space as a result of processing the page that we
8492 : : * just finished up with. This rule is the main way in which
8493 : : * we keep the cost of bottom-up deletion under control.
8494 : : */
8495 [ + + + + ]: 5950 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8496 : 2681 : break;
8497 : 3269 : lastfreespace = actualfreespace; /* for next time */
8498 : :
8499 : : /*
8500 : : * Deletion operation (which is bottom-up) will definitely
8501 : : * access the next block in line. Prepare for that now.
8502 : : *
8503 : : * Decay target free space so that we don't hang on for too
8504 : : * long with a marginal case. (Space target is only truly
8505 : : * helpful when it allows us to recognize that we don't need
8506 : : * to access more than 1 or 2 blocks to satisfy caller due to
8507 : : * agreeable workload characteristics.)
8508 : : *
8509 : : * We are a bit more patient when we encounter contiguous
8510 : : * blocks, though: these are treated as favorable blocks. The
8511 : : * decay process is only applied when the next block in line
8512 : : * is not a favorable/contiguous block. This is not an
8513 : : * exception to the general rule; we still insist on finding
8514 : : * at least one deletable item per block accessed. See
8515 : : * bottomup_nblocksfavorable() for full details of the theory
8516 : : * behind favorable blocks and heap block locality in general.
8517 : : *
8518 : : * Note: The first block in line is always treated as a
8519 : : * favorable block, so the earliest possible point that the
8520 : : * decay can be applied is just before we access the second
8521 : : * block in line. The Assert() verifies this for us.
8522 : : */
8523 [ + + - + ]: 3269 : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8524 [ + + ]: 3269 : if (nblocksfavorable > 0)
8525 : 3053 : nblocksfavorable--;
8526 : : else
8527 : 216 : curtargetfreespace /= 2;
8528 : : }
8529 : :
8530 : : /* release old buffer */
8531 [ + + ]: 17429 : if (BufferIsValid(buf))
8532 : 9698 : UnlockReleaseBuffer(buf);
8533 : :
8534 : 17429 : blkno = ItemPointerGetBlockNumber(htid);
2159 8535 : 17429 : buf = ReadBuffer(rel, blkno);
2145 8536 : 17429 : nblocksaccessed++;
8537 [ + + - + ]: 17429 : Assert(!delstate->bottomup ||
8538 : : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8539 : :
8540 : : #ifdef USE_PREFETCH
8541 : :
8542 : : /*
8543 : : * To maintain the prefetch distance, prefetch one more page for
8544 : : * each page we read.
8545 : : */
8546 : 17429 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8547 : : #endif
8548 : :
2159 8549 : 17429 : LockBuffer(buf, BUFFER_LOCK_SHARE);
8550 : :
8551 : 17429 : page = BufferGetPage(buf);
8552 : 17429 : maxoff = PageGetMaxOffsetNumber(page);
8553 : : }
8554 : :
8555 : : /*
8556 : : * In passing, detect index corruption involving an index page with a
8557 : : * TID that points to a location in the heap that couldn't possibly be
8558 : : * correct. We only do this with actual TIDs from caller's index page
8559 : : * (not items reached by traversing through a HOT chain).
8560 : : */
1850 8561 : 718704 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8562 : :
2145 8563 [ + + ]: 718704 : if (istatus->knowndeletable)
8564 [ + - - + ]: 158734 : Assert(!delstate->bottomup && !istatus->promising);
8565 : : else
8566 : : {
8567 : 559970 : ItemPointerData tmp = *htid;
8568 : : HeapTupleData heapTuple;
8569 : :
8570 : : /* Are any tuples from this HOT chain non-vacuumable? */
8571 [ + + ]: 559970 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8572 : : &heapTuple, NULL, true))
8573 : 347834 : continue; /* can't delete entry */
8574 : :
8575 : : /* Caller will delete, since whole HOT chain is vacuumable */
8576 : 212136 : istatus->knowndeletable = true;
8577 : :
8578 : : /* Maintain index free space info for bottom-up deletion case */
8579 [ + + ]: 212136 : if (delstate->bottomup)
8580 : : {
8581 [ - + ]: 11809 : Assert(istatus->freespace > 0);
8582 : 11809 : actualfreespace += istatus->freespace;
8583 [ + + ]: 11809 : if (actualfreespace >= curtargetfreespace)
8584 : 2527 : bottomup_final_block = true;
8585 : : }
8586 : : }
8587 : :
8588 : : /*
8589 : : * Maintain snapshotConflictHorizon value for deletion operation as a
8590 : : * whole by advancing current value using heap tuple headers. This is
8591 : : * loosely based on the logic for pruning a HOT chain.
8592 : : */
2159 8593 : 370870 : offnum = ItemPointerGetOffsetNumber(htid);
8594 : 370870 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8595 : : for (;;)
2804 andres@anarazel.de 8596 : 22118 : {
8597 : : ItemId lp;
8598 : : HeapTupleHeader htup;
8599 : :
8600 : : /* Sanity check (pure paranoia) */
1893 pg@bowt.ie 8601 [ - + ]: 392988 : if (offnum < FirstOffsetNumber)
1893 pg@bowt.ie 8602 :UBC 0 : break;
8603 : :
8604 : : /*
8605 : : * An offset past the end of page's line pointer array is possible
8606 : : * when the array was truncated
8607 : : */
1893 pg@bowt.ie 8608 [ - + ]:CBC 392988 : if (offnum > maxoff)
2159 pg@bowt.ie 8609 :UBC 0 : break;
8610 : :
2159 pg@bowt.ie 8611 :CBC 392988 : lp = PageGetItemId(page, offnum);
8612 [ + + ]: 392988 : if (ItemIdIsRedirected(lp))
8613 : : {
8614 : 9714 : offnum = ItemIdGetRedirect(lp);
8615 : 9714 : continue;
8616 : : }
8617 : :
8618 : : /*
8619 : : * We'll often encounter LP_DEAD line pointers (especially with an
8620 : : * entry marked knowndeletable by our caller up front). No heap
8621 : : * tuple headers get examined for an htid that leads us to an
8622 : : * LP_DEAD item. This is okay because the earlier pruning
8623 : : * operation that made the line pointer LP_DEAD in the first place
8624 : : * must have considered the original tuple header as part of
8625 : : * generating its own snapshotConflictHorizon value.
8626 : : *
8627 : : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8628 : : * the same strategy that index vacuuming uses in all cases. Index
8629 : : * VACUUM WAL records don't even have a snapshotConflictHorizon
8630 : : * field of their own for this reason.
8631 : : */
8632 [ + + ]: 383274 : if (!ItemIdIsNormal(lp))
8633 : 227469 : break;
8634 : :
8635 : 155805 : htup = (HeapTupleHeader) PageGetItem(page, lp);
8636 : :
8637 : : /*
8638 : : * Check the tuple XMIN against prior XMAX, if any
8639 : : */
8640 [ + + - + ]: 168209 : if (TransactionIdIsValid(priorXmax) &&
8641 : 12404 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
2159 pg@bowt.ie 8642 :UBC 0 : break;
8643 : :
1472 pg@bowt.ie 8644 :CBC 155805 : HeapTupleHeaderAdvanceConflictHorizon(htup,
8645 : : &snapshotConflictHorizon);
8646 : :
8647 : : /*
8648 : : * If the tuple is not HOT-updated, then we are at the end of this
8649 : : * HOT-chain. No need to visit later tuples from the same update
8650 : : * chain (they get their own index entries) -- just move on to
8651 : : * next htid from index AM caller.
8652 : : */
2159 8653 [ + + ]: 155805 : if (!HeapTupleHeaderIsHotUpdated(htup))
8654 : 143401 : break;
8655 : :
8656 : : /* Advance to next HOT chain member */
8657 [ - + ]: 12404 : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8658 : 12404 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8659 : 12404 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8660 : : }
8661 : :
8662 : : /* Enable further/final shrinking of deltids for caller */
2145 8663 : 370870 : finalndeltids = i + 1;
8664 : : }
8665 : :
8666 : 7731 : UnlockReleaseBuffer(buf);
8667 : :
8668 : : /*
8669 : : * Shrink deltids array to exclude non-deletable entries at the end. This
8670 : : * is not just a minor optimization. Final deltids array size might be
8671 : : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8672 : : * ndeltids being zero in all cases with zero total deletable entries.
8673 : : */
8674 [ + + - + ]: 7731 : Assert(finalndeltids > 0 || delstate->bottomup);
8675 : 7731 : delstate->ndeltids = finalndeltids;
8676 : :
1472 8677 : 7731 : return snapshotConflictHorizon;
8678 : : }
8679 : :
8680 : : /*
8681 : : * Specialized inlineable comparison function for index_delete_sort()
8682 : : */
8683 : : static inline int
2145 8684 : 17616349 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
8685 : : {
8686 : 17616349 : ItemPointer tid1 = &deltid1->tid;
8687 : 17616349 : ItemPointer tid2 = &deltid2->tid;
8688 : :
8689 : : {
8690 : 17616349 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
8691 : 17616349 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
8692 : :
8693 [ + + ]: 17616349 : if (blk1 != blk2)
8694 [ + + ]: 7186934 : return (blk1 < blk2) ? -1 : 1;
8695 : : }
8696 : : {
8697 : 10429415 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
8698 : 10429415 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
8699 : :
8700 [ + - ]: 10429415 : if (pos1 != pos2)
8701 [ + + ]: 10429415 : return (pos1 < pos2) ? -1 : 1;
8702 : : }
8703 : :
1856 pg@bowt.ie 8704 :UBC 0 : Assert(false);
8705 : :
8706 : : return 0;
8707 : : }
8708 : :
8709 : : /*
8710 : : * Sort deltids array from delstate by TID. This prepares it for further
8711 : : * processing by heap_index_delete_tuples().
8712 : : *
8713 : : * This operation becomes a noticeable consumer of CPU cycles with some
8714 : : * workloads, so we go to the trouble of specialization/micro optimization.
8715 : : * We use shellsort for this because it's easy to specialize, compiles to
8716 : : * relatively few instructions, and is adaptive to presorted inputs/subsets
8717 : : * (which are typical here).
8718 : : */
8719 : : static void
2145 pg@bowt.ie 8720 :CBC 7731 : index_delete_sort(TM_IndexDeleteOp *delstate)
8721 : : {
8722 : 7731 : TM_IndexDelete *deltids = delstate->deltids;
8723 : 7731 : int ndeltids = delstate->ndeltids;
8724 : :
8725 : : /*
8726 : : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8727 : : *
8728 : : * This implementation is fast with array sizes up to ~4500. This covers
8729 : : * all supported BLCKSZ values.
8730 : : */
8731 : 7731 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8732 : :
8733 : : /* Think carefully before changing anything here -- keep swaps cheap */
8734 : : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8735 : : "element size exceeds 8 bytes");
8736 : :
140 peter@eisentraut.org 8737 [ + + ]:GNC 77310 : for (size_t g = 0; g < lengthof(gaps); g++)
8738 : : {
752 dgustafsson@postgres 8739 [ + + ]:CBC 10628476 : for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8740 : : {
2145 pg@bowt.ie 8741 : 10558897 : TM_IndexDelete d = deltids[i];
8742 : 10558897 : int j = i;
8743 : :
8744 [ + + + + ]: 18114405 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8745 : : {
8746 : 7555508 : deltids[j] = deltids[j - hi];
8747 : 7555508 : j -= hi;
8748 : : }
8749 : 10558897 : deltids[j] = d;
8750 : : }
8751 : : }
8752 : 7731 : }
8753 : :
8754 : : /*
8755 : : * Returns how many blocks should be considered favorable/contiguous for a
8756 : : * bottom-up index deletion pass. This is a number of heap blocks that starts
8757 : : * from and includes the first block in line.
8758 : : *
8759 : : * There is always at least one favorable block during bottom-up index
8760 : : * deletion. In the worst case (i.e. with totally random heap blocks) the
8761 : : * first block in line (the only favorable block) can be thought of as a
8762 : : * degenerate array of contiguous blocks that consists of a single block.
8763 : : * heap_index_delete_tuples() will expect this.
8764 : : *
8765 : : * Caller passes blockgroups, a description of the final order that deltids
8766 : : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8767 : : * processing. Note that deltids need not actually be sorted just yet (caller
8768 : : * only passes deltids to us so that we can interpret blockgroups).
8769 : : *
8770 : : * You might guess that the existence of contiguous blocks cannot matter much,
8771 : : * since in general the main factor that determines which blocks we visit is
8772 : : * the number of promising TIDs, which is a fixed hint from the index AM.
8773 : : * We're not really targeting the general case, though -- the actual goal is
8774 : : * to adapt our behavior to a wide variety of naturally occurring conditions.
8775 : : * The effects of most of the heuristics we apply are only noticeable in the
8776 : : * aggregate, over time and across many _related_ bottom-up index deletion
8777 : : * passes.
8778 : : *
8779 : : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8780 : : * workloads where heap blocks visited during bottom-up index deletion can be
8781 : : * accessed contiguously, in the sense that each newly visited block is the
8782 : : * neighbor of the block that bottom-up deletion just finished processing (or
8783 : : * close enough to it). It will likely be cheaper to access more favorable
8784 : : * blocks sooner rather than later (e.g. in this pass, not across a series of
8785 : : * related bottom-up passes). Either way it is probably only a matter of time
8786 : : * (or a matter of further correlated version churn) before all blocks that
8787 : : * appear together as a single large batch of favorable blocks get accessed by
8788 : : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8789 : : * appear almost constantly or not even once (it all depends on per-index
8790 : : * workload characteristics).
8791 : : *
8792 : : * Note that the blockgroups sort order applies a power-of-two bucketing
8793 : : * scheme that creates opportunities for contiguous groups of blocks to get
8794 : : * batched together, at least with workloads that are naturally amenable to
8795 : : * being driven by heap block locality. This doesn't just enhance the spatial
8796 : : * locality of bottom-up heap block processing in the obvious way. It also
8797 : : * enables temporal locality of access, since sorting by heap block number
8798 : : * naturally tends to make the bottom-up processing order deterministic.
8799 : : *
8800 : : * Consider the following example to get a sense of how temporal locality
8801 : : * might matter: There is a heap relation with several indexes, each of which
8802 : : * is low to medium cardinality. It is subject to constant non-HOT updates.
8803 : : * The updates are skewed (in one part of the primary key, perhaps). None of
8804 : : * the indexes are logically modified by the UPDATE statements (if they were
8805 : : * then bottom-up index deletion would not be triggered in the first place).
8806 : : * Naturally, each new round of index tuples (for each heap tuple that gets a
8807 : : * heap_update() call) will have the same heap TID in each and every index.
8808 : : * Since these indexes are low cardinality and never get logically modified,
8809 : : * heapam processing during bottom-up deletion passes will access heap blocks
8810 : : * in approximately sequential order. Temporal locality of access occurs due
8811 : : * to bottom-up deletion passes behaving very similarly across each of the
8812 : : * indexes at any given moment. This keeps the number of buffer misses needed
8813 : : * to visit heap blocks to a minimum.
8814 : : */
8815 : : static int
8816 : 2843 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8817 : : TM_IndexDelete *deltids)
8818 : : {
8819 : 2843 : int64 lastblock = -1;
8820 : 2843 : int nblocksfavorable = 0;
8821 : :
8822 [ - + ]: 2843 : Assert(nblockgroups >= 1);
8823 [ - + ]: 2843 : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8824 : :
8825 : : /*
8826 : : * We tolerate heap blocks that will be accessed only slightly out of
8827 : : * physical order. Small blips occur when a pair of almost-contiguous
8828 : : * blocks happen to fall into different buckets (perhaps due only to a
8829 : : * small difference in npromisingtids that the bucketing scheme didn't
8830 : : * quite manage to ignore). We effectively ignore these blips by applying
8831 : : * a small tolerance. The precise tolerance we use is a little arbitrary,
8832 : : * but it works well enough in practice.
8833 : : */
8834 [ + + ]: 8620 : for (int b = 0; b < nblockgroups; b++)
8835 : : {
8836 : 8314 : IndexDeleteCounts *group = blockgroups + b;
8837 : 8314 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8838 : 8314 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8839 : :
8840 [ + + ]: 8314 : if (lastblock != -1 &&
8841 [ + + ]: 5471 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8842 [ + + ]: 4853 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8843 : : break;
8844 : :
8845 : 5777 : nblocksfavorable++;
8846 : 5777 : lastblock = block;
8847 : : }
8848 : :
8849 : : /* Always indicate that there is at least 1 favorable block */
8850 [ - + ]: 2843 : Assert(nblocksfavorable >= 1);
8851 : :
8852 : 2843 : return nblocksfavorable;
8853 : : }
8854 : :
8855 : : /*
8856 : : * qsort comparison function for bottomup_sort_and_shrink()
8857 : : */
8858 : : static int
8859 : 260726 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8860 : : {
8861 : 260726 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8862 : 260726 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8863 : :
8864 : : /*
8865 : : * Most significant field is npromisingtids (which we invert the order of
8866 : : * so as to sort in desc order).
8867 : : *
8868 : : * Caller should have already normalized npromisingtids fields into
8869 : : * power-of-two values (buckets).
8870 : : */
8871 [ + + ]: 260726 : if (group1->npromisingtids > group2->npromisingtids)
8872 : 11667 : return -1;
8873 [ + + ]: 249059 : if (group1->npromisingtids < group2->npromisingtids)
8874 : 15476 : return 1;
8875 : :
8876 : : /*
8877 : : * Tiebreak: desc ntids sort order.
8878 : : *
8879 : : * We cannot expect power-of-two values for ntids fields. We should
8880 : : * behave as if they were already rounded up for us instead.
8881 : : */
8882 [ + + ]: 233583 : if (group1->ntids != group2->ntids)
8883 : : {
8884 : 170540 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8885 : 170540 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8886 : :
8887 [ + + ]: 170540 : if (ntids1 > ntids2)
8888 : 24288 : return -1;
8889 [ + + ]: 146252 : if (ntids1 < ntids2)
8890 : 30968 : return 1;
8891 : : }
8892 : :
8893 : : /*
8894 : : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8895 : : * block in deltids array) order.
8896 : : *
8897 : : * This is equivalent to sorting in ascending heap block number order
8898 : : * (among otherwise equal subsets of the array). This approach allows us
8899 : : * to avoid accessing the out-of-line TID. (We rely on the assumption
8900 : : * that the deltids array was sorted in ascending heap TID order when
8901 : : * these offsets to the first TID from each heap block group were formed.)
8902 : : */
8903 [ + + ]: 178327 : if (group1->ifirsttid > group2->ifirsttid)
8904 : 87166 : return 1;
8905 [ + - ]: 91161 : if (group1->ifirsttid < group2->ifirsttid)
8906 : 91161 : return -1;
8907 : :
2145 pg@bowt.ie 8908 :UBC 0 : pg_unreachable();
8909 : :
8910 : : return 0;
8911 : : }
8912 : :
8913 : : /*
8914 : : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8915 : : *
8916 : : * Sorts deltids array in the order needed for useful processing by bottom-up
8917 : : * deletion. The array should already be sorted in TID order when we're
8918 : : * called. The sort process groups heap TIDs from deltids into heap block
8919 : : * groupings. Earlier/more-promising groups/blocks are usually those that are
8920 : : * known to have the most "promising" TIDs.
8921 : : *
8922 : : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8923 : : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8924 : : * return. This often means that deltids will be shrunk to a small fraction
8925 : : * of its original size (we eliminate many heap blocks from consideration for
8926 : : * caller up front).
8927 : : *
8928 : : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8929 : : * for a definition and full details.
8930 : : */
8931 : : static int
2145 pg@bowt.ie 8932 :CBC 2843 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8933 : : {
8934 : : IndexDeleteCounts *blockgroups;
8935 : : TM_IndexDelete *reordereddeltids;
8936 : 2843 : BlockNumber curblock = InvalidBlockNumber;
8937 : 2843 : int nblockgroups = 0;
8938 : 2843 : int ncopied = 0;
8939 : 2843 : int nblocksfavorable = 0;
8940 : :
8941 [ - + ]: 2843 : Assert(delstate->bottomup);
8942 [ - + ]: 2843 : Assert(delstate->ndeltids > 0);
8943 : :
8944 : : /* Calculate per-heap-block count of TIDs */
353 michael@paquier.xyz 8945 : 2843 : blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
2145 pg@bowt.ie 8946 [ + + ]: 1372135 : for (int i = 0; i < delstate->ndeltids; i++)
8947 : : {
8948 : 1369292 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8949 : 1369292 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8950 : 1369292 : ItemPointer htid = &ideltid->tid;
8951 : 1369292 : bool promising = istatus->promising;
8952 : :
8953 [ + + ]: 1369292 : if (curblock != ItemPointerGetBlockNumber(htid))
8954 : : {
8955 : : /* New block group */
8956 : 50759 : nblockgroups++;
8957 : :
8958 [ + + - + ]: 50759 : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8959 : : !BlockNumberIsValid(curblock));
8960 : :
8961 : 50759 : curblock = ItemPointerGetBlockNumber(htid);
8962 : 50759 : blockgroups[nblockgroups - 1].ifirsttid = i;
8963 : 50759 : blockgroups[nblockgroups - 1].ntids = 1;
8964 : 50759 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8965 : : }
8966 : : else
8967 : : {
8968 : 1318533 : blockgroups[nblockgroups - 1].ntids++;
8969 : : }
8970 : :
8971 [ + + ]: 1369292 : if (promising)
8972 : 260676 : blockgroups[nblockgroups - 1].npromisingtids++;
8973 : : }
8974 : :
8975 : : /*
8976 : : * We're about ready to sort block groups to determine the optimal order
8977 : : * for visiting heap blocks. But before we do, round the number of
8978 : : * promising tuples for each block group up to the next power-of-two,
8979 : : * unless it is very low (less than 4), in which case we round up to 4.
8980 : : * npromisingtids is far too noisy to trust when choosing between a pair
8981 : : * of block groups that both have very low values.
8982 : : *
8983 : : * This scheme divides heap blocks/block groups into buckets. Each bucket
8984 : : * contains blocks that have _approximately_ the same number of promising
8985 : : * TIDs as each other. The goal is to ignore relatively small differences
8986 : : * in the total number of promising entries, so that the whole process can
8987 : : * give a little weight to heapam factors (like heap block locality)
8988 : : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8989 : : * would be foolish to interpret small differences in npromisingtids
8990 : : * values as anything more than noise.
8991 : : *
8992 : : * We tiebreak on nhtids when sorting block group subsets that have the
8993 : : * same npromisingtids, but this has the same issues as npromisingtids,
8994 : : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8995 : : * only reason that we don't fix nhtids in the same way here too is that
8996 : : * we'll need accurate nhtids values after the sort. We handle nhtids
8997 : : * bucketization dynamically instead (in the sort comparator).
8998 : : *
8999 : : * See bottomup_nblocksfavorable() for a full explanation of when and how
9000 : : * heap locality/favorable blocks can significantly influence when and how
9001 : : * heap blocks are accessed.
9002 : : */
9003 [ + + ]: 53602 : for (int b = 0; b < nblockgroups; b++)
9004 : : {
9005 : 50759 : IndexDeleteCounts *group = blockgroups + b;
9006 : :
9007 : : /* Better off falling back on nhtids with low npromisingtids */
9008 [ + + ]: 50759 : if (group->npromisingtids <= 4)
9009 : 42189 : group->npromisingtids = 4;
9010 : : else
9011 : 8570 : group->npromisingtids =
9012 : 8570 : pg_nextpower2_32((uint32) group->npromisingtids);
9013 : : }
9014 : :
9015 : : /* Sort groups and rearrange caller's deltids array */
9016 : 2843 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
9017 : : bottomup_sort_and_shrink_cmp);
103 michael@paquier.xyz 9018 :GNC 2843 : reordereddeltids = palloc_array(TM_IndexDelete, delstate->ndeltids);
9019 : :
2145 pg@bowt.ie 9020 :CBC 2843 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
9021 : : /* Determine number of favorable blocks at the start of final deltids */
9022 : 2843 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
9023 : : delstate->deltids);
9024 : :
9025 [ + + ]: 18402 : for (int b = 0; b < nblockgroups; b++)
9026 : : {
9027 : 15559 : IndexDeleteCounts *group = blockgroups + b;
9028 : 15559 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
9029 : :
9030 : 15559 : memcpy(reordereddeltids + ncopied, firstdtid,
9031 : 15559 : sizeof(TM_IndexDelete) * group->ntids);
9032 : 15559 : ncopied += group->ntids;
9033 : : }
9034 : :
9035 : : /* Copy final grouped and sorted TIDs back into start of caller's array */
9036 : 2843 : memcpy(delstate->deltids, reordereddeltids,
9037 : : sizeof(TM_IndexDelete) * ncopied);
9038 : 2843 : delstate->ndeltids = ncopied;
9039 : :
9040 : 2843 : pfree(reordereddeltids);
9041 : 2843 : pfree(blockgroups);
9042 : :
9043 : 2843 : return nblocksfavorable;
9044 : : }
9045 : :
9046 : : /*
9047 : : * Perform XLogInsert for a heap-update operation. Caller must already
9048 : : * have modified the buffer(s) and marked them dirty.
9049 : : */
9050 : : static XLogRecPtr
136 melanieplageman@gmai 9051 : 2396887 : log_heap_update(Relation reln, Buffer oldbuf, Buffer vmbuffer_old,
9052 : : Buffer newbuf, Buffer vmbuffer_new,
9053 : : HeapTuple oldtup, HeapTuple newtup,
9054 : : HeapTuple old_key_tuple,
9055 : : bool all_visible_cleared, bool new_all_visible_cleared,
9056 : : bool walLogical)
9057 : : {
9058 : : xl_heap_update xlrec;
9059 : : xl_heap_header xlhdr;
9060 : : xl_heap_header xlhdr_idx;
9061 : : uint8 info;
9062 : : uint16 prefix_suffix[2];
4644 heikki.linnakangas@i 9063 : 2396887 : uint16 prefixlen = 0,
9064 : 2396887 : suffixlen = 0;
9065 : : XLogRecPtr recptr;
3874 kgrittn@postgresql.o 9066 : 2396887 : Page page = BufferGetPage(newbuf);
236 alvherre@kurilemu.de 9067 [ + + + + : 2396887 : bool need_tuple_data = walLogical && RelationIsLogicallyLogged(reln);
+ + + - -
+ - - - -
+ - + + +
- ]
9068 : : bool init;
9069 : : int bufflags;
9070 : :
9071 : : /* Caller should not call me on a non-WAL-logged relation */
5829 rhaas@postgresql.org 9072 [ + - + + : 2396887 : Assert(RelationNeedsWAL(reln));
+ - - + ]
9073 : :
4391 heikki.linnakangas@i 9074 : 2396887 : XLogBeginInsert();
9075 : :
6137 tgl@sss.pgh.pa.us 9076 [ + + ]: 2396887 : if (HeapTupleIsHeapOnly(newtup))
7009 9077 : 175524 : info = XLOG_HEAP_HOT_UPDATE;
9078 : : else
9079 : 2221363 : info = XLOG_HEAP_UPDATE;
9080 : :
9081 : : /*
9082 : : * If the old and new tuple are on the same page, we only need to log the
9083 : : * parts of the new tuple that were changed. That saves on the amount of
9084 : : * WAL we need to write. Currently, we just count any unchanged bytes in
9085 : : * the beginning and end of the tuple. That's quick to check, and
9086 : : * perfectly covers the common case that only one field is updated.
9087 : : *
9088 : : * We could do this even if the old and new tuple are on different pages,
9089 : : * but only if we don't make a full-page image of the old page, which is
9090 : : * difficult to know in advance. Also, if the old tuple is corrupt for
9091 : : * some reason, it would allow the corruption to propagate the new page,
9092 : : * so it seems best to avoid. Under the general assumption that most
9093 : : * updates tend to create the new tuple version on the same page, there
9094 : : * isn't much to be gained by doing this across pages anyway.
9095 : : *
9096 : : * Skip this if we're taking a full-page image of the new page, as we
9097 : : * don't include the new tuple in the WAL record in that case. Also
9098 : : * disable if effective_wal_level='logical', as logical decoding needs to
9099 : : * be able to read the new tuple in whole from the WAL record alone.
9100 : : */
4644 heikki.linnakangas@i 9101 [ + + + + ]: 2396887 : if (oldbuf == newbuf && !need_tuple_data &&
9102 [ + + ]: 180522 : !XLogCheckBufferNeedsBackup(newbuf))
9103 : : {
9104 : 179819 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
9105 : 179819 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
9106 : 179819 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
9107 : 179819 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
9108 : :
9109 : : /* Check for common prefix between old and new tuple */
9110 [ + + ]: 14998864 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
9111 : : {
9112 [ + + ]: 14968907 : if (newp[prefixlen] != oldp[prefixlen])
9113 : 149862 : break;
9114 : : }
9115 : :
9116 : : /*
9117 : : * Storing the length of the prefix takes 2 bytes, so we need to save
9118 : : * at least 3 bytes or there's no point.
9119 : : */
9120 [ + + ]: 179819 : if (prefixlen < 3)
9121 : 25871 : prefixlen = 0;
9122 : :
9123 : : /* Same for suffix */
9124 [ + + ]: 6330491 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
9125 : : {
9126 [ + + ]: 6300189 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
9127 : 149517 : break;
9128 : : }
9129 [ + + ]: 179819 : if (suffixlen < 3)
9130 : 43392 : suffixlen = 0;
9131 : : }
9132 : :
9133 : : /* Prepare main WAL data chain */
4736 rhaas@postgresql.org 9134 : 2396887 : xlrec.flags = 0;
9135 [ + + ]: 2396887 : if (all_visible_cleared)
4222 andres@anarazel.de 9136 : 2629 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
4736 rhaas@postgresql.org 9137 [ + + ]: 2396887 : if (new_all_visible_cleared)
4222 andres@anarazel.de 9138 : 1653 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
4644 heikki.linnakangas@i 9139 [ + + ]: 2396887 : if (prefixlen > 0)
4222 andres@anarazel.de 9140 : 153948 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
4644 heikki.linnakangas@i 9141 [ + + ]: 2396887 : if (suffixlen > 0)
4222 andres@anarazel.de 9142 : 136427 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
4391 heikki.linnakangas@i 9143 [ + + ]: 2396887 : if (need_tuple_data)
9144 : : {
4222 andres@anarazel.de 9145 : 47076 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
4391 heikki.linnakangas@i 9146 [ + + ]: 47076 : if (old_key_tuple)
9147 : : {
9148 [ + + ]: 160 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4222 andres@anarazel.de 9149 : 68 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
9150 : : else
9151 : 92 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
9152 : : }
9153 : : }
9154 : :
9155 : : /* If new tuple is the single and first tuple on page... */
4644 heikki.linnakangas@i 9156 [ + + + + ]: 2410258 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
9157 : 13371 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
9158 : : {
9159 : 12733 : info |= XLOG_HEAP_INIT_PAGE;
4391 9160 : 12733 : init = true;
9161 : : }
9162 : : else
9163 : 2384154 : init = false;
9164 : :
9165 : : /* Prepare WAL data for the old page */
9166 : 2396887 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
9167 : 2396887 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
9168 : 4793774 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
9169 : 2396887 : oldtup->t_data->t_infomask2);
9170 : :
9171 : : /* Prepare WAL data for the new page */
9172 : 2396887 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
9173 : 2396887 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
9174 : :
9175 : 2396887 : bufflags = REGBUF_STANDARD;
9176 [ + + ]: 2396887 : if (init)
9177 : 12733 : bufflags |= REGBUF_WILL_INIT;
9178 [ + + ]: 2396887 : if (need_tuple_data)
9179 : 47076 : bufflags |= REGBUF_KEEP_DATA;
9180 : :
136 melanieplageman@gmai 9181 : 2396887 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_NEW, newbuf, bufflags);
4391 heikki.linnakangas@i 9182 [ + + ]: 2396887 : if (oldbuf != newbuf)
136 melanieplageman@gmai 9183 : 2204369 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_OLD, oldbuf, REGBUF_STANDARD);
9184 : :
655 peter@eisentraut.org 9185 : 2396887 : XLogRegisterData(&xlrec, SizeOfHeapUpdate);
9186 : :
9187 : : /*
9188 : : * Prepare WAL data for the new tuple.
9189 : : */
4644 heikki.linnakangas@i 9190 [ + + + + ]: 2396887 : if (prefixlen > 0 || suffixlen > 0)
9191 : : {
9192 [ + + + + ]: 179234 : if (prefixlen > 0 && suffixlen > 0)
9193 : : {
9194 : 111141 : prefix_suffix[0] = prefixlen;
9195 : 111141 : prefix_suffix[1] = suffixlen;
136 melanieplageman@gmai 9196 : 111141 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefix_suffix,
9197 : : sizeof(uint16) * 2);
9198 : : }
4644 heikki.linnakangas@i 9199 [ + + ]: 68093 : else if (prefixlen > 0)
9200 : : {
136 melanieplageman@gmai 9201 : 42807 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefixlen,
9202 : : sizeof(uint16));
9203 : : }
9204 : : else
9205 : : {
9206 : 25286 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &suffixlen,
9207 : : sizeof(uint16));
9208 : : }
9209 : : }
9210 : :
4391 heikki.linnakangas@i 9211 : 2396887 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
9212 : 2396887 : xlhdr.t_infomask = newtup->t_data->t_infomask;
9213 : 2396887 : xlhdr.t_hoff = newtup->t_data->t_hoff;
4298 tgl@sss.pgh.pa.us 9214 [ - + ]: 2396887 : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
9215 : :
9216 : : /*
9217 : : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9218 : : *
9219 : : * The 'data' doesn't include the common prefix or suffix.
9220 : : */
136 melanieplageman@gmai 9221 : 2396887 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &xlhdr, SizeOfHeapHeader);
4644 heikki.linnakangas@i 9222 [ + + ]: 2396887 : if (prefixlen == 0)
9223 : : {
136 melanieplageman@gmai 9224 : 2242939 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
655 peter@eisentraut.org 9225 : 2242939 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3447 tgl@sss.pgh.pa.us 9226 : 2242939 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
9227 : : }
9228 : : else
9229 : : {
9230 : : /*
9231 : : * Have to write the null bitmap and data after the common prefix as
9232 : : * two separate rdata entries.
9233 : : */
9234 : : /* bitmap [+ padding] [+ oid] */
4298 9235 [ + - ]: 153948 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9236 : : {
136 melanieplageman@gmai 9237 : 153948 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
655 peter@eisentraut.org 9238 : 153948 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3447 tgl@sss.pgh.pa.us 9239 : 153948 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
9240 : : }
9241 : :
9242 : : /* data after common prefix */
136 melanieplageman@gmai 9243 : 153948 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
655 peter@eisentraut.org 9244 : 153948 : (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
3447 tgl@sss.pgh.pa.us 9245 : 153948 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9246 : : }
9247 : :
9248 : : /* We need to log a tuple identity */
4391 heikki.linnakangas@i 9249 [ + + + + ]: 2396887 : if (need_tuple_data && old_key_tuple)
9250 : : {
9251 : : /* don't really need this, but its more comfy to decode */
9252 : 160 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9253 : 160 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9254 : 160 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9255 : :
655 peter@eisentraut.org 9256 : 160 : XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
9257 : :
9258 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
4298 tgl@sss.pgh.pa.us 9259 : 160 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
9260 : 160 : old_key_tuple->t_len - SizeofHeapTupleHeader);
9261 : : }
9262 : :
9263 : : /*
9264 : : * Register VM buffers. If the old and new heap pages' VM bits are on the
9265 : : * same VM page and both their VM bits were cleared, the caller passes
9266 : : * only vmbuffer_new (mirroring the heap page convention where block 0 =
9267 : : * new is always registered).
9268 : : */
136 melanieplageman@gmai 9269 [ + + + + : 2396887 : Assert((BufferIsInvalid(vmbuffer_old) && BufferIsInvalid(vmbuffer_new)) ||
- + ]
9270 : : (vmbuffer_old != vmbuffer_new));
9271 : :
9272 [ + + ]: 2396887 : if (BufferIsValid(vmbuffer_new))
9273 : 1653 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_NEW, vmbuffer_new, 0);
9274 : :
9275 [ + + ]: 2396887 : if (BufferIsValid(vmbuffer_old))
9276 : 2458 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_OLD, vmbuffer_old, 0);
9277 : :
9278 : : /* filtering by origin on a row level is much more efficient */
3628 andres@anarazel.de 9279 : 2396887 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
9280 : :
4391 heikki.linnakangas@i 9281 : 2396887 : recptr = XLogInsert(RM_HEAP_ID, info);
9282 : :
7626 neilc@samurai.com 9283 : 2396887 : return recptr;
9284 : : }
9285 : :
9286 : : /*
9287 : : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
9288 : : *
9289 : : * This is only used when effective_wal_level is logical, and only for
9290 : : * catalog tuples.
9291 : : */
9292 : : static XLogRecPtr
4736 rhaas@postgresql.org 9293 : 31232 : log_heap_new_cid(Relation relation, HeapTuple tup)
9294 : : {
9295 : : xl_heap_new_cid xlrec;
9296 : :
9297 : : XLogRecPtr recptr;
9298 : 31232 : HeapTupleHeader hdr = tup->t_data;
9299 : :
9300 [ - + ]: 31232 : Assert(ItemPointerIsValid(&tup->t_self));
9301 [ - + ]: 31232 : Assert(tup->t_tableOid != InvalidOid);
9302 : :
9303 : 31232 : xlrec.top_xid = GetTopTransactionId();
1606 9304 : 31232 : xlrec.target_locator = relation->rd_locator;
4391 heikki.linnakangas@i 9305 : 31232 : xlrec.target_tid = tup->t_self;
9306 : :
9307 : : /*
9308 : : * If the tuple got inserted & deleted in the same TX we definitely have a
9309 : : * combo CID, set cmin and cmax.
9310 : : */
4736 rhaas@postgresql.org 9311 [ + + ]: 31232 : if (hdr->t_infomask & HEAP_COMBOCID)
9312 : : {
9313 [ - + ]: 2514 : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
4724 9314 [ - + ]: 2514 : Assert(!HeapTupleHeaderXminInvalid(hdr));
4736 9315 : 2514 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9316 : 2514 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9317 : 2514 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9318 : : }
9319 : : /* No combo CID, so only cmin or cmax can be set by this TX */
9320 : : else
9321 : : {
9322 : : /*
9323 : : * Tuple inserted.
9324 : : *
9325 : : * We need to check for LOCK ONLY because multixacts might be
9326 : : * transferred to the new tuple in case of FOR KEY SHARE updates in
9327 : : * which case there will be an xmax, although the tuple just got
9328 : : * inserted.
9329 : : */
9330 [ + + + + ]: 38162 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9331 : 9444 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
9332 : : {
9333 : 19275 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
9334 : 19275 : xlrec.cmax = InvalidCommandId;
9335 : : }
9336 : : /* Tuple from a different tx updated or deleted. */
9337 : : else
9338 : : {
9339 : 9443 : xlrec.cmin = InvalidCommandId;
9340 : 9443 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
9341 : : }
9342 : 28718 : xlrec.combocid = InvalidCommandId;
9343 : : }
9344 : :
9345 : : /*
9346 : : * Note that we don't need to register the buffer here, because this
9347 : : * operation does not modify the page. The insert/update/delete that
9348 : : * called us certainly did, but that's WAL-logged separately.
9349 : : */
4391 heikki.linnakangas@i 9350 : 31232 : XLogBeginInsert();
655 peter@eisentraut.org 9351 : 31232 : XLogRegisterData(&xlrec, SizeOfHeapNewCid);
9352 : :
9353 : : /* will be looked at irrespective of origin */
9354 : :
4391 heikki.linnakangas@i 9355 : 31232 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9356 : :
4736 rhaas@postgresql.org 9357 : 31232 : return recptr;
9358 : : }
9359 : :
9360 : : /*
9361 : : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9362 : : * the old tuple in an UPDATE or DELETE.
9363 : : *
9364 : : * Returns NULL if there's no need to log an identity or if there's no suitable
9365 : : * key defined.
9366 : : *
9367 : : * Pass key_required true if any replica identity columns changed value, or if
9368 : : * any of them have any external data. Delete must always pass true.
9369 : : *
9370 : : * *copy is set to true if the returned tuple is a modified copy rather than
9371 : : * the same tuple that was passed in.
9372 : : */
9373 : : static HeapTuple
1748 akapila@postgresql.o 9374 : 4301713 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
9375 : : bool *copy)
9376 : : {
4736 rhaas@postgresql.org 9377 : 4301713 : TupleDesc desc = RelationGetDescr(relation);
9378 : 4301713 : char replident = relation->rd_rel->relreplident;
9379 : : Bitmapset *idattrs;
9380 : : HeapTuple key_tuple;
9381 : : bool nulls[MaxHeapAttributeNumber];
9382 : : Datum values[MaxHeapAttributeNumber];
9383 : :
9384 : 4301713 : *copy = false;
9385 : :
9386 [ + + + + : 4301713 : if (!RelationIsLogicallyLogged(relation))
+ + - + -
- - - + -
+ + - + ]
9387 : 4201150 : return NULL;
9388 : :
9389 [ + + ]: 100563 : if (replident == REPLICA_IDENTITY_NOTHING)
9390 : 388 : return NULL;
9391 : :
9392 [ + + ]: 100175 : if (replident == REPLICA_IDENTITY_FULL)
9393 : : {
9394 : : /*
9395 : : * When logging the entire old tuple, it very well could contain
9396 : : * toasted columns. If so, force them to be inlined.
9397 : : */
9398 [ + + ]: 200 : if (HeapTupleHasExternal(tp))
9399 : : {
9400 : 4 : *copy = true;
2644 tgl@sss.pgh.pa.us 9401 : 4 : tp = toast_flatten_tuple(tp, desc);
9402 : :
9403 : : /* see below */
19 andres@anarazel.de 9404 [ - + ]: 4 : Assert(!HeapTupleHeaderIsDatum(tp->t_data));
9405 : : }
4736 rhaas@postgresql.org 9406 : 200 : return tp;
9407 : : }
9408 : :
9409 : : /* if the key isn't required and we're only logging the key, we're done */
1748 akapila@postgresql.o 9410 [ + + ]: 99975 : if (!key_required)
4736 rhaas@postgresql.org 9411 : 46956 : return NULL;
9412 : :
9413 : : /* find out the replica identity columns */
2644 tgl@sss.pgh.pa.us 9414 : 53019 : idattrs = RelationGetIndexAttrBitmap(relation,
9415 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
9416 : :
9417 : : /*
9418 : : * If there's no defined replica identity columns, treat as !key_required.
9419 : : * (This case should not be reachable from heap_update, since that should
9420 : : * calculate key_required accurately. But heap_delete just passes
9421 : : * constant true for key_required, so we can hit this case in deletes.)
9422 : : */
9423 [ + + ]: 53019 : if (bms_is_empty(idattrs))
9424 : 6022 : return NULL;
9425 : :
9426 : : /*
9427 : : * Construct a new tuple containing only the replica identity columns,
9428 : : * with nulls elsewhere. While we're at it, assert that the replica
9429 : : * identity columns aren't null.
9430 : : */
9431 : 46997 : heap_deform_tuple(tp, desc, values, nulls);
9432 : :
9433 [ + + ]: 151011 : for (int i = 0; i < desc->natts; i++)
9434 : : {
9435 [ + + ]: 104014 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
9436 : : idattrs))
9437 [ - + ]: 47011 : Assert(!nulls[i]);
9438 : : else
9439 : 57003 : nulls[i] = true;
9440 : : }
9441 : :
4736 rhaas@postgresql.org 9442 : 46997 : key_tuple = heap_form_tuple(desc, values, nulls);
9443 : 46997 : *copy = true;
9444 : :
2644 tgl@sss.pgh.pa.us 9445 : 46997 : bms_free(idattrs);
9446 : :
9447 : : /*
9448 : : * If the tuple, which by here only contains indexed columns, still has
9449 : : * toasted columns, force them to be inlined. This is somewhat unlikely
9450 : : * since there's limits on the size of indexed columns, so we don't
9451 : : * duplicate toast_flatten_tuple()s functionality in the above loop over
9452 : : * the indexed columns, even if it would be more efficient.
9453 : : */
4736 rhaas@postgresql.org 9454 [ + + ]: 46997 : if (HeapTupleHasExternal(key_tuple))
9455 : : {
4589 bruce@momjian.us 9456 : 4 : HeapTuple oldtup = key_tuple;
9457 : :
2644 tgl@sss.pgh.pa.us 9458 : 4 : key_tuple = toast_flatten_tuple(oldtup, desc);
4736 rhaas@postgresql.org 9459 : 4 : heap_freetuple(oldtup);
9460 : : }
9461 : :
9462 : : /*
9463 : : * Because we only WAL log the tuple data itself, we don't want the tuple
9464 : : * to be marked as a versioned tuple, as we couldn't verify it due to the
9465 : : * necessary metadata not having been preserved. We also don't need it, if
9466 : : * there were a danger of the format changing, we'd be in much bigger
9467 : : * trouble.
9468 : : */
19 andres@anarazel.de 9469 : 46997 : HeapTupleHeaderClearDatum(key_tuple->t_data);
9470 : :
4736 rhaas@postgresql.org 9471 : 46997 : return key_tuple;
9472 : : }
9473 : :
9474 : : /*
9475 : : * HeapCheckForSerializableConflictOut
9476 : : * We are reading a tuple. If it's not visible, there may be a
9477 : : * rw-conflict out with the inserter. Otherwise, if it is visible to us
9478 : : * but has been deleted, there may be a rw-conflict out with the deleter.
9479 : : *
9480 : : * We will determine the top level xid of the writing transaction with which
9481 : : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9482 : : * for overlap with our own transaction.
9483 : : *
9484 : : * This function should be called just about anywhere in heapam.c where a
9485 : : * tuple has been read. The caller must hold at least a shared lock on the
9486 : : * buffer, because this function might set hint bits on the tuple. There is
9487 : : * currently no known reason to call this function from an index AM.
9488 : : */
9489 : : void
2496 tmunro@postgresql.or 9490 : 41961295 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
9491 : : HeapTuple tuple, Buffer buffer,
9492 : : Snapshot snapshot)
9493 : : {
9494 : : TransactionId xid;
9495 : : HTSV_Result htsvResult;
9496 : :
9497 [ + + ]: 41961295 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9498 : 41953316 : return;
9499 : :
9500 : : /*
9501 : : * Check to see whether the tuple has been written to by a concurrent
9502 : : * transaction, either to create it not visible to us, or to delete it
9503 : : * while it is visible to us. The "visible" bool indicates whether the
9504 : : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9505 : : * is going on with it.
9506 : : *
9507 : : * In the event of a concurrently inserted tuple that also happens to have
9508 : : * been concurrently updated (by a separate transaction), the xmin of the
9509 : : * tuple will be used -- not the updater's xid.
9510 : : */
9511 : 7979 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9512 [ + + + + : 7979 : switch (htsvResult)
- ]
9513 : : {
9514 : 7151 : case HEAPTUPLE_LIVE:
9515 [ + + ]: 7151 : if (visible)
9516 : 7129 : return;
9517 : 22 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9518 : 22 : break;
9519 : 364 : case HEAPTUPLE_RECENTLY_DEAD:
9520 : : case HEAPTUPLE_DELETE_IN_PROGRESS:
2361 pg@bowt.ie 9521 [ + + ]: 364 : if (visible)
9522 : 289 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9523 : : else
9524 : 75 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9525 : :
9526 [ + + ]: 364 : if (TransactionIdPrecedes(xid, TransactionXmin))
9527 : : {
9528 : : /* This is like the HEAPTUPLE_DEAD case */
9529 [ - + ]: 68 : Assert(!visible);
9530 : 68 : return;
9531 : : }
2496 tmunro@postgresql.or 9532 : 296 : break;
9533 : 345 : case HEAPTUPLE_INSERT_IN_PROGRESS:
9534 : 345 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9535 : 345 : break;
9536 : 119 : case HEAPTUPLE_DEAD:
2361 pg@bowt.ie 9537 [ - + ]: 119 : Assert(!visible);
2496 tmunro@postgresql.or 9538 : 119 : return;
2496 tmunro@postgresql.or 9539 :UBC 0 : default:
9540 : :
9541 : : /*
9542 : : * The only way to get to this default clause is if a new value is
9543 : : * added to the enum type without adding it to this switch
9544 : : * statement. That's a bug, so elog.
9545 : : */
9546 [ # # ]: 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9547 : :
9548 : : /*
9549 : : * In spite of having all enum values covered and calling elog on
9550 : : * this default, some compilers think this is a code path which
9551 : : * allows xid to be used below without initialization. Silence
9552 : : * that warning.
9553 : : */
9554 : : xid = InvalidTransactionId;
9555 : : }
9556 : :
2496 tmunro@postgresql.or 9557 [ - + ]:CBC 663 : Assert(TransactionIdIsValid(xid));
9558 [ - + ]: 663 : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
9559 : :
9560 : : /*
9561 : : * Find top level xid. Bail out if xid is too early to be a conflict, or
9562 : : * if it's our own xid.
9563 : : */
9564 [ + + ]: 663 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
9565 : 82 : return;
9566 : 581 : xid = SubTransGetTopmostTransaction(xid);
9567 [ - + ]: 581 : if (TransactionIdPrecedes(xid, TransactionXmin))
2496 tmunro@postgresql.or 9568 :UBC 0 : return;
9569 : :
2496 tmunro@postgresql.or 9570 :CBC 581 : CheckForSerializableConflictOut(relation, xid, snapshot);
9571 : : }
|