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
500 nathan@postgresql.or 228 :CBC 16601732 : AssertHasSnapshotForToast(Relation rel)
229 : : {
230 : : #ifdef USE_ASSERT_CHECKING
231 : :
232 : : /* bootstrap mode in particular breaks this rule */
233 [ + + ]: 16601732 : if (!IsNormalProcessingMode())
234 : 681268 : return;
235 : :
236 : : /* if the relation doesn't have a TOAST table, we are good */
237 [ + + ]: 15920464 : if (!OidIsValid(rel->rd_rel->reltoastrelid))
238 : 10273350 : return;
239 : :
240 [ - + ]: 5647114 : 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
917 tmunro@postgresql.or 255 : 146297 : heap_scan_stream_read_next_parallel(ReadStream *stream,
256 : : void *callback_private_data,
257 : : void *per_buffer_data)
258 : : {
259 : 146297 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
260 : :
261 [ - + ]: 146297 : Assert(ScanDirectionIsForward(scan->rs_dir));
262 [ - + ]: 146297 : Assert(scan->rs_base.rs_parallel);
263 : :
264 [ + + ]: 146297 : if (unlikely(!scan->rs_inited))
265 : : {
266 : : /* parallel scan */
267 : 2836 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
268 : 2836 : scan->rs_parallelworkerdata,
319 drowley@postgresql.o 269 : 2836 : (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 */
917 tmunro@postgresql.or 274 : 5672 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
275 : 2836 : scan->rs_parallelworkerdata,
276 : 2836 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
277 : 2836 : scan->rs_inited = true;
278 : : }
279 : : else
280 : : {
281 : 143461 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
282 : 143461 : scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
283 : 143461 : scan->rs_base.rs_parallel);
284 : : }
285 : :
286 : 146297 : 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 : 4008150 : heap_scan_stream_read_next_serial(ReadStream *stream,
296 : : void *callback_private_data,
297 : : void *per_buffer_data)
298 : : {
299 : 4008150 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
300 : :
301 [ + + ]: 4008150 : if (unlikely(!scan->rs_inited))
302 : : {
303 : 1074885 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
304 : 1074885 : scan->rs_inited = true;
305 : : }
306 : : else
307 : 2933265 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
308 : : scan->rs_prefetch_block,
309 : : scan->rs_dir);
310 : :
311 : 4008150 : 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
576 melanieplageman@gmai 320 : 258221 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
321 : : void *per_buffer_data)
322 : : {
323 : 258221 : TBMIterateResult *tbmres = per_buffer_data;
324 : 258221 : BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
325 : 258221 : HeapScanDesc hscan = (HeapScanDesc) bscan;
326 : 258221 : TableScanDesc sscan = &hscan->rs_base;
327 : :
328 : : for (;;)
329 : : {
330 [ - + ]: 258221 : CHECK_FOR_INTERRUPTS();
331 : :
332 : : /* no more entries in the bitmap */
333 [ + + ]: 258221 : if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
334 : 14515 : 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 [ + + ]: 243706 : if (!IsolationIsSerializable() &&
345 [ - + ]: 243597 : tbmres->blockno >= hscan->rs_nblocks)
576 melanieplageman@gmai 346 :UBC 0 : continue;
347 : :
576 melanieplageman@gmai 348 :CBC 243706 : 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
4097 tgl@sss.pgh.pa.us 360 : 1113738 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
361 : : {
2772 andres@anarazel.de 362 : 1113738 : ParallelBlockTableScanDesc bpscan = NULL;
363 : : bool allow_strat;
364 : : bool allow_sync;
365 : :
366 : : /*
367 : : * Determine the number of blocks we have to scan.
368 : : *
369 : : * It is sufficient to do this once at scan start, since any tuples added
370 : : * while the scan is in progress will be invisible to my snapshot anyway.
371 : : * (That is not true when using a non-MVCC snapshot. However, we couldn't
372 : : * guarantee to return tuples added after scan start anyway, since they
373 : : * might go into pages we already scanned. To guarantee consistent
374 : : * results for a non-MVCC snapshot, the caller must hold some higher-level
375 : : * lock that ensures the interesting tuple(s) won't change.)
376 : : */
377 [ + + ]: 1113738 : if (scan->rs_base.rs_parallel != NULL)
378 : : {
379 : 4630 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
380 : 4630 : scan->rs_nblocks = bpscan->phs_nblocks;
381 : : }
382 : : else
383 : 1109108 : scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
384 : :
385 : : /*
386 : : * If the table is large relative to NBuffers, use a bulk-read access
387 : : * strategy and enable synchronized scanning (see syncscan.c). Although
388 : : * the thresholds for these features could be different, we make them the
389 : : * same so that there are only two behaviors to tune rather than four.
390 : : * (However, some callers need to be able to disable one or both of these
391 : : * behaviors, independently of the size of the table; also there is a GUC
392 : : * variable that can disable synchronized scanning.)
393 : : *
394 : : * Note that table_block_parallelscan_initialize has a very similar test;
395 : : * if you change this, consider changing that one, too.
396 : : */
397 [ + + ]: 1113736 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
7065 tgl@sss.pgh.pa.us 398 [ + + ]: 1095965 : scan->rs_nblocks > NBuffers / 4)
399 : : {
2703 andres@anarazel.de 400 : 15237 : allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
401 : 15237 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
402 : : }
403 : : else
6846 tgl@sss.pgh.pa.us 404 : 1098499 : allow_strat = allow_sync = false;
405 : :
406 [ + + ]: 1113736 : if (allow_strat)
407 : : {
408 : : /* During a rescan, keep the previous strategy object. */
7075 409 [ + + ]: 13883 : if (scan->rs_strategy == NULL)
410 : 13646 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
411 : : }
412 : : else
413 : : {
414 [ - + ]: 1099853 : if (scan->rs_strategy != NULL)
7075 tgl@sss.pgh.pa.us 415 :UBC 0 : FreeAccessStrategy(scan->rs_strategy);
7075 tgl@sss.pgh.pa.us 416 :CBC 1099853 : scan->rs_strategy = NULL;
417 : : }
418 : :
2772 andres@anarazel.de 419 [ + + ]: 1113736 : if (scan->rs_base.rs_parallel != NULL)
420 : : {
421 : : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
2703 422 [ + + ]: 4630 : if (scan->rs_base.rs_parallel->phs_syncscan)
423 : 5 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
424 : : else
425 : 4625 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
426 : :
427 : : /*
428 : : * If not rescanning, initialize the startblock. Finding the actual
429 : : * start location is done in table_block_parallelscan_startblock_init,
430 : : * based on whether an alternative start location has been set with
431 : : * heap_setscanlimits, or using the syncscan location, when syncscan
432 : : * is enabled.
433 : : */
318 drowley@postgresql.o 434 [ + + ]: 4630 : if (!keep_startblock)
435 : 4478 : scan->rs_startblock = InvalidBlockNumber;
436 : : }
437 : : else
438 : : {
439 [ + + ]: 1109106 : if (keep_startblock)
440 : : {
441 : : /*
442 : : * When rescanning, we want to keep the previous startblock
443 : : * setting, so that rewinding a cursor doesn't generate surprising
444 : : * results. Reset the active syncscan setting, though.
445 : : */
446 [ + + + + ]: 654201 : if (allow_sync && synchronize_seqscans)
447 : 84 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
448 : : else
449 : 654117 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
450 : : }
451 [ + + + + ]: 454905 : else if (allow_sync && synchronize_seqscans)
452 : : {
453 : 139 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
454 : 139 : scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
455 : : }
456 : : else
457 : : {
458 : 454766 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
459 : 454766 : scan->rs_startblock = 0;
460 : : }
461 : : }
462 : :
4357 alvherre@alvh.no-ip. 463 : 1113736 : scan->rs_numblocks = InvalidBlockNumber;
7625 tgl@sss.pgh.pa.us 464 : 1113736 : scan->rs_inited = false;
9256 465 : 1113736 : scan->rs_ctup.t_data = NULL;
7625 466 : 1113736 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
9256 467 : 1113736 : scan->rs_cbuf = InvalidBuffer;
7625 468 : 1113736 : scan->rs_cblock = InvalidBlockNumber;
663 melanieplageman@gmai 469 : 1113736 : scan->rs_ntuples = 0;
470 : 1113736 : scan->rs_cindex = 0;
471 : :
472 : : /*
473 : : * Initialize to ForwardScanDirection because it is most common and
474 : : * because heap scans go forward before going backward (e.g. CURSORs).
475 : : */
917 tmunro@postgresql.or 476 : 1113736 : scan->rs_dir = ForwardScanDirection;
477 : 1113736 : scan->rs_prefetch_block = InvalidBlockNumber;
478 : :
479 : : /* page-at-a-time fields are always invalid when not rs_inited */
480 : :
481 : : /*
482 : : * copy the scan key, if appropriate
483 : : */
1684 tgl@sss.pgh.pa.us 484 [ + + + + ]: 1113736 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
2772 andres@anarazel.de 485 : 257114 : memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
486 : :
487 : : /*
488 : : * Currently, we only have a stats counter for sequential heap scans (but
489 : : * e.g for bitmap scans the underlying bitmap index scans will be counted,
490 : : * and for sample scans we update stats for tuple fetches).
491 : : */
2703 492 [ + + ]: 1113736 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
2772 493 [ + + + + : 1078212 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
+ + - + ]
11052 scrappy@hub.org 494 : 1113736 : }
495 : :
496 : : /*
497 : : * heap_setscanlimits - restrict range of a heapscan
498 : : *
499 : : * startBlk is the page to start at
500 : : * numBlks is number of pages to scan (InvalidBlockNumber means "all")
501 : : */
502 : : void
2772 andres@anarazel.de 503 : 3279 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
504 : : {
505 : 3279 : HeapScanDesc scan = (HeapScanDesc) sscan;
506 : :
4101 tgl@sss.pgh.pa.us 507 [ - + ]: 3279 : Assert(!scan->rs_inited); /* else too late to change */
508 : : /* else rs_startblock is significant */
2703 andres@anarazel.de 509 [ - + ]: 3279 : Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
510 : :
511 : : /* Check startBlk is valid (but allow case of zero blocks...) */
4101 tgl@sss.pgh.pa.us 512 [ + + - + ]: 3279 : Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
513 : :
4357 alvherre@alvh.no-ip. 514 : 3279 : scan->rs_startblock = startBlk;
515 : 3279 : scan->rs_numblocks = numBlks;
516 : 3279 : }
517 : :
518 : : /*
519 : : * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
520 : : * multiple times, with constant arguments for all_visible,
521 : : * check_serializable.
522 : : */
523 : : pg_always_inline
524 : : static int
918 andres@anarazel.de 525 : 2947896 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
526 : : Page page, Buffer buffer,
527 : : BlockNumber block, int lines,
528 : : bool all_visible, bool check_serializable)
529 : : {
273 530 : 2947896 : Oid relid = RelationGetRelid(scan->rs_base.rs_rd);
919 531 : 2947896 : int ntup = 0;
273 532 : 2947896 : int nvis = 0;
533 : : BatchMVCCState batchmvcc;
534 : :
535 : : /* page at a time should have been disabled otherwise */
536 [ - + ]: 2947896 : Assert(IsMVCCSnapshot(snapshot));
537 : :
538 : : /* first find all tuples on the page */
539 [ + + ]: 159453431 : for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
540 : : {
919 541 : 156505535 : ItemId lpp = PageGetItemId(page, lineoff);
542 : : HeapTuple tup;
543 : :
273 544 [ + + ]: 156505535 : if (unlikely(!ItemIdIsNormal(lpp)))
919 545 : 26947201 : continue;
546 : :
547 : : /*
548 : : * If the page is not all-visible or we need to check serializability,
549 : : * maintain enough state to be able to refind the tuple efficiently,
550 : : * without again first needing to fetch the item and then via that the
551 : : * tuple.
552 : : */
273 553 [ + + - + ]: 129558334 : if (!all_visible || check_serializable)
554 : : {
555 : 66760731 : tup = &batchmvcc.tuples[ntup];
556 : :
557 : 66760731 : tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
558 : 66760731 : tup->t_len = ItemIdGetLength(lpp);
559 : 66760731 : tup->t_tableOid = relid;
560 : 66760731 : ItemPointerSet(&(tup->t_self), block, lineoff);
561 : : }
562 : :
563 : : /*
564 : : * If the page is all visible, these fields otherwise won't be
565 : : * populated in loop below.
566 : : */
567 [ + + ]: 129558334 : if (all_visible)
568 : : {
569 [ - + ]: 62797603 : if (check_serializable)
570 : : {
273 andres@anarazel.de 571 :UBC 0 : batchmvcc.visible[ntup] = true;
572 : : }
919 andres@anarazel.de 573 :CBC 62797603 : scan->rs_vistuples[ntup] = lineoff;
574 : : }
575 : :
273 576 : 129558334 : ntup++;
577 : : }
578 : :
919 579 [ - + ]: 2947896 : Assert(ntup <= MaxHeapTuplesPerPage);
580 : :
581 : : /*
582 : : * Unless the page is all visible, test visibility for all tuples one go.
583 : : * That is considerably more efficient than calling
584 : : * HeapTupleSatisfiesMVCC() one-by-one.
585 : : */
273 586 [ + + ]: 2947896 : if (all_visible)
587 : 1301355 : nvis = ntup;
588 : : else
589 : 1646541 : nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
590 : : ntup,
591 : : &batchmvcc,
592 : 1646541 : scan->rs_vistuples);
593 : :
594 : : /*
595 : : * So far we don't have batch API for testing serializabilty, so do so
596 : : * one-by-one.
597 : : */
598 [ + + ]: 2947896 : if (check_serializable)
599 : : {
600 [ + + ]: 2069 : for (int i = 0; i < ntup; i++)
601 : : {
602 : 1454 : HeapCheckForSerializableConflictOut(batchmvcc.visible[i],
603 : : scan->rs_base.rs_rd,
604 : : &batchmvcc.tuples[i],
605 : : buffer, snapshot);
606 : : }
607 : : }
608 : :
609 : 2947888 : return nvis;
610 : : }
611 : :
612 : : /*
613 : : * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
614 : : *
615 : : * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
616 : : * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
617 : : */
618 : : void
921 drowley@postgresql.o 619 : 2947896 : heap_prepare_pagescan(TableScanDesc sscan)
620 : : {
2772 andres@anarazel.de 621 : 2947896 : HeapScanDesc scan = (HeapScanDesc) sscan;
921 drowley@postgresql.o 622 : 2947896 : Buffer buffer = scan->rs_cbuf;
623 : 2947896 : BlockNumber block = scan->rs_cblock;
624 : : Snapshot snapshot;
625 : : Page page;
626 : : int lines;
627 : : bool all_visible;
628 : : bool check_serializable;
629 : :
630 [ - + ]: 2947896 : Assert(BufferGetBlockNumber(buffer) == block);
631 : :
632 : : /* ensure we're not accidentally being used when not in pagemode */
633 [ - + ]: 2947896 : Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
2772 andres@anarazel.de 634 : 2947896 : snapshot = scan->rs_base.rs_snapshot;
635 : :
636 : : /*
637 : : * Prune and repair fragmentation for the whole page, if possible.
638 : : */
196 melanieplageman@gmai 639 : 2947896 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer, &scan->rs_vmbuffer,
640 : 2947896 : sscan->rs_flags & SO_HINT_REL_READ_ONLY);
641 : :
642 : : /*
643 : : * We must hold share lock on the buffer content while examining tuple
644 : : * visibility. Afterwards, however, the tuples we have found to be
645 : : * visible are guaranteed good as long as we hold the buffer pin.
646 : : */
7625 tgl@sss.pgh.pa.us 647 : 2947896 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
648 : :
1426 peter@eisentraut.org 649 : 2947896 : page = BufferGetPage(buffer);
650 : 2947896 : lines = PageGetMaxOffsetNumber(page);
651 : :
652 : : /*
653 : : * If the all-visible flag indicates that all tuples on the page are
654 : : * visible to everyone, we can skip the per-tuple visibility tests.
655 : : *
656 : : * Note: In hot standby, a tuple that's already visible to all
657 : : * transactions on the primary might still be invisible to a read-only
658 : : * transaction in the standby. We partly handle this problem by tracking
659 : : * the minimum xmin of visible tuples as the cut-off XID while marking a
660 : : * page all-visible on the primary and WAL log that along with the
661 : : * visibility map SET operation. In hot standby, we wait for (or abort)
662 : : * all transactions that can potentially may not see one or more tuples on
663 : : * the page. That's how index-only scans work fine in hot standby. A
664 : : * crucial difference between index-only scans and heap scans is that the
665 : : * index-only scan completely relies on the visibility map where as heap
666 : : * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
667 : : * the page-level flag can be trusted in the same way, because it might
668 : : * get propagated somehow without being explicitly WAL-logged, e.g. via a
669 : : * full page write. Until we can prove that beyond doubt, let's check each
670 : : * tuple for visibility the hard way.
671 : : */
672 [ + + + + ]: 2947896 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
673 : : check_serializable =
919 andres@anarazel.de 674 : 2947896 : CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
675 : :
676 : : /*
677 : : * We call page_collect_tuples() with constant arguments, to get the
678 : : * compiler to constant fold the constant arguments. Separate calls with
679 : : * constant arguments, rather than variables, are needed on several
680 : : * compilers to actually perform constant folding.
681 : : */
682 [ + + ]: 2947896 : if (likely(all_visible))
683 : : {
684 [ + - ]: 1301355 : if (likely(!check_serializable))
918 685 : 1301355 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
686 : : block, lines, true, false);
687 : : else
918 andres@anarazel.de 688 :UBC 0 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
689 : : block, lines, true, true);
690 : : }
691 : : else
692 : : {
919 andres@anarazel.de 693 [ + + ]:CBC 1646541 : if (likely(!check_serializable))
918 694 : 1645918 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
695 : : block, lines, false, false);
696 : : else
697 : 623 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
698 : : block, lines, false, true);
699 : : }
700 : :
7625 tgl@sss.pgh.pa.us 701 : 2947888 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
702 : 2947888 : }
703 : :
704 : : /*
705 : : * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
706 : : *
707 : : * Read the next block of the scan relation from the read stream and save it
708 : : * in the scan descriptor. It is already pinned.
709 : : */
710 : : static inline void
921 drowley@postgresql.o 711 : 3948961 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
712 : : {
917 tmunro@postgresql.or 713 [ - + ]: 3948961 : Assert(scan->rs_read_stream);
714 : :
715 : : /* release previous scan buffer, if any */
921 drowley@postgresql.o 716 [ + + ]: 3948961 : if (BufferIsValid(scan->rs_cbuf))
717 : : {
718 : 2871236 : ReleaseBuffer(scan->rs_cbuf);
719 : 2871236 : scan->rs_cbuf = InvalidBuffer;
720 : : }
721 : :
722 : : /*
723 : : * Be sure to check for interrupts at least once per page. Checks at
724 : : * higher code levels won't be able to stop a seqscan that encounters many
725 : : * pages' worth of consecutive dead tuples.
726 : : */
727 [ + + ]: 3948961 : CHECK_FOR_INTERRUPTS();
728 : :
729 : : /*
730 : : * If the scan direction is changing, reset the prefetch block to the
731 : : * current block. Otherwise, we will incorrectly prefetch the blocks
732 : : * between the prefetch block and the current block again before
733 : : * prefetching blocks in the new, correct scan direction.
734 : : */
917 tmunro@postgresql.or 735 [ + + ]: 3948955 : if (unlikely(scan->rs_dir != dir))
736 : : {
737 : 109 : scan->rs_prefetch_block = scan->rs_cblock;
738 : 109 : read_stream_reset(scan->rs_read_stream);
739 : : }
740 : :
741 : 3948955 : scan->rs_dir = dir;
742 : :
743 : 3948955 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
744 [ + + ]: 3948927 : if (BufferIsValid(scan->rs_cbuf))
745 : 3058022 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
921 drowley@postgresql.o 746 : 3948927 : }
747 : :
748 : : /*
749 : : * heapgettup_initial_block - return the first BlockNumber to scan
750 : : *
751 : : * Returns InvalidBlockNumber when there are no blocks to scan. This can
752 : : * occur with empty tables and in parallel scans when parallel workers get all
753 : : * of the pages before we can get a chance to get our first page.
754 : : */
755 : : static pg_noinline BlockNumber
1348 756 : 1074885 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
757 : : {
758 [ - + ]: 1074885 : Assert(!scan->rs_inited);
917 tmunro@postgresql.or 759 [ - + ]: 1074885 : Assert(scan->rs_base.rs_parallel == NULL);
760 : :
761 : : /* When there are no pages to scan, return InvalidBlockNumber */
1348 drowley@postgresql.o 762 [ + + + + ]: 1074885 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
763 : 528896 : return InvalidBlockNumber;
764 : :
765 [ + + ]: 545989 : if (ScanDirectionIsForward(dir))
766 : : {
917 tmunro@postgresql.or 767 : 545944 : return scan->rs_startblock;
768 : : }
769 : : else
770 : : {
771 : : /*
772 : : * Disable reporting to syncscan logic in a backwards scan; it's not
773 : : * very likely anyone else is doing the same thing at the same time,
774 : : * and much more likely that we'll just bollix things for forward
775 : : * scanners.
776 : : */
1348 drowley@postgresql.o 777 : 45 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
778 : :
779 : : /*
780 : : * Start from last page of the scan. Ensure we take into account
781 : : * rs_numblocks if it's been adjusted by heap_setscanlimits().
782 : : */
783 [ + + ]: 45 : if (scan->rs_numblocks != InvalidBlockNumber)
784 : 8 : return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
785 : :
786 [ - + ]: 37 : if (scan->rs_startblock > 0)
1348 drowley@postgresql.o 787 :UBC 0 : return scan->rs_startblock - 1;
788 : :
1348 drowley@postgresql.o 789 :CBC 37 : return scan->rs_nblocks - 1;
790 : : }
791 : : }
792 : :
793 : :
794 : : /*
795 : : * heapgettup_start_page - helper function for heapgettup()
796 : : *
797 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
798 : : * to the number of tuples on this page. Also set *lineoff to the first
799 : : * offset to scan with forward scans getting the first offset and backward
800 : : * getting the final offset on the page.
801 : : */
802 : : static Page
1347 803 : 117193 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
804 : : OffsetNumber *lineoff)
805 : : {
806 : : Page page;
807 : :
808 [ - + ]: 117193 : Assert(scan->rs_inited);
809 [ - + ]: 117193 : Assert(BufferIsValid(scan->rs_cbuf));
810 : :
811 : : /* Caller is responsible for ensuring buffer is locked if needed */
812 : 117193 : page = BufferGetPage(scan->rs_cbuf);
813 : :
1343 814 : 117193 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
815 : :
1347 816 [ + - ]: 117193 : if (ScanDirectionIsForward(dir))
817 : 117193 : *lineoff = FirstOffsetNumber;
818 : : else
1347 drowley@postgresql.o 819 :UBC 0 : *lineoff = (OffsetNumber) (*linesleft);
820 : :
821 : : /* lineoff now references the physically previous or next tid */
1347 drowley@postgresql.o 822 :CBC 117193 : return page;
823 : : }
824 : :
825 : :
826 : : /*
827 : : * heapgettup_continue_page - helper function for heapgettup()
828 : : *
829 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
830 : : * to the number of tuples left to scan on this page. Also set *lineoff to
831 : : * the next offset to scan according to the ScanDirection in 'dir'.
832 : : */
833 : : static inline Page
834 : 9483754 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
835 : : OffsetNumber *lineoff)
836 : : {
837 : : Page page;
838 : :
839 [ - + ]: 9483754 : Assert(scan->rs_inited);
840 [ - + ]: 9483754 : Assert(BufferIsValid(scan->rs_cbuf));
841 : :
842 : : /* Caller is responsible for ensuring buffer is locked if needed */
843 : 9483754 : page = BufferGetPage(scan->rs_cbuf);
844 : :
845 [ + - ]: 9483754 : if (ScanDirectionIsForward(dir))
846 : : {
847 : 9483754 : *lineoff = OffsetNumberNext(scan->rs_coffset);
848 : 9483754 : *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
849 : : }
850 : : else
851 : : {
852 : : /*
853 : : * The previous returned tuple may have been vacuumed since the
854 : : * previous scan when we use a non-MVCC snapshot, so we must
855 : : * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
856 : : */
1347 drowley@postgresql.o 857 [ # # ]:UBC 0 : *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
858 : 0 : *linesleft = *lineoff;
859 : : }
860 : :
861 : : /* lineoff now references the physically previous or next tid */
1347 drowley@postgresql.o 862 :CBC 9483754 : return page;
863 : : }
864 : :
865 : : /*
866 : : * heapgettup_advance_block - helper for heap_fetch_next_buffer()
867 : : *
868 : : * Given the current block number, the scan direction, and various information
869 : : * contained in the scan descriptor, calculate the BlockNumber to scan next
870 : : * and return it. If there are no further blocks to scan, return
871 : : * InvalidBlockNumber to indicate this fact to the caller.
872 : : *
873 : : * This should not be called to determine the initial block number -- only for
874 : : * subsequent blocks.
875 : : *
876 : : * This also adjusts rs_numblocks when a limit has been imposed by
877 : : * heap_setscanlimits().
878 : : */
879 : : static inline BlockNumber
880 : 2933265 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
881 : : {
917 tmunro@postgresql.or 882 [ - + ]: 2933265 : Assert(scan->rs_base.rs_parallel == NULL);
883 : :
884 [ + + ]: 2933265 : if (likely(ScanDirectionIsForward(dir)))
885 : : {
886 : 2933176 : block++;
887 : :
888 : : /* wrap back to the start of the heap */
889 [ + + ]: 2933176 : if (block >= scan->rs_nblocks)
890 : 430457 : block = 0;
891 : :
892 : : /*
893 : : * Report our new scan position for synchronization purposes. We don't
894 : : * do that when moving backwards, however. That would just mess up any
895 : : * other forward-moving scanners.
896 : : *
897 : : * Note: we do this before checking for end of scan so that the final
898 : : * state of the position hint is back at the start of the rel. That's
899 : : * not strictly necessary, but otherwise when you run the same query
900 : : * multiple times the starting position would shift a little bit
901 : : * backwards on every invocation, which is confusing. We don't
902 : : * guarantee any specific ordering in general, though.
903 : : */
904 [ + + ]: 2933176 : if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
905 : 43636 : ss_report_location(scan->rs_base.rs_rd, block);
906 : :
907 : : /* we're done if we're back at where we started */
908 [ + + ]: 2933176 : if (block == scan->rs_startblock)
909 : 430407 : return InvalidBlockNumber;
910 : :
911 : : /* check if the limit imposed by heap_setscanlimits() is met */
912 [ + + ]: 2502769 : if (scan->rs_numblocks != InvalidBlockNumber)
913 : : {
914 : : BlockNumber endblock;
915 : :
18 drowley@postgresql.o 916 : 2828 : endblock = (scan->rs_startblock + scan->rs_numblocks) %
917 : 2828 : scan->rs_nblocks;
918 [ + + ]: 2828 : if (block == endblock)
917 tmunro@postgresql.or 919 : 1604 : return InvalidBlockNumber;
920 : : }
921 : :
922 : 2501165 : return block;
923 : : }
924 : : else
925 : : {
926 : : /*
927 : : * We're done if the last block is the start position. No need to
928 : : * check if rs_numblocks was set by heap_setscanlimits() as that only
929 : : * changes the end block. The start block is the same with or without
930 : : * scan limits.
931 : : */
1347 drowley@postgresql.o 932 [ + + ]: 89 : if (block == scan->rs_startblock)
933 : 77 : return InvalidBlockNumber;
934 : :
935 : : /* wrap to the end of the heap when the last page was page 0 */
936 [ - + ]: 12 : if (block == 0)
1347 drowley@postgresql.o 937 :UBC 0 : block = scan->rs_nblocks;
938 : :
1347 drowley@postgresql.o 939 :CBC 12 : block--;
940 : :
941 : 12 : return block;
942 : : }
943 : : }
944 : :
945 : : /* ----------------
946 : : * heapgettup - fetch next heap tuple
947 : : *
948 : : * Initialize the scan if not already done; then advance to the next
949 : : * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
950 : : * or set scan->rs_ctup.t_data = NULL if no more tuples.
951 : : *
952 : : * Note: the reason nkeys/key are passed separately, even though they are
953 : : * kept in the scan descriptor, is that the caller may not want us to check
954 : : * the scankeys.
955 : : *
956 : : * Note: when we fall off the end of the scan in either direction, we
957 : : * reset rs_inited. This means that a further request with the same
958 : : * scan direction will restart the scan, which is a bit odd, but a
959 : : * request with the opposite scan direction will start a fresh scan
960 : : * in the proper direction. The latter is required behavior for cursors,
961 : : * while the former case is generally undefined behavior in Postgres
962 : : * so we don't care too much.
963 : : * ----------------
964 : : */
965 : : static void
7625 tgl@sss.pgh.pa.us 966 : 9510294 : heapgettup(HeapScanDesc scan,
967 : : ScanDirection dir,
968 : : int nkeys,
969 : : ScanKey key)
970 : : {
971 : 9510294 : HeapTuple tuple = &(scan->rs_ctup);
972 : : Page page;
973 : : OffsetNumber lineoff;
974 : : int linesleft;
975 : :
921 drowley@postgresql.o 976 [ + + ]: 9510294 : if (likely(scan->rs_inited))
977 : : {
978 : : /* continue from previously returned page/tuple */
1347 979 : 9483754 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
980 : 9483754 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
1343 981 : 9483754 : goto continue_page;
982 : : }
983 : :
984 : : /*
985 : : * advance the scan until we find a qualifying tuple or run out of stuff
986 : : * to scan
987 : : */
988 : : while (true)
989 : : {
921 990 : 142854 : heap_fetch_next_buffer(scan, dir);
991 : :
992 : : /* did we run out of blocks to scan? */
993 [ + + ]: 142854 : if (!BufferIsValid(scan->rs_cbuf))
994 : 25661 : break;
995 : :
996 [ - + ]: 117193 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
997 : :
1343 998 : 117193 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
999 : 117193 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
1000 : 9600947 : continue_page:
1001 : :
1002 : : /*
1003 : : * Only continue scanning the page while we have lines left.
1004 : : *
1005 : : * Note that this protects us from accessing line pointers past
1006 : : * PageGetMaxOffsetNumber(); both for forward scans when we resume the
1007 : : * table scan, and for when we start scanning a new page.
1008 : : */
1009 [ + + ]: 9657490 : for (; linesleft > 0; linesleft--, lineoff += dir)
1010 : : {
1011 : : bool visible;
1012 : 9541176 : ItemId lpp = PageGetItemId(page, lineoff);
1013 : :
1014 [ + + ]: 9541176 : if (!ItemIdIsNormal(lpp))
1015 : 36131 : continue;
1016 : :
1017 : 9505045 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1018 : 9505045 : tuple->t_len = ItemIdGetLength(lpp);
921 1019 : 9505045 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1020 : :
1343 1021 : 9505045 : visible = HeapTupleSatisfiesVisibility(tuple,
1022 : : scan->rs_base.rs_snapshot,
1023 : : scan->rs_cbuf);
1024 : :
1025 : 9505045 : HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
1026 : : tuple, scan->rs_cbuf,
1027 : : scan->rs_base.rs_snapshot);
1028 : :
1029 : : /* skip tuples not visible to this snapshot */
1030 [ + + ]: 9505045 : if (!visible)
1031 : 6816 : continue;
1032 : :
1033 : : /* skip any tuples that don't match the scan key */
1034 [ + + ]: 9498229 : if (key != NULL &&
1035 [ + + ]: 14324 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1036 : : nkeys, key))
1037 : 13596 : continue;
1038 : :
1039 : 9484633 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1040 : 9484633 : scan->rs_coffset = lineoff;
1041 : 9484633 : return;
1042 : : }
1043 : :
1044 : : /*
1045 : : * if we get here, it means we've exhausted the items on this page and
1046 : : * it's time to move to the next.
1047 : : */
7625 tgl@sss.pgh.pa.us 1048 : 116314 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
1049 : : }
1050 : :
1051 : : /* end of scan */
1343 drowley@postgresql.o 1052 [ - + ]: 25661 : if (BufferIsValid(scan->rs_cbuf))
1343 drowley@postgresql.o 1053 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1054 : :
1343 drowley@postgresql.o 1055 :CBC 25661 : scan->rs_cbuf = InvalidBuffer;
1056 : 25661 : scan->rs_cblock = InvalidBlockNumber;
917 tmunro@postgresql.or 1057 : 25661 : scan->rs_prefetch_block = InvalidBlockNumber;
1343 drowley@postgresql.o 1058 : 25661 : tuple->t_data = NULL;
1059 : 25661 : scan->rs_inited = false;
1060 : : }
1061 : :
1062 : : /* ----------------
1063 : : * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
1064 : : *
1065 : : * Same API as heapgettup, but used in page-at-a-time mode
1066 : : *
1067 : : * The internal logic is much the same as heapgettup's too, but there are some
1068 : : * differences: we do not take the buffer content lock (that only needs to
1069 : : * happen inside heap_prepare_pagescan), and we iterate through just the
1070 : : * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
1071 : : * that lineindex is 0-based, where the corresponding loop variable lineoff in
1072 : : * heapgettup is 1-based.
1073 : : * ----------------
1074 : : */
1075 : : static void
7625 tgl@sss.pgh.pa.us 1076 : 63961306 : heapgettup_pagemode(HeapScanDesc scan,
1077 : : ScanDirection dir,
1078 : : int nkeys,
1079 : : ScanKey key)
1080 : : {
1081 : 63961306 : HeapTuple tuple = &(scan->rs_ctup);
1082 : : Page page;
1083 : : uint32 lineindex;
1084 : : uint32 linesleft;
1085 : :
921 drowley@postgresql.o 1086 [ + + ]: 63961306 : if (likely(scan->rs_inited))
1087 : : {
1088 : : /* continue from previously returned page/tuple */
1347 1089 : 62910121 : page = BufferGetPage(scan->rs_cbuf);
1090 : :
1091 : 62910121 : lineindex = scan->rs_cindex + dir;
1092 [ + + ]: 62910121 : if (ScanDirectionIsForward(dir))
1093 : 62909664 : linesleft = scan->rs_ntuples - lineindex;
1094 : : else
1095 : 457 : linesleft = scan->rs_cindex;
1096 : : /* lineindex now references the next or previous visible tid */
1097 : :
1343 1098 : 62910121 : goto continue_page;
1099 : : }
1100 : :
1101 : : /*
1102 : : * advance the scan until we find a qualifying tuple or run out of stuff
1103 : : * to scan
1104 : : */
1105 : : while (true)
1106 : : {
921 1107 : 3806107 : heap_fetch_next_buffer(scan, dir);
1108 : :
1109 : : /* did we run out of blocks to scan? */
1110 [ + + ]: 3806073 : if (!BufferIsValid(scan->rs_cbuf))
1111 : 865244 : break;
1112 : :
1113 [ - + ]: 2940829 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1114 : :
1115 : : /* prune the page and determine visible tuple offsets */
1116 : 2940829 : heap_prepare_pagescan((TableScanDesc) scan);
1343 1117 : 2940821 : page = BufferGetPage(scan->rs_cbuf);
1118 : 2940821 : linesleft = scan->rs_ntuples;
1119 [ + + ]: 2940821 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1120 : :
1121 : : /* block is the same for all tuples, set it once outside the loop */
559 heikki.linnakangas@i 1122 : 2940821 : ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1123 : :
1124 : : /* lineindex now references the next or previous visible tid */
1343 drowley@postgresql.o 1125 : 65850942 : continue_page:
1126 : :
1127 [ + + ]: 121427783 : for (; linesleft > 0; linesleft--, lineindex += dir)
1128 : : {
1129 : : ItemId lpp;
1130 : : OffsetNumber lineoff;
1131 : :
280 heikki.linnakangas@i 1132 [ - + ]: 118672861 : Assert(lineindex < scan->rs_ntuples);
7625 tgl@sss.pgh.pa.us 1133 : 118672861 : lineoff = scan->rs_vistuples[lineindex];
1426 peter@eisentraut.org 1134 : 118672861 : lpp = PageGetItemId(page, lineoff);
6970 tgl@sss.pgh.pa.us 1135 [ - + ]: 118672861 : Assert(ItemIdIsNormal(lpp));
1136 : :
1426 peter@eisentraut.org 1137 : 118672861 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
7625 tgl@sss.pgh.pa.us 1138 : 118672861 : tuple->t_len = ItemIdGetLength(lpp);
559 heikki.linnakangas@i 1139 : 118672861 : ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1140 : :
1141 : : /* skip any tuples that don't match the scan key */
1343 drowley@postgresql.o 1142 [ + + ]: 118672861 : if (key != NULL &&
1143 [ + + ]: 55955587 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1144 : : nkeys, key))
1145 : 55576841 : continue;
1146 : :
1147 : 63096020 : scan->rs_cindex = lineindex;
1148 : 63096020 : return;
1149 : : }
1150 : : }
1151 : :
1152 : : /* end of scan */
1153 [ - + ]: 865244 : if (BufferIsValid(scan->rs_cbuf))
1343 drowley@postgresql.o 1154 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
1343 drowley@postgresql.o 1155 :CBC 865244 : scan->rs_cbuf = InvalidBuffer;
1156 : 865244 : scan->rs_cblock = InvalidBlockNumber;
917 tmunro@postgresql.or 1157 : 865244 : scan->rs_prefetch_block = InvalidBlockNumber;
1343 drowley@postgresql.o 1158 : 865244 : tuple->t_data = NULL;
1159 : 865244 : scan->rs_inited = false;
1160 : : }
1161 : :
1162 : :
1163 : : /* ----------------------------------------------------------------
1164 : : * heap access method interface
1165 : : * ----------------------------------------------------------------
1166 : : */
1167 : :
1168 : :
1169 : : TableScanDesc
8911 tgl@sss.pgh.pa.us 1170 : 459385 : heap_beginscan(Relation relation, Snapshot snapshot,
1171 : : int nkeys, ScanKey key,
1172 : : ParallelTableScanDesc parallel_scan,
1173 : : uint32 flags)
1174 : : {
1175 : : HeapScanDesc scan;
1176 : :
1177 : : /*
1178 : : * increment relation ref count while scanning relation
1179 : : *
1180 : : * This is just to make really sure the relcache entry won't go away while
1181 : : * the scan has a pointer to it. Caller should be holding the rel open
1182 : : * anyway, so this is redundant in all normal scenarios...
1183 : : */
9469 1184 : 459385 : RelationIncrementReferenceCount(relation);
1185 : :
1186 : : /*
1187 : : * allocate and initialize scan descriptor
1188 : : */
634 melanieplageman@gmai 1189 [ + + ]: 459385 : if (flags & SO_TYPE_BITMAPSCAN)
1190 : : {
306 michael@paquier.xyz 1191 : 12369 : BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
1192 : :
1193 : : /*
1194 : : * Bitmap Heap scans do not have any fields that a normal Heap Scan
1195 : : * does not have, so no special initializations required here.
1196 : : */
634 melanieplageman@gmai 1197 : 12369 : scan = (HeapScanDesc) bscan;
1198 : : }
1199 : : else
306 michael@paquier.xyz 1200 : 447016 : scan = (HeapScanDesc) palloc_object(HeapScanDescData);
1201 : :
2772 andres@anarazel.de 1202 : 459385 : scan->rs_base.rs_rd = relation;
1203 : 459385 : scan->rs_base.rs_snapshot = snapshot;
1204 : 459385 : scan->rs_base.rs_nkeys = nkeys;
2703 1205 : 459385 : scan->rs_base.rs_flags = flags;
2772 1206 : 459385 : scan->rs_base.rs_parallel = parallel_scan;
188 tomas.vondra@postgre 1207 : 459385 : scan->rs_base.rs_instrument = NULL;
2703 andres@anarazel.de 1208 : 459385 : scan->rs_strategy = NULL; /* set in initscan */
576 melanieplageman@gmai 1209 : 459385 : scan->rs_cbuf = InvalidBuffer;
1210 : :
1211 : : /*
1212 : : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1213 : : */
2703 andres@anarazel.de 1214 [ + + + + ]: 459385 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
1215 : 37788 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1216 : :
1217 : : /* Check that a historic snapshot is not used for non-catalog tables */
416 heikki.linnakangas@i 1218 [ + + ]: 459385 : if (snapshot &&
1219 [ + + ]: 448137 : IsHistoricMVCCSnapshot(snapshot) &&
1220 [ + + + - : 728 : !RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - - +
- - - - -
- - - -
- ]
1221 : : {
416 heikki.linnakangas@i 1222 [ # # ]:UBC 0 : ereport(ERROR,
1223 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1224 : : errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1225 : : RelationGetRelationName(relation))));
1226 : : }
1227 : :
1228 : : /*
1229 : : * For seqscan and sample scans in a serializable transaction, acquire a
1230 : : * predicate lock on the entire relation. This is required not only to
1231 : : * lock all the matching tuples, but also to conflict with new insertions
1232 : : * into the table. In an indexscan, we take page locks on the index pages
1233 : : * covering the range specified in the scan qual, but in a heap scan there
1234 : : * is nothing more fine-grained to lock. A bitmap scan is a different
1235 : : * story, there we have already scanned the index and locked the index
1236 : : * pages covering the predicate. But in that case we still have to lock
1237 : : * any matching heap tuples. For sample scan we could optimize the locking
1238 : : * to be at least page-level granularity, but we'd need to add per-tuple
1239 : : * locking for that.
1240 : : */
2703 andres@anarazel.de 1241 [ + + ]:CBC 459385 : if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
1242 : : {
1243 : : /*
1244 : : * Ensure a missing snapshot is noticed reliably, even if the
1245 : : * isolation mode means predicate locking isn't performed (and
1246 : : * therefore the snapshot isn't used here).
1247 : : */
1248 [ - + ]: 433984 : Assert(snapshot);
5584 heikki.linnakangas@i 1249 : 433984 : PredicateLockRelation(relation, snapshot);
1250 : : }
1251 : :
1252 : : /* we only need to set this up once */
7625 tgl@sss.pgh.pa.us 1253 : 459385 : scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1254 : :
1255 : : /*
1256 : : * Allocate memory to keep track of page allocation for parallel workers
1257 : : * when doing a parallel scan.
1258 : : */
2022 drowley@postgresql.o 1259 [ + + ]: 459385 : if (parallel_scan != NULL)
306 michael@paquier.xyz 1260 : 4478 : scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
1261 : : else
2022 drowley@postgresql.o 1262 : 454907 : scan->rs_parallelworkerdata = NULL;
1263 : :
1264 : : /*
1265 : : * we do this here instead of in initscan() because heap_rescan also calls
1266 : : * initscan() and we don't want to allocate memory again
1267 : : */
8911 tgl@sss.pgh.pa.us 1268 [ + + ]: 459385 : if (nkeys > 0)
306 michael@paquier.xyz 1269 : 257114 : scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
1270 : : else
2772 andres@anarazel.de 1271 : 202271 : scan->rs_base.rs_key = NULL;
1272 : :
6333 tgl@sss.pgh.pa.us 1273 : 459385 : initscan(scan, key, false);
1274 : :
917 tmunro@postgresql.or 1275 : 459383 : scan->rs_read_stream = NULL;
1276 : :
1277 : : /*
1278 : : * Set up a read stream for sequential scans and TID range scans. This
1279 : : * should be done after initscan() because initscan() allocates the
1280 : : * BufferAccessStrategy object passed to the read stream API.
1281 : : */
1282 [ + + ]: 459383 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1283 [ + + ]: 25504 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
1284 : 435172 : {
1285 : : ReadStreamBlockNumberCB cb;
1286 : :
1287 [ + + ]: 435177 : if (scan->rs_base.rs_parallel)
1288 : 4478 : cb = heap_scan_stream_read_next_parallel;
1289 : : else
1290 : 430699 : cb = heap_scan_stream_read_next_serial;
1291 : :
1292 : : /* ---
1293 : : * It is safe to use batchmode as the only locks taken by `cb`
1294 : : * are never taken while waiting for IO:
1295 : : * - SyncScanLock is used in the non-parallel case
1296 : : * - in the parallel case, only spinlocks and atomics are used
1297 : : * ---
1298 : : */
561 andres@anarazel.de 1299 : 435177 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
1300 : : READ_STREAM_USE_BATCHING,
1301 : : scan->rs_strategy,
1302 : : scan->rs_base.rs_rd,
1303 : : MAIN_FORKNUM,
1304 : : cb,
1305 : : scan,
1306 : : 0);
1307 : : }
576 melanieplageman@gmai 1308 [ + + ]: 24206 : else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1309 : : {
557 1310 : 12369 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
1311 : : READ_STREAM_USE_BATCHING,
1312 : : scan->rs_strategy,
1313 : : scan->rs_base.rs_rd,
1314 : : MAIN_FORKNUM,
1315 : : bitmapheap_stream_read_next,
1316 : : scan,
1317 : : sizeof(TBMIterateResult));
1318 : : }
1319 : :
1320 : : /* enable read stream instrumentation */
188 tomas.vondra@postgre 1321 [ + + + - ]: 459378 : if ((flags & SO_SCAN_INSTRUMENT) && (scan->rs_read_stream != NULL))
1322 : : {
1323 : 8 : scan->rs_base.rs_instrument = palloc0_object(TableScanInstrumentation);
1324 : 8 : read_stream_enable_stats(scan->rs_read_stream,
1325 : 8 : &scan->rs_base.rs_instrument->io);
1326 : : }
1327 : :
211 melanieplageman@gmai 1328 : 459378 : scan->rs_vmbuffer = InvalidBuffer;
1329 : :
2772 andres@anarazel.de 1330 : 459378 : return (TableScanDesc) scan;
1331 : : }
1332 : :
1333 : : void
1334 : 654353 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1335 : : bool allow_strat, bool allow_sync, bool allow_pagemode)
1336 : : {
1337 : 654353 : HeapScanDesc scan = (HeapScanDesc) sscan;
1338 : :
1339 [ + + ]: 654353 : if (set_params)
1340 : : {
2703 1341 [ + + ]: 39 : if (allow_strat)
1342 : 23 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1343 : : else
1344 : 16 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1345 : :
1346 [ + + ]: 39 : if (allow_sync)
1347 : 12 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1348 : : else
1349 : 27 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1350 : :
1351 [ + - + - ]: 39 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1352 [ + - ]: 39 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1353 : 39 : scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
1354 : : else
2703 andres@anarazel.de 1355 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1356 : : }
1357 : :
1358 : : /*
1359 : : * unpin scan buffers
1360 : : */
9256 tgl@sss.pgh.pa.us 1361 [ + + ]:CBC 654353 : if (BufferIsValid(scan->rs_cbuf))
1362 : : {
1363 : 2069 : ReleaseBuffer(scan->rs_cbuf);
576 melanieplageman@gmai 1364 : 2069 : scan->rs_cbuf = InvalidBuffer;
1365 : : }
1366 : :
211 1367 [ + + ]: 654353 : if (BufferIsValid(scan->rs_vmbuffer))
1368 : : {
1369 : 19 : ReleaseBuffer(scan->rs_vmbuffer);
1370 : 19 : scan->rs_vmbuffer = InvalidBuffer;
1371 : : }
1372 : :
1373 : : /*
1374 : : * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1375 : : * additional data vs a normal HeapScan
1376 : : */
1377 : :
1378 : : /*
1379 : : * The read stream is reset on rescan. This must be done before
1380 : : * initscan(), as some state referred to by read_stream_reset() is reset
1381 : : * in initscan().
1382 : : */
917 tmunro@postgresql.or 1383 [ + + ]: 654353 : if (scan->rs_read_stream)
1384 : 646647 : read_stream_reset(scan->rs_read_stream);
1385 : :
1386 : : /*
1387 : : * reinitialize scan descriptor
1388 : : */
6333 tgl@sss.pgh.pa.us 1389 : 654353 : initscan(scan, key, true);
11052 scrappy@hub.org 1390 : 654353 : }
1391 : :
1392 : : void
2772 andres@anarazel.de 1393 : 456122 : heap_endscan(TableScanDesc sscan)
1394 : : {
1395 : 456122 : HeapScanDesc scan = (HeapScanDesc) sscan;
1396 : :
1397 : : /* Note: no locking manipulations needed */
1398 : :
1399 : : /*
1400 : : * unpin scan buffers
1401 : : */
9256 tgl@sss.pgh.pa.us 1402 [ + + ]: 456122 : if (BufferIsValid(scan->rs_cbuf))
1403 : 182438 : ReleaseBuffer(scan->rs_cbuf);
1404 : :
211 melanieplageman@gmai 1405 [ + + ]: 456122 : if (BufferIsValid(scan->rs_vmbuffer))
1406 : 2749 : ReleaseBuffer(scan->rs_vmbuffer);
1407 : :
1408 : : /*
1409 : : * Must free the read stream before freeing the BufferAccessStrategy.
1410 : : */
917 tmunro@postgresql.or 1411 [ + + ]: 456122 : if (scan->rs_read_stream)
1412 : 444352 : read_stream_end(scan->rs_read_stream);
1413 : :
1414 : : /*
1415 : : * decrement relation reference count and free scan descriptor storage
1416 : : */
2772 andres@anarazel.de 1417 : 456122 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1418 : :
1419 [ + + ]: 456122 : if (scan->rs_base.rs_key)
1420 : 257076 : pfree(scan->rs_base.rs_key);
1421 : :
7075 tgl@sss.pgh.pa.us 1422 [ + + ]: 456122 : if (scan->rs_strategy != NULL)
1423 : 13636 : FreeAccessStrategy(scan->rs_strategy);
1424 : :
2022 drowley@postgresql.o 1425 [ + + ]: 456122 : if (scan->rs_parallelworkerdata != NULL)
1426 : 4478 : pfree(scan->rs_parallelworkerdata);
1427 : :
2703 andres@anarazel.de 1428 [ + + ]: 456122 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
2772 1429 : 44973 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1430 : :
188 tomas.vondra@postgre 1431 [ + + ]: 456122 : if (scan->rs_base.rs_instrument)
1432 : 8 : pfree(scan->rs_base.rs_instrument);
1433 : :
9886 tgl@sss.pgh.pa.us 1434 : 456122 : pfree(scan);
11052 scrappy@hub.org 1435 : 456122 : }
1436 : :
1437 : : HeapTuple
2772 andres@anarazel.de 1438 : 11929515 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1439 : : {
1440 : 11929515 : HeapScanDesc scan = (HeapScanDesc) sscan;
1441 : :
1442 : : /*
1443 : : * This is still widely used directly, without going through table AM, so
1444 : : * add a safety check. It's possible we should, at a later point,
1445 : : * downgrade this to an assert. The reason for checking the AM routine,
1446 : : * rather than the AM oid, is that this allows to write regression tests
1447 : : * that create another AM reusing the heap handler.
1448 : : */
1449 [ - + ]: 11929515 : if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
2772 andres@anarazel.de 1450 [ # # ]:UBC 0 : ereport(ERROR,
1451 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1452 : : errmsg_internal("only heap AM is supported")));
1453 : :
1454 : : /* Note: no locking manipulations needed */
1455 : :
2703 andres@anarazel.de 1456 [ + + ]:CBC 11929515 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
7538 neilc@samurai.com 1457 : 3023902 : heapgettup_pagemode(scan, direction,
2772 andres@anarazel.de 1458 : 3023902 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1459 : : else
1460 : 8905613 : heapgettup(scan, direction,
1461 : 8905613 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1462 : :
7625 tgl@sss.pgh.pa.us 1463 [ + + ]: 11929514 : if (scan->rs_ctup.t_data == NULL)
8911 1464 : 75312 : return NULL;
1465 : :
1466 : : /*
1467 : : * if we get here it means we have a new current scan tuple, so point to
1468 : : * the proper return buffer and return the tuple.
1469 : : */
1470 : :
2772 andres@anarazel.de 1471 [ - + - - : 11854202 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - - + ]
1472 : :
1473 : 11854202 : return &scan->rs_ctup;
1474 : : }
1475 : :
1476 : : bool
1477 : 61535221 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1478 : : {
1479 : 61535221 : HeapScanDesc scan = (HeapScanDesc) sscan;
1480 : :
1481 : : /* Note: no locking manipulations needed */
1482 : :
2703 1483 [ + + ]: 61535221 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1484 : 60930540 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1485 : : else
1486 : 604681 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1487 : :
2772 1488 [ + + ]: 61535190 : if (scan->rs_ctup.t_data == NULL)
1489 : : {
1490 : 815451 : ExecClearTuple(slot);
1491 : 815451 : return false;
1492 : : }
1493 : :
1494 : : /*
1495 : : * if we get here it means we have a new current scan tuple, so point to
1496 : : * the proper return buffer and return the tuple.
1497 : : */
1498 : :
1499 [ + + - + : 60719739 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ + - + ]
1500 : :
1501 : 60719739 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1502 : : scan->rs_cbuf);
1503 : 60719739 : return true;
1504 : : }
1505 : :
1506 : : void
2053 drowley@postgresql.o 1507 : 1366 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
1508 : : ItemPointer maxtid)
1509 : : {
1510 : 1366 : HeapScanDesc scan = (HeapScanDesc) sscan;
1511 : : BlockNumber startBlk;
1512 : : BlockNumber numBlks;
1513 : : ItemPointerData highestItem;
1514 : : ItemPointerData lowestItem;
1515 : :
1516 : : /*
1517 : : * For relations without any pages, we can simply leave the TID range
1518 : : * unset. There will be no tuples to scan, therefore no tuples outside
1519 : : * the given TID range.
1520 : : */
1521 [ + + ]: 1366 : if (scan->rs_nblocks == 0)
1522 : 32 : return;
1523 : :
1524 : : /*
1525 : : * Set up some ItemPointers which point to the first and last possible
1526 : : * tuples in the heap.
1527 : : */
1528 : 1358 : ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1529 : 1358 : ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1530 : :
1531 : : /*
1532 : : * If the given maximum TID is below the highest possible TID in the
1533 : : * relation, then restrict the range to that, otherwise we scan to the end
1534 : : * of the relation.
1535 : : */
1536 [ + + ]: 1358 : if (ItemPointerCompare(maxtid, &highestItem) < 0)
1537 : 184 : ItemPointerCopy(maxtid, &highestItem);
1538 : :
1539 : : /*
1540 : : * If the given minimum TID is above the lowest possible TID in the
1541 : : * relation, then restrict the range to only scan for TIDs above that.
1542 : : */
1543 [ + + ]: 1358 : if (ItemPointerCompare(mintid, &lowestItem) > 0)
1544 : 1190 : ItemPointerCopy(mintid, &lowestItem);
1545 : :
1546 : : /*
1547 : : * Check for an empty range and protect from would be negative results
1548 : : * from the numBlks calculation below.
1549 : : */
1550 [ + + ]: 1358 : if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1551 : : {
1552 : : /* Set an empty range of blocks to scan */
1553 : 24 : heap_setscanlimits(sscan, 0, 0);
1554 : 24 : return;
1555 : : }
1556 : :
1557 : : /*
1558 : : * Calculate the first block and the number of blocks we must scan. We
1559 : : * could be more aggressive here and perform some more validation to try
1560 : : * and further narrow the scope of blocks to scan by checking if the
1561 : : * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1562 : : * advance startBlk by one. Likewise, if highestItem has an offset of 0
1563 : : * we could scan one fewer blocks. However, such an optimization does not
1564 : : * seem worth troubling over, currently.
1565 : : */
1566 : 1334 : startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1567 : :
1568 : 1334 : numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1569 : 1334 : ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1570 : :
1571 : : /* Set the start block and number of blocks to scan */
1572 : 1334 : heap_setscanlimits(sscan, startBlk, numBlks);
1573 : :
1574 : : /* Finally, set the TID range in sscan */
717 melanieplageman@gmai 1575 : 1334 : ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1576 : 1334 : ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1577 : : }
1578 : :
1579 : : bool
2053 drowley@postgresql.o 1580 : 6740 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1581 : : TupleTableSlot *slot)
1582 : : {
1583 : 6740 : HeapScanDesc scan = (HeapScanDesc) sscan;
717 melanieplageman@gmai 1584 : 6740 : ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
1585 : 6740 : ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
1586 : :
1587 : : /* Note: no locking manipulations needed */
1588 : : for (;;)
1589 : : {
2053 drowley@postgresql.o 1590 [ + - ]: 6864 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1591 : 6864 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1592 : : else
2053 drowley@postgresql.o 1593 :UBC 0 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1594 : :
2053 drowley@postgresql.o 1595 [ + + ]:CBC 6854 : if (scan->rs_ctup.t_data == NULL)
1596 : : {
1597 : 142 : ExecClearTuple(slot);
1598 : 142 : return false;
1599 : : }
1600 : :
1601 : : /*
1602 : : * heap_set_tidrange will have used heap_setscanlimits to limit the
1603 : : * range of pages we scan to only ones that can contain the TID range
1604 : : * we're scanning for. Here we must filter out any tuples from these
1605 : : * pages that are outside of that range.
1606 : : */
1607 [ + + ]: 6712 : if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1608 : : {
1609 : 124 : ExecClearTuple(slot);
1610 : :
1611 : : /*
1612 : : * When scanning backwards, the TIDs will be in descending order.
1613 : : * Future tuples in this direction will be lower still, so we can
1614 : : * just return false to indicate there will be no more tuples.
1615 : : */
1616 [ - + ]: 124 : if (ScanDirectionIsBackward(direction))
2053 drowley@postgresql.o 1617 :UBC 0 : return false;
1618 : :
2053 drowley@postgresql.o 1619 :CBC 124 : continue;
1620 : : }
1621 : :
1622 : : /*
1623 : : * Likewise for the final page, we must filter out TIDs greater than
1624 : : * maxtid.
1625 : : */
1626 [ + + ]: 6588 : if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1627 : : {
1628 : 74 : ExecClearTuple(slot);
1629 : :
1630 : : /*
1631 : : * When scanning forward, the TIDs will be in ascending order.
1632 : : * Future tuples in this direction will be higher still, so we can
1633 : : * just return false to indicate there will be no more tuples.
1634 : : */
1635 [ + - ]: 74 : if (ScanDirectionIsForward(direction))
1636 : 74 : return false;
2053 drowley@postgresql.o 1637 :UBC 0 : continue;
1638 : : }
1639 : :
2053 drowley@postgresql.o 1640 :CBC 6514 : break;
1641 : : }
1642 : :
1643 : : /*
1644 : : * if we get here it means we have a new current scan tuple, so point to
1645 : : * the proper return buffer and return the tuple.
1646 : : */
1647 [ - + - - : 6514 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - - + ]
1648 : :
1649 : 6514 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1650 : 6514 : return true;
1651 : : }
1652 : :
1653 : : /*
1654 : : * heap_fetch - retrieve tuple with given tid
1655 : : *
1656 : : * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1657 : : * the tuple, fill in the remaining fields of *tuple, and check the tuple
1658 : : * against the specified snapshot.
1659 : : *
1660 : : * If successful (tuple found and passes snapshot time qual), then *userbuf
1661 : : * is set to the buffer holding the tuple and true is returned. The caller
1662 : : * must unpin the buffer when done with the tuple.
1663 : : *
1664 : : * If the tuple is not found (ie, item number references a deleted slot),
1665 : : * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1666 : : * and false is returned.
1667 : : *
1668 : : * If the tuple is found but fails the time qual check, then the behavior
1669 : : * depends on the keep_buf parameter. If keep_buf is false, the results
1670 : : * are the same as for the tuple-not-found case. If keep_buf is true,
1671 : : * then tuple->t_data and *userbuf are returned as for the success case,
1672 : : * and again the caller must unpin the buffer; but false is returned.
1673 : : *
1674 : : * heap_fetch does not follow HOT chains: only the exact TID requested will
1675 : : * be fetched.
1676 : : *
1677 : : * It is somewhat inconsistent that we ereport() on invalid block number but
1678 : : * return false on invalid item number. There are a couple of reasons though.
1679 : : * One is that the caller can relatively easily check the block number for
1680 : : * validity, but cannot check the item number without reading the page
1681 : : * himself. Another is that when we are following a t_ctid link, we can be
1682 : : * reasonably confident that the page number is valid (since VACUUM shouldn't
1683 : : * truncate off the destination page without having killed the referencing
1684 : : * tuple first), but the item number might well not be good.
1685 : : */
1686 : : bool
11052 scrappy@hub.org 1687 : 2860303 : heap_fetch(Relation relation,
1688 : : Snapshot snapshot,
1689 : : HeapTuple tuple,
1690 : : Buffer *userbuf,
1691 : : bool keep_buf)
1692 : : {
8907 tgl@sss.pgh.pa.us 1693 : 2860303 : ItemPointer tid = &(tuple->t_self);
1694 : : ItemId lp;
1695 : : Buffer buffer;
1696 : : Page page;
1697 : : OffsetNumber offnum;
1698 : : bool valid;
1699 : :
1700 : : /*
1701 : : * Fetch and pin the appropriate page of the relation.
1702 : : */
6766 1703 : 2860303 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1704 : :
1705 : : /*
1706 : : * Need share lock on buffer to examine tuple commit status.
1707 : : */
10163 vadim4o@yahoo.com 1708 : 2860295 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3827 kgrittn@postgresql.o 1709 : 2860295 : page = BufferGetPage(buffer);
1710 : :
1711 : : /*
1712 : : * We'd better check for out-of-range offnum in case of VACUUM since the
1713 : : * TID was obtained.
1714 : : */
10627 bruce@momjian.us 1715 : 2860295 : offnum = ItemPointerGetOffsetNumber(tid);
6665 tgl@sss.pgh.pa.us 1716 [ + - + + ]: 2860295 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1717 : : {
199 andres@anarazel.de 1718 : 4 : UnlockReleaseBuffer(buffer);
2760 1719 : 4 : *userbuf = InvalidBuffer;
7869 tgl@sss.pgh.pa.us 1720 : 4 : tuple->t_data = NULL;
1721 : 4 : return false;
1722 : : }
1723 : :
1724 : : /*
1725 : : * get the item line pointer corresponding to the requested tid
1726 : : */
6665 1727 : 2860291 : lp = PageGetItemId(page, offnum);
1728 : :
1729 : : /*
1730 : : * Must check for deleted tuple.
1731 : : */
6970 1732 [ + + ]: 2860291 : if (!ItemIdIsNormal(lp))
1733 : : {
199 andres@anarazel.de 1734 : 332 : UnlockReleaseBuffer(buffer);
2760 1735 : 332 : *userbuf = InvalidBuffer;
8907 tgl@sss.pgh.pa.us 1736 : 332 : tuple->t_data = NULL;
1737 : 332 : return false;
1738 : : }
1739 : :
1740 : : /*
1741 : : * fill in *tuple fields
1742 : : */
6665 1743 : 2859959 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10181 vadim4o@yahoo.com 1744 : 2859959 : tuple->t_len = ItemIdGetLength(lp);
7723 tgl@sss.pgh.pa.us 1745 : 2859959 : tuple->t_tableOid = RelationGetRelid(relation);
1746 : :
1747 : : /*
1748 : : * check tuple visibility, then release lock
1749 : : */
7625 1750 : 2859959 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1751 : :
5726 heikki.linnakangas@i 1752 [ + + ]: 2859959 : if (valid)
2449 tmunro@postgresql.or 1753 : 2859870 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1754 : 2859870 : HeapTupleHeaderGetXmin(tuple->t_data));
1755 : :
1756 : 2859959 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1757 : :
5701 heikki.linnakangas@i 1758 : 2859959 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1759 : :
8907 tgl@sss.pgh.pa.us 1760 [ + + ]: 2859959 : if (valid)
1761 : : {
1762 : : /*
1763 : : * All checks passed, so return the tuple as valid. Caller is now
1764 : : * responsible for releasing the buffer.
1765 : : */
9880 1766 : 2859870 : *userbuf = buffer;
1767 : :
8907 1768 : 2859870 : return true;
1769 : : }
1770 : :
1771 : : /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1643 1772 [ + + ]: 89 : if (keep_buf)
1773 : 43 : *userbuf = buffer;
1774 : : else
1775 : : {
1776 : 46 : ReleaseBuffer(buffer);
1777 : 46 : *userbuf = InvalidBuffer;
1778 : 46 : tuple->t_data = NULL;
1779 : : }
1780 : :
8907 1781 : 89 : return false;
1782 : : }
1783 : :
1784 : : /*
1785 : : * heap_get_latest_tid - get the latest tid of a specified tuple
1786 : : *
1787 : : * Actually, this gets the latest version that is visible according to the
1788 : : * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1789 : : * possibly uncommitted version.
1790 : : *
1791 : : * *tid is both an input and an output parameter: it is updated to
1792 : : * show the latest version of the row. Note that it will not be changed
1793 : : * if no version of the row passes the snapshot test.
1794 : : */
1795 : : void
2705 andres@anarazel.de 1796 : 207 : heap_get_latest_tid(TableScanDesc sscan,
1797 : : ItemPointer tid)
1798 : : {
2700 tgl@sss.pgh.pa.us 1799 : 207 : Relation relation = sscan->rs_rd;
1800 : 207 : Snapshot snapshot = sscan->rs_snapshot;
1801 : : ItemPointerData ctid;
1802 : : TransactionId priorXmax;
1803 : :
1804 : : /*
1805 : : * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1806 : : * Assume that t_ctid links are valid however - there shouldn't be invalid
1807 : : * ones in the table.
1808 : : */
2705 andres@anarazel.de 1809 [ - + ]: 207 : Assert(ItemPointerIsValid(tid));
1810 : :
1811 : : /*
1812 : : * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1813 : : * need to examine, and *tid is the TID we will return if ctid turns out
1814 : : * to be bogus.
1815 : : *
1816 : : * Note that we will loop until we reach the end of the t_ctid chain.
1817 : : * Depending on the snapshot passed, there might be at most one visible
1818 : : * version of the row, but we don't try to optimize for that.
1819 : : */
7723 tgl@sss.pgh.pa.us 1820 : 207 : ctid = *tid;
1821 : 207 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1822 : : for (;;)
1823 : 64 : {
1824 : : Buffer buffer;
1825 : : Page page;
1826 : : OffsetNumber offnum;
1827 : : ItemId lp;
1828 : : HeapTupleData tp;
1829 : : bool valid;
1830 : :
1831 : : /*
1832 : : * Read, pin, and lock the page.
1833 : : */
1834 : 271 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1835 : 271 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3827 kgrittn@postgresql.o 1836 : 271 : page = BufferGetPage(buffer);
1837 : :
1838 : : /*
1839 : : * Check for bogus item number. This is not treated as an error
1840 : : * condition because it can happen while following a t_ctid link. We
1841 : : * just assume that the prior tid is OK and return it unchanged.
1842 : : */
7723 tgl@sss.pgh.pa.us 1843 : 271 : offnum = ItemPointerGetOffsetNumber(&ctid);
6665 1844 [ + - - + ]: 271 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1845 : : {
7500 tgl@sss.pgh.pa.us 1846 :UBC 0 : UnlockReleaseBuffer(buffer);
7723 1847 : 0 : break;
1848 : : }
6665 tgl@sss.pgh.pa.us 1849 :CBC 271 : lp = PageGetItemId(page, offnum);
6970 1850 [ - + ]: 271 : if (!ItemIdIsNormal(lp))
1851 : : {
7500 tgl@sss.pgh.pa.us 1852 :UBC 0 : UnlockReleaseBuffer(buffer);
7723 1853 : 0 : break;
1854 : : }
1855 : :
1856 : : /* OK to access the tuple */
7723 tgl@sss.pgh.pa.us 1857 :CBC 271 : tp.t_self = ctid;
6665 1858 : 271 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
7723 1859 : 271 : tp.t_len = ItemIdGetLength(lp);
4830 rhaas@postgresql.org 1860 : 271 : tp.t_tableOid = RelationGetRelid(relation);
1861 : :
1862 : : /*
1863 : : * After following a t_ctid link, we might arrive at an unrelated
1864 : : * tuple. Check for XMIN match.
1865 : : */
7723 tgl@sss.pgh.pa.us 1866 [ + + - + ]: 335 : if (TransactionIdIsValid(priorXmax) &&
3266 alvherre@alvh.no-ip. 1867 : 64 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1868 : : {
7500 tgl@sss.pgh.pa.us 1869 :UBC 0 : UnlockReleaseBuffer(buffer);
7723 1870 : 0 : break;
1871 : : }
1872 : :
1873 : : /*
1874 : : * Check tuple visibility; if visible, set it as the new result
1875 : : * candidate.
1876 : : */
7625 tgl@sss.pgh.pa.us 1877 :CBC 271 : valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2449 tmunro@postgresql.or 1878 : 271 : HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
7723 tgl@sss.pgh.pa.us 1879 [ + + ]: 271 : if (valid)
1880 : 191 : *tid = ctid;
1881 : :
1882 : : /*
1883 : : * If there's a valid t_ctid link, follow it, else we're done.
1884 : : */
5010 alvherre@alvh.no-ip. 1885 [ + + + + ]: 391 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1886 [ + - ]: 200 : HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
3110 andres@anarazel.de 1887 [ + + ]: 160 : HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
7723 tgl@sss.pgh.pa.us 1888 : 80 : ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1889 : : {
7500 1890 : 207 : UnlockReleaseBuffer(buffer);
7723 1891 : 207 : break;
1892 : : }
1893 : :
1894 : 64 : ctid = tp.t_data->t_ctid;
5010 alvherre@alvh.no-ip. 1895 : 64 : priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
7500 tgl@sss.pgh.pa.us 1896 : 64 : UnlockReleaseBuffer(buffer);
1897 : : } /* end of loop */
9863 inoue@tpf.co.jp 1898 : 207 : }
1899 : :
1900 : :
1901 : : /*
1902 : : * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1903 : : *
1904 : : * This is called after we have waited for the XMAX transaction to terminate.
1905 : : * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1906 : : * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1907 : : * hint bit if possible --- but beware that that may not yet be possible,
1908 : : * if the transaction committed asynchronously.
1909 : : *
1910 : : * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1911 : : * even if it commits.
1912 : : *
1913 : : * Hence callers should look only at XMAX_INVALID.
1914 : : *
1915 : : * Note this is not allowed for tuples whose xmax is a multixact.
1916 : : */
1917 : : static void
6999 tgl@sss.pgh.pa.us 1918 : 243 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1919 : : {
5010 alvherre@alvh.no-ip. 1920 [ - + ]: 243 : Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1921 [ - + ]: 243 : Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1922 : :
6999 tgl@sss.pgh.pa.us 1923 [ + + ]: 243 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1924 : : {
5010 alvherre@alvh.no-ip. 1925 [ + + + + ]: 433 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1926 : 191 : TransactionIdDidCommit(xid))
6999 tgl@sss.pgh.pa.us 1927 : 164 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1928 : : xid);
1929 : : else
1930 : 78 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1931 : : InvalidTransactionId);
1932 : : }
1933 : 243 : }
1934 : :
1935 : :
1936 : : /*
1937 : : * GetBulkInsertState - prepare status object for a bulk insert
1938 : : */
1939 : : BulkInsertState
6549 1940 : 3154 : GetBulkInsertState(void)
1941 : : {
1942 : : BulkInsertState bistate;
1943 : :
306 michael@paquier.xyz 1944 : 3154 : bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
6549 tgl@sss.pgh.pa.us 1945 : 3154 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1946 : 3154 : bistate->current_buf = InvalidBuffer;
1285 andres@anarazel.de 1947 : 3154 : bistate->next_free = InvalidBlockNumber;
1948 : 3154 : bistate->last_free = InvalidBlockNumber;
1155 1949 : 3154 : bistate->already_extended_by = 0;
6549 tgl@sss.pgh.pa.us 1950 : 3154 : return bistate;
1951 : : }
1952 : :
1953 : : /*
1954 : : * FreeBulkInsertState - clean up after finishing a bulk insert
1955 : : */
1956 : : void
1957 : 2918 : FreeBulkInsertState(BulkInsertState bistate)
1958 : : {
1959 [ + + ]: 2918 : if (bistate->current_buf != InvalidBuffer)
6332 bruce@momjian.us 1960 : 2384 : ReleaseBuffer(bistate->current_buf);
6549 tgl@sss.pgh.pa.us 1961 : 2918 : FreeAccessStrategy(bistate->strategy);
1962 : 2918 : pfree(bistate);
1963 : 2918 : }
1964 : :
1965 : : /*
1966 : : * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
1967 : : */
1968 : : void
3548 rhaas@postgresql.org 1969 : 90779 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
1970 : : {
1971 [ + + ]: 90779 : if (bistate->current_buf != InvalidBuffer)
1972 : 40028 : ReleaseBuffer(bistate->current_buf);
1973 : 90779 : bistate->current_buf = InvalidBuffer;
1974 : :
1975 : : /*
1976 : : * Despite the name, we also reset bulk relation extension state.
1977 : : * Otherwise we can end up erroring out due to looking for free space in
1978 : : * ->next_free of one partition, even though ->next_free was set when
1979 : : * extending another partition. It could obviously also be bad for
1980 : : * efficiency to look at existing blocks at offsets from another
1981 : : * partition, even if we don't error out.
1982 : : */
1095 andres@anarazel.de 1983 : 90779 : bistate->next_free = InvalidBlockNumber;
1984 : 90779 : bistate->last_free = InvalidBlockNumber;
3548 rhaas@postgresql.org 1985 : 90779 : }
1986 : :
1987 : :
1988 : : /*
1989 : : * heap_insert - insert tuple into a heap
1990 : : *
1991 : : * The new tuple is stamped with current transaction ID and the specified
1992 : : * command ID.
1993 : : *
1994 : : * See table_tuple_insert for comments about most of the input flags, except
1995 : : * that this routine directly takes a tuple rather than a slot.
1996 : : *
1997 : : * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
1998 : : * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
1999 : : * implement table_tuple_insert_speculative().
2000 : : *
2001 : : * On return the header fields of *tup are updated to match the stored tuple;
2002 : : * in particular tup->t_self receives the actual TID where the tuple was
2003 : : * stored. But note that any toasting of fields within the tuple data is NOT
2004 : : * reflected into *tup.
2005 : : */
2006 : : void
7784 tgl@sss.pgh.pa.us 2007 : 11897386 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2008 : : uint32 options, BulkInsertState bistate)
2009 : : {
8061 2010 : 11897386 : TransactionId xid = GetCurrentTransactionId();
2011 : : HeapTuple heaptup;
2012 : : Buffer buffer;
2013 : : Page page;
5592 rhaas@postgresql.org 2014 : 11897386 : Buffer vmbuffer = InvalidBuffer;
89 melanieplageman@gmai 2015 : 11897386 : bool clear_all_visible = false;
2016 : 11897386 : bool vmbuffer_modified = false;
2017 : :
2018 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1981 tgl@sss.pgh.pa.us 2019 [ - + ]: 11897386 : Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
2020 : : RelationGetNumberOfAttributes(relation));
2021 : :
500 nathan@postgresql.or 2022 : 11897386 : AssertHasSnapshotForToast(relation);
2023 : :
2024 : : /*
2025 : : * Fill in tuple header fields and toast the tuple if necessary.
2026 : : *
2027 : : * Note: below this point, heaptup is the data we actually intend to store
2028 : : * into the relation; tup is the caller's original untoasted data.
2029 : : */
5451 heikki.linnakangas@i 2030 : 11897386 : heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2031 : :
2032 : : /*
2033 : : * Find buffer to insert this tuple into. If the page is all visible,
2034 : : * this will also pin the requisite visibility map page.
2035 : : */
3999 kgrittn@postgresql.o 2036 : 11897386 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2037 : : InvalidBuffer, options, bistate,
2038 : : &vmbuffer, NULL,
2039 : : 0);
2040 : :
196 melanieplageman@gmai 2041 : 11897384 : page = BufferGetPage(buffer);
2042 : :
2043 : : /*
2044 : : * We're about to do the actual insert -- but check for conflict first, to
2045 : : * avoid possibly having to roll back work we've just done.
2046 : : *
2047 : : * This is safe without a recheck as long as there is no possibility of
2048 : : * another process scanning the page between this check and the insert
2049 : : * being visible to the scan (i.e., an exclusive buffer content lock is
2050 : : * continuously held from this point until the tuple insert is visible).
2051 : : *
2052 : : * For a heap insert, we only need to check for table-level SSI locks. Our
2053 : : * new tuple can't possibly conflict with existing tuple locks, and heap
2054 : : * page locks are only consolidated versions of tuple locks; they do not
2055 : : * lock "gaps" as index page locks do. So we don't need to specify a
2056 : : * buffer when making the call, which makes for a faster check.
2057 : : */
2449 tmunro@postgresql.or 2058 : 11897384 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2059 : :
2060 : : /* Lock the vmbuffer before the critical section */
89 melanieplageman@gmai 2061 [ + + ]: 11897367 : if (PageIsAllVisible(page))
2062 : : {
2063 : 9551 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2064 : 9551 : clear_all_visible = true;
2065 : : }
2066 : :
2067 : : /* NO EREPORT(ERROR) from here till changes are logged */
9404 tgl@sss.pgh.pa.us 2068 : 11897367 : START_CRIT_SECTION();
2069 : :
4175 andres@anarazel.de 2070 : 11897367 : RelationPutHeapTuple(relation, buffer, heaptup,
2071 : 11897367 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2072 : :
89 melanieplageman@gmai 2073 [ + + ]: 11897367 : if (clear_all_visible)
2074 : : {
2075 : : /* It's possible the VM bits were already clear */
89 melanieplageman@gmai 2076 [ + + ]:GNC 9551 : if (visibilitymap_clear(relation->rd_locator,
89 melanieplageman@gmai 2077 :CBC 9551 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2078 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
2079 : 9548 : vmbuffer_modified = true;
2080 : :
196 2081 : 9551 : PageClearAllVisible(page);
2082 : : }
2083 : :
2084 : : /*
2085 : : * Set pd_prune_xid to trigger heap_page_prune_and_freeze() once the page
2086 : : * is full so that we can set the page all-visible in the VM on the next
2087 : : * page access.
2088 : : *
2089 : : * Setting pd_prune_xid is also handy if the inserting transaction
2090 : : * eventually aborts making this tuple DEAD and hence available for
2091 : : * pruning. If no other tuple in this page is UPDATEd/DELETEd, the aborted
2092 : : * tuple would never otherwise be pruned until next vacuum is triggered.
2093 : : *
2094 : : * Don't set it if we are in bootstrap mode or we are inserting a frozen
2095 : : * tuple, as there is no further pruning/freezing needed in those cases.
2096 : : */
2097 [ + + + + ]: 11897367 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
2098 [ - + + + : 11233766 : PageSetPrunable(page, xid);
+ + ]
2099 : :
7500 tgl@sss.pgh.pa.us 2100 : 11897367 : MarkBufferDirty(buffer);
2101 : :
2102 : : /* XLOG stuff */
2382 noah@leadboat.com 2103 [ + + + + : 11897367 : if (RelationNeedsWAL(relation))
+ + + + ]
2104 : : {
2105 : : xl_heap_insert xlrec;
2106 : : xl_heap_header xlhdr;
2107 : : XLogRecPtr recptr;
9335 bruce@momjian.us 2108 : 10683738 : uint8 info = XLOG_HEAP_INSERT;
4344 heikki.linnakangas@i 2109 : 10683738 : int bufflags = 0;
2110 : :
2111 : : /*
2112 : : * If this is a catalog, we need to transmit combo CIDs to properly
2113 : : * decode, so log that as well.
2114 : : */
4689 rhaas@postgresql.org 2115 [ + + + + : 10683738 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
2116 : 3901 : log_heap_new_cid(relation, heaptup);
2117 : :
2118 : : /*
2119 : : * If this is the single and first tuple on page, we can reinit the
2120 : : * page instead of restoring the whole thing. Set flag, and hide
2121 : : * buffer references from XLogInsert.
2122 : : */
4344 heikki.linnakangas@i 2123 [ + + + + ]: 10806223 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2124 : 122485 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2125 : : {
2126 : 120824 : info |= XLOG_HEAP_INIT_PAGE;
2127 : 120824 : bufflags |= REGBUF_WILL_INIT;
2128 : : }
2129 : :
2130 : 10683738 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
4175 andres@anarazel.de 2131 : 10683738 : xlrec.flags = 0;
89 melanieplageman@gmai 2132 [ + + ]: 10683738 : if (clear_all_visible)
4175 andres@anarazel.de 2133 : 9472 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2134 [ + + ]: 10683738 : if (options & HEAP_INSERT_SPECULATIVE)
2135 : 2254 : xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
4344 heikki.linnakangas@i 2136 [ - + ]: 10683738 : Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2137 : :
2138 : : /*
2139 : : * For logical decoding, we need the tuple even if we're doing a full
2140 : : * page write, so make sure it's included even if we take a full-page
2141 : : * image. (XXX We could alternatively store a pointer into the FPW).
2142 : : */
2924 andres@anarazel.de 2143 [ + + + + : 10683738 : if (RelationIsLogicallyLogged(relation) &&
+ - - + -
- - - + -
+ + ]
2144 [ + + ]: 278685 : !(options & HEAP_INSERT_NO_LOGICAL))
2145 : : {
4175 2146 : 278447 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
4344 heikki.linnakangas@i 2147 : 278447 : bufflags |= REGBUF_KEEP_DATA;
2148 : :
2256 akapila@postgresql.o 2149 [ + + ]: 278447 : if (IsToastRelation(relation))
2150 : 1970 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2151 : : }
2152 : :
4344 heikki.linnakangas@i 2153 : 10683738 : XLogBeginInsert();
608 peter@eisentraut.org 2154 : 10683738 : XLogRegisterData(&xlrec, SizeOfHeapInsert);
2155 : :
4344 heikki.linnakangas@i 2156 : 10683738 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2157 : 10683738 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2158 : 10683738 : xlhdr.t_hoff = heaptup->t_data->t_hoff;
2159 : :
2160 : : /*
2161 : : * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2162 : : * write the whole page to the xlog, we don't need to store
2163 : : * xl_heap_header in the xlog.
2164 : : */
89 melanieplageman@gmai 2165 : 10683738 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_HEAP, buffer,
2166 : 10683738 : REGBUF_STANDARD | bufflags);
2167 : 10683738 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP, &xlhdr,
2168 : : SizeOfHeapHeader);
2169 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2170 : 10683738 : XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP,
4251 tgl@sss.pgh.pa.us 2171 : 10683738 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2172 : 10683738 : heaptup->t_len - SizeofHeapTupleHeader);
2173 : :
2174 : : /* filtering by origin on a row level is much more efficient */
3581 andres@anarazel.de 2175 : 10683738 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2176 : :
89 melanieplageman@gmai 2177 [ + + ]: 10683738 : if (vmbuffer_modified)
2178 : 9469 : XLogRegisterBuffer(HEAP_INSERT_BLKREF_VM, vmbuffer, 0);
2179 : :
4344 heikki.linnakangas@i 2180 : 10683738 : recptr = XLogInsert(RM_HEAP_ID, info);
2181 : :
9419 vadim4o@yahoo.com 2182 : 10683738 : PageSetLSN(page, recptr);
2183 : :
89 melanieplageman@gmai 2184 [ + + ]: 10683738 : if (vmbuffer_modified)
2185 : 9469 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2186 : : }
2187 : :
9404 tgl@sss.pgh.pa.us 2188 [ - + ]: 11897367 : END_CRIT_SECTION();
2189 : :
7500 2190 : 11897367 : UnlockReleaseBuffer(buffer);
2191 : :
2192 : : /*
2193 : : * We locked vmbuffer if clear_all_visible was true regardless of whether
2194 : : * or not we ended up modifying the vmbuffer.
2195 : : */
89 melanieplageman@gmai 2196 [ + + ]: 11897367 : if (clear_all_visible)
2197 : 9551 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2198 [ + + ]: 11897367 : if (BufferIsValid(vmbuffer))
5592 rhaas@postgresql.org 2199 : 9907 : ReleaseBuffer(vmbuffer);
2200 : :
2201 : : /*
2202 : : * If tuple is cacheable, mark it for invalidation from the caches in case
2203 : : * we abort. Note it is OK to do this after releasing the buffer, because
2204 : : * the heaptup data structure is all in local memory, not in the shared
2205 : : * buffer.
2206 : : */
5536 tgl@sss.pgh.pa.us 2207 : 11897367 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2208 : :
2209 : : /* Note: speculative insertions are counted too, even if aborted later */
5451 heikki.linnakangas@i 2210 : 11897367 : pgstat_count_heap_insert(relation, 1);
2211 : :
2212 : : /*
2213 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
2214 : : * back to the caller's image, too.
2215 : : */
7631 tgl@sss.pgh.pa.us 2216 [ + + ]: 11897367 : if (heaptup != tup)
2217 : : {
2218 : 22346 : tup->t_self = heaptup->t_self;
2219 : 22346 : heap_freetuple(heaptup);
2220 : : }
11052 scrappy@hub.org 2221 : 11897367 : }
2222 : :
2223 : : /*
2224 : : * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2225 : : * tuple header fields and toasts the tuple if necessary. Returns a toasted
2226 : : * version of the tuple if it was toasted, or the original tuple if not. Note
2227 : : * that in any case, the header fields are also set in the original tuple.
2228 : : */
2229 : : static HeapTuple
5451 heikki.linnakangas@i 2230 : 13688986 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2231 : : CommandId cid, uint32 options)
2232 : : {
2233 : : /*
2234 : : * To allow parallel inserts, we need to ensure that they are safe to be
2235 : : * performed in workers. We have the infrastructure to allow parallel
2236 : : * inserts in general except for the cases where inserts generate a new
2237 : : * CommandId (eg. inserts into a table having a foreign key column).
2238 : : */
3294 rhaas@postgresql.org 2239 [ - + ]: 13688986 : if (IsParallelWorker())
4183 rhaas@postgresql.org 2240 [ # # ]:UBC 0 : ereport(ERROR,
2241 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2242 : : errmsg("cannot insert tuples in a parallel worker")));
2243 : :
5451 heikki.linnakangas@i 2244 :CBC 13688986 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2245 : 13688986 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2246 : 13688986 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
4677 rhaas@postgresql.org 2247 : 13688986 : HeapTupleHeaderSetXmin(tup->t_data, xid);
5062 simon@2ndQuadrant.co 2248 [ + + ]: 13688986 : if (options & HEAP_INSERT_FROZEN)
4677 rhaas@postgresql.org 2249 : 102652 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2250 : :
5451 heikki.linnakangas@i 2251 : 13688986 : HeapTupleHeaderSetCmin(tup->t_data, cid);
3400 tgl@sss.pgh.pa.us 2252 : 13688986 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
5451 heikki.linnakangas@i 2253 : 13688986 : tup->t_tableOid = RelationGetRelid(relation);
2254 : :
2255 : : /*
2256 : : * If the new tuple is too big for storage or contains already toasted
2257 : : * out-of-line attributes from some other relation, invoke the toaster.
2258 : : */
4971 kgrittn@postgresql.o 2259 [ + + ]: 13688986 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2260 [ + + ]: 41195 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2261 : : {
2262 : : /* toast table entries should never be recursively toasted */
5451 heikki.linnakangas@i 2263 [ - + ]: 41134 : Assert(!HeapTupleHasExternal(tup));
2264 : 41134 : return tup;
2265 : : }
2266 [ + + + + ]: 13647852 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2565 rhaas@postgresql.org 2267 : 22421 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2268 : : else
5451 heikki.linnakangas@i 2269 : 13625431 : return tup;
2270 : : }
2271 : :
2272 : : /*
2273 : : * Helper for heap_multi_insert() that computes the number of entire pages
2274 : : * that inserting the remaining heaptuples requires. Used to determine how
2275 : : * much the relation needs to be extended by.
2276 : : */
2277 : : static int
1285 andres@anarazel.de 2278 : 467057 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2279 : : {
2280 : 467057 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2281 : 467057 : int npages = 1;
2282 : :
2283 [ + + ]: 2937562 : for (int i = done; i < ntuples; i++)
2284 : : {
2285 : 2470505 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2286 : :
2287 [ + + ]: 2470505 : if (page_avail < tup_sz)
2288 : : {
2289 : 17508 : npages++;
2290 : 17508 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2291 : : }
2292 : 2470505 : page_avail -= tup_sz;
2293 : : }
2294 : :
2295 : 467057 : return npages;
2296 : : }
2297 : :
2298 : : /*
2299 : : * heap_multi_insert - insert multiple tuples into a heap
2300 : : *
2301 : : * This is like heap_insert(), but inserts multiple tuples in one operation.
2302 : : * That's faster than calling heap_insert() in a loop, because when multiple
2303 : : * tuples can be inserted on a single page, we can write just a single WAL
2304 : : * record covering all of them, and only need to lock/unlock the page once.
2305 : : *
2306 : : * Note: this leaks memory into the current memory context. You can create a
2307 : : * temporary context before calling this, if that's a problem.
2308 : : */
2309 : : void
2748 2310 : 458639 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2311 : : CommandId cid, uint32 options, BulkInsertState bistate)
2312 : : {
5451 heikki.linnakangas@i 2313 : 458639 : TransactionId xid = GetCurrentTransactionId();
2314 : : HeapTuple *heaptuples;
2315 : : int i;
2316 : : int ndone;
2317 : : PGAlignedBlock scratch;
2318 : : Page page;
2094 tomas.vondra@postgre 2319 : 458639 : Buffer vmbuffer = InvalidBuffer;
2320 : : bool needwal;
2321 : : Size saveFreeSpace;
4689 rhaas@postgresql.org 2322 [ + + + + : 458639 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
+ - - + -
- - - + -
+ + ]
2323 [ + + + + : 458639 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
+ - - + -
- - - + +
- + - - -
- - - ]
1285 andres@anarazel.de 2324 : 458639 : bool starting_with_empty_page = false;
2325 : 458639 : int npages = 0;
2326 : 458639 : int npages_used = 0;
2327 : :
2328 : : /* currently not needed (thus unsupported) for heap_multi_insert() */
1445 peter@eisentraut.org 2329 [ - + ]: 458639 : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2330 : :
500 nathan@postgresql.or 2331 : 458639 : AssertHasSnapshotForToast(relation);
2332 : :
2382 noah@leadboat.com 2333 [ + + + + : 458639 : needwal = RelationNeedsWAL(relation);
+ - + + ]
914 akorotkov@postgresql 2334 [ + + ]: 458639 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2335 : : HEAP_DEFAULT_FILLFACTOR);
2336 : :
2337 : : /* Toast and set header data in all the slots */
56 michael@paquier.xyz 2338 :GNC 458639 : heaptuples = palloc_array(HeapTuple, ntuples);
5451 heikki.linnakangas@i 2339 [ + + ]:CBC 2250239 : for (i = 0; i < ntuples; i++)
2340 : : {
2341 : : HeapTuple tuple;
2342 : :
2748 andres@anarazel.de 2343 : 1791600 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2344 : 1791600 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2345 : 1791600 : tuple->t_tableOid = slots[i]->tts_tableOid;
2346 : 1791600 : heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2347 : : options);
2348 : : }
2349 : :
2350 : : /*
2351 : : * We're about to do the actual inserts -- but check for conflict first,
2352 : : * to minimize the possibility of having to roll back work we've just
2353 : : * done.
2354 : : *
2355 : : * A check here does not definitively prevent a serialization anomaly;
2356 : : * that check MUST be done at least past the point of acquiring an
2357 : : * exclusive buffer content lock on every buffer that will be affected,
2358 : : * and MAY be done after all inserts are reflected in the buffers and
2359 : : * those locks are released; otherwise there is a race condition. Since
2360 : : * multiple buffers can be locked and unlocked in the loop below, and it
2361 : : * would not be feasible to identify and lock all of those buffers before
2362 : : * the loop, we must do a final check at the end.
2363 : : *
2364 : : * The check here could be omitted with no loss of correctness; it is
2365 : : * present strictly as an optimization.
2366 : : *
2367 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2368 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2369 : : * page locks are only consolidated versions of tuple locks; they do not
2370 : : * lock "gaps" as index page locks do. So we don't need to specify a
2371 : : * buffer when making the call, which makes for a faster check.
2372 : : */
2449 tmunro@postgresql.or 2373 : 458639 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2374 : :
5451 heikki.linnakangas@i 2375 : 458639 : ndone = 0;
2376 [ + + ]: 934938 : while (ndone < ntuples)
2377 : : {
2378 : : Buffer buffer;
89 melanieplageman@gmai 2379 : 476299 : bool clear_all_visible = false;
2094 tomas.vondra@postgre 2380 : 476299 : bool all_frozen_set = false;
89 melanieplageman@gmai 2381 : 476299 : bool vmbuffer_modified = false;
2382 : : int nthispage;
2383 : :
4494 rhaas@postgresql.org 2384 [ + + ]: 476299 : CHECK_FOR_INTERRUPTS();
2385 : :
2386 : : /*
2387 : : * Compute number of pages needed to fit the to-be-inserted tuples in
2388 : : * the worst case. This will be used to determine how much to extend
2389 : : * the relation by in RelationGetBufferForTuple(), if needed. If we
2390 : : * filled a prior page from scratch, we can just update our last
2391 : : * computation, but if we started with a partially filled page,
2392 : : * recompute from scratch, the number of potentially required pages
2393 : : * can vary due to tuples needing to fit onto the page, page headers
2394 : : * etc.
2395 : : */
1285 andres@anarazel.de 2396 [ + + + + ]: 476299 : if (ndone == 0 || !starting_with_empty_page)
2397 : : {
2398 : 467057 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2399 : : saveFreeSpace);
2400 : 467057 : npages_used = 0;
2401 : : }
2402 : : else
2403 : 9242 : npages_used++;
2404 : :
2405 : : /*
2406 : : * Find buffer where at least the next tuple will fit. If the page is
2407 : : * all-visible, this will also pin the requisite visibility map page.
2408 : : *
2409 : : * Also pin visibility map page if COPY FREEZE inserts tuples into an
2410 : : * empty page. See all_frozen_set below.
2411 : : */
5451 heikki.linnakangas@i 2412 : 476299 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2413 : : InvalidBuffer, options, bistate,
2414 : : &vmbuffer, NULL,
2415 : : npages - npages_used);
3827 kgrittn@postgresql.o 2416 : 476299 : page = BufferGetPage(buffer);
2417 : :
2094 tomas.vondra@postgre 2418 : 476299 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2419 : :
2420 [ + + + + ]: 476299 : if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2421 : : {
2422 : 1665 : all_frozen_set = true;
2423 : : /* Lock the vmbuffer before entering the critical section */
368 melanieplageman@gmai 2424 : 1665 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2425 : : }
89 2426 [ + + + + ]: 474634 : else if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2427 : : {
2428 : 6484 : clear_all_visible = true;
2429 : : /* Lock the vmbuffer before entering the critical section */
2430 : 6484 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
2431 : : }
2432 : :
2433 : : /* NO EREPORT(ERROR) from here till changes are logged */
5451 heikki.linnakangas@i 2434 : 476299 : START_CRIT_SECTION();
2435 : :
2436 : : /*
2437 : : * RelationGetBufferForTuple has ensured that the first tuple fits.
2438 : : * Put that on the page, and then as many other tuples as fit.
2439 : : */
4175 andres@anarazel.de 2440 : 476299 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2441 : :
2442 : : /*
2443 : : * For logical decoding we need combo CIDs to properly decode the
2444 : : * catalog.
2445 : : */
2421 michael@paquier.xyz 2446 [ + + + + ]: 476299 : if (needwal && need_cids)
2447 : 5703 : log_heap_new_cid(relation, heaptuples[ndone]);
2448 : :
5052 heikki.linnakangas@i 2449 [ + + ]: 1791600 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2450 : : {
5451 2451 : 1332961 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2452 : :
5262 2453 [ + + ]: 1332961 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
5451 2454 : 17660 : break;
2455 : :
4175 andres@anarazel.de 2456 : 1315301 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2457 : :
2458 : : /*
2459 : : * For logical decoding we need combo CIDs to properly decode the
2460 : : * catalog.
2461 : : */
4344 heikki.linnakangas@i 2462 [ + + + + ]: 1315301 : if (needwal && need_cids)
2463 : 5256 : log_heap_new_cid(relation, heaptup);
2464 : : }
2465 : :
2466 : : /*
2467 : : * If the page is all visible, need to clear that, unless we're only
2468 : : * going to add further frozen rows to it.
2469 : : *
2470 : : * If we're only adding already frozen rows to a previously empty
2471 : : * page, mark it as all-frozen and update the visibility map. We're
2472 : : * already holding a pin on the vmbuffer.
2473 : : */
89 melanieplageman@gmai 2474 [ + + ]: 476299 : if (clear_all_visible)
2475 : : {
2476 [ - + ]: 6484 : Assert(!(options & HEAP_INSERT_FROZEN));
2477 : : /* It's possible the VM bits were already clear */
89 melanieplageman@gmai 2478 [ + + ]:GNC 6484 : if (visibilitymap_clear(relation->rd_locator,
2479 : : BufferGetBlockNumber(buffer),
2480 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
89 melanieplageman@gmai 2481 :CBC 6483 : vmbuffer_modified = true;
2482 : :
5240 rhaas@postgresql.org 2483 : 6484 : PageClearAllVisible(page);
2484 : : }
2094 tomas.vondra@postgre 2485 [ + + ]: 469815 : else if (all_frozen_set)
2486 : : {
2487 : 1665 : PageSetAllVisible(page);
224 melanieplageman@gmai 2488 : 1665 : PageClearPrunable(page);
28 2489 : 1665 : (void) visibilitymap_set(BufferGetBlockNumber(buffer),
2490 : : vmbuffer,
2491 : : VISIBILITYMAP_ALL_VISIBLE |
2492 : : VISIBILITYMAP_ALL_FROZEN,
2493 : : relation->rd_locator);
2494 : : }
2495 : :
2496 : : /*
2497 : : * Set pd_prune_xid. See heap_insert() for more on why we do this when
2498 : : * inserting tuples. This only makes sense if the tuples aren't frozen
2499 : : * and we're not in bootstrap mode.
2500 : : */
2501 [ + + + + ]: 476299 : if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
196 2502 [ - + + + : 453306 : PageSetPrunable(page, xid);
+ + ]
2503 : :
5451 heikki.linnakangas@i 2504 : 476299 : MarkBufferDirty(buffer);
2505 : :
2506 : : /* XLOG stuff */
2507 [ + + ]: 476299 : if (needwal)
2508 : : {
2509 : : XLogRecPtr recptr;
2510 : : xl_heap_multi_insert *xlrec;
2511 : 472400 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2512 : : char *tupledata;
2513 : : int totaldatalen;
2963 tgl@sss.pgh.pa.us 2514 : 472400 : char *scratchptr = scratch.data;
2515 : : bool init;
4344 heikki.linnakangas@i 2516 : 472400 : int bufflags = 0;
2517 : :
2518 : : /*
2519 : : * If the page was previously empty, we can reinit the page
2520 : : * instead of restoring the whole thing.
2521 : : */
2094 tomas.vondra@postgre 2522 : 472400 : init = starting_with_empty_page;
2523 : :
2524 : : /* allocate xl_heap_multi_insert struct from the scratch area */
5451 heikki.linnakangas@i 2525 : 472400 : xlrec = (xl_heap_multi_insert *) scratchptr;
2526 : 472400 : scratchptr += SizeOfHeapMultiInsert;
2527 : :
2528 : : /*
2529 : : * Allocate offsets array. Unless we're reinitializing the page,
2530 : : * in that case the tuples are stored in order starting at
2531 : : * FirstOffsetNumber and we don't need to store the offsets
2532 : : * explicitly.
2533 : : */
2534 [ + + ]: 472400 : if (!init)
2535 : 457966 : scratchptr += nthispage * sizeof(OffsetNumber);
2536 : :
2537 : : /* the rest of the scratch space is used for tuple data */
2538 : 472400 : tupledata = scratchptr;
2539 : :
2540 : : /* check that the mutually exclusive flags are not both set */
89 melanieplageman@gmai 2541 [ + + - + ]: 472400 : Assert(!(clear_all_visible && all_frozen_set));
2542 : :
2094 tomas.vondra@postgre 2543 : 472400 : xlrec->flags = 0;
89 melanieplageman@gmai 2544 [ + + ]: 472400 : if (clear_all_visible)
2094 tomas.vondra@postgre 2545 : 6484 : xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
2546 : :
2547 : : /*
2548 : : * We don't have to worry about including a conflict xid in the
2549 : : * WAL record, as HEAP_INSERT_FROZEN intentionally violates
2550 : : * visibility rules.
2551 : : */
2552 [ + + ]: 472400 : if (all_frozen_set)
2553 : 21 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2554 : :
5451 heikki.linnakangas@i 2555 : 472400 : xlrec->ntuples = nthispage;
2556 : :
2557 : : /*
2558 : : * Write out an xl_multi_insert_tuple and the tuple data itself
2559 : : * for each tuple.
2560 : : */
2561 [ + + ]: 2056825 : for (i = 0; i < nthispage; i++)
2562 : : {
2563 : 1584425 : HeapTuple heaptup = heaptuples[ndone + i];
2564 : : xl_multi_insert_tuple *tuphdr;
2565 : : int datalen;
2566 : :
2567 [ + + ]: 1584425 : if (!init)
2568 : 956464 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2569 : : /* xl_multi_insert_tuple needs two-byte alignment. */
2570 : 1584425 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2571 : 1584425 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2572 : :
2573 : 1584425 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2574 : 1584425 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2575 : 1584425 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2576 : :
2577 : : /* write bitmap [+ padding] [+ oid] + data */
4251 tgl@sss.pgh.pa.us 2578 : 1584425 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
5451 heikki.linnakangas@i 2579 : 1584425 : memcpy(scratchptr,
4251 tgl@sss.pgh.pa.us 2580 : 1584425 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2581 : : datalen);
5451 heikki.linnakangas@i 2582 : 1584425 : tuphdr->datalen = datalen;
2583 : 1584425 : scratchptr += datalen;
2584 : : }
2585 : 472400 : totaldatalen = scratchptr - tupledata;
2963 tgl@sss.pgh.pa.us 2586 [ - + ]: 472400 : Assert((scratchptr - scratch.data) < BLCKSZ);
2587 : :
4689 rhaas@postgresql.org 2588 [ + + ]: 472400 : if (need_tuple_data)
4175 andres@anarazel.de 2589 : 75 : xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2590 : :
2591 : : /*
2592 : : * Signal that this is the last xl_heap_multi_insert record
2593 : : * emitted by this call to heap_multi_insert(). Needed for logical
2594 : : * decoding so it knows when to cleanup temporary data.
2595 : : */
4344 heikki.linnakangas@i 2596 [ + + ]: 472400 : if (ndone + nthispage == ntuples)
4175 andres@anarazel.de 2597 : 458185 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2598 : :
5451 heikki.linnakangas@i 2599 [ + + ]: 472400 : if (init)
2600 : : {
2601 : 14434 : info |= XLOG_HEAP_INIT_PAGE;
4344 2602 : 14434 : bufflags |= REGBUF_WILL_INIT;
2603 : : }
2604 : :
2605 : : /*
2606 : : * If we're doing logical decoding, include the new tuple data
2607 : : * even if we take a full-page image of the page.
2608 : : */
2609 [ + + ]: 472400 : if (need_tuple_data)
2610 : 75 : bufflags |= REGBUF_KEEP_DATA;
2611 : :
2612 : 472400 : XLogBeginInsert();
608 peter@eisentraut.org 2613 : 472400 : XLogRegisterData(xlrec, tupledata - scratch.data);
89 melanieplageman@gmai 2614 : 472400 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_HEAP, buffer,
2615 : 472400 : REGBUF_STANDARD | bufflags);
2616 [ + + + + ]: 472400 : if (all_frozen_set || vmbuffer_modified)
2617 : 6504 : XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_VM, vmbuffer, 0);
2618 : :
2619 : 472400 : XLogRegisterBufData(HEAP_MULTI_INSERT_BLKREF_HEAP, tupledata,
2620 : : totaldatalen);
2621 : :
2622 : : /* filtering by origin on a row level is much more efficient */
3581 andres@anarazel.de 2623 : 472400 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2624 : :
4344 heikki.linnakangas@i 2625 : 472400 : recptr = XLogInsert(RM_HEAP2_ID, info);
2626 : :
5451 2627 : 472400 : PageSetLSN(page, recptr);
89 melanieplageman@gmai 2628 [ + + + + ]: 472400 : if (all_frozen_set || vmbuffer_modified)
2629 : : {
368 2630 [ - + ]: 6504 : Assert(BufferIsDirty(vmbuffer));
2631 : 6504 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
2632 : : }
2633 : : }
2634 : :
5451 heikki.linnakangas@i 2635 [ - + ]: 476299 : END_CRIT_SECTION();
2636 : :
2637 : : /*
2638 : : * We locked vmbuffer if clear_all_visible was true regardless of
2639 : : * whether or not we ended up modifying the vmbuffer.
2640 : : */
89 melanieplageman@gmai 2641 [ + + + + ]: 476299 : if (all_frozen_set || clear_all_visible)
368 2642 : 8149 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2643 : :
2094 tomas.vondra@postgre 2644 : 476299 : UnlockReleaseBuffer(buffer);
5451 heikki.linnakangas@i 2645 : 476299 : ndone += nthispage;
2646 : :
2647 : : /*
2648 : : * NB: Only release vmbuffer after inserting all tuples - it's fairly
2649 : : * likely that we'll insert into subsequent heap pages that are likely
2650 : : * to use the same vm page.
2651 : : */
2652 : : }
2653 : :
2654 : : /* We're done with inserting all tuples, so release the last vmbuffer. */
2094 tomas.vondra@postgre 2655 [ + + ]: 458639 : if (vmbuffer != InvalidBuffer)
2656 : 6521 : ReleaseBuffer(vmbuffer);
2657 : :
2658 : : /*
2659 : : * We're done with the actual inserts. Check for conflicts again, to
2660 : : * ensure that all rw-conflicts in to these inserts are detected. Without
2661 : : * this final check, a sequential scan of the heap may have locked the
2662 : : * table after the "before" check, missing one opportunity to detect the
2663 : : * conflict, and then scanned the table before the new tuples were there,
2664 : : * missing the other chance to detect the conflict.
2665 : : *
2666 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2667 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2668 : : * page locks are only consolidated versions of tuple locks; they do not
2669 : : * lock "gaps" as index page locks do. So we don't need to specify a
2670 : : * buffer when making the call.
2671 : : */
2449 tmunro@postgresql.or 2672 : 458639 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2673 : :
2674 : : /*
2675 : : * If tuples are cacheable, mark them for invalidation from the caches in
2676 : : * case we abort. Note it is OK to do this after releasing the buffer,
2677 : : * because the heaptuples data structure is all in local memory, not in
2678 : : * the shared buffer.
2679 : : */
4701 rhaas@postgresql.org 2680 [ + + ]: 458639 : if (IsCatalogRelation(relation))
2681 : : {
5451 heikki.linnakangas@i 2682 [ + + ]: 1535354 : for (i = 0; i < ntuples; i++)
2683 : 1078195 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2684 : : }
2685 : :
2686 : : /* copy t_self fields back to the caller's slots */
5355 2687 [ + + ]: 2250239 : for (i = 0; i < ntuples; i++)
2748 andres@anarazel.de 2688 : 1791600 : slots[i]->tts_tid = heaptuples[i]->t_self;
2689 : :
5451 heikki.linnakangas@i 2690 : 458639 : pgstat_count_heap_insert(relation, ntuples);
2691 : 458639 : }
2692 : :
2693 : : /*
2694 : : * simple_heap_insert - insert a tuple
2695 : : *
2696 : : * Currently, this routine differs from heap_insert only in supplying
2697 : : * a default command ID and not allowing access to the speedup options.
2698 : : *
2699 : : * This should be used rather than using heap_insert directly in most places
2700 : : * where we are modifying system catalogs.
2701 : : */
2702 : : void
8910 tgl@sss.pgh.pa.us 2703 : 1086047 : simple_heap_insert(Relation relation, HeapTuple tup)
2704 : : {
2883 andres@anarazel.de 2705 : 1086047 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
8910 tgl@sss.pgh.pa.us 2706 : 1086047 : }
2707 : :
2708 : : /*
2709 : : * Given infomask/infomask2, compute the bits that must be saved in the
2710 : : * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2711 : : * xl_heap_lock_updated WAL records.
2712 : : *
2713 : : * See fix_infomask_from_infobits.
2714 : : */
2715 : : static uint8
5010 alvherre@alvh.no-ip. 2716 : 6490626 : compute_infobits(uint16 infomask, uint16 infomask2)
2717 : : {
2718 : : return
2719 : 6490626 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2720 : 6490626 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2721 : 6490626 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2722 : : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2723 : 12981252 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2724 : : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2725 : 6490626 : XLHL_KEYS_UPDATED : 0);
2726 : : }
2727 : :
2728 : : /*
2729 : : * Given two versions of the same t_infomask for a tuple, compare them and
2730 : : * return whether the relevant status for a tuple Xmax has changed. This is
2731 : : * used after a buffer lock has been released and reacquired: we want to ensure
2732 : : * that the tuple state continues to be the same it was when we previously
2733 : : * examined it.
2734 : : *
2735 : : * Note the Xmax field itself must be compared separately.
2736 : : */
2737 : : static inline bool
4554 2738 : 5415 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2739 : : {
4542 bruce@momjian.us 2740 : 5415 : const uint16 interesting =
2741 : : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2742 : :
4554 alvherre@alvh.no-ip. 2743 [ + + ]: 5415 : if ((new_infomask & interesting) != (old_infomask & interesting))
2744 : 17 : return true;
2745 : :
2746 : 5398 : return false;
2747 : : }
2748 : :
2749 : : /*
2750 : : * heap_delete - delete a tuple
2751 : : *
2752 : : * See table_tuple_delete() for an explanation of the parameters, except that
2753 : : * this routine directly takes a tuple rather than a slot.
2754 : : *
2755 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2756 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2757 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2758 : : * generated by another transaction).
2759 : : */
2760 : : TM_Result
347 peter@eisentraut.org 2761 : 1850301 : heap_delete(Relation relation, const ItemPointerData *tid,
2762 : : CommandId cid, uint32 options, Snapshot crosscheck,
2763 : : bool wait, TM_FailureData *tmfd)
2764 : : {
2765 : : TM_Result result;
8061 tgl@sss.pgh.pa.us 2766 : 1850301 : TransactionId xid = GetCurrentTransactionId();
2767 : : ItemId lp;
2768 : : HeapTupleData tp;
2769 : : Page page;
2770 : : BlockNumber block;
2771 : : Buffer buffer;
5592 rhaas@postgresql.org 2772 : 1850301 : Buffer vmbuffer = InvalidBuffer;
89 melanieplageman@gmai 2773 : 1850301 : bool vmbuffer_modified = false;
2774 : : TransactionId new_xmax;
2775 : : uint16 new_infomask,
2776 : : new_infomask2;
194 alvherre@kurilemu.de 2777 : 1850301 : bool changingPart = (options & TABLE_DELETE_CHANGING_PARTITION) != 0;
189 2778 : 1850301 : bool walLogical = (options & TABLE_DELETE_NO_LOGICAL) == 0;
7835 tgl@sss.pgh.pa.us 2779 : 1850301 : bool have_tuple_lock = false;
2780 : : bool iscombo;
89 melanieplageman@gmai 2781 : 1850301 : bool clear_all_visible = false;
4542 bruce@momjian.us 2782 : 1850301 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
4689 rhaas@postgresql.org 2783 : 1850301 : bool old_key_copied = false;
2784 : :
10627 bruce@momjian.us 2785 [ - + ]: 1850301 : Assert(ItemPointerIsValid(tid));
2786 : :
500 nathan@postgresql.or 2787 : 1850301 : AssertHasSnapshotForToast(relation);
2788 : :
2789 : : /*
2790 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
2791 : : * Other workers might need that combo CID for visibility checks, and we
2792 : : * have no provision for broadcasting it to them.
2793 : : */
4183 rhaas@postgresql.org 2794 [ - + ]: 1850301 : if (IsInParallelMode())
4183 rhaas@postgresql.org 2795 [ # # ]:UBC 0 : ereport(ERROR,
2796 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2797 : : errmsg("cannot delete tuples during a parallel operation")));
2798 : :
5592 rhaas@postgresql.org 2799 :CBC 1850301 : block = ItemPointerGetBlockNumber(tid);
2800 : 1850301 : buffer = ReadBuffer(relation, block);
3827 kgrittn@postgresql.o 2801 : 1850301 : page = BufferGetPage(buffer);
2802 : :
2803 : : /*
2804 : : * Before locking the buffer, pin the visibility map page if it appears to
2805 : : * be necessary. Since we haven't got the lock yet, someone else might be
2806 : : * in the middle of changing this, so we'll need to recheck after we have
2807 : : * the lock.
2808 : : */
5592 rhaas@postgresql.org 2809 [ + + ]: 1850301 : if (PageIsAllVisible(page))
2810 : 3180 : visibilitymap_pin(relation, block, &vmbuffer);
2811 : :
10163 vadim4o@yahoo.com 2812 : 1850301 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2813 : :
1481 jdavis@postgresql.or 2814 : 1850301 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2815 [ - + ]: 1850301 : Assert(ItemIdIsNormal(lp));
2816 : :
2817 : 1850301 : tp.t_tableOid = RelationGetRelid(relation);
2818 : 1850301 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2819 : 1850301 : tp.t_len = ItemIdGetLength(lp);
2820 : 1850301 : tp.t_self = *tid;
2821 : :
2822 : 1 : l1:
2823 : :
2824 : : /*
2825 : : * If we didn't pin the visibility map page and the page has become all
2826 : : * visible while we were busy locking the buffer, we'll have to unlock and
2827 : : * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2828 : : * unfortunate, but hopefully shouldn't happen often.
2829 : : */
5592 rhaas@postgresql.org 2830 [ + + - + ]: 1850302 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2831 : : {
5592 rhaas@postgresql.org 2832 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2833 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
2834 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2835 : : }
2836 : :
4830 rhaas@postgresql.org 2837 :CBC 1850302 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2838 : :
2760 andres@anarazel.de 2839 [ - + ]: 1850302 : if (result == TM_Invisible)
2840 : : {
7500 tgl@sss.pgh.pa.us 2841 :UBC 0 : UnlockReleaseBuffer(buffer);
4089 2842 [ # # ]: 0 : ereport(ERROR,
2843 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2844 : : errmsg("attempted to delete invisible tuple")));
2845 : : }
914 akorotkov@postgresql 2846 [ + + + - ]:CBC 1850302 : else if (result == TM_BeingModified && wait)
2847 : : {
2848 : : TransactionId xwait;
2849 : : uint16 infomask;
2850 : :
2851 : : /* must copy state data before unlocking buffer */
5010 alvherre@alvh.no-ip. 2852 : 40606 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
7835 tgl@sss.pgh.pa.us 2853 : 40606 : infomask = tp.t_data->t_infomask;
2854 : :
2855 : : /*
2856 : : * Sleep until concurrent transaction ends -- except when there's a
2857 : : * single locker and it's our own transaction. Note we don't care
2858 : : * which lock mode the locker has, because we need the strongest one.
2859 : : *
2860 : : * Before sleeping, we need to acquire tuple lock to establish our
2861 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
2862 : : * release us when we are next-in-line for the tuple.
2863 : : *
2864 : : * If we are forced to "start over" below, we keep the tuple lock;
2865 : : * this arranges that we stay at the head of the line while rechecking
2866 : : * tuple state.
2867 : : */
7837 2868 [ + + ]: 40606 : if (infomask & HEAP_XMAX_IS_MULTI)
2869 : : {
2673 alvherre@alvh.no-ip. 2870 : 8 : bool current_is_member = false;
2871 : :
4203 2872 [ + - ]: 8 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2873 : : LockTupleExclusive, ¤t_is_member))
2874 : : {
2875 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2876 : :
2877 : : /*
2878 : : * Acquire the lock, if necessary (but skip it when we're
2879 : : * requesting a lock and already have one; avoids deadlock).
2880 : : */
2673 2881 [ + + ]: 8 : if (!current_is_member)
2882 : 6 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2883 : : LockWaitBlock, &have_tuple_lock);
2884 : :
2885 : : /* wait for multixact */
4203 2886 : 8 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2887 : : relation, &(tp.t_self), XLTW_Delete,
2888 : : NULL);
2889 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2890 : :
2891 : : /*
2892 : : * If xwait had just locked the tuple then some other xact
2893 : : * could update this tuple before we get to this point. Check
2894 : : * for xmax change, and start over if so.
2895 : : *
2896 : : * We also must start over if we didn't pin the VM page, and
2897 : : * the page has become all visible.
2898 : : */
1481 jdavis@postgresql.or 2899 [ + - + - : 16 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ - ]
2900 [ - + ]: 16 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4203 alvherre@alvh.no-ip. 2901 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2902 : : xwait))
4203 alvherre@alvh.no-ip. 2903 :UBC 0 : goto l1;
2904 : : }
2905 : :
2906 : : /*
2907 : : * You might think the multixact is necessarily done here, but not
2908 : : * so: it could have surviving members, namely our own xact or
2909 : : * other subxacts of this backend. It is legal for us to delete
2910 : : * the tuple in either case, however (the latter case is
2911 : : * essentially a situation of upgrading our former shared lock to
2912 : : * exclusive). We don't bother changing the on-disk hint bits
2913 : : * since we are about to overwrite the xmax altogether.
2914 : : */
2915 : : }
4203 alvherre@alvh.no-ip. 2916 [ + + ]:CBC 40598 : else if (!TransactionIdIsCurrentTransactionId(xwait))
2917 : : {
2918 : : /*
2919 : : * Wait for regular transaction to end; but first, acquire tuple
2920 : : * lock.
2921 : : */
2922 : 55 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2923 : 55 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2924 : : LockWaitBlock, &have_tuple_lock);
4268 heikki.linnakangas@i 2925 : 55 : XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
7837 tgl@sss.pgh.pa.us 2926 : 51 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2927 : :
2928 : : /*
2929 : : * xwait is done, but if xwait had just locked the tuple then some
2930 : : * other xact could update this tuple before we get to this point.
2931 : : * Check for xmax change, and start over if so.
2932 : : *
2933 : : * We also must start over if we didn't pin the VM page, and the
2934 : : * page has become all visible.
2935 : : */
1481 jdavis@postgresql.or 2936 [ + - + - : 102 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ + ]
2937 [ - + ]: 101 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
5010 alvherre@alvh.no-ip. 2938 : 50 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2939 : : xwait))
7837 tgl@sss.pgh.pa.us 2940 : 1 : goto l1;
2941 : :
2942 : : /* Otherwise check if it committed or aborted */
6999 2943 : 50 : UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2944 : : }
2945 : :
2946 : : /*
2947 : : * We may overwrite if previous xmax aborted, or if it committed but
2948 : : * only locked the tuple without updating it.
2949 : : */
5010 alvherre@alvh.no-ip. 2950 [ + + + + ]: 81182 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2951 [ + + ]: 40615 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2952 : 34 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2760 andres@anarazel.de 2953 : 40571 : result = TM_Ok;
2058 alvherre@alvh.no-ip. 2954 [ + + ]: 30 : else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2760 andres@anarazel.de 2955 : 25 : result = TM_Updated;
2956 : : else
2957 : 5 : result = TM_Deleted;
2958 : : }
2959 : :
2960 : : /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2961 [ + + ]: 1850297 : if (result != TM_Ok)
2962 : : {
2963 [ + + + + : 71 : Assert(result == TM_SelfModified ||
- + - - ]
2964 : : result == TM_Updated ||
2965 : : result == TM_Deleted ||
2966 : : result == TM_BeingModified);
7723 tgl@sss.pgh.pa.us 2967 [ - + ]: 71 : Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2760 andres@anarazel.de 2968 [ + + - + ]: 71 : Assert(result != TM_Updated ||
2969 : : !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2970 : : }
2971 : :
1049 heikki.linnakangas@i 2972 [ + + + - ]: 1850297 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
2973 : : {
2974 : : /* Perform additional check for transaction-snapshot mode RI updates */
2975 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2976 : 1 : result = TM_Updated;
2977 : : }
2978 : :
2979 [ + + ]: 1850297 : if (result != TM_Ok)
2980 : : {
2760 andres@anarazel.de 2981 : 72 : tmfd->ctid = tp.t_data->t_ctid;
2982 : 72 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2983 [ + + ]: 72 : if (result == TM_SelfModified)
2984 : 28 : tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2985 : : else
2986 : 44 : tmfd->cmax = InvalidCommandId;
914 akorotkov@postgresql 2987 : 72 : UnlockReleaseBuffer(buffer);
7835 tgl@sss.pgh.pa.us 2988 [ + + ]: 72 : if (have_tuple_lock)
5010 alvherre@alvh.no-ip. 2989 : 30 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
5592 rhaas@postgresql.org 2990 [ - + ]: 72 : if (vmbuffer != InvalidBuffer)
5592 rhaas@postgresql.org 2991 :UBC 0 : ReleaseBuffer(vmbuffer);
10163 vadim4o@yahoo.com 2992 :CBC 72 : return result;
2993 : : }
2994 : :
2995 : : /*
2996 : : * We're about to do the actual delete -- check for conflict first, to
2997 : : * avoid possibly having to roll back work we've just done.
2998 : : *
2999 : : * This is safe without a recheck as long as there is no possibility of
3000 : : * another process scanning the page between this check and the delete
3001 : : * being visible to the scan (i.e., an exclusive buffer content lock is
3002 : : * continuously held from this point until the tuple delete is visible).
3003 : : */
2449 tmunro@postgresql.or 3004 : 1850225 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
3005 : :
3006 : : /* replace cid with a combo CID if necessary */
7185 tgl@sss.pgh.pa.us 3007 : 1850211 : HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
3008 : :
3009 : : /*
3010 : : * Compute replica identity tuple before entering the critical section so
3011 : : * we don't PANIC upon a memory allocation failure.
3012 : : */
189 alvherre@kurilemu.de 3013 : 1850211 : old_key_tuple = walLogical ?
3014 [ + + ]: 1850211 : ExtractReplicaIdentity(relation, &tp, true, &old_key_copied) : NULL;
3015 : :
3016 : : /*
3017 : : * If this is the first possibly-multixact-able operation in the current
3018 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
3019 : : * certain that the transaction will never become a member of any older
3020 : : * MultiXactIds than that. (We have to do this even if we end up just
3021 : : * using our own TransactionId below, since some other backend could
3022 : : * incorporate our XID into a MultiXact immediately afterwards.)
3023 : : */
4574 heikki.linnakangas@i 3024 : 1850211 : MultiXactIdSetOldestMember();
3025 : :
3026 : 1850211 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
3027 : 1850211 : tp.t_data->t_infomask, tp.t_data->t_infomask2,
3028 : : xid, LockTupleExclusive, true,
3029 : : &new_xmax, &new_infomask, &new_infomask2);
3030 : :
3031 : : /* Lock the VM before entering the critical section */
89 melanieplageman@gmai 3032 [ + + ]: 1850211 : if (PageIsAllVisible(page))
3033 : : {
3034 : 3180 : clear_all_visible = true;
3035 : 3180 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3036 : : }
3037 : :
9404 tgl@sss.pgh.pa.us 3038 : 1850211 : START_CRIT_SECTION();
3039 : :
3040 : : /*
3041 : : * If this transaction commits, the tuple will become DEAD sooner or
3042 : : * later. Set flag that this page is a candidate for pruning once our xid
3043 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
3044 : : * the subsequent page pruning will be a no-op and the hint will be
3045 : : * cleared.
3046 : : */
6665 3047 [ - + + + : 1850211 : PageSetPrunable(page, xid);
+ + ]
3048 : :
89 melanieplageman@gmai 3049 [ + + ]: 1850211 : if (clear_all_visible)
3050 : : {
3051 : : /* It's possible the VM bits were already clear */
89 melanieplageman@gmai 3052 [ + - ]:GNC 3180 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(buffer),
3053 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
89 melanieplageman@gmai 3054 :CBC 3180 : vmbuffer_modified = true;
3055 : :
6522 heikki.linnakangas@i 3056 : 3180 : PageClearAllVisible(page);
3057 : : }
3058 : :
3059 : : /* store transaction information of xact deleting the tuple */
5010 alvherre@alvh.no-ip. 3060 : 1850211 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3061 : 1850211 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3062 : 1850211 : tp.t_data->t_infomask |= new_infomask;
3063 : 1850211 : tp.t_data->t_infomask2 |= new_infomask2;
6962 tgl@sss.pgh.pa.us 3064 : 1850211 : HeapTupleHeaderClearHotUpdated(tp.t_data);
5010 alvherre@alvh.no-ip. 3065 : 1850211 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
7185 tgl@sss.pgh.pa.us 3066 : 1850211 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3067 : : /* Make sure there is no forward chain link in t_ctid */
8826 3068 : 1850211 : tp.t_data->t_ctid = tp.t_self;
3069 : :
3070 : : /* Signal that this is actually a move into another partition */
3110 andres@anarazel.de 3071 [ + + ]: 1850211 : if (changingPart)
3072 : 635 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
3073 : :
7500 tgl@sss.pgh.pa.us 3074 : 1850211 : MarkBufferDirty(buffer);
3075 : :
3076 : : /*
3077 : : * XLOG stuff
3078 : : *
3079 : : * NB: heap_abort_speculative() uses the same xlog record and replay
3080 : : * routines.
3081 : : */
5782 rhaas@postgresql.org 3082 [ + + + + : 1850211 : if (RelationNeedsWAL(relation))
+ - + + ]
3083 : : {
3084 : : xl_heap_delete xlrec;
3085 : : xl_heap_header xlhdr;
3086 : : XLogRecPtr recptr;
3087 : :
3088 : : /*
3089 : : * For logical decode we need combo CIDs to properly decode the
3090 : : * catalog
3091 : : */
4689 3092 [ + + + + : 1741800 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- - + ]
3093 : 7582 : log_heap_new_cid(relation, &tp);
3094 : :
3110 andres@anarazel.de 3095 : 1741800 : xlrec.flags = 0;
89 melanieplageman@gmai 3096 [ + + ]: 1741800 : if (clear_all_visible)
3110 andres@anarazel.de 3097 : 2130 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3098 [ + + ]: 1741800 : if (changingPart)
3099 : 635 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
5010 alvherre@alvh.no-ip. 3100 : 3483600 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3101 : 1741800 : tp.t_data->t_infomask2);
4344 heikki.linnakangas@i 3102 : 1741800 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
5010 alvherre@alvh.no-ip. 3103 : 1741800 : xlrec.xmax = new_xmax;
3104 : :
4344 heikki.linnakangas@i 3105 [ + + ]: 1741800 : if (old_key_tuple != NULL)
3106 : : {
3107 [ + + ]: 47028 : if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4175 andres@anarazel.de 3108 : 132 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
3109 : : else
3110 : 46896 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
3111 : : }
3112 : :
3113 : : /*
3114 : : * Mark the change as not-for-logical-decoding if caller requested so.
3115 : : *
3116 : : * (This is used for changes that affect relations not visible to
3117 : : * other transactions, such as the transient table during concurrent
3118 : : * repack.)
3119 : : */
189 alvherre@kurilemu.de 3120 [ + + ]: 1741800 : if (!walLogical)
3121 : 4 : xlrec.flags |= XLH_DELETE_NO_LOGICAL;
3122 : :
4344 heikki.linnakangas@i 3123 : 1741800 : XLogBeginInsert();
608 peter@eisentraut.org 3124 : 1741800 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3125 : :
89 melanieplageman@gmai 3126 : 1741800 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3127 : :
3128 : : /*
3129 : : * Log replica identity of the deleted tuple if there is one
3130 : : */
4689 rhaas@postgresql.org 3131 [ + + ]: 1741800 : if (old_key_tuple != NULL)
3132 : : {
3133 : 47028 : xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3134 : 47028 : xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3135 : 47028 : xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3136 : :
608 peter@eisentraut.org 3137 : 47028 : XLogRegisterData(&xlhdr, SizeOfHeapHeader);
4344 heikki.linnakangas@i 3138 : 47028 : XLogRegisterData((char *) old_key_tuple->t_data
3139 : : + SizeofHeapTupleHeader,
3140 : 47028 : old_key_tuple->t_len
3141 : : - SizeofHeapTupleHeader);
3142 : : }
3143 : :
3144 : : /* filtering by origin on a row level is much more efficient */
3581 andres@anarazel.de 3145 : 1741800 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3146 : :
89 melanieplageman@gmai 3147 [ + + ]: 1741800 : if (vmbuffer_modified)
3148 : 2130 : XLogRegisterBuffer(HEAP_DELETE_BLKREF_VM, vmbuffer, 0);
3149 : :
4344 heikki.linnakangas@i 3150 : 1741800 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3151 : :
6665 tgl@sss.pgh.pa.us 3152 : 1741800 : PageSetLSN(page, recptr);
3153 : :
89 melanieplageman@gmai 3154 [ + + ]: 1741800 : if (vmbuffer_modified)
3155 : 2130 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3156 : : }
3157 : :
9404 tgl@sss.pgh.pa.us 3158 [ - + ]: 1850211 : END_CRIT_SECTION();
3159 : :
3160 : : /*
3161 : : * Release VM lock first, since it covers many heap blocks. We locked
3162 : : * vmbuffer if clear_all_visible was true regardless of whether or not we
3163 : : * ended up modifying the vmbuffer.
3164 : : */
89 melanieplageman@gmai 3165 [ + + ]: 1850211 : if (clear_all_visible)
3166 : 3180 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3167 : :
9401 tgl@sss.pgh.pa.us 3168 : 1850211 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3169 : :
5592 rhaas@postgresql.org 3170 [ + + ]: 1850211 : if (vmbuffer != InvalidBuffer)
3171 : 3180 : ReleaseBuffer(vmbuffer);
3172 : :
3173 : : /*
3174 : : * If the tuple has toasted out-of-line attributes, we need to delete
3175 : : * those items too. We have to do this before releasing the buffer
3176 : : * because we need to look at the contents of the tuple, but it's OK to
3177 : : * release the content lock on the buffer first.
3178 : : */
4971 kgrittn@postgresql.o 3179 [ + + ]: 1850211 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3180 [ + + ]: 4525 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3181 : : {
3182 : : /* toast table entries should never be recursively toasted */
7132 tgl@sss.pgh.pa.us 3183 [ - + ]: 4512 : Assert(!HeapTupleHasExternal(&tp));
3184 : : }
3185 [ + + ]: 1845699 : else if (HeapTupleHasExternal(&tp))
2565 rhaas@postgresql.org 3186 : 530 : heap_toast_delete(relation, &tp, false);
3187 : :
3188 : : /*
3189 : : * Mark tuple for invalidation from system caches at next command
3190 : : * boundary. We have to do this before releasing the buffer because we
3191 : : * need to look at the contents of the tuple.
3192 : : */
5536 tgl@sss.pgh.pa.us 3193 : 1850211 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3194 : :
3195 : : /* Now we can release the buffer */
914 akorotkov@postgresql 3196 : 1850211 : ReleaseBuffer(buffer);
3197 : :
3198 : : /*
3199 : : * Release the lmgr tuple lock, if we had it.
3200 : : */
7835 tgl@sss.pgh.pa.us 3201 [ + + ]: 1850211 : if (have_tuple_lock)
5010 alvherre@alvh.no-ip. 3202 : 26 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3203 : :
7078 tgl@sss.pgh.pa.us 3204 : 1850211 : pgstat_count_heap_delete(relation);
3205 : :
4689 rhaas@postgresql.org 3206 [ + + + + ]: 1850211 : if (old_key_tuple != NULL && old_key_copied)
3207 : 46897 : heap_freetuple(old_key_tuple);
3208 : :
2760 andres@anarazel.de 3209 : 1850211 : return TM_Ok;
3210 : : }
3211 : :
3212 : : /*
3213 : : * simple_heap_delete - delete a tuple
3214 : : *
3215 : : * This routine may be used to delete a tuple when concurrent updates of
3216 : : * the target tuple are not expected (for example, because we have a lock
3217 : : * on the relation associated with the tuple). Any failure is reported
3218 : : * via ereport().
3219 : : */
3220 : : void
347 peter@eisentraut.org 3221 : 797847 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
3222 : : {
3223 : : TM_Result result;
3224 : : TM_FailureData tmfd;
3225 : :
8428 tgl@sss.pgh.pa.us 3226 : 797847 : result = heap_delete(relation, tid,
3227 : : GetCurrentCommandId(true),
3228 : : 0,
3229 : : InvalidSnapshot,
3230 : : true /* wait for commit */ ,
3231 : : &tmfd);
9393 3232 [ - + - - : 797847 : switch (result)
- ]
3233 : : {
2760 andres@anarazel.de 3234 :UBC 0 : case TM_SelfModified:
3235 : : /* Tuple was already updated in current command? */
8484 tgl@sss.pgh.pa.us 3236 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
3237 : : break;
3238 : :
2760 andres@anarazel.de 3239 :CBC 797847 : case TM_Ok:
3240 : : /* done successfully */
9393 tgl@sss.pgh.pa.us 3241 : 797847 : break;
3242 : :
2760 andres@anarazel.de 3243 :UBC 0 : case TM_Updated:
8484 tgl@sss.pgh.pa.us 3244 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
3245 : : break;
3246 : :
2760 andres@anarazel.de 3247 : 0 : case TM_Deleted:
3248 [ # # ]: 0 : elog(ERROR, "tuple concurrently deleted");
3249 : : break;
3250 : :
9393 tgl@sss.pgh.pa.us 3251 : 0 : default:
8484 3252 [ # # ]: 0 : elog(ERROR, "unrecognized heap_delete status: %u", result);
3253 : : break;
3254 : : }
9393 tgl@sss.pgh.pa.us 3255 :CBC 797847 : }
3256 : :
3257 : : /*
3258 : : * heap_update - replace a tuple
3259 : : *
3260 : : * See table_tuple_update() for an explanation of the parameters, except that
3261 : : * this routine directly takes a tuple rather than a slot.
3262 : : *
3263 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3264 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3265 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3266 : : * generated by another transaction).
3267 : : */
3268 : : TM_Result
347 peter@eisentraut.org 3269 : 2395406 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
3270 : : CommandId cid, uint32 options, Snapshot crosscheck, bool wait,
3271 : : TM_FailureData *tmfd, LockTupleMode *lockmode,
3272 : : TU_UpdateIndexes *update_indexes)
3273 : : {
3274 : : TM_Result result;
8061 tgl@sss.pgh.pa.us 3275 : 2395406 : TransactionId xid = GetCurrentTransactionId();
3276 : : Bitmapset *hot_attrs;
3277 : : Bitmapset *sum_attrs;
3278 : : Bitmapset *key_attrs;
3279 : : Bitmapset *id_attrs;
3280 : : Bitmapset *interesting_attrs;
3281 : : Bitmapset *modified_attrs;
3282 : : ItemId lp;
3283 : : HeapTupleData oldtup;
3284 : : HeapTuple heaptup;
4689 rhaas@postgresql.org 3285 : 2395406 : HeapTuple old_key_tuple = NULL;
3286 : 2395406 : bool old_key_copied = false;
189 alvherre@kurilemu.de 3287 : 2395406 : bool walLogical = (options & TABLE_UPDATE_NO_LOGICAL) == 0;
3288 : : Page page,
3289 : : newpage;
3290 : : BlockNumber block;
3291 : : MultiXactStatus mxact_status;
3292 : : Buffer buffer,
3293 : : newbuf,
5592 rhaas@postgresql.org 3294 : 2395406 : vmbuffer = InvalidBuffer,
3295 : 2395406 : vmbuffer_new = InvalidBuffer;
89 melanieplageman@gmai 3296 : 2395406 : bool unlock_vmbuffer = false;
3297 : 2395406 : bool unlock_vmbuffer_new = false;
3298 : : bool need_toast;
3299 : : Size newtupsize,
3300 : : pagefree;
7835 tgl@sss.pgh.pa.us 3301 : 2395406 : bool have_tuple_lock = false;
3302 : : bool iscombo;
6962 3303 : 2395406 : bool use_hot_update = false;
1302 tomas.vondra@postgre 3304 : 2395406 : bool summarized_update = false;
3305 : : bool key_intact;
89 melanieplageman@gmai 3306 : 2395406 : bool clear_all_visible = false;
3307 : 2395406 : bool clear_all_visible_new = false;
3308 : 2395406 : bool vmbuffer_modified = false;
3309 : 2395406 : bool vmbuffer_new_modified = false;
3310 : : bool checked_lockers;
3311 : : bool locker_remains;
1701 akapila@postgresql.o 3312 : 2395406 : bool id_has_external = false;
3313 : : TransactionId xmax_new_tuple,
3314 : : xmax_old_tuple;
3315 : : uint16 infomask_old_tuple,
3316 : : infomask2_old_tuple,
3317 : : infomask_new_tuple,
3318 : : infomask2_new_tuple;
3319 : :
10627 bruce@momjian.us 3320 [ - + ]: 2395406 : Assert(ItemPointerIsValid(otid));
3321 : :
3322 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1981 tgl@sss.pgh.pa.us 3323 [ - + ]: 2395406 : Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
3324 : : RelationGetNumberOfAttributes(relation));
3325 : :
500 nathan@postgresql.or 3326 : 2395406 : AssertHasSnapshotForToast(relation);
3327 : :
3328 : : /*
3329 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
3330 : : * Other workers might need that combo CID for visibility checks, and we
3331 : : * have no provision for broadcasting it to them.
3332 : : */
4183 rhaas@postgresql.org 3333 [ - + ]: 2395406 : if (IsInParallelMode())
4183 rhaas@postgresql.org 3334 [ # # ]:UBC 0 : ereport(ERROR,
3335 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3336 : : errmsg("cannot update tuples during a parallel operation")));
3337 : :
3338 : : #ifdef USE_ASSERT_CHECKING
748 noah@leadboat.com 3339 :CBC 2395406 : check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3340 : : #endif
3341 : :
3342 : : /*
3343 : : * Fetch the list of attributes to be checked for various operations.
3344 : : *
3345 : : * For HOT considerations, this is wasted effort if we fail to update or
3346 : : * have to put the new tuple on a different page. But we must compute the
3347 : : * list before obtaining buffer lock --- in the worst case, if we are
3348 : : * doing an update on one of the relevant system catalogs, we could
3349 : : * deadlock if we try to fetch the list later. In any case, the relcache
3350 : : * caches the data so this is usually pretty cheap.
3351 : : *
3352 : : * We also need columns used by the replica identity and columns that are
3353 : : * considered the "key" of rows in the table.
3354 : : *
3355 : : * Note that we get copies of each bitmap, so we need not worry about
3356 : : * relcache flush happening midway through.
3357 : : */
1302 tomas.vondra@postgre 3358 : 2395406 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3359 : : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3360 : 2395406 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3361 : : INDEX_ATTR_BITMAP_SUMMARIZED);
4689 rhaas@postgresql.org 3362 : 2395406 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3363 : 2395406 : id_attrs = RelationGetIndexAttrBitmap(relation,
3364 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
1781 pg@bowt.ie 3365 : 2395406 : interesting_attrs = NULL;
3366 : 2395406 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
1302 tomas.vondra@postgre 3367 : 2395406 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
1781 pg@bowt.ie 3368 : 2395406 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3369 : 2395406 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3370 : :
5592 rhaas@postgresql.org 3371 : 2395406 : block = ItemPointerGetBlockNumber(otid);
520 michael@paquier.xyz 3372 : 2395406 : INJECTION_POINT("heap_update-before-pin", NULL);
5592 rhaas@postgresql.org 3373 : 2395406 : buffer = ReadBuffer(relation, block);
3827 kgrittn@postgresql.o 3374 : 2395406 : page = BufferGetPage(buffer);
3375 : :
3376 : : /*
3377 : : * Before locking the buffer, pin the visibility map page if it appears to
3378 : : * be necessary. Since we haven't got the lock yet, someone else might be
3379 : : * in the middle of changing this, so we'll need to recheck after we have
3380 : : * the lock.
3381 : : */
5592 rhaas@postgresql.org 3382 [ + + ]: 2395406 : if (PageIsAllVisible(page))
3383 : 2615 : visibilitymap_pin(relation, block, &vmbuffer);
3384 : :
10163 vadim4o@yahoo.com 3385 : 2395406 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3386 : :
6665 tgl@sss.pgh.pa.us 3387 : 2395406 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3388 : :
3389 : : /*
3390 : : * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3391 : : * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3392 : : * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3393 : : * of which indicates concurrent pruning.
3394 : : *
3395 : : * Failing with TM_Updated would be most accurate. However, unlike other
3396 : : * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3397 : : * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3398 : : * does matter to SQL statements UPDATE and MERGE, those SQL statements
3399 : : * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3400 : : * TM_Updated and TM_Deleted affects only the wording of error messages.
3401 : : * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3402 : : * the specification of when tmfd->ctid is valid. Second, it creates
3403 : : * error log evidence that we took this branch.
3404 : : *
3405 : : * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3406 : : * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3407 : : * unrelated row, we'll fail with "duplicate key value violates unique".
3408 : : * XXX if otid is the live, newer version of the newtup row, we'll discard
3409 : : * changes originating in versions of this catalog row after the version
3410 : : * the caller got from syscache. See syscache-update-pruned.spec.
3411 : : */
625 noah@leadboat.com 3412 [ + + ]: 2395406 : if (!ItemIdIsNormal(lp))
3413 : : {
3414 [ - + ]: 1 : Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
3415 : :
3416 : 1 : UnlockReleaseBuffer(buffer);
3417 [ - + ]: 1 : Assert(!have_tuple_lock);
3418 [ + - ]: 1 : if (vmbuffer != InvalidBuffer)
3419 : 1 : ReleaseBuffer(vmbuffer);
3420 : 1 : tmfd->ctid = *otid;
3421 : 1 : tmfd->xmax = InvalidTransactionId;
3422 : 1 : tmfd->cmax = InvalidCommandId;
3423 : 1 : *update_indexes = TU_None;
3424 : :
3425 : 1 : bms_free(hot_attrs);
3426 : 1 : bms_free(sum_attrs);
3427 : 1 : bms_free(key_attrs);
3428 : 1 : bms_free(id_attrs);
3429 : : /* modified_attrs not yet initialized */
3430 : 1 : bms_free(interesting_attrs);
3431 : 1 : return TM_Deleted;
3432 : : }
3433 : :
3434 : : /*
3435 : : * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3436 : : * properly.
3437 : : */
5001 alvherre@alvh.no-ip. 3438 : 2395405 : oldtup.t_tableOid = RelationGetRelid(relation);
6665 tgl@sss.pgh.pa.us 3439 : 2395405 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
10181 vadim4o@yahoo.com 3440 : 2395405 : oldtup.t_len = ItemIdGetLength(lp);
3441 : 2395405 : oldtup.t_self = *otid;
3442 : :
3443 : : /* the new tuple is ready, except for this: */
5001 alvherre@alvh.no-ip. 3444 : 2395405 : newtup->t_tableOid = RelationGetRelid(relation);
3445 : :
3446 : : /*
3447 : : * Determine columns modified by the update. Additionally, identify
3448 : : * whether any of the unmodified replica identity key attributes in the
3449 : : * old tuple is externally stored or not. This is required because for
3450 : : * such attributes the flattened value won't be WAL logged as part of the
3451 : : * new tuple so we must include it as part of the old_key_tuple. See
3452 : : * ExtractReplicaIdentity.
3453 : : */
1701 akapila@postgresql.o 3454 : 2395405 : modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3455 : : id_attrs, &oldtup,
3456 : : newtup, &id_has_external);
3457 : :
3458 : : /*
3459 : : * If we're not updating any "key" column, we can grab a weaker lock type.
3460 : : * This allows for more concurrency when we are running simultaneously
3461 : : * with foreign key checks.
3462 : : *
3463 : : * Note that if a column gets detoasted while executing the update, but
3464 : : * the value ends up being the same, this test will fail and we will use
3465 : : * the stronger lock. This is acceptable; the important case to optimize
3466 : : * is updates that don't manipulate key columns, not those that
3467 : : * serendipitously arrive at the same key values.
3468 : : */
3484 alvherre@alvh.no-ip. 3469 [ + + ]: 2395405 : if (!bms_overlap(modified_attrs, key_attrs))
3470 : : {
3105 simon@2ndQuadrant.co 3471 : 2389951 : *lockmode = LockTupleNoKeyExclusive;
5010 alvherre@alvh.no-ip. 3472 : 2389951 : mxact_status = MultiXactStatusNoKeyUpdate;
3473 : 2389951 : key_intact = true;
3474 : :
3475 : : /*
3476 : : * If this is the first possibly-multixact-able operation in the
3477 : : * current transaction, set my per-backend OldestMemberMXactId
3478 : : * setting. We can be certain that the transaction will never become a
3479 : : * member of any older MultiXactIds than that. (We have to do this
3480 : : * even if we end up just using our own TransactionId below, since
3481 : : * some other backend could incorporate our XID into a MultiXact
3482 : : * immediately afterwards.)
3483 : : */
3484 : 2389951 : MultiXactIdSetOldestMember();
3485 : : }
3486 : : else
3487 : : {
3105 simon@2ndQuadrant.co 3488 : 5454 : *lockmode = LockTupleExclusive;
5010 alvherre@alvh.no-ip. 3489 : 5454 : mxact_status = MultiXactStatusUpdate;
3490 : 5454 : key_intact = false;
3491 : : }
3492 : :
3493 : : /*
3494 : : * Note: beyond this point, use oldtup not otid to refer to old tuple.
3495 : : * otid may very well point at newtup->t_self, which we will overwrite
3496 : : * with the new tuple's location, so there's great risk of confusion if we
3497 : : * use otid anymore.
3498 : : */
3499 : :
10163 vadim4o@yahoo.com 3500 : 1 : l2:
5010 alvherre@alvh.no-ip. 3501 : 2395406 : checked_lockers = false;
3502 : 2395406 : locker_remains = false;
4830 rhaas@postgresql.org 3503 : 2395406 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3504 : :
3505 : : /* see below about the "no wait" case */
914 akorotkov@postgresql 3506 [ + + - + ]: 2395406 : Assert(result != TM_BeingModified || wait);
3507 : :
2760 andres@anarazel.de 3508 [ - + ]: 2395406 : if (result == TM_Invisible)
3509 : : {
7500 tgl@sss.pgh.pa.us 3510 :UBC 0 : UnlockReleaseBuffer(buffer);
4089 3511 [ # # ]: 0 : ereport(ERROR,
3512 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3513 : : errmsg("attempted to update invisible tuple")));
3514 : : }
914 akorotkov@postgresql 3515 [ + + + - ]:CBC 2395406 : else if (result == TM_BeingModified && wait)
3516 : : {
3517 : : TransactionId xwait;
3518 : : uint16 infomask;
5010 alvherre@alvh.no-ip. 3519 : 36488 : bool can_continue = false;
3520 : :
3521 : : /*
3522 : : * XXX note that we don't consider the "no wait" case here. This
3523 : : * isn't a problem currently because no caller uses that case, but it
3524 : : * should be fixed if such a caller is introduced. It wasn't a
3525 : : * problem previously because this code would always wait, but now
3526 : : * that some tuple locks do not conflict with one of the lock modes we
3527 : : * use, it is possible that this case is interesting to handle
3528 : : * specially.
3529 : : *
3530 : : * This may cause failures with third-party code that calls
3531 : : * heap_update directly.
3532 : : */
3533 : :
3534 : : /* must copy state data before unlocking buffer */
3535 : 36488 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
7835 tgl@sss.pgh.pa.us 3536 : 36488 : infomask = oldtup.t_data->t_infomask;
3537 : :
3538 : : /*
3539 : : * Now we have to do something about the existing locker. If it's a
3540 : : * multi, sleep on it; we might be awakened before it is completely
3541 : : * gone (or even not sleep at all in some cases); we need to preserve
3542 : : * it as locker, unless it is gone completely.
3543 : : *
3544 : : * If it's not a multi, we need to check for sleeping conditions
3545 : : * before actually going to sleep. If the update doesn't conflict
3546 : : * with the locks, we just continue without sleeping (but making sure
3547 : : * it is preserved).
3548 : : *
3549 : : * Before sleeping, we need to acquire tuple lock to establish our
3550 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
3551 : : * release us when we are next-in-line for the tuple. Note we must
3552 : : * not acquire the tuple lock until we're sure we're going to sleep;
3553 : : * otherwise we're open for race conditions with other transactions
3554 : : * holding the tuple lock which sleep on us.
3555 : : *
3556 : : * If we are forced to "start over" below, we keep the tuple lock;
3557 : : * this arranges that we stay at the head of the line while rechecking
3558 : : * tuple state.
3559 : : */
7837 3560 [ + + ]: 36488 : if (infomask & HEAP_XMAX_IS_MULTI)
3561 : : {
3562 : : TransactionId update_xact;
3563 : : int remain;
2673 alvherre@alvh.no-ip. 3564 : 179 : bool current_is_member = false;
3565 : :
4203 3566 [ + + ]: 179 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3567 : : *lockmode, ¤t_is_member))
3568 : : {
3569 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3570 : :
3571 : : /*
3572 : : * Acquire the lock, if necessary (but skip it when we're
3573 : : * requesting a lock and already have one; avoids deadlock).
3574 : : */
2673 3575 [ - + ]: 8 : if (!current_is_member)
2673 alvherre@alvh.no-ip. 3576 :UBC 0 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3577 : : LockWaitBlock, &have_tuple_lock);
3578 : :
3579 : : /* wait for multixact */
4203 alvherre@alvh.no-ip. 3580 :CBC 8 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3581 : : relation, &oldtup.t_self, XLTW_Update,
3582 : : &remain);
3583 : 8 : checked_lockers = true;
3584 : 8 : locker_remains = remain != 0;
3585 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3586 : :
3587 : : /*
3588 : : * If xwait had just locked the tuple then some other xact
3589 : : * could update this tuple before we get to this point. Check
3590 : : * for xmax change, and start over if so.
3591 : : */
3592 [ + - ]: 8 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3593 [ - + ]: 8 : infomask) ||
3400 tgl@sss.pgh.pa.us 3594 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3595 : : xwait))
4203 alvherre@alvh.no-ip. 3596 :UBC 0 : goto l2;
3597 : : }
3598 : :
3599 : : /*
3600 : : * Note that the multixact may not be done by now. It could have
3601 : : * surviving members; our own xact or other subxacts of this
3602 : : * backend, and also any other concurrent transaction that locked
3603 : : * the tuple with LockTupleKeyShare if we only got
3604 : : * LockTupleNoKeyExclusive. If this is the case, we have to be
3605 : : * careful to mark the updated tuple with the surviving members in
3606 : : * Xmax.
3607 : : *
3608 : : * Note that there could have been another update in the
3609 : : * MultiXact. In that case, we need to check whether it committed
3610 : : * or aborted. If it aborted we are safe to update it again;
3611 : : * otherwise there is an update conflict, and we have to return
3612 : : * TableTuple{Deleted, Updated} below.
3613 : : *
3614 : : * In the LockTupleExclusive case, we still need to preserve the
3615 : : * surviving members: those would include the tuple locks we had
3616 : : * before this one, which are important to keep in case this
3617 : : * subxact aborts.
3618 : : */
5010 alvherre@alvh.no-ip. 3619 [ + + ]:CBC 179 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3620 : 8 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3621 : : else
4203 3622 : 171 : update_xact = InvalidTransactionId;
3623 : :
3624 : : /*
3625 : : * There was no UPDATE in the MultiXact; or it aborted. No
3626 : : * TransactionIdIsInProgress() call needed here, since we called
3627 : : * MultiXactIdWait() above.
3628 : : */
5010 3629 [ + + + + ]: 187 : if (!TransactionIdIsValid(update_xact) ||
3630 : 8 : TransactionIdDidAbort(update_xact))
3631 : 172 : can_continue = true;
3632 : : }
4203 3633 [ + + ]: 36309 : else if (TransactionIdIsCurrentTransactionId(xwait))
3634 : : {
3635 : : /*
3636 : : * The only locker is ourselves; we can avoid grabbing the tuple
3637 : : * lock here, but must preserve our locking information.
3638 : : */
3639 : 36196 : checked_lockers = true;
3640 : 36196 : locker_remains = true;
3641 : 36196 : can_continue = true;
3642 : : }
3643 [ + + + + ]: 113 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3644 : : {
3645 : : /*
3646 : : * If it's just a key-share locker, and we're not changing the key
3647 : : * columns, we don't need to wait for it to end; but we need to
3648 : : * preserve it as locker.
3649 : : */
3650 : 30 : checked_lockers = true;
3651 : 30 : locker_remains = true;
3652 : 30 : can_continue = true;
3653 : : }
3654 : : else
3655 : : {
3656 : : /*
3657 : : * Wait for regular transaction to end; but first, acquire tuple
3658 : : * lock.
3659 : : */
3660 : 83 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3105 simon@2ndQuadrant.co 3661 : 83 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3662 : : LockWaitBlock, &have_tuple_lock);
4203 alvherre@alvh.no-ip. 3663 : 83 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3664 : : XLTW_Update);
3665 : 83 : checked_lockers = true;
3666 : 83 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3667 : :
3668 : : /*
3669 : : * xwait is done, but if xwait had just locked the tuple then some
3670 : : * other xact could update this tuple before we get to this point.
3671 : : * Check for xmax change, and start over if so.
3672 : : */
3673 [ + + - + ]: 165 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3674 : 82 : !TransactionIdEquals(xwait,
3675 : : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3676 : 1 : goto l2;
3677 : :
3678 : : /* Otherwise check if it committed or aborted */
3679 : 82 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3680 [ + + ]: 82 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
5010 3681 : 23 : can_continue = true;
3682 : : }
3683 : :
2760 andres@anarazel.de 3684 [ + + ]: 36487 : if (can_continue)
3685 : 36421 : result = TM_Ok;
2058 alvherre@alvh.no-ip. 3686 [ + + ]: 66 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
2760 andres@anarazel.de 3687 : 60 : result = TM_Updated;
3688 : : else
3689 : 6 : result = TM_Deleted;
3690 : : }
3691 : :
3692 : : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3693 [ + + ]: 2395405 : if (result != TM_Ok)
3694 : : {
3695 [ + + + + : 180 : Assert(result == TM_SelfModified ||
- + - - ]
3696 : : result == TM_Updated ||
3697 : : result == TM_Deleted ||
3698 : : result == TM_BeingModified);
7723 tgl@sss.pgh.pa.us 3699 [ - + ]: 180 : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
2760 andres@anarazel.de 3700 [ + + - + ]: 180 : Assert(result != TM_Updated ||
3701 : : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3702 : : }
3703 : :
1049 heikki.linnakangas@i 3704 [ + + + - ]: 2395405 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3705 : : {
3706 : : /* Perform additional check for transaction-snapshot mode RI updates */
3707 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3708 : 1 : result = TM_Updated;
3709 : : }
3710 : :
3711 [ + + ]: 2395405 : if (result != TM_Ok)
3712 : : {
2760 andres@anarazel.de 3713 : 181 : tmfd->ctid = oldtup.t_data->t_ctid;
3714 : 181 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3715 [ + + ]: 181 : if (result == TM_SelfModified)
3716 : 69 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3717 : : else
3718 : 112 : tmfd->cmax = InvalidCommandId;
914 akorotkov@postgresql 3719 : 181 : UnlockReleaseBuffer(buffer);
7835 tgl@sss.pgh.pa.us 3720 [ + + ]: 181 : if (have_tuple_lock)
3105 simon@2ndQuadrant.co 3721 : 59 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
5592 rhaas@postgresql.org 3722 [ - + ]: 181 : if (vmbuffer != InvalidBuffer)
5592 rhaas@postgresql.org 3723 :UBC 0 : ReleaseBuffer(vmbuffer);
1302 tomas.vondra@postgre 3724 :CBC 181 : *update_indexes = TU_None;
3725 : :
6962 tgl@sss.pgh.pa.us 3726 : 181 : bms_free(hot_attrs);
1302 tomas.vondra@postgre 3727 : 181 : bms_free(sum_attrs);
5010 alvherre@alvh.no-ip. 3728 : 181 : bms_free(key_attrs);
3701 tgl@sss.pgh.pa.us 3729 : 181 : bms_free(id_attrs);
3484 alvherre@alvh.no-ip. 3730 : 181 : bms_free(modified_attrs);
3731 : 181 : bms_free(interesting_attrs);
10163 vadim4o@yahoo.com 3732 : 181 : return result;
3733 : : }
3734 : :
3735 : : /*
3736 : : * If we didn't pin the visibility map page and the page has become all
3737 : : * visible while we were busy locking the buffer, or during some
3738 : : * subsequent window during which we had it unlocked, we'll have to unlock
3739 : : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3740 : : * bit unfortunate, especially since we'll now have to recheck whether the
3741 : : * tuple has been locked or updated under us, but hopefully it won't
3742 : : * happen very often.
3743 : : */
5586 rhaas@postgresql.org 3744 [ + + - + ]: 2395224 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3745 : : {
5586 rhaas@postgresql.org 3746 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3747 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
3748 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5494 3749 : 0 : goto l2;
3750 : : }
3751 : :
3752 : : /* Fill in transaction status data */
3753 : :
3754 : : /*
3755 : : * If the tuple we're updating is locked, we need to preserve the locking
3756 : : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3757 : : */
5010 alvherre@alvh.no-ip. 3758 :CBC 2395224 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3759 : 2395224 : oldtup.t_data->t_infomask,
3760 : 2395224 : oldtup.t_data->t_infomask2,
3761 : : xid, *lockmode, true,
3762 : : &xmax_old_tuple, &infomask_old_tuple,
3763 : : &infomask2_old_tuple);
3764 : :
3765 : : /*
3766 : : * And also prepare an Xmax value for the new copy of the tuple. If there
3767 : : * was no xmax previously, or there was one but all lockers are now gone,
3768 : : * then use InvalidTransactionId; otherwise, get the xmax from the old
3769 : : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3770 : : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3771 : : */
3772 [ + + + - ]: 2431622 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3762 3773 [ + + ]: 72796 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
5010 3774 [ - + ]: 36227 : (checked_lockers && !locker_remains))
3775 : 2358826 : xmax_new_tuple = InvalidTransactionId;
3776 : : else
3777 : 36398 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3778 : :
3779 [ + + ]: 2395224 : if (!TransactionIdIsValid(xmax_new_tuple))
3780 : : {
3781 : 2358826 : infomask_new_tuple = HEAP_XMAX_INVALID;
3782 : 2358826 : infomask2_new_tuple = 0;
3783 : : }
3784 : : else
3785 : : {
3786 : : /*
3787 : : * If we found a valid Xmax for the new tuple, then the infomask bits
3788 : : * to use on the new tuple depend on what was there on the old one.
3789 : : * Note that since we're doing an update, the only possibility is that
3790 : : * the lockers had FOR KEY SHARE lock.
3791 : : */
3792 [ + + ]: 36398 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3793 : : {
3794 : 172 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3795 : : &infomask2_new_tuple);
3796 : : }
3797 : : else
3798 : : {
3799 : 36226 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3800 : 36226 : infomask2_new_tuple = 0;
3801 : : }
3802 : : }
3803 : :
3804 : : /*
3805 : : * Prepare the new tuple with the appropriate initial values of Xmin and
3806 : : * Xmax, as well as initial infomask bits as computed above.
3807 : : */
10181 vadim4o@yahoo.com 3808 : 2395224 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
6962 tgl@sss.pgh.pa.us 3809 : 2395224 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
8061 3810 : 2395224 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
8885 bruce@momjian.us 3811 : 2395224 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
5010 alvherre@alvh.no-ip. 3812 : 2395224 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3813 : 2395224 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3814 : 2395224 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3815 : :
3816 : : /*
3817 : : * Replace cid with a combo CID if necessary. Note that we already put
3818 : : * the plain cid into the new tuple.
3819 : : */
7185 tgl@sss.pgh.pa.us 3820 : 2395224 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3821 : :
3822 : : /*
3823 : : * If the toaster needs to be activated, OR if the new tuple will not fit
3824 : : * on the same page as the old, then we need to release the content lock
3825 : : * (but not the pin!) on the old tuple's buffer while we are off doing
3826 : : * TOAST and/or table-file-extension work. We must mark the old tuple to
3827 : : * show that it's locked, else other processes may try to update it
3828 : : * themselves.
3829 : : *
3830 : : * We need to invoke the toaster if there are already any out-of-line
3831 : : * toasted values present, or if the new tuple is over-threshold.
3832 : : */
4971 kgrittn@postgresql.o 3833 [ - + ]: 2395224 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
4971 kgrittn@postgresql.o 3834 [ # # ]:UBC 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3835 : : {
3836 : : /* toast table entries should never be recursively toasted */
7132 tgl@sss.pgh.pa.us 3837 [ # # ]: 0 : Assert(!HeapTupleHasExternal(&oldtup));
3838 [ # # ]: 0 : Assert(!HeapTupleHasExternal(newtup));
3839 : 0 : need_toast = false;
3840 : : }
3841 : : else
7132 tgl@sss.pgh.pa.us 3842 [ + + ]:CBC 7185004 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3843 [ + + ]: 4789780 : HeapTupleHasExternal(newtup) ||
3844 [ + + ]: 2394524 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3845 : :
6665 3846 : 2395224 : pagefree = PageGetHeapFreeSpace(page);
3847 : :
7190 3848 : 2395224 : newtupsize = MAXALIGN(newtup->t_len);
3849 : :
9280 3850 [ + + + + ]: 2395224 : if (need_toast || newtupsize > pagefree)
9531 vadim4o@yahoo.com 3851 : 2213036 : {
3852 : : TransactionId xmax_lock_old_tuple;
3853 : : uint16 infomask_lock_old_tuple,
3854 : : infomask2_lock_old_tuple;
3738 andres@anarazel.de 3855 : 2213036 : bool cleared_all_frozen = false;
3856 : :
3857 : : /*
3858 : : * To prevent concurrent sessions from updating the tuple, we have to
3859 : : * temporarily mark it locked, while we release the page-level lock.
3860 : : *
3861 : : * To satisfy the rule that any xid potentially appearing in a buffer
3862 : : * written out to disk, we unfortunately have to WAL log this
3863 : : * temporary modification. We can reuse xl_heap_lock for this
3864 : : * purpose. If we crash/error before following through with the
3865 : : * actual update, xmax will be of an aborted transaction, allowing
3866 : : * other sessions to proceed.
3867 : : */
3868 : :
3869 : : /*
3870 : : * Compute xmax / infomask appropriate for locking the tuple. This has
3871 : : * to be done separately from the combo that's going to be used for
3872 : : * updating, because the potentially created multixact would otherwise
3873 : : * be wrong.
3874 : : */
3741 3875 : 2213036 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3876 : 2213036 : oldtup.t_data->t_infomask,
3877 : 2213036 : oldtup.t_data->t_infomask2,
3878 : : xid, *lockmode, false,
3879 : : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3880 : : &infomask2_lock_old_tuple);
3881 : :
3882 [ - + ]: 2213036 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3883 : :
89 melanieplageman@gmai 3884 [ + + ]: 2213036 : if (PageIsAllVisible(page))
3885 : : {
3886 : 1574 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
3887 : 1574 : unlock_vmbuffer = true;
3888 : : }
3889 : :
3741 andres@anarazel.de 3890 : 2213036 : START_CRIT_SECTION();
3891 : :
3892 : : /* Clear obsolete visibility flags ... */
5010 alvherre@alvh.no-ip. 3893 : 2213036 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3894 : 2213036 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6962 tgl@sss.pgh.pa.us 3895 : 2213036 : HeapTupleClearHotUpdated(&oldtup);
3896 : : /* ... and store info about transaction updating this tuple */
3741 andres@anarazel.de 3897 [ - + ]: 2213036 : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3898 : 2213036 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3899 : 2213036 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3900 : 2213036 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
7185 tgl@sss.pgh.pa.us 3901 : 2213036 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3902 : :
3903 : : /* temporarily make it look not-updated, but locked */
7631 3904 : 2213036 : oldtup.t_data->t_ctid = oldtup.t_self;
3905 : :
3906 : : /*
3907 : : * Clear all-frozen bit on visibility map if needed. We could
3908 : : * immediately reset ALL_VISIBLE, but given that the WAL logging
3909 : : * overhead would be unchanged, that doesn't seem necessarily
3910 : : * worthwhile.
3911 : : */
89 melanieplageman@gmai 3912 [ + + ]: 2213036 : if (PageIsAllVisible(page))
3913 : : {
3914 : : /* It's possible all-frozen was already clear */
89 melanieplageman@gmai 3915 [ + + ]:GNC 1574 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
3916 : : VISIBILITYMAP_ALL_FROZEN))
89 melanieplageman@gmai 3917 :CBC 799 : cleared_all_frozen = true;
3918 : : }
3919 : :
3741 andres@anarazel.de 3920 : 2213036 : MarkBufferDirty(buffer);
3921 : :
3922 [ + + + + : 2213036 : if (RelationNeedsWAL(relation))
+ - + + ]
3923 : : {
3924 : : xl_heap_lock xlrec;
3925 : : XLogRecPtr recptr;
3926 : :
3927 : 2202900 : XLogBeginInsert();
89 melanieplageman@gmai 3928 : 2202900 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buffer, REGBUF_STANDARD);
3929 : :
3741 andres@anarazel.de 3930 : 2202900 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
1280 pg@bowt.ie 3931 : 2202900 : xlrec.xmax = xmax_lock_old_tuple;
3741 andres@anarazel.de 3932 : 4405800 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3933 : 2202900 : oldtup.t_data->t_infomask2);
3738 3934 : 2202900 : xlrec.flags =
3935 : 2202900 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
608 peter@eisentraut.org 3936 : 2202900 : XLogRegisterData(&xlrec, SizeOfHeapLock);
3937 : :
89 melanieplageman@gmai 3938 [ + + ]: 2202900 : if (cleared_all_frozen)
3939 : 799 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
3940 : :
3741 andres@anarazel.de 3941 : 2202900 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3942 : 2202900 : PageSetLSN(page, recptr);
3943 : :
89 melanieplageman@gmai 3944 [ + + ]: 2202900 : if (cleared_all_frozen)
3945 : 799 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
3946 : : }
3947 : :
3741 andres@anarazel.de 3948 [ - + ]: 2213036 : END_CRIT_SECTION();
3949 : :
3950 : : /* release VM lock first, since it covers many heap blocks */
89 melanieplageman@gmai 3951 [ + + ]: 2213036 : if (unlock_vmbuffer)
3952 : 1574 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
3953 : 2213036 : unlock_vmbuffer = false;
3954 : :
9531 vadim4o@yahoo.com 3955 : 2213036 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3956 : :
3957 : : /*
3958 : : * Let the toaster do its thing, if needed.
3959 : : *
3960 : : * Note: below this point, heaptup is the data we actually intend to
3961 : : * store into the relation; newtup is the caller's original untoasted
3962 : : * data.
3963 : : */
9401 tgl@sss.pgh.pa.us 3964 [ + + ]: 2213036 : if (need_toast)
3965 : : {
3966 : : /*
3967 : : * If logical decoding is not needed, suppress it for the TOAST
3968 : : * tuples too. We never skip the FSM here.
3969 : : */
31 msawada@postgresql.o 3970 [ + + ]: 2245 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
3971 : : walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
7631 tgl@sss.pgh.pa.us 3972 : 2245 : newtupsize = MAXALIGN(heaptup->t_len);
3973 : : }
3974 : : else
3975 : 2210791 : heaptup = newtup;
3976 : :
3977 : : /*
3978 : : * Now, do we need a new page for the tuple, or not? This is a bit
3979 : : * tricky since someone else could have added tuples to the page while
3980 : : * we weren't looking. We have to recheck the available space after
3981 : : * reacquiring the buffer lock. But don't bother to do that if the
3982 : : * former amount of free space is still not enough; it's unlikely
3983 : : * there's more free now than before.
3984 : : *
3985 : : * What's more, if we need to get a new page, we will need to acquire
3986 : : * buffer locks on both old and new pages. To avoid deadlock against
3987 : : * some other backend trying to get the same two locks in the other
3988 : : * order, we must be consistent about the order we get the locks in.
3989 : : * We use the rule "lock the lower-numbered page of the relation
3990 : : * first". To implement this, we must do RelationGetBufferForTuple
3991 : : * while not holding the lock on the old page, and we must rely on it
3992 : : * to get the locks on both pages in the correct order.
3993 : : *
3994 : : * Another consideration is that we need visibility map page pin(s) if
3995 : : * we will have to clear the all-visible flag on either page. If we
3996 : : * call RelationGetBufferForTuple, we rely on it to acquire any such
3997 : : * pins; but if we don't, we have to handle that here. Hence we need
3998 : : * a loop.
3999 : : */
4000 : : for (;;)
4001 : : {
2008 4002 [ + + ]: 2213036 : if (newtupsize > pagefree)
4003 : : {
4004 : : /* It doesn't fit, must use RelationGetBufferForTuple. */
4005 : 2212182 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
4006 : : buffer, 0, NULL,
4007 : : &vmbuffer_new, &vmbuffer,
4008 : : 0);
4009 : : /* We're all done. */
4010 : 2212182 : break;
4011 : : }
4012 : : /* Acquire VM page pin if needed and we don't have it. */
4013 [ + + - + ]: 854 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2008 tgl@sss.pgh.pa.us 4014 :UBC 0 : visibilitymap_pin(relation, block, &vmbuffer);
4015 : : /* Re-acquire the lock on the old tuple's page. */
9280 tgl@sss.pgh.pa.us 4016 :CBC 854 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4017 : : /* Re-check using the up-to-date free space */
6665 4018 : 854 : pagefree = PageGetHeapFreeSpace(page);
2008 4019 [ + - ]: 854 : if (newtupsize > pagefree ||
4020 [ + + - + ]: 854 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
4021 : : {
4022 : : /*
4023 : : * Rats, it doesn't fit anymore, or somebody just now set the
4024 : : * all-visible flag. We must now unlock and loop to avoid
4025 : : * deadlock. Fortunately, this path should seldom be taken.
4026 : : */
9280 tgl@sss.pgh.pa.us 4027 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4028 : : }
4029 : : else
4030 : : {
4031 : : /* We're all done. */
9280 tgl@sss.pgh.pa.us 4032 :CBC 854 : newbuf = buffer;
2008 4033 : 854 : break;
4034 : : }
4035 : : }
4036 : : }
4037 : : else
4038 : : {
4039 : : /* No TOAST work needed, and it'll fit on same page */
9401 4040 : 182188 : newbuf = buffer;
7631 4041 : 182188 : heaptup = newtup;
4042 : : }
4043 : :
211 melanieplageman@gmai 4044 : 2395224 : newpage = BufferGetPage(newbuf);
4045 : :
4046 : : /*
4047 : : * We're about to do the actual update -- check for conflict first, to
4048 : : * avoid possibly having to roll back work we've just done.
4049 : : *
4050 : : * This is safe without a recheck as long as there is no possibility of
4051 : : * another process scanning the pages between this check and the update
4052 : : * being visible to the scan (i.e., exclusive buffer content lock(s) are
4053 : : * continuously held from this point until the tuple update is visible).
4054 : : *
4055 : : * For the new tuple the only check needed is at the relation level, but
4056 : : * since both tuples are in the same relation and the check for oldtup
4057 : : * will include checking the relation level, there is no benefit to a
4058 : : * separate check for the new tuple.
4059 : : */
2008 tmunro@postgresql.or 4060 : 2395224 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
4061 : : BufferGetBlockNumber(buffer));
4062 : :
4063 : : /*
4064 : : * At this point newbuf and buffer are both pinned and locked, and newbuf
4065 : : * has enough space for the new tuple. If they are the same buffer, only
4066 : : * one pin is held.
4067 : : */
4068 : :
6962 tgl@sss.pgh.pa.us 4069 [ + + ]: 2395211 : if (newbuf == buffer)
4070 : : {
4071 : : /*
4072 : : * Since the new tuple is going into the same page, we might be able
4073 : : * to do a HOT update. Check if any of the index columns have been
4074 : : * changed.
4075 : : */
1781 pg@bowt.ie 4076 [ + + ]: 183029 : if (!bms_overlap(modified_attrs, hot_attrs))
4077 : : {
6962 tgl@sss.pgh.pa.us 4078 : 166989 : use_hot_update = true;
4079 : :
4080 : : /*
4081 : : * If none of the columns that are used in hot-blocking indexes
4082 : : * were updated, we can apply HOT, but we do still need to check
4083 : : * if we need to update the summarizing indexes, and update those
4084 : : * indexes if the columns were updated, or we may fail to detect
4085 : : * e.g. value bound changes in BRIN minmax indexes.
4086 : : */
1302 tomas.vondra@postgre 4087 [ + + ]: 166989 : if (bms_overlap(modified_attrs, sum_attrs))
4088 : 2188 : summarized_update = true;
4089 : : }
4090 : : }
4091 : : else
4092 : : {
4093 : : /* Set a hint that the old page could use prune/defrag */
6665 tgl@sss.pgh.pa.us 4094 : 2212182 : PageSetFull(page);
4095 : : }
4096 : :
4097 : : /*
4098 : : * Compute replica identity tuple before entering the critical section so
4099 : : * we don't PANIC upon a memory allocation failure.
4100 : : * ExtractReplicaIdentity() will return NULL if nothing needs to be
4101 : : * logged. Pass old key required as true only if the replica identity key
4102 : : * columns are modified or it has external data.
4103 : : */
3484 alvherre@alvh.no-ip. 4104 : 2395211 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
1701 akapila@postgresql.o 4105 [ + + + + ]: 2395211 : bms_overlap(modified_attrs, id_attrs) ||
4106 : : id_has_external,
3484 alvherre@alvh.no-ip. 4107 : 2395211 : &old_key_copied);
4108 : :
89 melanieplageman@gmai 4109 : 2395211 : clear_all_visible = PageIsAllVisible(page);
4110 [ + + + + ]: 2395211 : clear_all_visible_new = newbuf != buffer && PageIsAllVisible(newpage);
4111 : :
4112 : : /*
4113 : : * Clear PD_ALL_VISIBLE flags and reset visibility map bits for any heap
4114 : : * pages that were all-visible. If there are two heap pages, we may need
4115 : : * to clear VM bits for both.
4116 : : */
4117 [ + + + + ]: 2395211 : if (clear_all_visible && clear_all_visible_new &&
4118 [ + - ]: 181 : vmbuffer_new == vmbuffer)
4119 : : {
4120 : : /*
4121 : : * This is the more complicated case: both the new and old heap pages
4122 : : * are all-visible and both their VM bits are on the same page of the
4123 : : * VM, so we register a single VM buffer as HEAP_UPDATE_BLKREF_VM_NEW
4124 : : * in the WAL record. We must be careful to only lock and register one
4125 : : * buffer, even though we modify it twice -- once for each heap
4126 : : * block's VM bits.
4127 : : */
4128 : 181 : LockBuffer(vmbuffer_new, BUFFER_LOCK_EXCLUSIVE);
4129 : 181 : unlock_vmbuffer_new = true;
4130 : :
4131 : : /* We will not lock or attempt to modify old VM buffer */
4132 : : }
4133 : : else
4134 : : {
4135 : : /*
4136 : : * In all the remaining cases, we will clear at most one heap block's
4137 : : * VM bits per VM page.
4138 : : */
4139 : 4790060 : Buffer vmbuffers[2] = {
4140 [ + + ]: 2395030 : clear_all_visible ? vmbuffer : InvalidBuffer,
4141 [ + + ]: 2395030 : clear_all_visible_new ? vmbuffer_new : InvalidBuffer
4142 : : };
4143 : :
4144 : : /*
4145 : : * When both pages need different VM pages cleared, acquire the VM
4146 : : * buffer locks in VM block order to avoid deadlocks between backends
4147 : : * updating tuples in opposite directions across VM pages.
4148 : : */
4149 [ + + - + : 2395030 : if (clear_all_visible && clear_all_visible_new &&
- - ]
89 melanieplageman@gmai 4150 :UBC 0 : BufferGetBlockNumber(vmbuffers[0]) > BufferGetBlockNumber(vmbuffers[1]))
4151 : : {
4152 : 0 : Buffer swap = vmbuffers[0];
4153 : :
4154 : 0 : vmbuffers[0] = vmbuffers[1];
4155 : 0 : vmbuffers[1] = swap;
4156 : : }
4157 : :
89 melanieplageman@gmai 4158 [ + + + + :CBC 2395030 : Assert((!BufferIsValid(vmbuffers[0]) && !BufferIsValid(vmbuffers[1])) ||
- + ]
4159 : : vmbuffers[0] != vmbuffers[1]);
4160 : :
4161 [ + + ]: 2395030 : if (BufferIsValid(vmbuffers[0]))
4162 : 2433 : LockBuffer(vmbuffers[0], BUFFER_LOCK_EXCLUSIVE);
4163 [ + + ]: 2395030 : if (BufferIsValid(vmbuffers[1]))
4164 : 1282 : LockBuffer(vmbuffers[1], BUFFER_LOCK_EXCLUSIVE);
4165 : :
4166 [ + + ]: 2395030 : if (clear_all_visible)
4167 : 2433 : unlock_vmbuffer = true;
4168 [ + + ]: 2395030 : if (clear_all_visible_new)
4169 : 1282 : unlock_vmbuffer_new = true;
4170 : : }
4171 : :
4172 : : /* NO EREPORT(ERROR) from here till changes are logged */
9404 tgl@sss.pgh.pa.us 4173 : 2395211 : START_CRIT_SECTION();
4174 : :
4175 : : /*
4176 : : * If this transaction commits, the old tuple will become DEAD sooner or
4177 : : * later. Set flag that this page is a candidate for pruning once our xid
4178 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
4179 : : * the subsequent page pruning will be a no-op and the hint will be
4180 : : * cleared.
4181 : : *
4182 : : * We set the new page prunable as well. See heap_insert() for more on why
4183 : : * we do this when inserting tuples.
4184 : : */
6665 4185 [ - + + + : 2395211 : PageSetPrunable(page, xid);
+ + ]
196 melanieplageman@gmai 4186 [ + + ]: 2395211 : if (newbuf != buffer)
4187 [ - + + + : 2212182 : PageSetPrunable(newpage, xid);
+ + ]
4188 : :
6962 tgl@sss.pgh.pa.us 4189 [ + + ]: 2395211 : if (use_hot_update)
4190 : : {
4191 : : /* Mark the old tuple as HOT-updated */
4192 : 166989 : HeapTupleSetHotUpdated(&oldtup);
4193 : : /* And mark the new tuple as heap-only */
4194 : 166989 : HeapTupleSetHeapOnly(heaptup);
4195 : : /* Mark the caller's copy too, in case different from heaptup */
4196 : 166989 : HeapTupleSetHeapOnly(newtup);
4197 : : }
4198 : : else
4199 : : {
4200 : : /* Make sure tuples are correctly marked as not-HOT */
4201 : 2228222 : HeapTupleClearHotUpdated(&oldtup);
4202 : 2228222 : HeapTupleClearHeapOnly(heaptup);
4203 : 2228222 : HeapTupleClearHeapOnly(newtup);
4204 : : }
4205 : :
3400 4206 : 2395211 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4207 : :
4208 : :
4209 : : /* Clear obsolete visibility flags, possibly set by ourselves above... */
3741 andres@anarazel.de 4210 : 2395211 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4211 : 2395211 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4212 : : /* ... and store info about transaction updating this tuple */
4213 [ - + ]: 2395211 : Assert(TransactionIdIsValid(xmax_old_tuple));
4214 : 2395211 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4215 : 2395211 : oldtup.t_data->t_infomask |= infomask_old_tuple;
4216 : 2395211 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4217 : 2395211 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4218 : :
4219 : : /* record address of new tuple in t_ctid of old one */
7631 tgl@sss.pgh.pa.us 4220 : 2395211 : oldtup.t_data->t_ctid = heaptup->t_self;
4221 : :
4222 : : /*
4223 : : * Clear PD_ALL_VISIBLE flags and reset all visibilitymap bits. In all
4224 : : * cases, it's possible that PD_ALL_VISIBLE was set but the corresponding
4225 : : * visibility map bits were already clear.
4226 : : */
89 melanieplageman@gmai 4227 [ + + ]: 2395211 : if (clear_all_visible)
4228 : : {
89 melanieplageman@gmai 4229 [ + - ]:GNC 2614 : if (visibilitymap_clear(relation->rd_locator, block,
4230 : : vmbuffer, VISIBILITYMAP_VALID_BITS))
4231 : : {
4232 : : /*
4233 : : * When old and new heap blocks' VM bits are on the same VM page,
4234 : : * that page is registered in the WAL record only once. If both
4235 : : * heap pages were PD_ALL_VISIBLE and either VM bit needs
4236 : : * clearing, we register the VM buffer as
4237 : : * HEAP_UPDATE_BLKREF_VM_NEW.
4238 : : */
89 melanieplageman@gmai 4239 [ + + + - ]:CBC 2614 : if (clear_all_visible_new && vmbuffer == vmbuffer_new)
4240 : 181 : vmbuffer_new_modified = true;
4241 : : else
4242 : 2433 : vmbuffer_modified = true;
4243 : : }
4244 : :
211 4245 : 2614 : PageClearAllVisible(page);
4246 : : }
89 4247 [ + + ]: 2395211 : if (clear_all_visible_new)
4248 : : {
4249 : : /*
4250 : : * If both heap blocks' VM bits are on the same VM buffer, this will
4251 : : * clear the new heap block's VM bits from the shared vmbuffer.
4252 : : */
89 melanieplageman@gmai 4253 [ + - ]:GNC 1463 : if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(newbuf),
4254 : : vmbuffer_new, VISIBILITYMAP_VALID_BITS))
89 melanieplageman@gmai 4255 :CBC 1463 : vmbuffer_new_modified = true;
4256 : :
211 4257 : 1463 : PageClearAllVisible(newpage);
4258 : : }
4259 : :
7500 tgl@sss.pgh.pa.us 4260 [ + + ]: 2395211 : if (newbuf != buffer)
4261 : 2212182 : MarkBufferDirty(newbuf);
4262 : 2395211 : MarkBufferDirty(buffer);
4263 : :
4264 : : /* XLOG stuff */
5782 rhaas@postgresql.org 4265 [ + + + + : 2395211 : if (RelationNeedsWAL(relation))
+ - + + ]
4266 : : {
4267 : : XLogRecPtr recptr;
4268 : :
4269 : : /*
4270 : : * For logical decoding we need combo CIDs to properly decode the
4271 : : * catalog.
4272 : : */
4689 4273 [ + + + + : 2383366 : if (RelationIsAccessibleInLogicalDecoding(relation))
+ - - + -
- - - + +
+ + - + -
- + + ]
4274 : : {
4275 : 2770 : log_heap_new_cid(relation, &oldtup);
4276 : 2770 : log_heap_new_cid(relation, heaptup);
4277 : : }
4278 : :
4279 [ + + + + ]: 2383366 : recptr = log_heap_update(relation, buffer,
4280 : : vmbuffer_modified ? vmbuffer : InvalidBuffer,
4281 : : newbuf,
4282 : : vmbuffer_new_modified ? vmbuffer_new : InvalidBuffer,
4283 : : &oldtup, heaptup,
4284 : : old_key_tuple,
4285 : : clear_all_visible,
4286 : : clear_all_visible_new,
4287 : : walLogical);
9597 vadim4o@yahoo.com 4288 [ + + ]: 2383366 : if (newbuf != buffer)
4289 : : {
211 melanieplageman@gmai 4290 : 2202054 : PageSetLSN(newpage, recptr);
4291 : : }
4292 : 2383366 : PageSetLSN(page, recptr);
4293 : :
89 4294 [ + + ]: 2383366 : if (vmbuffer_modified)
4295 : 2326 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
4296 [ + + ]: 2383366 : if (vmbuffer_new_modified)
4297 : 1463 : PageSetLSN(BufferGetPage(vmbuffer_new), recptr);
4298 : : }
4299 : :
9404 tgl@sss.pgh.pa.us 4300 [ - + ]: 2395211 : END_CRIT_SECTION();
4301 : :
89 melanieplageman@gmai 4302 [ + + ]: 2395211 : if (unlock_vmbuffer)
4303 : 2433 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
4304 [ + + ]: 2395211 : if (unlock_vmbuffer_new)
4305 : 1463 : LockBuffer(vmbuffer_new, BUFFER_LOCK_UNLOCK);
4306 : :
9597 vadim4o@yahoo.com 4307 [ + + ]: 2395211 : if (newbuf != buffer)
4308 : 2212182 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
10163 4309 : 2395211 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4310 : :
4311 : : /*
4312 : : * Mark old tuple for invalidation from system caches at next command
4313 : : * boundary, and mark the new tuple for invalidation in case we abort. We
4314 : : * have to do this before releasing the buffer because oldtup is in the
4315 : : * buffer. (heaptup is all in local memory, but it's necessary to process
4316 : : * both tuple versions in one call to inval.c so we can avoid redundant
4317 : : * sinval messages.)
4318 : : */
5536 tgl@sss.pgh.pa.us 4319 : 2395211 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4320 : :
4321 : : /* Now we can release the buffer(s) */
9409 4322 [ + + ]: 2395211 : if (newbuf != buffer)
7500 4323 : 2212182 : ReleaseBuffer(newbuf);
914 akorotkov@postgresql 4324 : 2395211 : ReleaseBuffer(buffer);
5592 rhaas@postgresql.org 4325 [ + + ]: 2395211 : if (BufferIsValid(vmbuffer_new))
4326 : 1466 : ReleaseBuffer(vmbuffer_new);
4327 [ + + ]: 2395211 : if (BufferIsValid(vmbuffer))
4328 : 2614 : ReleaseBuffer(vmbuffer);
4329 : :
4330 : : /*
4331 : : * Release the lmgr tuple lock, if we had it.
4332 : : */
7835 tgl@sss.pgh.pa.us 4333 [ + + ]: 2395211 : if (have_tuple_lock)
3105 simon@2ndQuadrant.co 4334 : 22 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4335 : :
1299 pg@bowt.ie 4336 : 2395211 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4337 : :
4338 : : /*
4339 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
4340 : : * back to the caller's image, too.
4341 : : */
7631 tgl@sss.pgh.pa.us 4342 [ + + ]: 2395211 : if (heaptup != newtup)
4343 : : {
4344 : 2172 : newtup->t_self = heaptup->t_self;
4345 : 2172 : heap_freetuple(heaptup);
4346 : : }
4347 : :
4348 : : /*
4349 : : * If it is a HOT update, the update may still need to update summarized
4350 : : * indexes, lest we fail to update those summaries and get incorrect
4351 : : * results (for example, minmax bounds of the block may change with this
4352 : : * update).
4353 : : */
1302 tomas.vondra@postgre 4354 [ + + ]: 2395211 : if (use_hot_update)
4355 : : {
4356 [ + + ]: 166989 : if (summarized_update)
4357 : 2188 : *update_indexes = TU_Summarizing;
4358 : : else
4359 : 164801 : *update_indexes = TU_None;
4360 : : }
4361 : : else
4362 : 2228222 : *update_indexes = TU_All;
4363 : :
4689 rhaas@postgresql.org 4364 [ + + + + ]: 2395211 : if (old_key_tuple != NULL && old_key_copied)
4365 : 95 : heap_freetuple(old_key_tuple);
4366 : :
6962 tgl@sss.pgh.pa.us 4367 : 2395211 : bms_free(hot_attrs);
1302 tomas.vondra@postgre 4368 : 2395211 : bms_free(sum_attrs);
5010 alvherre@alvh.no-ip. 4369 : 2395211 : bms_free(key_attrs);
3701 tgl@sss.pgh.pa.us 4370 : 2395211 : bms_free(id_attrs);
3484 alvherre@alvh.no-ip. 4371 : 2395211 : bms_free(modified_attrs);
4372 : 2395211 : bms_free(interesting_attrs);
4373 : :
2760 andres@anarazel.de 4374 : 2395211 : return TM_Ok;
4375 : : }
4376 : :
4377 : : #ifdef USE_ASSERT_CHECKING
4378 : : /*
4379 : : * Confirm adequate lock held during heap_update(), per rules from
4380 : : * README.tuplock section "Locking to write inplace-updated tables".
4381 : : */
4382 : : static void
748 noah@leadboat.com 4383 : 2395406 : check_lock_if_inplace_updateable_rel(Relation relation,
4384 : : const ItemPointerData *otid,
4385 : : HeapTuple newtup)
4386 : : {
4387 : : /* LOCKTAG_TUPLE acceptable for any catalog */
4388 [ + + ]: 2395406 : switch (RelationGetRelid(relation))
4389 : : {
4390 : 85338 : case RelationRelationId:
4391 : : case DatabaseRelationId:
4392 : : {
4393 : : LOCKTAG tuptag;
4394 : :
4395 : 85338 : SET_LOCKTAG_TUPLE(tuptag,
4396 : : relation->rd_lockInfo.lockRelId.dbId,
4397 : : relation->rd_lockInfo.lockRelId.relId,
4398 : : ItemPointerGetBlockNumber(otid),
4399 : : ItemPointerGetOffsetNumber(otid));
4400 [ + + ]: 85338 : if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
4401 : 36231 : return;
4402 : : }
4403 : 49107 : break;
4404 : 2310068 : default:
4405 [ - + ]: 2310068 : Assert(!IsInplaceUpdateRelation(relation));
4406 : 2310068 : return;
4407 : : }
4408 : :
4409 [ + - - ]: 49107 : switch (RelationGetRelid(relation))
4410 : : {
4411 : 49107 : case RelationRelationId:
4412 : : {
4413 : : /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4414 : 49107 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
4415 : 49107 : Oid relid = classForm->oid;
4416 : : Oid dbid;
4417 : : LOCKTAG tag;
4418 : :
4419 [ + + ]: 49107 : if (IsSharedRelation(relid))
4420 : 47 : dbid = InvalidOid;
4421 : : else
4422 : 49060 : dbid = MyDatabaseId;
4423 : :
4424 [ + + ]: 49107 : if (classForm->relkind == RELKIND_INDEX)
4425 : : {
4426 : 1397 : Relation irel = index_open(relid, AccessShareLock);
4427 : :
4428 : 1397 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4429 : 1397 : index_close(irel, AccessShareLock);
4430 : : }
4431 : : else
4432 : 47710 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4433 : :
4434 [ + + ]: 49107 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4435 [ - + ]: 44603 : !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
748 noah@leadboat.com 4436 [ # # ]:UBC 0 : elog(WARNING,
4437 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4438 : : NameStr(classForm->relname),
4439 : : relid,
4440 : : classForm->relkind,
4441 : : ItemPointerGetBlockNumber(otid),
4442 : : ItemPointerGetOffsetNumber(otid));
4443 : : }
748 noah@leadboat.com 4444 :CBC 49107 : break;
748 noah@leadboat.com 4445 :UBC 0 : case DatabaseRelationId:
4446 : : {
4447 : : /* LOCKTAG_TUPLE required */
4448 : 0 : Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
4449 : :
4450 [ # # ]: 0 : elog(WARNING,
4451 : : "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4452 : : NameStr(dbForm->datname),
4453 : : dbForm->oid,
4454 : : ItemPointerGetBlockNumber(otid),
4455 : : ItemPointerGetOffsetNumber(otid));
4456 : : }
4457 : 0 : break;
4458 : : }
4459 : : }
4460 : :
4461 : : /*
4462 : : * Confirm adequate relation lock held, per rules from README.tuplock section
4463 : : * "Locking to write inplace-updated tables".
4464 : : */
4465 : : static void
748 noah@leadboat.com 4466 :CBC 113028 : check_inplace_rel_lock(HeapTuple oldtup)
4467 : : {
4468 : 113028 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
4469 : 113028 : Oid relid = classForm->oid;
4470 : : Oid dbid;
4471 : : LOCKTAG tag;
4472 : :
4473 [ + + ]: 113028 : if (IsSharedRelation(relid))
4474 : 10091 : dbid = InvalidOid;
4475 : : else
4476 : 102937 : dbid = MyDatabaseId;
4477 : :
4478 [ + + ]: 113028 : if (classForm->relkind == RELKIND_INDEX)
4479 : : {
4480 : 49579 : Relation irel = index_open(relid, AccessShareLock);
4481 : :
4482 : 49579 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4483 : 49579 : index_close(irel, AccessShareLock);
4484 : : }
4485 : : else
4486 : 63449 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4487 : :
4488 [ - + ]: 113028 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
748 noah@leadboat.com 4489 [ # # ]:UBC 0 : elog(WARNING,
4490 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4491 : : NameStr(classForm->relname),
4492 : : relid,
4493 : : classForm->relkind,
4494 : : ItemPointerGetBlockNumber(&oldtup->t_self),
4495 : : ItemPointerGetOffsetNumber(&oldtup->t_self));
748 noah@leadboat.com 4496 :CBC 113028 : }
4497 : : #endif
4498 : :
4499 : : /*
4500 : : * Check if the specified attribute's values are the same. Subroutine for
4501 : : * HeapDetermineColumnsInfo.
4502 : : */
4503 : : static bool
1701 akapila@postgresql.o 4504 : 1006744 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4505 : : bool isnull1, bool isnull2)
4506 : : {
4507 : : /*
4508 : : * If one value is NULL and other is not, then they are certainly not
4509 : : * equal
4510 : : */
6962 tgl@sss.pgh.pa.us 4511 [ + + ]: 1006744 : if (isnull1 != isnull2)
4512 : 62 : return false;
4513 : :
4514 : : /*
4515 : : * If both are NULL, they can be considered equal.
4516 : : */
4517 [ + + ]: 1006682 : if (isnull1)
4518 : 6641 : return true;
4519 : :
4520 : : /*
4521 : : * We do simple binary comparison of the two datums. This may be overly
4522 : : * strict because there can be multiple binary representations for the
4523 : : * same logical value. But we should be OK as long as there are no false
4524 : : * positives. Using a type-specific equality operator is messy because
4525 : : * there could be multiple notions of equality in different operator
4526 : : * classes; furthermore, we cannot safely invoke user-defined functions
4527 : : * while holding exclusive buffer lock.
4528 : : */
4529 [ - + ]: 1000041 : if (attrnum <= 0)
4530 : : {
4531 : : /* The only allowed system columns are OIDs, so do this */
6962 tgl@sss.pgh.pa.us 4532 :UBC 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4533 : : }
4534 : : else
4535 : : {
4536 : : CompactAttribute *att;
4537 : :
6962 tgl@sss.pgh.pa.us 4538 [ - + ]:CBC 1000041 : Assert(attrnum <= tupdesc->natts);
661 drowley@postgresql.o 4539 : 1000041 : att = TupleDescCompactAttr(tupdesc, attrnum - 1);
6962 tgl@sss.pgh.pa.us 4540 : 1000041 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4541 : : }
4542 : : }
4543 : :
4544 : : /*
4545 : : * Check which columns are being updated.
4546 : : *
4547 : : * Given an updated tuple, determine (and return into the output bitmapset),
4548 : : * from those listed as interesting, the set of columns that changed.
4549 : : *
4550 : : * has_external indicates if any of the unmodified attributes (from those
4551 : : * listed as interesting) of the old tuple is a member of external_cols and is
4552 : : * stored externally.
4553 : : */
4554 : : static Bitmapset *
1701 akapila@postgresql.o 4555 : 2395405 : HeapDetermineColumnsInfo(Relation relation,
4556 : : Bitmapset *interesting_cols,
4557 : : Bitmapset *external_cols,
4558 : : HeapTuple oldtup, HeapTuple newtup,
4559 : : bool *has_external)
4560 : : {
4561 : : int attidx;
3435 bruce@momjian.us 4562 : 2395405 : Bitmapset *modified = NULL;
1701 akapila@postgresql.o 4563 : 2395405 : TupleDesc tupdesc = RelationGetDescr(relation);
4564 : :
1320 tgl@sss.pgh.pa.us 4565 : 2395405 : attidx = -1;
4566 [ + + ]: 3402149 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4567 : : {
4568 : : /* attidx is zero-based, attrnum is the normal attribute number */
4569 : 1006744 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4570 : : Datum value1,
4571 : : value2;
4572 : : bool isnull1,
4573 : : isnull2;
4574 : :
4575 : : /*
4576 : : * If it's a whole-tuple reference, say "not equal". It's not really
4577 : : * worth supporting this case, since it could only succeed after a
4578 : : * no-op update, which is hardly a case worth optimizing for.
4579 : : */
1701 akapila@postgresql.o 4580 [ - + ]: 1006744 : if (attrnum == 0)
4581 : : {
1320 tgl@sss.pgh.pa.us 4582 :UBC 0 : modified = bms_add_member(modified, attidx);
1701 akapila@postgresql.o 4583 :CBC 974630 : continue;
4584 : : }
4585 : :
4586 : : /*
4587 : : * Likewise, automatically say "not equal" for any system attribute
4588 : : * other than tableOID; we cannot expect these to be consistent in a
4589 : : * HOT chain, or even to be set correctly yet in the new tuple.
4590 : : */
4591 [ - + ]: 1006744 : if (attrnum < 0)
4592 : : {
1701 akapila@postgresql.o 4593 [ # # ]:UBC 0 : if (attrnum != TableOidAttributeNumber)
4594 : : {
1320 tgl@sss.pgh.pa.us 4595 : 0 : modified = bms_add_member(modified, attidx);
1701 akapila@postgresql.o 4596 : 0 : continue;
4597 : : }
4598 : : }
4599 : :
4600 : : /*
4601 : : * Extract the corresponding values. XXX this is pretty inefficient
4602 : : * if there are many indexed columns. Should we do a single
4603 : : * heap_deform_tuple call on each tuple, instead? But that doesn't
4604 : : * work for system columns ...
4605 : : */
1701 akapila@postgresql.o 4606 :CBC 1006744 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4607 : 1006744 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4608 : :
4609 [ + + ]: 1006744 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4610 : : value2, isnull1, isnull2))
4611 : : {
1320 tgl@sss.pgh.pa.us 4612 : 64211 : modified = bms_add_member(modified, attidx);
1701 akapila@postgresql.o 4613 : 64211 : continue;
4614 : : }
4615 : :
4616 : : /*
4617 : : * No need to check attributes that can't be stored externally. Note
4618 : : * that system attributes can't be stored externally.
4619 : : */
4620 [ + - + + ]: 942533 : if (attrnum < 0 || isnull1 ||
661 drowley@postgresql.o 4621 [ + + ]: 935892 : TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
1701 akapila@postgresql.o 4622 : 910419 : continue;
4623 : :
4624 : : /*
4625 : : * Check if the old tuple's attribute is stored externally and is a
4626 : : * member of external_cols.
4627 : : */
243 michael@paquier.xyz 4628 [ + + + + ]: 32119 : if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
1320 tgl@sss.pgh.pa.us 4629 : 5 : bms_is_member(attidx, external_cols))
1701 akapila@postgresql.o 4630 : 2 : *has_external = true;
4631 : : }
4632 : :
3484 alvherre@alvh.no-ip. 4633 : 2395405 : return modified;
4634 : : }
4635 : :
4636 : : /*
4637 : : * simple_heap_update - replace a tuple
4638 : : *
4639 : : * This routine may be used to update a tuple when concurrent updates of
4640 : : * the target tuple are not expected (for example, because we have a lock
4641 : : * on the relation associated with the tuple). Any failure is reported
4642 : : * via ereport().
4643 : : */
4644 : : void
347 peter@eisentraut.org 4645 : 137469 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
4646 : : TU_UpdateIndexes *update_indexes)
4647 : : {
4648 : : TM_Result result;
4649 : : TM_FailureData tmfd;
4650 : : LockTupleMode lockmode;
4651 : :
8428 tgl@sss.pgh.pa.us 4652 : 137469 : result = heap_update(relation, otid, tup,
4653 : : GetCurrentCommandId(true), 0,
4654 : : InvalidSnapshot,
4655 : : true /* wait for commit */ ,
4656 : : &tmfd, &lockmode, update_indexes);
9393 4657 [ - + - + : 137469 : switch (result)
- ]
4658 : : {
2760 andres@anarazel.de 4659 :UBC 0 : case TM_SelfModified:
4660 : : /* Tuple was already updated in current command? */
8484 tgl@sss.pgh.pa.us 4661 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
4662 : : break;
4663 : :
2760 andres@anarazel.de 4664 :CBC 137468 : case TM_Ok:
4665 : : /* done successfully */
9393 tgl@sss.pgh.pa.us 4666 : 137468 : break;
4667 : :
2760 andres@anarazel.de 4668 :UBC 0 : case TM_Updated:
8484 tgl@sss.pgh.pa.us 4669 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
4670 : : break;
4671 : :
2760 andres@anarazel.de 4672 :CBC 1 : case TM_Deleted:
4673 [ + - ]: 1 : elog(ERROR, "tuple concurrently deleted");
4674 : : break;
4675 : :
9393 tgl@sss.pgh.pa.us 4676 :UBC 0 : default:
8484 4677 [ # # ]: 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4678 : : break;
4679 : : }
9393 tgl@sss.pgh.pa.us 4680 :CBC 137468 : }
4681 : :
4682 : :
4683 : : /*
4684 : : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4685 : : */
4686 : : static MultiXactStatus
5010 alvherre@alvh.no-ip. 4687 : 115467 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4688 : : {
4689 : : int retval;
4690 : :
4691 [ + + ]: 115467 : if (is_update)
4692 : 217 : retval = tupleLockExtraInfo[mode].updstatus;
4693 : : else
4694 : 115250 : retval = tupleLockExtraInfo[mode].lockstatus;
4695 : :
4696 [ - + ]: 115467 : if (retval == -1)
5010 alvherre@alvh.no-ip. 4697 [ # # # # ]:UBC 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4698 : : is_update ? "true" : "false");
4699 : :
4857 alvherre@alvh.no-ip. 4700 :CBC 115467 : return (MultiXactStatus) retval;
4701 : : }
4702 : :
4703 : : /*
4704 : : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4705 : : *
4706 : : * Note that this acquires a buffer pin, which the caller must release.
4707 : : *
4708 : : * Input parameters:
4709 : : * relation: relation containing tuple (caller must hold suitable lock)
4710 : : * cid: current command ID (used for visibility test, and stored into
4711 : : * tuple's cmax if lock is successful)
4712 : : * mode: indicates if shared or exclusive tuple lock is desired
4713 : : * wait_policy: what to do if tuple lock is not available
4714 : : * follow_updates: if true, follow the update chain to also lock descendant
4715 : : * tuples.
4716 : : *
4717 : : * Output parameters:
4718 : : * *tuple: all fields filled in
4719 : : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4720 : : * *tmfd: filled in failure cases (see below)
4721 : : *
4722 : : * Function results are the same as the ones for table_tuple_lock().
4723 : : *
4724 : : * In the failure cases other than TM_Invisible, the routine fills
4725 : : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4726 : : * if necessary), and t_cmax (the last only for TM_SelfModified,
4727 : : * since we cannot obtain cmax from a combo CID generated by another
4728 : : * transaction).
4729 : : * See comments for struct TM_FailureData for additional info.
4730 : : *
4731 : : * See README.tuplock for a thorough explanation of this mechanism.
4732 : : */
4733 : : TM_Result
914 akorotkov@postgresql 4734 : 762340 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4735 : : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4736 : : bool follow_updates,
4737 : : Buffer *buffer, TM_FailureData *tmfd)
4738 : : {
4739 : : TM_Result result;
4740 : 762340 : ItemPointer tid = &(tuple->t_self);
4741 : : ItemId lp;
4742 : : Page page;
3738 andres@anarazel.de 4743 : 762340 : Buffer vmbuffer = InvalidBuffer;
89 melanieplageman@gmai 4744 : 762340 : bool unlock_vmbuffer = false;
4745 : : BlockNumber block;
4746 : : TransactionId xid,
4747 : : xmax;
4748 : : uint16 old_infomask,
4749 : : new_infomask,
4750 : : new_infomask2;
4203 alvherre@alvh.no-ip. 4751 : 762340 : bool first_time = true;
2673 4752 : 762340 : bool skip_tuple_lock = false;
7835 tgl@sss.pgh.pa.us 4753 : 762340 : bool have_tuple_lock = false;
3738 andres@anarazel.de 4754 : 762340 : bool cleared_all_frozen = false;
4755 : :
914 akorotkov@postgresql 4756 : 762340 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3738 andres@anarazel.de 4757 : 762340 : block = ItemPointerGetBlockNumber(tid);
89 melanieplageman@gmai 4758 : 762340 : page = BufferGetPage(*buffer);
4759 : :
4760 : : /*
4761 : : * Before locking the buffer, pin the visibility map page if it appears to
4762 : : * be necessary. Since we haven't got the lock yet, someone else might be
4763 : : * in the middle of changing this, so we'll need to recheck after we have
4764 : : * the lock.
4765 : : */
4766 [ + + ]: 762340 : if (PageIsAllVisible(page))
3738 andres@anarazel.de 4767 : 604033 : visibilitymap_pin(relation, block, &vmbuffer);
4768 : :
914 akorotkov@postgresql 4769 : 762340 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4770 : :
6665 tgl@sss.pgh.pa.us 4771 : 762340 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6970 4772 [ - + ]: 762340 : Assert(ItemIdIsNormal(lp));
4773 : :
6665 4774 : 762340 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10163 vadim4o@yahoo.com 4775 : 762340 : tuple->t_len = ItemIdGetLength(lp);
7723 tgl@sss.pgh.pa.us 4776 : 762340 : tuple->t_tableOid = RelationGetRelid(relation);
4777 : :
10163 vadim4o@yahoo.com 4778 : 16 : l3:
914 akorotkov@postgresql 4779 : 762356 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4780 : :
2760 andres@anarazel.de 4781 [ + + ]: 762356 : if (result == TM_Invisible)
4782 : : {
4783 : : /*
4784 : : * This is possible, but only when locking a tuple for ON CONFLICT DO
4785 : : * SELECT/UPDATE. We return this value here rather than throwing an
4786 : : * error in order to give that case the opportunity to throw a more
4787 : : * specific error.
4788 : : */
4789 : 28 : result = TM_Invisible;
3738 4790 : 28 : goto out_locked;
4791 : : }
2760 4792 [ + + + + ]: 762328 : else if (result == TM_BeingModified ||
4793 [ + + ]: 81377 : result == TM_Updated ||
4794 : : result == TM_Deleted)
4795 : : {
4796 : : TransactionId xwait;
4797 : : uint16 infomask;
4798 : : uint16 infomask2;
4799 : : bool require_sleep;
4800 : : ItemPointerData t_ctid;
4801 : :
4802 : : /* must copy state data before unlocking buffer */
5010 alvherre@alvh.no-ip. 4803 : 680953 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
7835 tgl@sss.pgh.pa.us 4804 : 680953 : infomask = tuple->t_data->t_infomask;
5010 alvherre@alvh.no-ip. 4805 : 680953 : infomask2 = tuple->t_data->t_infomask2;
4806 : 680953 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4807 : :
914 akorotkov@postgresql 4808 : 680953 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4809 : :
4810 : : /*
4811 : : * If any subtransaction of the current top transaction already holds
4812 : : * a lock as strong as or stronger than what we're requesting, we
4813 : : * effectively hold the desired lock already. We *must* succeed
4814 : : * without trying to take the tuple lock, else we will deadlock
4815 : : * against anyone wanting to acquire a stronger lock.
4816 : : *
4817 : : * Note we only do this the first time we loop on the HTSU result;
4818 : : * there is no point in testing in subsequent passes, because
4819 : : * evidently our own transaction cannot have acquired a new lock after
4820 : : * the first time we checked.
4821 : : */
4203 alvherre@alvh.no-ip. 4822 [ + + ]: 680953 : if (first_time)
4823 : : {
4824 : 680942 : first_time = false;
4825 : :
4826 [ + + ]: 680942 : if (infomask & HEAP_XMAX_IS_MULTI)
4827 : : {
4828 : : int i;
4829 : : int nmembers;
4830 : : MultiXactMember *members;
4831 : :
4832 : : /*
4833 : : * We don't need to allow old multixacts here; if that had
4834 : : * been the case, HeapTupleSatisfiesUpdate would have returned
4835 : : * MayBeUpdated and we wouldn't be here.
4836 : : */
4837 : : nmembers =
4838 : 73298 : GetMultiXactIdMembers(xwait, &members, false,
4839 : 73298 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4840 : :
4841 [ + + ]: 1422665 : for (i = 0; i < nmembers; i++)
4842 : : {
4843 : : /* only consider members of our own transaction */
4844 [ + + ]: 1349381 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4845 : 1349331 : continue;
4846 : :
4847 [ + + ]: 50 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4848 : : {
5010 4849 : 14 : pfree(members);
2760 andres@anarazel.de 4850 : 14 : result = TM_Ok;
3738 4851 : 14 : goto out_unlocked;
4852 : : }
4853 : : else
4854 : : {
4855 : : /*
4856 : : * Disable acquisition of the heavyweight tuple lock.
4857 : : * Otherwise, when promoting a weaker lock, we might
4858 : : * deadlock with another locker that has acquired the
4859 : : * heavyweight tuple lock and is waiting for our
4860 : : * transaction to finish.
4861 : : *
4862 : : * Note that in this case we still need to wait for
4863 : : * the multixact if required, to avoid acquiring
4864 : : * conflicting locks.
4865 : : */
2673 alvherre@alvh.no-ip. 4866 : 36 : skip_tuple_lock = true;
4867 : : }
4868 : : }
4869 : :
4203 4870 [ + - ]: 73284 : if (members)
4871 : 73284 : pfree(members);
4872 : : }
4873 [ + + ]: 607644 : else if (TransactionIdIsCurrentTransactionId(xwait))
4874 : : {
4875 [ + + + + : 606281 : switch (mode)
- ]
4876 : : {
4877 : 599838 : case LockTupleKeyShare:
4878 [ - + - - : 599838 : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
- - ]
4879 : : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4880 : : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
2760 andres@anarazel.de 4881 : 599838 : result = TM_Ok;
3738 4882 : 599838 : goto out_unlocked;
4203 alvherre@alvh.no-ip. 4883 : 40 : case LockTupleShare:
4884 [ + + - + ]: 46 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4885 : 6 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4886 : : {
2760 andres@anarazel.de 4887 : 34 : result = TM_Ok;
3738 4888 : 34 : goto out_unlocked;
4889 : : }
4203 alvherre@alvh.no-ip. 4890 : 6 : break;
4891 : 85 : case LockTupleNoKeyExclusive:
4892 [ + + ]: 85 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4893 : : {
2760 andres@anarazel.de 4894 : 72 : result = TM_Ok;
3738 4895 : 72 : goto out_unlocked;
4896 : : }
4203 alvherre@alvh.no-ip. 4897 : 13 : break;
4898 : 6318 : case LockTupleExclusive:
4899 [ + + ]: 6318 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4900 [ + + ]: 1275 : infomask2 & HEAP_KEYS_UPDATED)
4901 : : {
2760 andres@anarazel.de 4902 : 1246 : result = TM_Ok;
3738 4903 : 1246 : goto out_unlocked;
4904 : : }
4203 alvherre@alvh.no-ip. 4905 : 5072 : break;
4906 : : }
4907 : : }
4908 : : }
4909 : :
4910 : : /*
4911 : : * Initially assume that we will have to wait for the locking
4912 : : * transaction(s) to finish. We check various cases below in which
4913 : : * this can be turned off.
4914 : : */
5010 4915 : 79749 : require_sleep = true;
4916 [ + + ]: 79749 : if (mode == LockTupleKeyShare)
4917 : : {
4918 : : /*
4919 : : * If we're requesting KeyShare, and there's no update present, we
4920 : : * don't need to wait. Even if there is an update, we can still
4921 : : * continue if the key hasn't been modified.
4922 : : *
4923 : : * However, if there are updates, we need to walk the update chain
4924 : : * to mark future versions of the row as locked, too. That way,
4925 : : * if somebody deletes that future version, we're protected
4926 : : * against the key going away. This locking of future versions
4927 : : * could block momentarily, if a concurrent transaction is
4928 : : * deleting a key; or it could return a value to the effect that
4929 : : * the transaction deleting the key has already committed. So we
4930 : : * do this before re-locking the buffer; otherwise this would be
4931 : : * prone to deadlocks.
4932 : : *
4933 : : * Note that the TID we're locking was grabbed before we unlocked
4934 : : * the buffer. For it to change while we're not looking, the
4935 : : * other properties we're testing for below after re-locking the
4936 : : * buffer would also change, in which case we would restart this
4937 : : * loop above.
4938 : : */
4939 [ + + ]: 73880 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4940 : : {
4941 : : bool updated;
4942 : :
4943 : 73828 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4944 : :
4945 : : /*
4946 : : * If there are updates, follow the update chain; bail out if
4947 : : * that cannot be done.
4948 : : */
293 heikki.linnakangas@i 4949 [ + + + + ]: 73828 : if (follow_updates && updated &&
4950 [ + - ]: 2171 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
4951 : : {
4952 : : TM_Result res;
4953 : :
4954 : 2171 : res = heap_lock_updated_tuple(relation,
4955 : : infomask, xwait, &t_ctid,
4956 : : GetCurrentTransactionId(),
4957 : : mode);
2760 andres@anarazel.de 4958 [ + + ]: 2171 : if (res != TM_Ok)
4959 : : {
5010 alvherre@alvh.no-ip. 4960 : 6 : result = res;
4961 : : /* recovery code expects to have buffer lock held */
914 akorotkov@postgresql 4962 : 6 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5010 alvherre@alvh.no-ip. 4963 : 204 : goto failed;
4964 : : }
4965 : : }
4966 : :
914 akorotkov@postgresql 4967 : 73822 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4968 : :
4969 : : /*
4970 : : * Make sure it's still an appropriate lock, else start over.
4971 : : * Also, if it wasn't updated before we released the lock, but
4972 : : * is updated now, we start over too; the reason is that we
4973 : : * now need to follow the update chain to lock the new
4974 : : * versions.
4975 : : */
5010 alvherre@alvh.no-ip. 4976 [ + + ]: 73822 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4977 [ + - ]: 2154 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4978 [ - + ]: 2154 : !updated))
4979 : 16 : goto l3;
4980 : :
4981 : : /* Things look okay, so we can skip sleeping */
4982 : 73822 : require_sleep = false;
4983 : :
4984 : : /*
4985 : : * Note we allow Xmax to change here; other updaters/lockers
4986 : : * could have modified it before we grabbed the buffer lock.
4987 : : * However, this is not a problem, because with the recheck we
4988 : : * just did we ensure that they still don't conflict with the
4989 : : * lock we want.
4990 : : */
4991 : : }
4992 : : }
4993 [ + + ]: 5869 : else if (mode == LockTupleShare)
4994 : : {
4995 : : /*
4996 : : * If we're requesting Share, we can similarly avoid sleeping if
4997 : : * there's no update and no exclusive lock present.
4998 : : */
4999 [ + - ]: 451 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5000 [ + + ]: 451 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
5001 : : {
914 akorotkov@postgresql 5002 : 445 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5003 : :
5004 : : /*
5005 : : * Make sure it's still an appropriate lock, else start over.
5006 : : * See above about allowing xmax to change.
5007 : : */
5010 alvherre@alvh.no-ip. 5008 [ + - - + ]: 890 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5009 : 445 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
5010 alvherre@alvh.no-ip. 5010 :UBC 0 : goto l3;
5010 alvherre@alvh.no-ip. 5011 :CBC 445 : require_sleep = false;
5012 : : }
5013 : : }
5014 [ + + ]: 5418 : else if (mode == LockTupleNoKeyExclusive)
5015 : : {
5016 : : /*
5017 : : * If we're requesting NoKeyExclusive, we might also be able to
5018 : : * avoid sleeping; just ensure that there no conflicting lock
5019 : : * already acquired.
5020 : : */
5021 [ + + ]: 173 : if (infomask & HEAP_XMAX_IS_MULTI)
5022 : : {
4308 5023 [ + + ]: 26 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
5024 : : mode, NULL))
5025 : : {
5026 : : /*
5027 : : * No conflict, but if the xmax changed under us in the
5028 : : * meantime, start over.
5029 : : */
914 akorotkov@postgresql 5030 : 13 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4308 alvherre@alvh.no-ip. 5031 [ + - - + ]: 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5032 : 13 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5033 : : xwait))
4308 alvherre@alvh.no-ip. 5034 :UBC 0 : goto l3;
5035 : :
5036 : : /* otherwise, we're good */
4308 alvherre@alvh.no-ip. 5037 :CBC 13 : require_sleep = false;
5038 : : }
5039 : : }
5010 5040 [ + + ]: 147 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
5041 : : {
914 akorotkov@postgresql 5042 : 19 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5043 : :
5044 : : /* if the xmax changed in the meantime, start over */
4554 alvherre@alvh.no-ip. 5045 [ + - - + ]: 38 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
2447 5046 : 19 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5047 : : xwait))
5010 alvherre@alvh.no-ip. 5048 :UBC 0 : goto l3;
5049 : : /* otherwise, we're good */
5010 alvherre@alvh.no-ip. 5050 :CBC 19 : require_sleep = false;
5051 : : }
5052 : : }
5053 : :
5054 : : /*
5055 : : * As a check independent from those above, we can also avoid sleeping
5056 : : * if the current transaction is the sole locker of the tuple. Note
5057 : : * that the strength of the lock already held is irrelevant; this is
5058 : : * not about recording the lock in Xmax (which will be done regardless
5059 : : * of this optimization, below). Also, note that the cases where we
5060 : : * hold a lock stronger than we are requesting are already handled
5061 : : * above by not doing anything.
5062 : : *
5063 : : * Note we only deal with the non-multixact case here; MultiXactIdWait
5064 : : * is well equipped to deal with this situation on its own.
5065 : : */
4203 5066 [ + + + + : 85144 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
+ + ]
5067 : 5401 : TransactionIdIsCurrentTransactionId(xwait))
5068 : : {
5069 : : /* ... but if the xmax changed in the meantime, start over */
914 akorotkov@postgresql 5070 : 5072 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4203 alvherre@alvh.no-ip. 5071 [ + - - + ]: 10144 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5072 : 5072 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5073 : : xwait))
4203 alvherre@alvh.no-ip. 5074 :UBC 0 : goto l3;
4203 alvherre@alvh.no-ip. 5075 [ - + ]:CBC 5072 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
5076 : 5072 : require_sleep = false;
5077 : : }
5078 : :
5079 : : /*
5080 : : * Time to sleep on the other transaction/multixact, if necessary.
5081 : : *
5082 : : * If the other transaction is an update/delete that's already
5083 : : * committed, then sleeping cannot possibly do any good: if we're
5084 : : * required to sleep, get out to raise an error instead.
5085 : : *
5086 : : * By here, we either have already acquired the buffer exclusive lock,
5087 : : * or we must wait for the locking transaction or multixact; so below
5088 : : * we ensure that we grab buffer lock after the sleep.
5089 : : */
2760 andres@anarazel.de 5090 [ + + + + : 79743 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
+ + ]
5091 : : {
914 akorotkov@postgresql 5092 : 157 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3741 alvherre@alvh.no-ip. 5093 : 157 : goto failed;
5094 : : }
5095 [ + + ]: 79586 : else if (require_sleep)
5096 : : {
5097 : : /*
5098 : : * Acquire tuple lock to establish our priority for the tuple, or
5099 : : * die trying. LockTuple will release us when we are next-in-line
5100 : : * for the tuple. We must do this even if we are share-locking,
5101 : : * but not if we already have a weaker lock on the tuple.
5102 : : *
5103 : : * If we are forced to "start over" below, we keep the tuple lock;
5104 : : * this arranges that we stay at the head of the line while
5105 : : * rechecking tuple state.
5106 : : */
2673 5107 [ + + ]: 215 : if (!skip_tuple_lock &&
5108 [ + + ]: 198 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
5109 : : &have_tuple_lock))
5110 : : {
5111 : : /*
5112 : : * This can only happen if wait_policy is Skip and the lock
5113 : : * couldn't be obtained.
5114 : : */
2760 andres@anarazel.de 5115 : 1 : result = TM_WouldBlock;
5116 : : /* recovery code expects to have buffer lock held */
914 akorotkov@postgresql 5117 : 1 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4308 alvherre@alvh.no-ip. 5118 : 1 : goto failed;
5119 : : }
5120 : :
5010 5121 [ + + ]: 213 : if (infomask & HEAP_XMAX_IS_MULTI)
5122 : : {
5123 : 43 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
5124 : :
5125 : : /* We only ever lock tuples, never update them */
5126 [ - + ]: 43 : if (status >= MultiXactStatusNoKeyUpdate)
5010 alvherre@alvh.no-ip. 5127 [ # # ]:UBC 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
5128 : :
5129 : : /* wait for multixact to end, or die trying */
4388 alvherre@alvh.no-ip. 5130 [ + + + - ]:CBC 43 : switch (wait_policy)
5131 : : {
5132 : 37 : case LockWaitBlock:
5133 : 37 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
3400 tgl@sss.pgh.pa.us 5134 : 37 : relation, &tuple->t_self, XLTW_Lock, NULL);
4388 alvherre@alvh.no-ip. 5135 : 37 : break;
5136 : 2 : case LockWaitSkip:
5137 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5138 : : status, infomask, relation,
5139 : : NULL, false))
5140 : : {
2760 andres@anarazel.de 5141 : 2 : result = TM_WouldBlock;
5142 : : /* recovery code expects to have buffer lock held */
914 akorotkov@postgresql 5143 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4388 alvherre@alvh.no-ip. 5144 : 2 : goto failed;
5145 : : }
4388 alvherre@alvh.no-ip. 5146 :UBC 0 : break;
4388 alvherre@alvh.no-ip. 5147 :CBC 4 : case LockWaitError:
5148 [ + - ]: 4 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
5149 : : status, infomask, relation,
5150 : : NULL, log_lock_failures))
5151 [ + - ]: 4 : ereport(ERROR,
5152 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5153 : : errmsg("could not obtain lock on row in relation \"%s\"",
5154 : : RelationGetRelationName(relation))));
5155 : :
4388 alvherre@alvh.no-ip. 5156 :UBC 0 : break;
5157 : : }
5158 : :
5159 : : /*
5160 : : * Of course, the multixact might not be done here: if we're
5161 : : * requesting a light lock mode, other transactions with light
5162 : : * locks could still be alive, as well as locks owned by our
5163 : : * own xact or other subxacts of this backend. We need to
5164 : : * preserve the surviving MultiXact members. Note that it
5165 : : * isn't absolutely necessary in the latter case, but doing so
5166 : : * is simpler.
5167 : : */
5168 : : }
5169 : : else
5170 : : {
5171 : : /* wait for regular transaction to end, or die trying */
4388 alvherre@alvh.no-ip. 5172 [ + + + - ]:CBC 170 : switch (wait_policy)
5173 : : {
5174 : 129 : case LockWaitBlock:
4268 heikki.linnakangas@i 5175 : 129 : XactLockTableWait(xwait, relation, &tuple->t_self,
5176 : : XLTW_Lock);
4388 alvherre@alvh.no-ip. 5177 : 129 : break;
5178 : 33 : case LockWaitSkip:
577 fujii@postgresql.org 5179 [ + - ]: 33 : if (!ConditionalXactLockTableWait(xwait, false))
5180 : : {
2760 andres@anarazel.de 5181 : 33 : result = TM_WouldBlock;
5182 : : /* recovery code expects to have buffer lock held */
914 akorotkov@postgresql 5183 : 33 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4388 alvherre@alvh.no-ip. 5184 : 33 : goto failed;
5185 : : }
4388 alvherre@alvh.no-ip. 5186 :UBC 0 : break;
4388 alvherre@alvh.no-ip. 5187 :CBC 8 : case LockWaitError:
496 fujii@postgresql.org 5188 [ + - ]: 8 : if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
4388 alvherre@alvh.no-ip. 5189 [ + - ]: 8 : ereport(ERROR,
5190 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5191 : : errmsg("could not obtain lock on row in relation \"%s\"",
5192 : : RelationGetRelationName(relation))));
4388 alvherre@alvh.no-ip. 5193 :UBC 0 : break;
5194 : : }
5195 : : }
5196 : :
5197 : : /* if there are updates, follow the update chain */
293 heikki.linnakangas@i 5198 [ + + + + ]:CBC 166 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
5199 [ + + ]: 70 : !ItemPointerEquals(&tuple->t_self, &t_ctid))
5200 : : {
5201 : : TM_Result res;
5202 : :
5203 : 55 : res = heap_lock_updated_tuple(relation,
5204 : : infomask, xwait, &t_ctid,
5205 : : GetCurrentTransactionId(),
5206 : : mode);
2760 andres@anarazel.de 5207 [ + + ]: 55 : if (res != TM_Ok)
5208 : : {
4203 alvherre@alvh.no-ip. 5209 : 5 : result = res;
5210 : : /* recovery code expects to have buffer lock held */
914 akorotkov@postgresql 5211 : 5 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4203 alvherre@alvh.no-ip. 5212 : 5 : goto failed;
5213 : : }
5214 : : }
5215 : :
914 akorotkov@postgresql 5216 : 161 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5217 : :
5218 : : /*
5219 : : * xwait is done, but if xwait had just locked the tuple then some
5220 : : * other xact could update this tuple before we get to this point.
5221 : : * Check for xmax change, and start over if so.
5222 : : */
4203 alvherre@alvh.no-ip. 5223 [ + + + + ]: 307 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5224 : 146 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5225 : : xwait))
5226 : 16 : goto l3;
5227 : :
5228 [ + + ]: 145 : if (!(infomask & HEAP_XMAX_IS_MULTI))
5229 : : {
5230 : : /*
5231 : : * Otherwise check if it committed or aborted. Note we cannot
5232 : : * be here if the tuple was only locked by somebody who didn't
5233 : : * conflict with us; that would have been handled above. So
5234 : : * that transaction must necessarily be gone by now. But
5235 : : * don't check for this in the multixact case, because some
5236 : : * locker transactions might still be running.
5237 : : */
914 akorotkov@postgresql 5238 : 111 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5239 : : }
5240 : : }
5241 : :
5242 : : /* By here, we're certain that we hold buffer exclusive lock again */
5243 : :
5244 : : /*
5245 : : * We may lock if previous xmax aborted, or if it committed but only
5246 : : * locked the tuple without updating it; or if we didn't have to wait
5247 : : * at all for whatever reason.
5248 : : */
5010 alvherre@alvh.no-ip. 5249 [ + + ]: 79516 : if (!require_sleep ||
5250 [ + + + + ]: 254 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5251 [ + + ]: 203 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5252 : 94 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
2760 andres@anarazel.de 5253 : 79430 : result = TM_Ok;
2058 alvherre@alvh.no-ip. 5254 [ + + ]: 86 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
2760 andres@anarazel.de 5255 : 65 : result = TM_Updated;
5256 : : else
5257 : 21 : result = TM_Deleted;
5258 : : }
5259 : :
5010 alvherre@alvh.no-ip. 5260 : 81375 : failed:
2760 andres@anarazel.de 5261 [ + + ]: 161095 : if (result != TM_Ok)
5262 : : {
5263 [ + + + + : 302 : Assert(result == TM_SelfModified || result == TM_Updated ||
+ + - + ]
5264 : : result == TM_Deleted || result == TM_WouldBlock);
5265 : :
5266 : : /*
5267 : : * When locking a tuple under LockWaitSkip semantics and we fail with
5268 : : * TM_WouldBlock above, it's possible for concurrent transactions to
5269 : : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5270 : : * this assert is slightly different from the equivalent one in
5271 : : * heap_delete and heap_update.
5272 : : */
1742 alvherre@alvh.no-ip. 5273 [ + + - + ]: 302 : Assert((result == TM_WouldBlock) ||
5274 : : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
2760 andres@anarazel.de 5275 [ + + - + ]: 302 : Assert(result != TM_Updated ||
5276 : : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5277 : 302 : tmfd->ctid = tuple->t_data->t_ctid;
5278 : 302 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5279 [ + + ]: 302 : if (result == TM_SelfModified)
5280 : 12 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5281 : : else
5282 : 290 : tmfd->cmax = InvalidCommandId;
3738 5283 : 302 : goto out_locked;
5284 : : }
5285 : :
5286 : : /*
5287 : : * If we didn't pin the visibility map page and the page has become all
5288 : : * visible while we were busy locking the buffer, or during some
5289 : : * subsequent window during which we had it unlocked, we'll have to unlock
5290 : : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5291 : : * unfortunate, especially since we'll now have to recheck whether the
5292 : : * tuple has been locked or updated under us, but hopefully it won't
5293 : : * happen very often.
5294 : : */
3721 5295 [ + + - + ]: 160793 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5296 : : {
914 akorotkov@postgresql 5297 :UBC 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3721 andres@anarazel.de 5298 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
914 akorotkov@postgresql 5299 : 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3721 andres@anarazel.de 5300 : 0 : goto l3;
5301 : : }
5302 : :
5010 alvherre@alvh.no-ip. 5303 :CBC 160793 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5304 : 160793 : old_infomask = tuple->t_data->t_infomask;
5305 : :
5306 : : /*
5307 : : * If this is the first possibly-multixact-able operation in the current
5308 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
5309 : : * certain that the transaction will never become a member of any older
5310 : : * MultiXactIds than that. (We have to do this even if we end up just
5311 : : * using our own TransactionId below, since some other backend could
5312 : : * incorporate our XID into a MultiXact immediately afterwards.)
5313 : : */
5314 : 160793 : MultiXactIdSetOldestMember();
5315 : :
5316 : : /*
5317 : : * Compute the new xmax and infomask to store into the tuple. Note we do
5318 : : * not modify the tuple just yet, because that would leave it in the wrong
5319 : : * state if multixact.c elogs.
5320 : : */
5321 : 160793 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5322 : : GetCurrentTransactionId(), mode, false,
5323 : : &xid, &new_infomask, &new_infomask2);
5324 : :
5325 : : /* Lock VM buffer before entering critical section */
89 melanieplageman@gmai 5326 [ + + ]: 160793 : if (PageIsAllVisible(page))
5327 : : {
5328 : 3514 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
5329 : 3514 : unlock_vmbuffer = true;
5330 : : }
5331 : :
7837 tgl@sss.pgh.pa.us 5332 : 160793 : START_CRIT_SECTION();
5333 : :
5334 : : /*
5335 : : * Store transaction information of xact locking the tuple.
5336 : : *
5337 : : * Note: Cmax is meaningless in this context, so don't set it; this avoids
5338 : : * possibly generating a useless combo CID. Moreover, if we're locking a
5339 : : * previously updated tuple, it's important to preserve the Cmax.
5340 : : *
5341 : : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5342 : : * we would break the HOT chain.
5343 : : */
5010 alvherre@alvh.no-ip. 5344 : 160793 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5345 : 160793 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5346 : 160793 : tuple->t_data->t_infomask |= new_infomask;
5347 : 160793 : tuple->t_data->t_infomask2 |= new_infomask2;
5348 [ + + ]: 160793 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5349 : 158643 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
8061 tgl@sss.pgh.pa.us 5350 : 160793 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
5351 : :
5352 : : /*
5353 : : * Make sure there is no forward chain link in t_ctid. Note that in the
5354 : : * cases where the tuple has been updated, we must not overwrite t_ctid,
5355 : : * because it was set by the updater. Moreover, if the tuple has been
5356 : : * updated, we need to follow the update chain to lock the new versions of
5357 : : * the tuple as well.
5358 : : */
5010 alvherre@alvh.no-ip. 5359 [ + + ]: 160793 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5360 : 158643 : tuple->t_data->t_ctid = *tid;
5361 : :
5362 : : /* Clear only the all-frozen bit on visibility map if needed */
89 melanieplageman@gmai 5363 [ + + ]: 160793 : if (PageIsAllVisible(page))
5364 : : {
89 melanieplageman@gmai 5365 [ + + ]:GNC 3514 : if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
5366 : : VISIBILITYMAP_ALL_FROZEN))
89 melanieplageman@gmai 5367 :CBC 16 : cleared_all_frozen = true;
5368 : : }
5369 : :
5370 : :
914 akorotkov@postgresql 5371 : 160793 : MarkBufferDirty(*buffer);
5372 : :
5373 : : /*
5374 : : * XLOG stuff. You might think that we don't need an XLOG record because
5375 : : * there is no state change worth restoring after a crash. You would be
5376 : : * wrong however: we have just written either a TransactionId or a
5377 : : * MultiXactId that may never have been seen on disk before, and we need
5378 : : * to make sure that there are XLOG entries covering those ID numbers.
5379 : : * Else the same IDs might be re-used after a crash, which would be
5380 : : * disastrous if this page made it to disk before the crash. Essentially
5381 : : * we have to enforce the WAL log-before-data rule even in this case.
5382 : : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5383 : : * entries for everything anyway.)
5384 : : */
5782 rhaas@postgresql.org 5385 [ + + + + : 160793 : if (RelationNeedsWAL(relation))
+ - + - ]
5386 : : {
5387 : : xl_heap_lock xlrec;
5388 : : XLogRecPtr recptr;
5389 : :
4344 heikki.linnakangas@i 5390 : 160360 : XLogBeginInsert();
89 melanieplageman@gmai 5391 : 160360 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, *buffer, REGBUF_STANDARD);
5392 : :
4344 heikki.linnakangas@i 5393 : 160360 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
1280 pg@bowt.ie 5394 : 160360 : xlrec.xmax = xid;
5010 alvherre@alvh.no-ip. 5395 : 320720 : xlrec.infobits_set = compute_infobits(new_infomask,
5396 : 160360 : tuple->t_data->t_infomask2);
3738 andres@anarazel.de 5397 : 160360 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
608 peter@eisentraut.org 5398 : 160360 : XLogRegisterData(&xlrec, SizeOfHeapLock);
5399 : :
89 melanieplageman@gmai 5400 [ + + ]: 160360 : if (cleared_all_frozen)
5401 : 16 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
5402 : :
5403 : : /* we don't decode row locks atm, so no need to log the origin */
5404 : :
4344 heikki.linnakangas@i 5405 : 160360 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5406 : :
6665 tgl@sss.pgh.pa.us 5407 : 160360 : PageSetLSN(page, recptr);
5408 : :
89 melanieplageman@gmai 5409 [ + + ]: 160360 : if (cleared_all_frozen)
5410 : 16 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
5411 : : }
5412 : :
7837 tgl@sss.pgh.pa.us 5413 [ - + ]: 160793 : END_CRIT_SECTION();
5414 : :
5415 : : /* release VM lock first, since it covers many heap blocks */
89 melanieplageman@gmai 5416 [ + + ]: 160793 : if (unlock_vmbuffer)
5417 : : {
5418 : 3514 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
5419 : 3514 : unlock_vmbuffer = false;
5420 : : }
5421 : :
2760 andres@anarazel.de 5422 : 160793 : result = TM_Ok;
5423 : :
3738 5424 : 161123 : out_locked:
914 akorotkov@postgresql 5425 : 161123 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
89 melanieplageman@gmai 5426 [ - + ]: 161123 : Assert(!unlock_vmbuffer);
5427 : :
3738 andres@anarazel.de 5428 : 161123 : out_unlocked:
5429 [ + + ]: 762327 : if (BufferIsValid(vmbuffer))
5430 : 604033 : ReleaseBuffer(vmbuffer);
5431 : :
5432 : : /*
5433 : : * Don't update the visibility map here. Locking a tuple doesn't change
5434 : : * visibility info.
5435 : : */
5436 : :
5437 : : /*
5438 : : * Now that we have successfully marked the tuple as locked, we can
5439 : : * release the lmgr tuple lock, if we had it.
5440 : : */
7835 tgl@sss.pgh.pa.us 5441 [ + + ]: 762327 : if (have_tuple_lock)
5010 alvherre@alvh.no-ip. 5442 : 179 : UnlockTupleTuplock(relation, tid, mode);
5443 : :
3738 andres@anarazel.de 5444 : 762327 : return result;
5445 : : }
5446 : :
5447 : : /*
5448 : : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5449 : : * its normal, Xmax-based tuple lock.
5450 : : *
5451 : : * have_tuple_lock is an input and output parameter: on input, it indicates
5452 : : * whether the lock has previously been acquired (and this function does
5453 : : * nothing in that case). If this function returns success, have_tuple_lock
5454 : : * has been flipped to true.
5455 : : *
5456 : : * Returns false if it was unable to obtain the lock; this can only happen if
5457 : : * wait_policy is Skip.
5458 : : */
5459 : : static bool
347 peter@eisentraut.org 5460 : 342 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
5461 : : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5462 : : {
4308 alvherre@alvh.no-ip. 5463 [ + + ]: 342 : if (*have_tuple_lock)
5464 : 9 : return true;
5465 : :
5466 [ + + + - ]: 333 : switch (wait_policy)
5467 : : {
5468 : 288 : case LockWaitBlock:
5469 : 288 : LockTupleTuplock(relation, tid, mode);
5470 : 288 : break;
5471 : :
5472 : 34 : case LockWaitSkip:
577 fujii@postgresql.org 5473 [ + + ]: 34 : if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
4308 alvherre@alvh.no-ip. 5474 : 1 : return false;
5475 : 33 : break;
5476 : :
5477 : 11 : case LockWaitError:
496 fujii@postgresql.org 5478 [ + + ]: 11 : if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
4308 alvherre@alvh.no-ip. 5479 [ + - ]: 1 : ereport(ERROR,
5480 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5481 : : errmsg("could not obtain lock on row in relation \"%s\"",
5482 : : RelationGetRelationName(relation))));
5483 : 10 : break;
5484 : : }
5485 : 331 : *have_tuple_lock = true;
5486 : :
5487 : 331 : return true;
5488 : : }
5489 : :
5490 : : /*
5491 : : * Given an original set of Xmax and infomask, and a transaction (identified by
5492 : : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5493 : : * corresponding infomasks to use on the tuple.
5494 : : *
5495 : : * Note that this might have side effects such as creating a new MultiXactId.
5496 : : *
5497 : : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5498 : : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5499 : : * but it was not running anymore. There is a race condition, which is that the
5500 : : * MultiXactId may have finished since then, but that uncommon case is handled
5501 : : * either here, or within MultiXactIdExpand.
5502 : : *
5503 : : * There is a similar race condition possible when the old xmax was a regular
5504 : : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5505 : : * window, but it's still possible to end up creating an unnecessary
5506 : : * MultiXactId. Fortunately this is harmless.
5507 : : */
5508 : : static void
5010 5509 : 6621453 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5510 : : uint16 old_infomask2, TransactionId add_to_xmax,
5511 : : LockTupleMode mode, bool is_update,
5512 : : TransactionId *result_xmax, uint16 *result_infomask,
5513 : : uint16 *result_infomask2)
5514 : : {
5515 : : TransactionId new_xmax;
5516 : : uint16 new_infomask,
5517 : : new_infomask2;
5518 : :
4680 5519 [ + - ]: 6621453 : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5520 : :
5010 5521 : 6725986 : l5:
5522 : 6725986 : new_infomask = 0;
5523 : 6725986 : new_infomask2 = 0;
5524 [ + + ]: 6725986 : if (old_infomask & HEAP_XMAX_INVALID)
5525 : : {
5526 : : /*
5527 : : * No previous locker; we just insert our own TransactionId.
5528 : : *
5529 : : * Note that it's critical that this case be the first one checked,
5530 : : * because there are several blocks below that come back to this one
5531 : : * to implement certain optimizations; old_infomask might contain
5532 : : * other dirty bits in those cases, but we don't really care.
5533 : : */
5534 [ + + ]: 6544806 : if (is_update)
5535 : : {
5536 : 4245218 : new_xmax = add_to_xmax;
5537 [ + + ]: 4245218 : if (mode == LockTupleExclusive)
5538 : 1887747 : new_infomask2 |= HEAP_KEYS_UPDATED;
5539 : : }
5540 : : else
5541 : : {
5542 : 2299588 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5543 [ + + + + : 2299588 : switch (mode)
- ]
5544 : : {
5545 : 6253 : case LockTupleKeyShare:
5546 : 6253 : new_xmax = add_to_xmax;
5547 : 6253 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5548 : 6253 : break;
5549 : 785 : case LockTupleShare:
5550 : 785 : new_xmax = add_to_xmax;
5551 : 785 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5552 : 785 : break;
5553 : 2196501 : case LockTupleNoKeyExclusive:
5554 : 2196501 : new_xmax = add_to_xmax;
5555 : 2196501 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5556 : 2196501 : break;
5557 : 96049 : case LockTupleExclusive:
5558 : 96049 : new_xmax = add_to_xmax;
5559 : 96049 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5560 : 96049 : new_infomask2 |= HEAP_KEYS_UPDATED;
5561 : 96049 : break;
5010 alvherre@alvh.no-ip. 5562 :UBC 0 : default:
5563 : 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5564 [ # # ]: 0 : elog(ERROR, "invalid lock mode");
5565 : : }
5566 : : }
5567 : : }
5010 alvherre@alvh.no-ip. 5568 [ + + ]:CBC 181180 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5569 : : {
5570 : : MultiXactStatus new_status;
5571 : :
5572 : : /*
5573 : : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5574 : : * cross-check.
5575 : : */
5576 [ - + ]: 75560 : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5577 : :
5578 : : /*
5579 : : * A multixact together with LOCK_ONLY set but neither lock bit set
5580 : : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5581 : : * anymore. This check is critical for databases upgraded by
5582 : : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5583 : : * that such multis are never passed.
5584 : : */
3762 5585 [ - + ]: 75560 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5586 : : {
5010 alvherre@alvh.no-ip. 5587 :UBC 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5588 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5589 : 0 : goto l5;
5590 : : }
5591 : :
5592 : : /*
5593 : : * If the XMAX is already a MultiXactId, then we need to expand it to
5594 : : * include add_to_xmax; but if all the members were lockers and are
5595 : : * all gone, we can do away with the IS_MULTI bit and just set
5596 : : * add_to_xmax as the only locker/updater. If all lockers are gone
5597 : : * and we have an updater that aborted, we can also do without a
5598 : : * multi.
5599 : : *
5600 : : * The cost of doing GetMultiXactIdMembers would be paid by
5601 : : * MultiXactIdExpand if we weren't to do this, so this check is not
5602 : : * incurring extra work anyhow.
5603 : : */
4458 alvherre@alvh.no-ip. 5604 [ + + ]:CBC 75560 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5605 : : {
5010 5606 [ + + ]: 24 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4203 5607 [ + - ]: 9 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5608 : : old_infomask)))
5609 : : {
5610 : : /*
5611 : : * Reset these bits and restart; otherwise fall through to
5612 : : * create a new multi below.
5613 : : */
5010 5614 : 24 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5615 : 24 : old_infomask |= HEAP_XMAX_INVALID;
5616 : 24 : goto l5;
5617 : : }
5618 : : }
5619 : :
5620 : 75536 : new_status = get_mxact_status_for_lock(mode, is_update);
5621 : :
5622 : 75536 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5623 : : new_status);
5624 : 75536 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5625 : : }
5626 [ + + ]: 105620 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5627 : : {
5628 : : /*
5629 : : * It's a committed update, so we need to preserve him as updater of
5630 : : * the tuple.
5631 : : */
5632 : : MultiXactStatus status;
5633 : : MultiXactStatus new_status;
5634 : :
5635 [ - + ]: 14 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5010 alvherre@alvh.no-ip. 5636 :UBC 0 : status = MultiXactStatusUpdate;
5637 : : else
5010 alvherre@alvh.no-ip. 5638 :CBC 14 : status = MultiXactStatusNoKeyUpdate;
5639 : :
5640 : 14 : new_status = get_mxact_status_for_lock(mode, is_update);
5641 : :
5642 : : /*
5643 : : * since it's not running, it's obviously impossible for the old
5644 : : * updater to be identical to the current one, so we need not check
5645 : : * for that case as we do in the block above.
5646 : : */
5647 : 14 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5648 : 14 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5649 : : }
5650 [ + + ]: 105606 : else if (TransactionIdIsInProgress(xmax))
5651 : : {
5652 : : /*
5653 : : * If the XMAX is a valid, in-progress TransactionId, then we need to
5654 : : * create a new MultiXactId that includes both the old locker or
5655 : : * updater and our own TransactionId.
5656 : : */
5657 : : MultiXactStatus new_status;
5658 : : MultiXactStatus old_status;
5659 : : LockTupleMode old_mode;
5660 : :
5661 [ + + ]: 105597 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5662 : : {
5663 [ + + ]: 105569 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4680 5664 : 5702 : old_status = MultiXactStatusForKeyShare;
5010 5665 [ + + ]: 99867 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4680 5666 : 442 : old_status = MultiXactStatusForShare;
5010 5667 [ + - ]: 99425 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5668 : : {
5669 [ + + ]: 99425 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4680 5670 : 92888 : old_status = MultiXactStatusForUpdate;
5671 : : else
5672 : 6537 : old_status = MultiXactStatusForNoKeyUpdate;
5673 : : }
5674 : : else
5675 : : {
5676 : : /*
5677 : : * LOCK_ONLY can be present alone only when a page has been
5678 : : * upgraded by pg_upgrade. But in that case,
5679 : : * TransactionIdIsInProgress() should have returned false. We
5680 : : * assume it's no longer locked in this case.
5681 : : */
5010 alvherre@alvh.no-ip. 5682 [ # # ]:UBC 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5683 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5684 : 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5685 : 0 : goto l5;
5686 : : }
5687 : : }
5688 : : else
5689 : : {
5690 : : /* it's an update, but which kind? */
5010 alvherre@alvh.no-ip. 5691 [ - + ]:CBC 28 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4680 alvherre@alvh.no-ip. 5692 :UBC 0 : old_status = MultiXactStatusUpdate;
5693 : : else
4680 alvherre@alvh.no-ip. 5694 :CBC 28 : old_status = MultiXactStatusNoKeyUpdate;
5695 : : }
5696 : :
5697 : 105597 : old_mode = TUPLOCK_from_mxstatus(old_status);
5698 : :
5699 : : /*
5700 : : * If the lock to be acquired is for the same TransactionId as the
5701 : : * existing lock, there's an optimization possible: consider only the
5702 : : * strongest of both locks as the only one present, and restart.
5703 : : */
5010 5704 [ + + ]: 105597 : if (xmax == add_to_xmax)
5705 : : {
5706 : : /*
5707 : : * Note that it's not possible for the original tuple to be
5708 : : * updated: we wouldn't be here because the tuple would have been
5709 : : * invisible and we wouldn't try to update it. As a subtlety,
5710 : : * this code can also run when traversing an update chain to lock
5711 : : * future versions of a tuple. But we wouldn't be here either,
5712 : : * because the add_to_xmax would be different from the original
5713 : : * updater.
5714 : : */
4680 5715 [ - + ]: 104501 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5716 : :
5717 : : /* acquire the strongest of both */
5718 [ + + ]: 104501 : if (mode < old_mode)
5719 : 52283 : mode = old_mode;
5720 : : /* mustn't touch is_update */
5721 : :
5722 : 104501 : old_infomask |= HEAP_XMAX_INVALID;
5723 : 104501 : goto l5;
5724 : : }
5725 : :
5726 : : /* otherwise, just fall back to creating a new multixact */
5727 : 1096 : new_status = get_mxact_status_for_lock(mode, is_update);
5728 : 1096 : new_xmax = MultiXactIdCreate(xmax, old_status,
5729 : : add_to_xmax, new_status);
5010 5730 : 1096 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5731 : : }
5732 [ + + + + ]: 14 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5733 : 5 : TransactionIdDidCommit(xmax))
5734 : 1 : {
5735 : : /*
5736 : : * It's a committed update, so we gotta preserve him as updater of the
5737 : : * tuple.
5738 : : */
5739 : : MultiXactStatus status;
5740 : : MultiXactStatus new_status;
5741 : :
5742 [ - + ]: 1 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5010 alvherre@alvh.no-ip. 5743 :UBC 0 : status = MultiXactStatusUpdate;
5744 : : else
5010 alvherre@alvh.no-ip. 5745 :CBC 1 : status = MultiXactStatusNoKeyUpdate;
5746 : :
5747 : 1 : new_status = get_mxact_status_for_lock(mode, is_update);
5748 : :
5749 : : /*
5750 : : * since it's not running, it's obviously impossible for the old
5751 : : * updater to be identical to the current one, so we need not check
5752 : : * for that case as we do in the block above.
5753 : : */
5754 : 1 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5755 : 1 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5756 : : }
5757 : : else
5758 : : {
5759 : : /*
5760 : : * Can get here iff the locking/updating transaction was running when
5761 : : * the infomask was extracted from the tuple, but finished before
5762 : : * TransactionIdIsInProgress got to run. Deal with it as if there was
5763 : : * no locker at all in the first place.
5764 : : */
5765 : 8 : old_infomask |= HEAP_XMAX_INVALID;
5766 : 8 : goto l5;
5767 : : }
5768 : :
5769 : 6621453 : *result_infomask = new_infomask;
5770 : 6621453 : *result_infomask2 = new_infomask2;
5771 : 6621453 : *result_xmax = new_xmax;
5772 : 6621453 : }
5773 : :
5774 : : /*
5775 : : * Subroutine for heap_lock_updated_tuple_rec.
5776 : : *
5777 : : * Given a hypothetical multixact status held by the transaction identified
5778 : : * with the given xid, does the current transaction need to wait, fail, or can
5779 : : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5780 : : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5781 : : * returned. If the lock is already held by the current transaction, return
5782 : : * TM_SelfModified. In case of a conflict with another transaction, a
5783 : : * different HeapTupleSatisfiesUpdate return code is returned.
5784 : : *
5785 : : * The held status is said to be hypothetical because it might correspond to a
5786 : : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5787 : : * way for simplicity of API.
5788 : : */
5789 : : static TM_Result
4702 5790 : 38777 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5791 : : LockTupleMode mode, HeapTuple tup,
5792 : : bool *needwait)
5793 : : {
5794 : : MultiXactStatus wantedstatus;
5795 : :
5796 : 38777 : *needwait = false;
5797 : 38777 : wantedstatus = get_mxact_status_for_lock(mode, false);
5798 : :
5799 : : /*
5800 : : * Note: we *must* check TransactionIdIsInProgress before
5801 : : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5802 : : * for an explanation.
5803 : : */
5804 [ - + ]: 38777 : if (TransactionIdIsCurrentTransactionId(xid))
5805 : : {
5806 : : /*
5807 : : * The tuple has already been locked by our own transaction. This is
5808 : : * very rare but can happen if multiple transactions are trying to
5809 : : * lock an ancient version of the same tuple.
5810 : : */
2760 andres@anarazel.de 5811 :UBC 0 : return TM_SelfModified;
5812 : : }
4702 alvherre@alvh.no-ip. 5813 [ + + ]:CBC 38777 : else if (TransactionIdIsInProgress(xid))
5814 : : {
5815 : : /*
5816 : : * If the locking transaction is running, what we do depends on
5817 : : * whether the lock modes conflict: if they do, then we must wait for
5818 : : * it to finish; otherwise we can fall through to lock this tuple
5819 : : * version without waiting.
5820 : : */
5821 [ + + ]: 36539 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5822 : 36539 : LOCKMODE_from_mxstatus(wantedstatus)))
5823 : : {
5824 : 8 : *needwait = true;
5825 : : }
5826 : :
5827 : : /*
5828 : : * If we set needwait above, then this value doesn't matter;
5829 : : * otherwise, this value signals to caller that it's okay to proceed.
5830 : : */
2760 andres@anarazel.de 5831 : 36539 : return TM_Ok;
5832 : : }
4702 alvherre@alvh.no-ip. 5833 [ + + ]: 2238 : else if (TransactionIdDidAbort(xid))
2760 andres@anarazel.de 5834 : 206 : return TM_Ok;
4702 alvherre@alvh.no-ip. 5835 [ + - ]: 2032 : else if (TransactionIdDidCommit(xid))
5836 : : {
5837 : : /*
5838 : : * The other transaction committed. If it was only a locker, then the
5839 : : * lock is completely gone now and we can return success; but if it
5840 : : * was an update, then what we do depends on whether the two lock
5841 : : * modes conflict. If they conflict, then we must report error to
5842 : : * caller. But if they don't, we can fall through to allow the current
5843 : : * transaction to lock the tuple.
5844 : : *
5845 : : * Note: the reason we worry about ISUPDATE here is because as soon as
5846 : : * a transaction ends, all its locks are gone and meaningless, and
5847 : : * thus we can ignore them; whereas its updates persist. In the
5848 : : * TransactionIdIsInProgress case, above, we don't need to check
5849 : : * because we know the lock is still "alive" and thus a conflict needs
5850 : : * always be checked.
5851 : : */
4694 5852 [ + + ]: 2032 : if (!ISUPDATE_from_mxstatus(status))
2760 andres@anarazel.de 5853 : 2020 : return TM_Ok;
5854 : :
4702 alvherre@alvh.no-ip. 5855 [ + + ]: 12 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5856 : 12 : LOCKMODE_from_mxstatus(wantedstatus)))
5857 : : {
5858 : : /* bummer */
2058 5859 [ + + ]: 11 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
2760 andres@anarazel.de 5860 : 9 : return TM_Updated;
5861 : : else
5862 : 2 : return TM_Deleted;
5863 : : }
5864 : :
5865 : 1 : return TM_Ok;
5866 : : }
5867 : :
5868 : : /* Not in progress, not aborted, not committed -- must have crashed */
2760 andres@anarazel.de 5869 :UBC 0 : return TM_Ok;
5870 : : }
5871 : :
5872 : :
5873 : : /*
5874 : : * Recursive part of heap_lock_updated_tuple
5875 : : *
5876 : : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5877 : : * xid with the given mode; if this tuple is updated, recurse to lock the new
5878 : : * version as well.
5879 : : */
5880 : : static TM_Result
293 heikki.linnakangas@i 5881 :CBC 2224 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
5882 : : const ItemPointerData *tid, TransactionId xid,
5883 : : LockTupleMode mode)
5884 : : {
5885 : : TM_Result result;
5886 : : ItemPointerData tupid;
5887 : : HeapTupleData mytup;
5888 : : Buffer buf;
5889 : : Page page;
5890 : : uint16 new_infomask,
5891 : : new_infomask2,
5892 : : old_infomask,
5893 : : old_infomask2;
5894 : : TransactionId xmax,
5895 : : new_xmax;
3738 andres@anarazel.de 5896 : 2224 : bool cleared_all_frozen = false;
5897 : : bool pinned_desired_page;
5898 : 2224 : Buffer vmbuffer = InvalidBuffer;
89 melanieplageman@gmai 5899 : 2224 : bool unlock_vmbuffer = false;
5900 : : BlockNumber block;
5901 : :
5010 alvherre@alvh.no-ip. 5902 : 2224 : ItemPointerCopy(tid, &tupid);
5903 : :
5904 : : for (;;)
5905 : : {
5906 : 2227 : new_infomask = 0;
5907 : 2227 : new_xmax = InvalidTransactionId;
89 melanieplageman@gmai 5908 : 2227 : cleared_all_frozen = false;
3738 andres@anarazel.de 5909 : 2227 : block = ItemPointerGetBlockNumber(&tupid);
5010 alvherre@alvh.no-ip. 5910 : 2227 : ItemPointerCopy(&tupid, &(mytup.t_self));
5911 : :
1643 tgl@sss.pgh.pa.us 5912 [ + - ]: 2227 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5913 : : {
5914 : : /*
5915 : : * if we fail to find the updated version of the tuple, it's
5916 : : * because it was vacuumed/pruned away after its creator
5917 : : * transaction aborted. So behave as if we got to the end of the
5918 : : * chain, and there's no further tuple to lock: return success to
5919 : : * caller.
5920 : : */
2760 andres@anarazel.de 5921 :UBC 0 : result = TM_Ok;
3146 tgl@sss.pgh.pa.us 5922 : 0 : goto out_unlocked;
5923 : : }
5924 : :
5010 alvherre@alvh.no-ip. 5925 :CBC 2227 : l4:
5926 [ - + ]: 2235 : CHECK_FOR_INTERRUPTS();
5927 : :
89 melanieplageman@gmai 5928 : 2235 : page = BufferGetPage(buf);
5929 : :
5930 : : /*
5931 : : * Before locking the buffer, pin the visibility map page if it
5932 : : * appears to be necessary. Since we haven't got the lock yet,
5933 : : * someone else might be in the middle of changing this, so we'll need
5934 : : * to recheck after we have the lock.
5935 : : */
5936 [ - + ]: 2235 : if (PageIsAllVisible(page))
5937 : : {
3738 andres@anarazel.de 5938 :UBC 0 : visibilitymap_pin(rel, block, &vmbuffer);
3146 tgl@sss.pgh.pa.us 5939 : 0 : pinned_desired_page = true;
5940 : : }
5941 : : else
3146 tgl@sss.pgh.pa.us 5942 :CBC 2235 : pinned_desired_page = false;
5943 : :
5010 alvherre@alvh.no-ip. 5944 : 2235 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5945 : :
5946 : : /*
5947 : : * If we didn't pin the visibility map page and the page has become
5948 : : * all visible while we were busy locking the buffer, we'll have to
5949 : : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5950 : : * That's a bit unfortunate, but hopefully shouldn't happen often.
5951 : : *
5952 : : * Note: in some paths through this function, we will reach here
5953 : : * holding a pin on a vm page that may or may not be the one matching
5954 : : * this page. If this page isn't all-visible, we won't use the vm
5955 : : * page, but we hold onto such a pin till the end of the function.
5956 : : */
89 melanieplageman@gmai 5957 [ + - - + ]: 2235 : if (!pinned_desired_page && PageIsAllVisible(page))
5958 : : {
3721 andres@anarazel.de 5959 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5960 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5961 : 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5962 : : }
5963 : :
5964 : : /*
5965 : : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5966 : : * end of the chain, we're done, so return success.
5967 : : */
4702 alvherre@alvh.no-ip. 5968 [ + - + + ]:CBC 4470 : if (TransactionIdIsValid(priorXmax) &&
3266 5969 : 2235 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5970 : : priorXmax))
5971 : : {
2760 andres@anarazel.de 5972 : 2 : result = TM_Ok;
3738 5973 : 2 : goto out_locked;
5974 : : }
5975 : :
5976 : : /*
5977 : : * Also check Xmin: if this tuple was created by an aborted
5978 : : * (sub)transaction, then we already locked the last live one in the
5979 : : * chain, thus we're done, so return success.
5980 : : */
3685 alvherre@alvh.no-ip. 5981 [ + + ]: 2233 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
5982 : : {
2760 andres@anarazel.de 5983 : 25 : result = TM_Ok;
3146 tgl@sss.pgh.pa.us 5984 : 25 : goto out_locked;
5985 : : }
5986 : :
5010 alvherre@alvh.no-ip. 5987 : 2208 : old_infomask = mytup.t_data->t_infomask;
4702 5988 : 2208 : old_infomask2 = mytup.t_data->t_infomask2;
5010 5989 : 2208 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5990 : :
5991 : : /*
5992 : : * If this tuple version has been updated or locked by some concurrent
5993 : : * transaction(s), what we do depends on whether our lock mode
5994 : : * conflicts with what those other transactions hold, and also on the
5995 : : * status of them.
5996 : : */
4702 5997 [ + + ]: 2208 : if (!(old_infomask & HEAP_XMAX_INVALID))
5998 : : {
5999 : : TransactionId rawxmax;
6000 : : bool needwait;
6001 : :
6002 : 2141 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
6003 [ + + ]: 2141 : if (old_infomask & HEAP_XMAX_IS_MULTI)
6004 : : {
6005 : : int nmembers;
6006 : : int i;
6007 : : MultiXactMember *members;
6008 : :
6009 : : /*
6010 : : * We don't need a test for pg_upgrade'd tuples: this is only
6011 : : * applied to tuples after the first in an update chain. Said
6012 : : * first tuple in the chain may well be locked-in-9.2-and-
6013 : : * pg_upgraded, but that one was already locked by our caller,
6014 : : * not us; and any subsequent ones cannot be because our
6015 : : * caller must necessarily have obtained a snapshot later than
6016 : : * the pg_upgrade itself.
6017 : : */
3762 6018 [ - + ]: 2109 : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
6019 : :
4458 6020 : 2109 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
3400 tgl@sss.pgh.pa.us 6021 : 2109 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4702 alvherre@alvh.no-ip. 6022 [ + + ]: 40854 : for (i = 0; i < nmembers; i++)
6023 : : {
3738 andres@anarazel.de 6024 : 38745 : result = test_lockmode_for_conflict(members[i].status,
6025 : 38745 : members[i].xid,
6026 : : mode,
6027 : : &mytup,
6028 : : &needwait);
6029 : :
6030 : : /*
6031 : : * If the tuple was already locked by ourselves in a
6032 : : * previous iteration of this (say heap_lock_tuple was
6033 : : * forced to restart the locking loop because of a change
6034 : : * in xmax), then we hold the lock already on this tuple
6035 : : * version and we don't need to do anything; and this is
6036 : : * not an error condition either. We just need to skip
6037 : : * this tuple and continue locking the next version in the
6038 : : * update chain.
6039 : : */
2760 6040 [ - + ]: 38745 : if (result == TM_SelfModified)
6041 : : {
3365 alvherre@alvh.no-ip. 6042 :UBC 0 : pfree(members);
6043 : 0 : goto next;
6044 : : }
6045 : :
4702 alvherre@alvh.no-ip. 6046 [ - + ]:CBC 38745 : if (needwait)
6047 : : {
4702 alvherre@alvh.no-ip. 6048 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4590 6049 : 0 : XactLockTableWait(members[i].xid, rel,
6050 : : &mytup.t_self,
6051 : : XLTW_LockUpdated);
4702 6052 : 0 : pfree(members);
6053 : 0 : goto l4;
6054 : : }
2760 andres@anarazel.de 6055 [ - + ]:CBC 38745 : if (result != TM_Ok)
6056 : : {
4702 alvherre@alvh.no-ip. 6057 :UBC 0 : pfree(members);
3738 andres@anarazel.de 6058 : 0 : goto out_locked;
6059 : : }
6060 : : }
4702 alvherre@alvh.no-ip. 6061 [ + - ]:CBC 2109 : if (members)
6062 : 2109 : pfree(members);
6063 : : }
6064 : : else
6065 : : {
6066 : : MultiXactStatus status;
6067 : :
6068 : : /*
6069 : : * For a non-multi Xmax, we first need to compute the
6070 : : * corresponding MultiXactStatus by using the infomask bits.
6071 : : */
6072 [ + + ]: 32 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
6073 : : {
6074 [ + - ]: 10 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
6075 : 10 : status = MultiXactStatusForKeyShare;
4702 alvherre@alvh.no-ip. 6076 [ # # ]:UBC 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
6077 : 0 : status = MultiXactStatusForShare;
6078 [ # # ]: 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
6079 : : {
6080 [ # # ]: 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6081 : 0 : status = MultiXactStatusForUpdate;
6082 : : else
6083 : 0 : status = MultiXactStatusForNoKeyUpdate;
6084 : : }
6085 : : else
6086 : : {
6087 : : /*
6088 : : * LOCK_ONLY present alone (a pg_upgraded tuple marked
6089 : : * as share-locked in the old cluster) shouldn't be
6090 : : * seen in the middle of an update chain.
6091 : : */
6092 [ # # ]: 0 : elog(ERROR, "invalid lock status in tuple");
6093 : : }
6094 : : }
6095 : : else
6096 : : {
6097 : : /* it's an update, but which kind? */
4702 alvherre@alvh.no-ip. 6098 [ + + ]:CBC 22 : if (old_infomask2 & HEAP_KEYS_UPDATED)
6099 : 17 : status = MultiXactStatusUpdate;
6100 : : else
6101 : 5 : status = MultiXactStatusNoKeyUpdate;
6102 : : }
6103 : :
3738 andres@anarazel.de 6104 : 32 : result = test_lockmode_for_conflict(status, rawxmax, mode,
6105 : : &mytup, &needwait);
6106 : :
6107 : : /*
6108 : : * If the tuple was already locked by ourselves in a previous
6109 : : * iteration of this (say heap_lock_tuple was forced to
6110 : : * restart the locking loop because of a change in xmax), then
6111 : : * we hold the lock already on this tuple version and we don't
6112 : : * need to do anything; and this is not an error condition
6113 : : * either. We just need to skip this tuple and continue
6114 : : * locking the next version in the update chain.
6115 : : */
2760 6116 [ - + ]: 32 : if (result == TM_SelfModified)
3365 alvherre@alvh.no-ip. 6117 :UBC 0 : goto next;
6118 : :
4702 alvherre@alvh.no-ip. 6119 [ + + ]:CBC 32 : if (needwait)
6120 : : {
6121 : 8 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4268 heikki.linnakangas@i 6122 : 8 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
6123 : : XLTW_LockUpdated);
4702 alvherre@alvh.no-ip. 6124 : 8 : goto l4;
6125 : : }
2760 andres@anarazel.de 6126 [ + + ]: 24 : if (result != TM_Ok)
6127 : : {
3738 6128 : 11 : goto out_locked;
6129 : : }
6130 : : }
6131 : : }
6132 : :
6133 : : /* compute the new Xmax and infomask values for the tuple ... */
5010 alvherre@alvh.no-ip. 6134 : 2189 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
6135 : : xid, mode, false,
6136 : : &new_xmax, &new_infomask, &new_infomask2);
6137 : :
89 melanieplageman@gmai 6138 [ - + ]: 2189 : if (PageIsAllVisible(page))
6139 : : {
89 melanieplageman@gmai 6140 :UBC 0 : LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
6141 : 0 : unlock_vmbuffer = true;
6142 : : }
6143 : :
5010 alvherre@alvh.no-ip. 6144 :CBC 2189 : START_CRIT_SECTION();
6145 : :
6146 : : /* ... and set them */
6147 : 2189 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
6148 : 2189 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
6149 : 2189 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6150 : 2189 : mytup.t_data->t_infomask |= new_infomask;
6151 : 2189 : mytup.t_data->t_infomask2 |= new_infomask2;
6152 : :
6153 : 2189 : MarkBufferDirty(buf);
6154 : :
89 melanieplageman@gmai 6155 [ - + ]: 2189 : if (PageIsAllVisible(page))
6156 : : {
6157 : : /* It's possible all-frozen was already clear */
89 melanieplageman@gmai 6158 [ # # ]:UNC 0 : if (visibilitymap_clear(rel->rd_locator, block, vmbuffer,
6159 : : VISIBILITYMAP_ALL_FROZEN))
89 melanieplageman@gmai 6160 :UBC 0 : cleared_all_frozen = true;
6161 : : }
6162 : :
6163 : : /* XLOG stuff */
5010 alvherre@alvh.no-ip. 6164 [ + - + + :CBC 2189 : if (RelationNeedsWAL(rel))
+ - + - ]
6165 : : {
6166 : : xl_heap_lock_updated xlrec;
6167 : : XLogRecPtr recptr;
6168 : :
4344 heikki.linnakangas@i 6169 : 2189 : XLogBeginInsert();
89 melanieplageman@gmai 6170 : 2189 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buf, REGBUF_STANDARD);
6171 : :
4344 heikki.linnakangas@i 6172 : 2189 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5010 alvherre@alvh.no-ip. 6173 : 2189 : xlrec.xmax = new_xmax;
6174 : 2189 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
3738 andres@anarazel.de 6175 : 2189 : xlrec.flags =
6176 : 2189 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
6177 : :
608 peter@eisentraut.org 6178 : 2189 : XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
6179 : :
89 melanieplageman@gmai 6180 [ - + ]: 2189 : if (cleared_all_frozen)
89 melanieplageman@gmai 6181 :UBC 0 : XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
6182 : :
4344 heikki.linnakangas@i 6183 :CBC 2189 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
6184 : :
5010 alvherre@alvh.no-ip. 6185 : 2189 : PageSetLSN(page, recptr);
6186 : :
89 melanieplageman@gmai 6187 [ - + ]: 2189 : if (cleared_all_frozen)
89 melanieplageman@gmai 6188 :UBC 0 : PageSetLSN(BufferGetPage(vmbuffer), recptr);
6189 : : }
6190 : :
5010 alvherre@alvh.no-ip. 6191 [ - + ]:CBC 2189 : END_CRIT_SECTION();
6192 : :
6193 : : /* release VM lock first, since it covers many heap blocks */
89 melanieplageman@gmai 6194 [ + - ]: 2189 : if (unlock_vmbuffer)
6195 : : {
89 melanieplageman@gmai 6196 :UBC 0 : LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
6197 : 0 : unlock_vmbuffer = false;
6198 : : }
6199 : :
3365 alvherre@alvh.no-ip. 6200 :CBC 2189 : next:
6201 : : /* if we find the end of update chain, we're done. */
5010 6202 [ + - + - ]: 4378 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
3110 andres@anarazel.de 6203 [ + + ]: 4378 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
4884 bruce@momjian.us 6204 [ + + ]: 2193 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5010 alvherre@alvh.no-ip. 6205 : 4 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
6206 : : {
2760 andres@anarazel.de 6207 : 2186 : result = TM_Ok;
3738 6208 : 2186 : goto out_locked;
6209 : : }
6210 : :
6211 : : /* tail recursion */
4702 alvherre@alvh.no-ip. 6212 : 3 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5010 6213 : 3 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6214 : 3 : UnlockReleaseBuffer(buf);
6215 : : }
6216 : :
6217 : : result = TM_Ok;
6218 : :
3738 andres@anarazel.de 6219 : 2224 : out_locked:
6220 : 2224 : UnlockReleaseBuffer(buf);
6221 : :
3146 tgl@sss.pgh.pa.us 6222 : 2224 : out_unlocked:
3738 andres@anarazel.de 6223 [ - + ]: 2224 : if (vmbuffer != InvalidBuffer)
3738 andres@anarazel.de 6224 :UBC 0 : ReleaseBuffer(vmbuffer);
89 melanieplageman@gmai 6225 [ - + ]:CBC 2224 : Assert(!unlock_vmbuffer);
6226 : :
3738 andres@anarazel.de 6227 : 2224 : return result;
6228 : : }
6229 : :
6230 : : /*
6231 : : * heap_lock_updated_tuple
6232 : : * Follow update chain when locking an updated tuple, acquiring locks (row
6233 : : * marks) on the updated versions.
6234 : : *
6235 : : * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
6236 : : * fields from the initial tuple. We will lock the tuples starting from the
6237 : : * one that 'prior_ctid' points to. Note: This function does not lock the
6238 : : * initial tuple itself.
6239 : : *
6240 : : * This function doesn't check visibility, it just unconditionally marks the
6241 : : * tuple(s) as locked. If any tuple in the updated chain is being deleted
6242 : : * concurrently (or updated with the key being modified), sleep until the
6243 : : * transaction doing it is finished.
6244 : : *
6245 : : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6246 : : * when we have to wait for other transactions to release them, as opposed to
6247 : : * what heap_lock_tuple does. The reason is that having more than one
6248 : : * transaction walking the chain is probably uncommon enough that risk of
6249 : : * starvation is not likely: one of the preconditions for being here is that
6250 : : * the snapshot in use predates the update that created this tuple (because we
6251 : : * started at an earlier version of the tuple), but at the same time such a
6252 : : * transaction cannot be using repeatable read or serializable isolation
6253 : : * levels, because that would lead to a serializability failure.
6254 : : */
6255 : : static TM_Result
293 heikki.linnakangas@i 6256 : 2226 : heap_lock_updated_tuple(Relation rel,
6257 : : uint16 prior_infomask,
6258 : : TransactionId prior_raw_xmax,
6259 : : const ItemPointerData *prior_ctid,
6260 : : TransactionId xid, LockTupleMode mode)
6261 : : {
6262 : 2226 : INJECTION_POINT("heap_lock_updated_tuple", NULL);
6263 : :
6264 : : /*
6265 : : * If the tuple has moved into another partition (effectively a delete)
6266 : : * stop here.
6267 : : */
6268 [ + + ]: 2226 : if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
6269 : : {
6270 : : TransactionId prior_xmax;
6271 : :
6272 : : /*
6273 : : * If this is the first possibly-multixact-able operation in the
6274 : : * current transaction, set my per-backend OldestMemberMXactId
6275 : : * setting. We can be certain that the transaction will never become a
6276 : : * member of any older MultiXactIds than that. (We have to do this
6277 : : * even if we end up just using our own TransactionId below, since
6278 : : * some other backend could incorporate our XID into a MultiXact
6279 : : * immediately afterwards.)
6280 : : */
5010 alvherre@alvh.no-ip. 6281 : 2224 : MultiXactIdSetOldestMember();
6282 : :
293 heikki.linnakangas@i 6283 : 4448 : prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
6284 [ + + ]: 2224 : MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
6285 : 2224 : return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
6286 : : }
6287 : :
6288 : : /* nothing to lock */
2760 andres@anarazel.de 6289 : 2 : return TM_Ok;
6290 : : }
6291 : :
6292 : : /*
6293 : : * heap_finish_speculative - mark speculative insertion as successful
6294 : : *
6295 : : * To successfully finish a speculative insertion we have to clear speculative
6296 : : * token from tuple. To do so the t_ctid field, which will contain a
6297 : : * speculative token value, is modified in place to point to the tuple itself,
6298 : : * which is characteristic of a newly inserted ordinary tuple.
6299 : : *
6300 : : * NB: It is not ok to commit without either finishing or aborting a
6301 : : * speculative insertion. We could treat speculative tuples of committed
6302 : : * transactions implicitly as completed, but then we would have to be prepared
6303 : : * to deal with speculative tokens on committed tuples. That wouldn't be
6304 : : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6305 : : * but clearing the token at completion isn't very expensive either.
6306 : : * An explicit confirmation WAL record also makes logical decoding simpler.
6307 : : */
6308 : : void
347 peter@eisentraut.org 6309 : 2235 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
6310 : : {
6311 : : Buffer buffer;
6312 : : Page page;
6313 : : OffsetNumber offnum;
6314 : : ItemId lp;
6315 : : HeapTupleHeader htup;
6316 : :
2760 andres@anarazel.de 6317 : 2235 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4175 6318 : 2235 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
409 peter@eisentraut.org 6319 : 2235 : page = BufferGetPage(buffer);
6320 : :
2760 andres@anarazel.de 6321 : 2235 : offnum = ItemPointerGetOffsetNumber(tid);
301 tgl@sss.pgh.pa.us 6322 [ + - - + ]: 2235 : if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
301 tgl@sss.pgh.pa.us 6323 [ # # ]:UBC 0 : elog(ERROR, "offnum out of range");
301 tgl@sss.pgh.pa.us 6324 :CBC 2235 : lp = PageGetItemId(page, offnum);
6325 [ - + ]: 2235 : if (!ItemIdIsNormal(lp))
3980 andres@anarazel.de 6326 [ # # ]:UBC 0 : elog(ERROR, "invalid lp");
6327 : :
4175 andres@anarazel.de 6328 :CBC 2235 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6329 : :
6330 : : /* NO EREPORT(ERROR) from here till changes are logged */
6331 : 2235 : START_CRIT_SECTION();
6332 : :
2760 6333 [ - + ]: 2235 : Assert(HeapTupleHeaderIsSpeculative(htup));
6334 : :
4175 6335 : 2235 : MarkBufferDirty(buffer);
6336 : :
6337 : : /*
6338 : : * Replace the speculative insertion token with a real t_ctid, pointing to
6339 : : * itself like it does on regular tuples.
6340 : : */
2760 6341 : 2235 : htup->t_ctid = *tid;
6342 : :
6343 : : /* XLOG stuff */
4175 6344 [ + + + + : 2235 : if (RelationNeedsWAL(relation))
+ - + - ]
6345 : : {
6346 : : xl_heap_confirm xlrec;
6347 : : XLogRecPtr recptr;
6348 : :
2760 6349 : 2216 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
6350 : :
4175 6351 : 2216 : XLogBeginInsert();
6352 : :
6353 : : /* We want the same filtering on this as on a plain insert */
3581 6354 : 2216 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6355 : :
608 peter@eisentraut.org 6356 : 2216 : XLogRegisterData(&xlrec, SizeOfHeapConfirm);
4175 andres@anarazel.de 6357 : 2216 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6358 : :
6359 : 2216 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6360 : :
6361 : 2216 : PageSetLSN(page, recptr);
6362 : : }
6363 : :
6364 [ - + ]: 2235 : END_CRIT_SECTION();
6365 : :
6366 : 2235 : UnlockReleaseBuffer(buffer);
6367 : 2235 : }
6368 : :
6369 : : /*
6370 : : * heap_abort_speculative - kill a speculatively inserted tuple
6371 : : *
6372 : : * Marks a tuple that was speculatively inserted in the same command as dead,
6373 : : * by setting its xmin as invalid. That makes it immediately appear as dead
6374 : : * to all transactions, including our own. In particular, it makes
6375 : : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6376 : : * inserting a duplicate key value won't unnecessarily wait for our whole
6377 : : * transaction to finish (it'll just wait for our speculative insertion to
6378 : : * finish).
6379 : : *
6380 : : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6381 : : * that arise due to a mutual dependency that is not user visible. By
6382 : : * definition, unprincipled deadlocks cannot be prevented by the user
6383 : : * reordering lock acquisition in client code, because the implementation level
6384 : : * lock acquisitions are not under the user's direct control. If speculative
6385 : : * inserters did not take this precaution, then under high concurrency they
6386 : : * could deadlock with each other, which would not be acceptable.
6387 : : *
6388 : : * This is somewhat redundant with heap_delete, but we prefer to have a
6389 : : * dedicated routine with stripped down requirements. Note that this is also
6390 : : * used to delete the TOAST tuples created during speculative insertion.
6391 : : *
6392 : : * This routine does not affect logical decoding as it only looks at
6393 : : * confirmation records.
6394 : : */
6395 : : void
347 peter@eisentraut.org 6396 : 15 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
6397 : : {
4175 andres@anarazel.de 6398 : 15 : TransactionId xid = GetCurrentTransactionId();
6399 : : ItemId lp;
6400 : : HeapTupleData tp;
6401 : : Page page;
6402 : : BlockNumber block;
6403 : : Buffer buffer;
6404 : :
6405 [ - + ]: 15 : Assert(ItemPointerIsValid(tid));
6406 : :
6407 : 15 : block = ItemPointerGetBlockNumber(tid);
6408 : 15 : buffer = ReadBuffer(relation, block);
3827 kgrittn@postgresql.o 6409 : 15 : page = BufferGetPage(buffer);
6410 : :
4175 andres@anarazel.de 6411 : 15 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6412 : :
6413 : : /*
6414 : : * Page can't be all visible, we just inserted into it, and are still
6415 : : * running.
6416 : : */
6417 [ - + ]: 15 : Assert(!PageIsAllVisible(page));
6418 : :
6419 : 15 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6420 [ - + ]: 15 : Assert(ItemIdIsNormal(lp));
6421 : :
6422 : 15 : tp.t_tableOid = RelationGetRelid(relation);
6423 : 15 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6424 : 15 : tp.t_len = ItemIdGetLength(lp);
6425 : 15 : tp.t_self = *tid;
6426 : :
6427 : : /*
6428 : : * Sanity check that the tuple really is a speculatively inserted tuple,
6429 : : * inserted by us.
6430 : : */
6431 [ - + ]: 15 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
4175 andres@anarazel.de 6432 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
3708 andres@anarazel.de 6433 [ + + - + ]:CBC 15 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
4175 andres@anarazel.de 6434 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
4175 andres@anarazel.de 6435 [ - + ]:CBC 15 : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
6436 : :
6437 : : /*
6438 : : * No need to check for serializable conflicts here. There is never a
6439 : : * need for a combo CID, either. No need to extract replica identity, or
6440 : : * do anything special with infomask bits.
6441 : : */
6442 : :
6443 : 15 : START_CRIT_SECTION();
6444 : :
6445 : : /*
6446 : : * The tuple will become DEAD immediately. Flag that this page is a
6447 : : * candidate for pruning by setting xmin to TransactionXmin. While not
6448 : : * immediately prunable, it is the oldest xid we can cheaply determine
6449 : : * that's safe against wraparound / being older than the table's
6450 : : * relfrozenxid. To defend against the unlikely case of a new relation
6451 : : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6452 : : * if so (vacuum can't subsequently move relfrozenxid to beyond
6453 : : * TransactionXmin, so there's no race here).
6454 : : */
2381 6455 [ - + ]: 15 : Assert(TransactionIdIsValid(TransactionXmin));
6456 : : {
896 noah@leadboat.com 6457 : 15 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6458 : : TransactionId prune_xid;
6459 : :
6460 [ - + ]: 15 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
896 noah@leadboat.com 6461 :UBC 0 : prune_xid = relfrozenxid;
6462 : : else
896 noah@leadboat.com 6463 :CBC 15 : prune_xid = TransactionXmin;
6464 [ - + + - : 15 : PageSetPrunable(page, prune_xid);
+ + ]
6465 : : }
6466 : :
6467 : : /* store transaction information of xact deleting the tuple */
4175 andres@anarazel.de 6468 : 15 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
6469 : 15 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6470 : :
6471 : : /*
6472 : : * Set the tuple header xmin to InvalidTransactionId. This makes the
6473 : : * tuple immediately invisible everyone. (In particular, to any
6474 : : * transactions waiting on the speculative token, woken up later.)
6475 : : */
6476 : 15 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
6477 : :
6478 : : /* Clear the speculative insertion token too */
6479 : 15 : tp.t_data->t_ctid = tp.t_self;
6480 : :
6481 : 15 : MarkBufferDirty(buffer);
6482 : :
6483 : : /*
6484 : : * XLOG stuff
6485 : : *
6486 : : * The WAL records generated here match heap_delete(). The same recovery
6487 : : * routines are used.
6488 : : */
6489 [ + + + + : 15 : if (RelationNeedsWAL(relation))
+ - + - ]
6490 : : {
6491 : : xl_heap_delete xlrec;
6492 : : XLogRecPtr recptr;
6493 : :
6494 : 11 : xlrec.flags = XLH_DELETE_IS_SUPER;
6495 : 22 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6496 : 11 : tp.t_data->t_infomask2);
6497 : 11 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6498 : 11 : xlrec.xmax = xid;
6499 : :
6500 : 11 : XLogBeginInsert();
608 peter@eisentraut.org 6501 : 11 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
4175 andres@anarazel.de 6502 : 11 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6503 : :
6504 : : /* No replica identity & replication origin logged */
6505 : :
6506 : 11 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6507 : :
6508 : 11 : PageSetLSN(page, recptr);
6509 : : }
6510 : :
6511 [ - + ]: 15 : END_CRIT_SECTION();
6512 : :
6513 : 15 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6514 : :
6515 [ + + ]: 15 : if (HeapTupleHasExternal(&tp))
6516 : : {
3708 6517 [ - + ]: 1 : Assert(!IsToastRelation(relation));
2565 rhaas@postgresql.org 6518 : 1 : heap_toast_delete(relation, &tp, true);
6519 : : }
6520 : :
6521 : : /*
6522 : : * Never need to mark tuple for invalidation, since catalogs don't support
6523 : : * speculative insertion
6524 : : */
6525 : :
6526 : : /* Now we can release the buffer */
4175 andres@anarazel.de 6527 : 15 : ReleaseBuffer(buffer);
6528 : :
6529 : : /* count deletion, as we counted the insertion too */
6530 : 15 : pgstat_count_heap_delete(relation);
6531 : 15 : }
6532 : :
6533 : : /*
6534 : : * heap_inplace_lock - protect inplace update from concurrent heap_update()
6535 : : *
6536 : : * Evaluate whether the tuple's state is compatible with a no-key update.
6537 : : * Current transaction rowmarks are fine, as is KEY SHARE from any
6538 : : * transaction. If compatible, return true with the buffer exclusive-locked,
6539 : : * and the caller must release that by calling
6540 : : * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6541 : : * an error. Otherwise, call release_callback(arg), wait for blocking
6542 : : * transactions to end, and return false.
6543 : : *
6544 : : * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6545 : : * DDL, this doesn't guarantee any particular predicate locking.
6546 : : *
6547 : : * heap_delete() is a rarer source of blocking transactions (xwait). We'll
6548 : : * wait for such a transaction just like for the normal heap_update() case.
6549 : : * Normal concurrent DROP commands won't cause that, because all inplace
6550 : : * updaters take some lock that conflicts with DROP. An explicit SQL "DELETE
6551 : : * FROM pg_class" can cause it. By waiting, if the concurrent transaction
6552 : : * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
6553 : : * can find the successor tuple.
6554 : : *
6555 : : * Readers of inplace-updated fields expect changes to those fields are
6556 : : * durable. For example, vac_truncate_clog() reads datfrozenxid from
6557 : : * pg_database tuples via catalog snapshots. A future snapshot must not
6558 : : * return a lower datfrozenxid for the same database OID (lower in the
6559 : : * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6560 : : * tuple can start while we hold a lock on its buffer. In cases like
6561 : : * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6562 : : * to this transaction. ROLLBACK then is one case where it's okay to lose
6563 : : * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6564 : : * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6565 : : * committed tuple.)
6566 : : *
6567 : : * In principle, we could avoid waiting by overwriting every tuple in the
6568 : : * updated tuple chain. Reader expectations permit updating a tuple only if
6569 : : * it's aborted, is the tail of the chain, or we already updated the tuple
6570 : : * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6571 : : * order from tail to head. That would imply either (a) mutating all tuples
6572 : : * in one critical section or (b) accepting a chance of partial completion.
6573 : : * Partial completion of a relfrozenxid update would have the weird
6574 : : * consequence that the table's next VACUUM could see the table's relfrozenxid
6575 : : * move forward between vacuum_get_cutoffs() and finishing.
6576 : : */
6577 : : pg_attribute_no_sanitize_function()
6578 : : bool
748 noah@leadboat.com 6579 : 114420 : heap_inplace_lock(Relation relation,
6580 : : HeapTuple oldtup_ptr, Buffer buffer,
6581 : : void (*release_callback) (void *), void *arg)
6582 : : {
6583 : 114420 : HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6584 : : TM_Result result;
6585 : : bool ret;
6586 : :
6587 : : #ifdef USE_ASSERT_CHECKING
6588 [ + + ]: 114420 : if (RelationGetRelid(relation) == RelationRelationId)
6589 : 113028 : check_inplace_rel_lock(oldtup_ptr);
6590 : : #endif
6591 : :
6592 [ - + ]: 114420 : Assert(BufferIsValid(buffer));
6593 : :
6594 : : /*
6595 : : * Register shared cache invals if necessary. Other sessions may finish
6596 : : * inplace updates of this tuple between this step and LockTuple(). Since
6597 : : * inplace updates don't change cache keys, that's harmless.
6598 : : *
6599 : : * While it's tempting to register invals only after confirming we can
6600 : : * return true, the following obstacle precludes reordering steps that
6601 : : * way. Registering invals might reach a CatalogCacheInitializeCache()
6602 : : * that locks "buffer". That would hang indefinitely if running after our
6603 : : * own LockBuffer(). Hence, we must register invals before LockBuffer().
6604 : : */
301 6605 : 114420 : CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
6606 : :
748 6607 : 114420 : LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6608 : 114420 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6609 : :
6610 : : /*----------
6611 : : * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6612 : : *
6613 : : * - wait unconditionally
6614 : : * - already locked tuple above, since inplace needs that unconditionally
6615 : : * - don't recheck header after wait: simpler to defer to next iteration
6616 : : * - don't try to continue even if the updater aborts: likewise
6617 : : * - no crosscheck
6618 : : */
6619 : 114420 : result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6620 : : buffer);
6621 : :
6622 [ - + ]: 114420 : if (result == TM_Invisible)
6623 : : {
6624 : : /* no known way this can happen */
4183 rhaas@postgresql.org 6625 [ # # ]:UBC 0 : ereport(ERROR,
6626 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6627 : : errmsg_internal("attempted to overwrite invisible tuple")));
6628 : : }
748 noah@leadboat.com 6629 [ - + ]:CBC 114420 : else if (result == TM_SelfModified)
6630 : : {
6631 : : /*
6632 : : * CREATE INDEX might reach this if an expression is silly enough to
6633 : : * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6634 : : * statements might get here after a heap_update() of the same row, in
6635 : : * the absence of an intervening CommandCounterIncrement().
6636 : : */
748 noah@leadboat.com 6637 [ # # ]:UBC 0 : ereport(ERROR,
6638 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6639 : : errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6640 : : }
748 noah@leadboat.com 6641 [ + + ]:CBC 114420 : else if (result == TM_BeingModified)
6642 : : {
6643 : : TransactionId xwait;
6644 : : uint16 infomask;
6645 : :
6646 : 59 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6647 : 59 : infomask = oldtup.t_data->t_infomask;
6648 : :
6649 [ + + ]: 59 : if (infomask & HEAP_XMAX_IS_MULTI)
6650 : : {
6651 : 5 : LockTupleMode lockmode = LockTupleNoKeyExclusive;
6652 : 5 : MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
6653 : : int remain;
6654 : :
6655 [ + + ]: 5 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6656 : : lockmode, NULL))
6657 : : {
6658 : 2 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
713 6659 : 2 : release_callback(arg);
748 6660 : 2 : ret = false;
6661 : 2 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6662 : : relation, &oldtup.t_self, XLTW_Update,
6663 : : &remain);
6664 : : }
6665 : : else
6666 : 3 : ret = true;
6667 : : }
6668 [ + + ]: 54 : else if (TransactionIdIsCurrentTransactionId(xwait))
6669 : 1 : ret = true;
6670 [ + + ]: 53 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6671 : 1 : ret = true;
6672 : : else
6673 : : {
6674 : 52 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
713 6675 : 52 : release_callback(arg);
748 6676 : 52 : ret = false;
6677 : 52 : XactLockTableWait(xwait, relation, &oldtup.t_self,
6678 : : XLTW_Update);
6679 : : }
6680 : : }
6681 : : else
6682 : : {
6683 : 114361 : ret = (result == TM_Ok);
6684 [ + + ]: 114361 : if (!ret)
6685 : : {
6686 : 1 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
713 6687 : 1 : release_callback(arg);
6688 : : }
6689 : : }
6690 : :
6691 : : /*
6692 : : * GetCatalogSnapshot() relies on invalidation messages to know when to
6693 : : * take a new snapshot. COMMIT of xwait is responsible for sending the
6694 : : * invalidation. We're not acquiring heavyweight locks sufficient to
6695 : : * block if not yet sent, so we must take a new snapshot to ensure a later
6696 : : * attempt has a fair chance. While we don't need this if xwait aborted,
6697 : : * don't bother optimizing that.
6698 : : */
748 6699 [ + + ]: 114420 : if (!ret)
6700 : : {
6701 : 55 : UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
709 6702 : 55 : ForgetInplace_Inval();
748 6703 : 55 : InvalidateCatalogSnapshot();
6704 : : }
6705 : 114420 : return ret;
6706 : : }
6707 : :
6708 : : /*
6709 : : * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6710 : : *
6711 : : * The tuple cannot change size, and therefore its header fields and null
6712 : : * bitmap (if any) don't change either.
6713 : : *
6714 : : * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6715 : : */
6716 : : void
6717 : 79374 : heap_inplace_update_and_unlock(Relation relation,
6718 : : HeapTuple oldtup, HeapTuple tuple,
6719 : : Buffer buffer)
6720 : : {
6721 : 79374 : HeapTupleHeader htup = oldtup->t_data;
6722 : : uint32 oldlen;
6723 : : uint32 newlen;
6724 : : char *dst;
6725 : : char *src;
717 6726 : 79374 : int nmsgs = 0;
6727 : 79374 : SharedInvalidationMessage *invalMessages = NULL;
6728 : 79374 : bool RelcacheInitFileInval = false;
6729 : :
748 6730 [ - + ]: 79374 : Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6731 : 79374 : oldlen = oldtup->t_len - htup->t_hoff;
7460 tgl@sss.pgh.pa.us 6732 : 79374 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6733 [ + - - + ]: 79374 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
3980 andres@anarazel.de 6734 [ # # ]:UBC 0 : elog(ERROR, "wrong tuple length");
6735 : :
717 noah@leadboat.com 6736 :CBC 79374 : dst = (char *) htup + htup->t_hoff;
6737 : 79374 : src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6738 : :
6739 : : /* Like RecordTransactionCommit(), log only if needed */
6740 [ + + ]: 79374 : if (XLogStandbyInfoActive())
6741 : 72063 : nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6742 : : &RelcacheInitFileInval);
6743 : :
6744 : : /*
6745 : : * Unlink relcache init files as needed. If unlinking, acquire
6746 : : * RelCacheInitLock until after associated invalidations. By doing this
6747 : : * in advance, if we checkpoint and then crash between inplace
6748 : : * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6749 : : * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6750 : : * neglect to PANIC on EIO.
6751 : : */
6752 : 79374 : PreInplace_Inval();
6753 : :
6754 : : /*----------
6755 : : * NO EREPORT(ERROR) from here till changes are complete
6756 : : *
6757 : : * Our exclusive buffer lock won't stop a reader having already pinned and
6758 : : * checked visibility for this tuple. With the usual order of changes
6759 : : * (i.e. updating the buffer contents before WAL logging), a reader could
6760 : : * observe our not-yet-persistent update to relfrozenxid and update
6761 : : * datfrozenxid based on that. A crash in that moment could allow
6762 : : * datfrozenxid to overtake relfrozenxid:
6763 : : *
6764 : : * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6765 : : * ["R" is a VACUUM tbl]
6766 : : * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6767 : : * D: systable_getnext() returns pg_class tuple of tbl
6768 : : * R: memcpy() into pg_class tuple of tbl
6769 : : * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6770 : : * [crash]
6771 : : * [recovery restores datfrozenxid w/o relfrozenxid]
6772 : : *
6773 : : * We avoid that by using a temporary copy of the buffer to hide our
6774 : : * change from other backends until the change has been WAL-logged. We
6775 : : * apply our change to the temporary copy and WAL-log it, before modifying
6776 : : * the real page. That way any action a reader of the in-place-updated
6777 : : * value takes will be WAL logged after this change.
6778 : : */
6779 : 79374 : START_CRIT_SECTION();
6780 : :
216 andres@anarazel.de 6781 : 79374 : MarkBufferDirty(buffer);
6782 : :
6783 : : /* XLOG stuff */
5782 rhaas@postgresql.org 6784 [ + - + + : 79374 : if (RelationNeedsWAL(relation))
+ - + + ]
6785 : : {
6786 : : xl_heap_inplace xlrec;
6787 : : PGAlignedBlock copied_buffer;
717 noah@leadboat.com 6788 : 79370 : char *origdata = (char *) BufferGetBlock(buffer);
6789 : 79370 : Page page = BufferGetPage(buffer);
6790 : 79370 : uint16 lower = ((PageHeader) page)->pd_lower;
6791 : 79370 : uint16 upper = ((PageHeader) page)->pd_upper;
6792 : : uintptr_t dst_offset_in_block;
6793 : : RelFileLocator rlocator;
6794 : : ForkNumber forkno;
6795 : : BlockNumber blkno;
6796 : : XLogRecPtr recptr;
6797 : :
4344 heikki.linnakangas@i 6798 : 79370 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
717 noah@leadboat.com 6799 : 79370 : xlrec.dbId = MyDatabaseId;
6800 : 79370 : xlrec.tsId = MyDatabaseTableSpace;
6801 : 79370 : xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6802 : 79370 : xlrec.nmsgs = nmsgs;
6803 : :
4344 heikki.linnakangas@i 6804 : 79370 : XLogBeginInsert();
608 peter@eisentraut.org 6805 : 79370 : XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
717 noah@leadboat.com 6806 [ + + ]: 79370 : if (nmsgs != 0)
608 peter@eisentraut.org 6807 : 55069 : XLogRegisterData(invalMessages,
6808 : : nmsgs * sizeof(SharedInvalidationMessage));
6809 : :
6810 : : /* register block matching what buffer will look like after changes */
717 noah@leadboat.com 6811 : 79370 : memcpy(copied_buffer.data, origdata, lower);
6812 : 79370 : memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6813 : 79370 : dst_offset_in_block = dst - origdata;
6814 : 79370 : memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6815 : 79370 : BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6816 [ - + ]: 79370 : Assert(forkno == MAIN_FORKNUM);
6817 : 79370 : XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6818 : : REGBUF_STANDARD);
6819 : 79370 : XLogRegisterBufData(0, src, newlen);
6820 : :
6821 : : /* inplace updates aren't decoded atm, don't log the origin */
6822 : :
4344 heikki.linnakangas@i 6823 : 79370 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6824 : :
717 noah@leadboat.com 6825 : 79370 : PageSetLSN(page, recptr);
6826 : : }
6827 : :
6828 : 79374 : memcpy(dst, src, newlen);
6829 : :
6830 : 79374 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6831 : :
6832 : : /*
6833 : : * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6834 : : * do this before UnlockTuple().
6835 : : */
6836 : 79374 : AtInplace_Inval();
6837 : :
7460 tgl@sss.pgh.pa.us 6838 [ - + ]: 79374 : END_CRIT_SECTION();
717 noah@leadboat.com 6839 : 79374 : UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6840 : :
6841 : 79374 : AcceptInvalidationMessages(); /* local processing of just-sent inval */
6842 : :
6843 : : /*
6844 : : * Queue a transactional inval, for logical decoding and for third-party
6845 : : * code that might have been relying on it since long before inplace
6846 : : * update adopted immediate invalidation. See README.tuplock section
6847 : : * "Reading inplace-updated columns" for logical decoding details.
6848 : : */
7460 tgl@sss.pgh.pa.us 6849 [ + + ]: 79374 : if (!IsBootstrapProcessingMode())
5536 6850 : 62380 : CacheInvalidateHeapTuple(relation, tuple, NULL);
7460 6851 : 79374 : }
6852 : :
6853 : : /*
6854 : : * heap_inplace_unlock - reverse of heap_inplace_lock
6855 : : */
6856 : : void
748 noah@leadboat.com 6857 : 34991 : heap_inplace_unlock(Relation relation,
6858 : : HeapTuple oldtup, Buffer buffer)
6859 : : {
6860 : 34991 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6861 : 34991 : UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
709 6862 : 34991 : ForgetInplace_Inval();
748 6863 : 34991 : }
6864 : :
6865 : : #define FRM_NOOP 0x0001
6866 : : #define FRM_INVALIDATE_XMAX 0x0002
6867 : : #define FRM_RETURN_IS_XID 0x0004
6868 : : #define FRM_RETURN_IS_MULTI 0x0008
6869 : : #define FRM_MARK_COMMITTED 0x0010
6870 : :
6871 : : /*
6872 : : * FreezeMultiXactId
6873 : : * Determine what to do during freezing when a tuple is marked by a
6874 : : * MultiXactId.
6875 : : *
6876 : : * "flags" is an output value; it's used to tell caller what to do on return.
6877 : : * "pagefrz" is an input/output value, used to manage page level freezing.
6878 : : *
6879 : : * Possible values that we can set in "flags":
6880 : : * FRM_NOOP
6881 : : * don't do anything -- keep existing Xmax
6882 : : * FRM_INVALIDATE_XMAX
6883 : : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6884 : : * FRM_RETURN_IS_XID
6885 : : * The Xid return value is a single update Xid to set as xmax.
6886 : : * FRM_MARK_COMMITTED
6887 : : * Xmax can be marked as HEAP_XMAX_COMMITTED
6888 : : * FRM_RETURN_IS_MULTI
6889 : : * The return value is a new MultiXactId to set as new Xmax.
6890 : : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6891 : : *
6892 : : * Caller delegates control of page freezing to us. In practice we always
6893 : : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6894 : : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6895 : : * can never be left behind. We freely choose when and how to process each
6896 : : * Multi, without ever violating the cutoff postconditions for freezing.
6897 : : *
6898 : : * It's useful to remove Multis on a proactive timeline (relative to freezing
6899 : : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6900 : : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6901 : : * misses through eager processing.
6902 : : *
6903 : : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6904 : : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6905 : : * This can usually be put off, which is usually enough to avoid it altogether.
6906 : : * Allocating new multis during VACUUM should be avoided on general principle;
6907 : : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6908 : : * its own special risks.
6909 : : *
6910 : : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6911 : : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6912 : : *
6913 : : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6914 : : * have already forced page-level freezing, since that might incur the same
6915 : : * SLRU buffer misses that we specifically intended to avoid by freezing.
6916 : : */
6917 : : static TransactionId
4683 alvherre@alvh.no-ip. 6918 : 7 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6919 : : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6920 : : HeapPageFreeze *pagefrz)
6921 : : {
6922 : : TransactionId newxmax;
6923 : : MultiXactMember *members;
6924 : : int nmembers;
6925 : : bool need_replace;
6926 : : int nnewmembers;
6927 : : MultiXactMember *newmembers;
6928 : : bool has_lockers;
6929 : : TransactionId update_xid;
6930 : : bool update_committed;
6931 : : TransactionId FreezePageRelfrozenXid;
6932 : :
6933 : 7 : *flags = 0;
6934 : :
6935 : : /* We should only be called in Multis */
6936 [ - + ]: 7 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6937 : :
3762 6938 [ + - - + ]: 14 : if (!MultiXactIdIsValid(multi) ||
6939 : 7 : HEAP_LOCKED_UPGRADED(t_infomask))
6940 : : {
4683 alvherre@alvh.no-ip. 6941 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1384 pg@bowt.ie 6942 : 0 : pagefrz->freeze_required = true;
4683 alvherre@alvh.no-ip. 6943 : 0 : return InvalidTransactionId;
6944 : : }
1390 pg@bowt.ie 6945 [ - + ]:CBC 7 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
3255 andres@anarazel.de 6946 [ # # ]:UBC 0 : ereport(ERROR,
6947 : : (errcode(ERRCODE_DATA_CORRUPTED),
6948 : : errmsg_internal("found multixact %u from before relminmxid %u",
6949 : : multi, cutoffs->relminmxid)));
1384 pg@bowt.ie 6950 [ + + ]:CBC 7 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6951 : : {
6952 : : TransactionId update_xact;
6953 : :
6954 : : /*
6955 : : * This old multi cannot possibly have members still running, but
6956 : : * verify just in case. If it was a locker only, it can be removed
6957 : : * without any further consideration; but if it contained an update,
6958 : : * we might need to preserve it.
6959 : : */
3255 andres@anarazel.de 6960 [ - + ]: 5 : if (MultiXactIdIsRunning(multi,
6961 : 5 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
3255 andres@anarazel.de 6962 [ # # ]:UBC 0 : ereport(ERROR,
6963 : : (errcode(ERRCODE_DATA_CORRUPTED),
6964 : : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6965 : : multi, cutoffs->OldestMxact)));
6966 : :
4683 alvherre@alvh.no-ip. 6967 [ + - ]:CBC 5 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6968 : : {
6969 : 5 : *flags |= FRM_INVALIDATE_XMAX;
1384 pg@bowt.ie 6970 : 5 : pagefrz->freeze_required = true;
6971 : 5 : return InvalidTransactionId;
6972 : : }
6973 : :
6974 : : /* replace multi with single XID for its updater? */
1384 pg@bowt.ie 6975 :UBC 0 : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6976 [ # # ]: 0 : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6977 [ # # ]: 0 : ereport(ERROR,
6978 : : (errcode(ERRCODE_DATA_CORRUPTED),
6979 : : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6980 : : multi, update_xact,
6981 : : cutoffs->relfrozenxid)));
6982 [ # # ]: 0 : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6983 : : {
6984 : : /*
6985 : : * Updater XID has to have aborted (otherwise the tuple would have
6986 : : * been pruned away instead, since updater XID is < OldestXmin).
6987 : : * Just remove xmax.
6988 : : */
1378 6989 [ # # ]: 0 : if (TransactionIdDidCommit(update_xact))
1384 6990 [ # # ]: 0 : ereport(ERROR,
6991 : : (errcode(ERRCODE_DATA_CORRUPTED),
6992 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6993 : : multi, update_xact,
6994 : : cutoffs->OldestXmin)));
6995 : 0 : *flags |= FRM_INVALIDATE_XMAX;
6996 : 0 : pagefrz->freeze_required = true;
6997 : 0 : return InvalidTransactionId;
6998 : : }
6999 : :
7000 : : /* Have to keep updater XID as new xmax */
7001 : 0 : *flags |= FRM_RETURN_IS_XID;
7002 : 0 : pagefrz->freeze_required = true;
7003 : 0 : return update_xact;
7004 : : }
7005 : :
7006 : : /*
7007 : : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
7008 : : * need to walk the whole members array to figure out what to do, if
7009 : : * anything.
7010 : : */
7011 : : nmembers =
3762 alvherre@alvh.no-ip. 7012 :CBC 2 : GetMultiXactIdMembers(multi, &members, false,
4458 7013 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
4683 7014 [ - + ]: 2 : if (nmembers <= 0)
7015 : : {
7016 : : /* Nothing worth keeping */
4683 alvherre@alvh.no-ip. 7017 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1384 pg@bowt.ie 7018 : 0 : pagefrz->freeze_required = true;
4683 alvherre@alvh.no-ip. 7019 : 0 : return InvalidTransactionId;
7020 : : }
7021 : :
7022 : : /*
7023 : : * The FRM_NOOP case is the only case where we might need to ratchet back
7024 : : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
7025 : : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
7026 : : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
7027 : : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
7028 : : * trackers managed by VACUUM being ratcheting back by xmax to the degree
7029 : : * required to make it safe to leave xmax undisturbed, independent of
7030 : : * whether or not page freezing is triggered somewhere else.
7031 : : *
7032 : : * Our policy is to force freezing in every case other than FRM_NOOP,
7033 : : * which obviates the need to maintain either set of trackers, anywhere.
7034 : : * Every other case will reliably execute a freeze plan for xmax that
7035 : : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
7036 : : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
7037 : : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
7038 : : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
7039 : : */
4683 alvherre@alvh.no-ip. 7040 :CBC 2 : need_replace = false;
1384 pg@bowt.ie 7041 : 2 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
1390 7042 [ + + ]: 4 : for (int i = 0; i < nmembers; i++)
7043 : : {
7044 : 3 : TransactionId xid = members[i].xid;
7045 : :
7046 [ - + ]: 3 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7047 : :
7048 [ + + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7049 : : {
7050 : : /* Can't violate the FreezeLimit postcondition */
4683 alvherre@alvh.no-ip. 7051 : 1 : need_replace = true;
7052 : 1 : break;
7053 : : }
1384 pg@bowt.ie 7054 [ - + ]: 2 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
1384 pg@bowt.ie 7055 :UBC 0 : FreezePageRelfrozenXid = xid;
7056 : : }
7057 : :
7058 : : /* Can't violate the MultiXactCutoff postcondition, either */
1384 pg@bowt.ie 7059 [ + + ]:CBC 2 : if (!need_replace)
7060 : 1 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
7061 : :
4683 alvherre@alvh.no-ip. 7062 [ + + ]: 2 : if (!need_replace)
7063 : : {
7064 : : /*
7065 : : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
7066 : : * both together to make it safe to retain this particular multi after
7067 : : * freezing its page
7068 : : */
7069 : 1 : *flags |= FRM_NOOP;
1384 pg@bowt.ie 7070 : 1 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
7071 [ - + ]: 1 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
1384 pg@bowt.ie 7072 :UBC 0 : pagefrz->FreezePageRelminMxid = multi;
4683 alvherre@alvh.no-ip. 7073 :CBC 1 : pfree(members);
1653 pg@bowt.ie 7074 : 1 : return multi;
7075 : : }
7076 : :
7077 : : /*
7078 : : * Do a more thorough second pass over the multi to figure out which
7079 : : * member XIDs actually need to be kept. Checking the precise status of
7080 : : * individual members might even show that we don't need to keep anything.
7081 : : * That is quite possible even though the Multi must be >= OldestMxact,
7082 : : * since our second pass only keeps member XIDs when it's truly necessary;
7083 : : * even member XIDs >= OldestXmin often won't be kept by second pass.
7084 : : */
4683 alvherre@alvh.no-ip. 7085 : 1 : nnewmembers = 0;
306 michael@paquier.xyz 7086 : 1 : newmembers = palloc_array(MultiXactMember, nmembers);
4683 alvherre@alvh.no-ip. 7087 : 1 : has_lockers = false;
7088 : 1 : update_xid = InvalidTransactionId;
7089 : 1 : update_committed = false;
7090 : :
7091 : : /*
7092 : : * Determine whether to keep each member xid, or to ignore it instead
7093 : : */
1390 pg@bowt.ie 7094 [ + + ]: 3 : for (int i = 0; i < nmembers; i++)
7095 : : {
7096 : 2 : TransactionId xid = members[i].xid;
7097 : 2 : MultiXactStatus mstatus = members[i].status;
7098 : :
7099 [ - + ]: 2 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
7100 : :
7101 [ + - ]: 2 : if (!ISUPDATE_from_mxstatus(mstatus))
7102 : : {
7103 : : /*
7104 : : * Locker XID (not updater XID). We only keep lockers that are
7105 : : * still running.
7106 : : */
7107 [ + - + + ]: 4 : if (TransactionIdIsCurrentTransactionId(xid) ||
7108 : 2 : TransactionIdIsInProgress(xid))
7109 : : {
1384 7110 [ - + ]: 1 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
1384 pg@bowt.ie 7111 [ # # ]:UBC 0 : ereport(ERROR,
7112 : : (errcode(ERRCODE_DATA_CORRUPTED),
7113 : : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
7114 : : multi, xid,
7115 : : cutoffs->OldestXmin)));
1390 pg@bowt.ie 7116 :CBC 1 : newmembers[nnewmembers++] = members[i];
7117 : 1 : has_lockers = true;
7118 : : }
7119 : :
7120 : 2 : continue;
7121 : : }
7122 : :
7123 : : /*
7124 : : * Updater XID (not locker XID). Should we keep it?
7125 : : *
7126 : : * Since the tuple wasn't totally removed when vacuum pruned, the
7127 : : * update Xid cannot possibly be older than OldestXmin cutoff unless
7128 : : * the updater XID aborted. If the updater transaction is known
7129 : : * aborted or crashed then it's okay to ignore it, otherwise not.
7130 : : *
7131 : : * In any case the Multi should never contain two updaters, whatever
7132 : : * their individual commit status. Check for that first, in passing.
7133 : : */
1390 pg@bowt.ie 7134 [ # # ]:UBC 0 : if (TransactionIdIsValid(update_xid))
7135 [ # # ]: 0 : ereport(ERROR,
7136 : : (errcode(ERRCODE_DATA_CORRUPTED),
7137 : : errmsg_internal("multixact %u has two or more updating members",
7138 : : multi),
7139 : : errdetail_internal("First updater XID=%u second updater XID=%u.",
7140 : : update_xid, xid)));
7141 : :
7142 : : /*
7143 : : * As with all tuple visibility routines, it's critical to test
7144 : : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
7145 : : * race conditions explained in detail in heapam_visibility.c.
7146 : : */
7147 [ # # # # ]: 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
7148 : 0 : TransactionIdIsInProgress(xid))
7149 : 0 : update_xid = xid;
7150 [ # # ]: 0 : else if (TransactionIdDidCommit(xid))
7151 : : {
7152 : : /*
7153 : : * The transaction committed, so we can tell caller to set
7154 : : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
7155 : : * transaction is not running.)
7156 : : */
7157 : 0 : update_committed = true;
7158 : 0 : update_xid = xid;
7159 : : }
7160 : : else
7161 : : {
7162 : : /*
7163 : : * Not in progress, not committed -- must be aborted or crashed;
7164 : : * we can ignore it.
7165 : : */
7166 : 0 : continue;
7167 : : }
7168 : :
7169 : : /*
7170 : : * We determined that updater must be kept -- add it to pending new
7171 : : * members list
7172 : : */
1384 7173 [ # # ]: 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
7174 [ # # ]: 0 : ereport(ERROR,
7175 : : (errcode(ERRCODE_DATA_CORRUPTED),
7176 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
7177 : : multi, xid, cutoffs->OldestXmin)));
1390 7178 : 0 : newmembers[nnewmembers++] = members[i];
7179 : : }
7180 : :
4683 alvherre@alvh.no-ip. 7181 :CBC 1 : pfree(members);
7182 : :
7183 : : /*
7184 : : * Determine what to do with caller's multi based on information gathered
7185 : : * during our second pass
7186 : : */
7187 [ - + ]: 1 : if (nnewmembers == 0)
7188 : : {
7189 : : /* Nothing worth keeping */
4683 alvherre@alvh.no-ip. 7190 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
1390 pg@bowt.ie 7191 : 0 : newxmax = InvalidTransactionId;
7192 : : }
4683 alvherre@alvh.no-ip. 7193 [ - + - - ]:CBC 1 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
7194 : : {
7195 : : /*
7196 : : * If there's a single member and it's an update, pass it back alone
7197 : : * without creating a new Multi. (XXX we could do this when there's a
7198 : : * single remaining locker, too, but that would complicate the API too
7199 : : * much; moreover, the case with the single updater is more
7200 : : * interesting, because those are longer-lived.)
7201 : : */
4683 alvherre@alvh.no-ip. 7202 [ # # ]:UBC 0 : Assert(nnewmembers == 1);
7203 : 0 : *flags |= FRM_RETURN_IS_XID;
7204 [ # # ]: 0 : if (update_committed)
7205 : 0 : *flags |= FRM_MARK_COMMITTED;
1390 pg@bowt.ie 7206 : 0 : newxmax = update_xid;
7207 : : }
7208 : : else
7209 : : {
7210 : : /*
7211 : : * Create a new multixact with the surviving members of the previous
7212 : : * one, to set as new Xmax in the tuple
7213 : : */
1390 pg@bowt.ie 7214 :CBC 1 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
4683 alvherre@alvh.no-ip. 7215 : 1 : *flags |= FRM_RETURN_IS_MULTI;
7216 : : }
7217 : :
7218 : 1 : pfree(newmembers);
7219 : :
1384 pg@bowt.ie 7220 : 1 : pagefrz->freeze_required = true;
1390 7221 : 1 : return newxmax;
7222 : : }
7223 : :
7224 : : /*
7225 : : * heap_prepare_freeze_tuple
7226 : : *
7227 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7228 : : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
7229 : : * setup enough state (in the *frz output argument) to enable caller to
7230 : : * process this tuple as part of freezing its page, and return true. Return
7231 : : * false if nothing can be changed about the tuple right now.
7232 : : *
7233 : : * FreezePageConflictXid is advanced only for xmin/xvac freezing, not for xmax
7234 : : * changes. We only remove xmax state here when it is lock-only, or when the
7235 : : * updater XID (including an updater member of a MultiXact) must be aborted;
7236 : : * otherwise, the tuple would already be removable. Neither case affects
7237 : : * visibility on a standby.
7238 : : *
7239 : : * Also sets *totally_frozen to true if the tuple will be totally frozen once
7240 : : * caller executes returned freeze plan (or if the tuple was already totally
7241 : : * frozen by an earlier VACUUM). This indicates that there are no remaining
7242 : : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
7243 : : *
7244 : : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
7245 : : * tuple that we returned true for, and then execute freezing. Caller must
7246 : : * initialize pagefrz fields for page as a whole before first call here for
7247 : : * each heap page.
7248 : : *
7249 : : * VACUUM caller decides on whether or not to freeze the page as a whole.
7250 : : * We'll often prepare freeze plans for a page that caller just discards.
7251 : : * However, VACUUM doesn't always get to make a choice; it must freeze when
7252 : : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7253 : : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7254 : : * that VACUUM always follows that rule.
7255 : : *
7256 : : * We sometimes force freezing of xmax MultiXactId values long before it is
7257 : : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7258 : : * It's worth processing MultiXactIds proactively when it is cheap to do so,
7259 : : * and it's convenient to make that happen by piggy-backing it on the "force
7260 : : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7261 : : * because it is expensive right now (though only when it's still possible to
7262 : : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7263 : : *
7264 : : * It is assumed that the caller has checked the tuple with
7265 : : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7266 : : * (else we should be removing the tuple, not freezing it).
7267 : : *
7268 : : * NB: This function has side effects: it might allocate a new MultiXactId.
7269 : : * It will be set as tuple's new xmax when our *frz output is processed within
7270 : : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7271 : : * then caller had better have an exclusive lock on it already.
7272 : : */
7273 : : bool
3255 andres@anarazel.de 7274 : 5513021 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
7275 : : const struct VacuumCutoffs *cutoffs,
7276 : : HeapPageFreeze *pagefrz,
7277 : : HeapTupleFreeze *frz, bool *totally_frozen)
7278 : : {
1390 pg@bowt.ie 7279 : 5513021 : bool xmin_already_frozen = false,
7280 : 5513021 : xmax_already_frozen = false;
7281 : 5513021 : bool freeze_xmin = false,
7282 : 5513021 : replace_xvac = false,
7283 : 5513021 : replace_xmax = false,
7284 : 5513021 : freeze_xmax = false;
7285 : : TransactionId xid;
7286 : :
1378 7287 : 5513021 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
4683 alvherre@alvh.no-ip. 7288 : 5513021 : frz->t_infomask2 = tuple->t_infomask2;
7289 : 5513021 : frz->t_infomask = tuple->t_infomask;
1378 pg@bowt.ie 7290 : 5513021 : frz->frzflags = 0;
7291 : 5513021 : frz->checkflags = 0;
7292 : :
7293 : : /*
7294 : : * Process xmin, while keeping track of whether it's already frozen, or
7295 : : * will become frozen iff our freeze plan is executed by caller (could be
7296 : : * neither).
7297 : : */
7281 tgl@sss.pgh.pa.us 7298 : 5513021 : xid = HeapTupleHeaderGetXmin(tuple);
2720 alvherre@alvh.no-ip. 7299 [ + + ]: 5513021 : if (!TransactionIdIsNormal(xid))
1390 pg@bowt.ie 7300 : 900485 : xmin_already_frozen = true;
7301 : : else
7302 : : {
7303 [ - + ]: 4612536 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3255 andres@anarazel.de 7304 [ # # ]:UBC 0 : ereport(ERROR,
7305 : : (errcode(ERRCODE_DATA_CORRUPTED),
7306 : : errmsg_internal("found xmin %u from before relfrozenxid %u",
7307 : : xid, cutoffs->relfrozenxid)));
7308 : :
7309 : : /* Will set freeze_xmin flags in freeze plan below */
1384 pg@bowt.ie 7310 :CBC 4612536 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7311 : :
7312 : : /* Verify that xmin committed if and when freeze plan is executed */
1378 7313 [ + + ]: 4612536 : if (freeze_xmin)
7314 : : {
7315 : 3737842 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
216 melanieplageman@gmai 7316 [ + + ]: 3737842 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7317 : 545636 : pagefrz->FreezePageConflictXid = xid;
7318 : : }
7319 : : }
7320 : :
7321 : : /*
7322 : : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7323 : : * as we support having MOVED_OFF/MOVED_IN tuples in the database
7324 : : */
1390 pg@bowt.ie 7325 : 5513021 : xid = HeapTupleHeaderGetXvac(tuple);
7326 [ - + ]: 5513021 : if (TransactionIdIsNormal(xid))
7327 : : {
1390 pg@bowt.ie 7328 [ # # ]:UBC 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7329 [ # # ]: 0 : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7330 : :
7331 : : /*
7332 : : * For Xvac, we always freeze proactively. This allows totally_frozen
7333 : : * tracking to ignore xvac.
7334 : : */
1384 7335 : 0 : replace_xvac = pagefrz->freeze_required = true;
7336 : :
216 melanieplageman@gmai 7337 [ # # ]: 0 : if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
7338 : 0 : pagefrz->FreezePageConflictXid = xid;
7339 : :
7340 : : /* Will set replace_xvac flags in freeze plan below */
7341 : : }
7342 : :
7343 : : /* Now process xmax */
1378 pg@bowt.ie 7344 :CBC 5513021 : xid = frz->xmax;
4701 alvherre@alvh.no-ip. 7345 [ + + ]: 5513021 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7346 : : {
7347 : : /* Raw xmax is a MultiXactId */
7348 : : TransactionId newxmax;
7349 : : uint16 flags;
7350 : :
7351 : : /*
7352 : : * We will either remove xmax completely (in the "freeze_xmax" path),
7353 : : * process xmax by replacing it (in the "replace_xmax" path), or
7354 : : * perform no-op xmax processing. The only constraint is that the
7355 : : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7356 : : */
1390 pg@bowt.ie 7357 : 7 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7358 : : &flags, pagefrz);
7359 : :
1384 7360 [ + + ]: 7 : if (flags & FRM_NOOP)
7361 : : {
7362 : : /*
7363 : : * xmax is a MultiXactId, and nothing about it changes for now.
7364 : : * This is the only case where 'freeze_required' won't have been
7365 : : * set for us by FreezeMultiXactId, as well as the only case where
7366 : : * neither freeze_xmax nor replace_xmax are set (given a multi).
7367 : : *
7368 : : * This is a no-op, but the call to FreezeMultiXactId might have
7369 : : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7370 : : * for us (the "freeze page" variants, specifically). That'll
7371 : : * make it safe for our caller to freeze the page later on, while
7372 : : * leaving this particular xmax undisturbed.
7373 : : *
7374 : : * FreezeMultiXactId is _not_ responsible for the "no freeze"
7375 : : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7376 : : * job. A call to heap_tuple_should_freeze for this same tuple
7377 : : * will take place below if 'freeze_required' isn't set already.
7378 : : * (This repeats work from FreezeMultiXactId, but allows "no
7379 : : * freeze" tracker maintenance to happen in only one place.)
7380 : : */
7381 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7382 [ + - - + ]: 1 : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7383 : : }
7384 [ - + ]: 6 : else if (flags & FRM_RETURN_IS_XID)
7385 : : {
7386 : : /*
7387 : : * xmax will become an updater Xid (original MultiXact's updater
7388 : : * member Xid will be carried forward as a simple Xid in Xmax).
7389 : : */
1390 pg@bowt.ie 7390 [ # # ]:UBC 0 : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7391 : :
7392 : : /*
7393 : : * NB -- some of these transformations are only valid because we
7394 : : * know the return Xid is a tuple updater (i.e. not merely a
7395 : : * locker.) Also note that the only reason we don't explicitly
7396 : : * worry about HEAP_KEYS_UPDATED is because it lives in
7397 : : * t_infomask2 rather than t_infomask.
7398 : : */
4683 alvherre@alvh.no-ip. 7399 : 0 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7400 : 0 : frz->xmax = newxmax;
7401 [ # # ]: 0 : if (flags & FRM_MARK_COMMITTED)
3385 teodor@sigaev.ru 7402 : 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
1390 pg@bowt.ie 7403 : 0 : replace_xmax = true;
7404 : : }
4683 alvherre@alvh.no-ip. 7405 [ + + ]:CBC 6 : else if (flags & FRM_RETURN_IS_MULTI)
7406 : : {
7407 : : uint16 newbits;
7408 : : uint16 newbits2;
7409 : :
7410 : : /*
7411 : : * xmax is an old MultiXactId that we have to replace with a new
7412 : : * MultiXactId, to carry forward two or more original member XIDs.
7413 : : */
1390 pg@bowt.ie 7414 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7415 : :
7416 : : /*
7417 : : * We can't use GetMultiXactIdHintBits directly on the new multi
7418 : : * here; that routine initializes the masks to all zeroes, which
7419 : : * would lose other bits we need. Doing it this way ensures all
7420 : : * unrelated bits remain untouched.
7421 : : */
4683 alvherre@alvh.no-ip. 7422 : 1 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7423 : 1 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7424 : 1 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7425 : 1 : frz->t_infomask |= newbits;
7426 : 1 : frz->t_infomask2 |= newbits2;
7427 : 1 : frz->xmax = newxmax;
1390 pg@bowt.ie 7428 : 1 : replace_xmax = true;
7429 : : }
7430 : : else
7431 : : {
7432 : : /*
7433 : : * Freeze plan for tuple "freezes xmax" in the strictest sense:
7434 : : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7435 : : */
7436 [ - + ]: 5 : Assert(flags & FRM_INVALIDATE_XMAX);
1653 7437 [ - + ]: 5 : Assert(!TransactionIdIsValid(newxmax));
7438 : :
7439 : : /* Will set freeze_xmax flags in freeze plan below */
1390 7440 : 5 : freeze_xmax = true;
7441 : : }
7442 : :
7443 : : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
1384 7444 [ - + - - : 7 : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
- - ]
7445 : : }
3771 rhaas@postgresql.org 7446 [ + + ]: 5513014 : else if (TransactionIdIsNormal(xid))
7447 : : {
7448 : : /* Raw xmax is normal XID */
1390 pg@bowt.ie 7449 [ - + ]: 432601 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
3255 andres@anarazel.de 7450 [ # # ]:UBC 0 : ereport(ERROR,
7451 : : (errcode(ERRCODE_DATA_CORRUPTED),
7452 : : errmsg_internal("found xmax %u from before relfrozenxid %u",
7453 : : xid, cutoffs->relfrozenxid)));
7454 : :
7455 : : /* Will set freeze_xmax flags in freeze plan below */
1378 pg@bowt.ie 7456 :CBC 432601 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7457 : :
7458 : : /*
7459 : : * Verify that xmax aborted if and when freeze plan is executed,
7460 : : * provided it's from an update. (A lock-only xmax can be removed
7461 : : * independent of this, since the lock is released at xact end.)
7462 : : */
7463 [ + + + + ]: 432601 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7464 : 5051 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7465 : : }
1419 7466 [ + - ]: 5080413 : else if (!TransactionIdIsValid(xid))
7467 : : {
7468 : : /* Raw xmax is InvalidTransactionId XID */
7469 [ - + ]: 5080413 : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
3083 alvherre@alvh.no-ip. 7470 : 5080413 : xmax_already_frozen = true;
7471 : : }
7472 : : else
3083 alvherre@alvh.no-ip. 7473 [ # # ]:UBC 0 : ereport(ERROR,
7474 : : (errcode(ERRCODE_DATA_CORRUPTED),
7475 : : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7476 : : xid, tuple->t_infomask)));
7477 : :
1390 pg@bowt.ie 7478 [ + + ]:CBC 5513021 : if (freeze_xmin)
7479 : : {
7480 [ - + ]: 3737842 : Assert(!xmin_already_frozen);
7481 : :
7482 : 3737842 : frz->t_infomask |= HEAP_XMIN_FROZEN;
7483 : : }
7484 [ - + ]: 5513021 : if (replace_xvac)
7485 : : {
7486 : : /*
7487 : : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7488 : : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7489 : : * transaction succeeded.
7490 : : */
1384 pg@bowt.ie 7491 [ # # ]:UBC 0 : Assert(pagefrz->freeze_required);
1390 7492 [ # # ]: 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
7493 : 0 : frz->frzflags |= XLH_INVALID_XVAC;
7494 : : else
7495 : 0 : frz->frzflags |= XLH_FREEZE_XVAC;
7496 : : }
1390 pg@bowt.ie 7497 [ + + ]:CBC 5513021 : if (replace_xmax)
7498 : : {
7499 [ + - - + ]: 1 : Assert(!xmax_already_frozen && !freeze_xmax);
1384 7500 [ - + ]: 1 : Assert(pagefrz->freeze_required);
7501 : :
7502 : : /* Already set replace_xmax flags in freeze plan earlier */
7503 : : }
4701 alvherre@alvh.no-ip. 7504 [ + + ]: 5513021 : if (freeze_xmax)
7505 : : {
1390 pg@bowt.ie 7506 [ + - - + ]: 6169 : Assert(!xmax_already_frozen && !replace_xmax);
7507 : :
4683 alvherre@alvh.no-ip. 7508 : 6169 : frz->xmax = InvalidTransactionId;
7509 : :
7510 : : /*
7511 : : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7512 : : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7513 : : * Also get rid of the HEAP_KEYS_UPDATED bit.
7514 : : */
7515 : 6169 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7516 : 6169 : frz->t_infomask |= HEAP_XMAX_INVALID;
7517 : 6169 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7518 : 6169 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7519 : : }
7520 : :
7521 : : /*
7522 : : * Determine if this tuple is already totally frozen, or will become
7523 : : * totally frozen (provided caller executes freeze plans for the page)
7524 : : */
1390 pg@bowt.ie 7525 [ + + + + : 10145179 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
+ + ]
7526 [ + + ]: 4632158 : (freeze_xmax || xmax_already_frozen));
7527 : :
1384 7528 [ + + + + : 5513021 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
+ + ]
7529 : : xmax_already_frozen))
7530 : : {
7531 : : /*
7532 : : * So far no previous tuple from the page made freezing mandatory.
7533 : : * Does this tuple force caller to freeze the entire page?
7534 : : */
7535 : 3259176 : pagefrz->freeze_required =
7536 : 3259176 : heap_tuple_should_freeze(tuple, cutoffs,
7537 : : &pagefrz->NoFreezePageRelfrozenXid,
7538 : : &pagefrz->NoFreezePageRelminMxid);
7539 : : }
7540 : :
7541 : : /* Tell caller if this tuple has a usable freeze plan set in *frz */
1390 7542 [ + + + - : 5513021 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
+ - + + ]
7543 : : }
7544 : :
7545 : : /*
7546 : : * Perform xmin/xmax XID status sanity checks before actually executing freeze
7547 : : * plans.
7548 : : *
7549 : : * heap_prepare_freeze_tuple doesn't perform these checks directly because
7550 : : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7551 : : * successive VACUUMs that each decide against freezing the same page.
7552 : : */
7553 : : void
922 heikki.linnakangas@i 7554 : 25403 : heap_pre_freeze_checks(Buffer buffer,
7555 : : HeapTupleFreeze *tuples, int ntuples)
7556 : : {
1427 pg@bowt.ie 7557 : 25403 : Page page = BufferGetPage(buffer);
7558 : :
1378 7559 [ + + ]: 1357030 : for (int i = 0; i < ntuples; i++)
7560 : : {
7561 : 1331627 : HeapTupleFreeze *frz = tuples + i;
7562 : 1331627 : ItemId itemid = PageGetItemId(page, frz->offset);
7563 : : HeapTupleHeader htup;
7564 : :
7565 : 1331627 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7566 : :
7567 : : /* Deliberately avoid relying on tuple hint bits here */
7568 [ + + ]: 1331627 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7569 : : {
7570 : 1331626 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
7571 : :
7572 [ - + ]: 1331626 : Assert(!HeapTupleHeaderXminFrozen(htup));
7573 [ - + ]: 1331626 : if (unlikely(!TransactionIdDidCommit(xmin)))
1378 pg@bowt.ie 7574 [ # # ]:UBC 0 : ereport(ERROR,
7575 : : (errcode(ERRCODE_DATA_CORRUPTED),
7576 : : errmsg_internal("uncommitted xmin %u needs to be frozen",
7577 : : xmin)));
7578 : : }
7579 : :
7580 : : /*
7581 : : * TransactionIdDidAbort won't work reliably in the presence of XIDs
7582 : : * left behind by transactions that were in progress during a crash,
7583 : : * so we can only check that xmax didn't commit
7584 : : */
1378 pg@bowt.ie 7585 [ + + ]:CBC 1331627 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7586 : : {
7587 : 1004 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
7588 : :
7589 [ - + ]: 1004 : Assert(TransactionIdIsNormal(xmax));
7590 [ - + ]: 1004 : if (unlikely(TransactionIdDidCommit(xmax)))
1378 pg@bowt.ie 7591 [ # # ]:UBC 0 : ereport(ERROR,
7592 : : (errcode(ERRCODE_DATA_CORRUPTED),
7593 : : errmsg_internal("cannot freeze committed xmax %u",
7594 : : xmax)));
7595 : : }
7596 : : }
922 heikki.linnakangas@i 7597 :CBC 25403 : }
7598 : :
7599 : : /*
7600 : : * Helper which executes freezing of one or more heap tuples on a page on
7601 : : * behalf of caller. Caller passes an array of tuple plans from
7602 : : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7603 : : * Must be called in a critical section that also marks the buffer dirty and,
7604 : : * if needed, emits WAL.
7605 : : */
7606 : : void
7607 : 25403 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
7608 : : {
7609 : 25403 : Page page = BufferGetPage(buffer);
7610 : :
1427 pg@bowt.ie 7611 [ + + ]: 1357030 : for (int i = 0; i < ntuples; i++)
7612 : : {
1378 7613 : 1331627 : HeapTupleFreeze *frz = tuples + i;
7614 : 1331627 : ItemId itemid = PageGetItemId(page, frz->offset);
7615 : : HeapTupleHeader htup;
7616 : :
1427 7617 : 1331627 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
1378 7618 : 1331627 : heap_execute_freeze_tuple(htup, frz);
7619 : : }
1427 7620 : 25403 : }
7621 : :
7622 : : /*
7623 : : * heap_freeze_tuple
7624 : : * Freeze tuple in place, without WAL logging.
7625 : : *
7626 : : * Useful for callers like CLUSTER that perform their own WAL logging.
7627 : : */
7628 : : bool
3255 andres@anarazel.de 7629 : 477856 : heap_freeze_tuple(HeapTupleHeader tuple,
7630 : : TransactionId relfrozenxid, TransactionId relminmxid,
7631 : : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7632 : : {
7633 : : HeapTupleFreeze frz;
7634 : : bool do_freeze;
7635 : : bool totally_frozen;
7636 : : struct VacuumCutoffs cutoffs;
7637 : : HeapPageFreeze pagefrz;
7638 : :
1390 pg@bowt.ie 7639 : 477856 : cutoffs.relfrozenxid = relfrozenxid;
7640 : 477856 : cutoffs.relminmxid = relminmxid;
7641 : 477856 : cutoffs.OldestXmin = FreezeLimit;
7642 : 477856 : cutoffs.OldestMxact = MultiXactCutoff;
7643 : 477856 : cutoffs.FreezeLimit = FreezeLimit;
7644 : 477856 : cutoffs.MultiXactCutoff = MultiXactCutoff;
7645 : :
1384 7646 : 477856 : pagefrz.freeze_required = true;
7647 : 477856 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7648 : 477856 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
216 melanieplageman@gmai 7649 : 477856 : pagefrz.FreezePageConflictXid = InvalidTransactionId;
1384 pg@bowt.ie 7650 : 477856 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7651 : 477856 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7652 : :
1390 7653 : 477856 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7654 : : &pagefrz, &frz, &totally_frozen);
7655 : :
7656 : : /*
7657 : : * Note that because this is not a WAL-logged operation, we don't need to
7658 : : * fill in the offset in the freeze record.
7659 : : */
7660 : :
4683 alvherre@alvh.no-ip. 7661 [ + + ]: 477856 : if (do_freeze)
7662 : 379028 : heap_execute_freeze_tuple(tuple, &frz);
7663 : 477856 : return do_freeze;
7664 : : }
7665 : :
7666 : : /*
7667 : : * For a given MultiXactId, return the hint bits that should be set in the
7668 : : * tuple's infomask.
7669 : : *
7670 : : * Normally this should be called for a multixact that was just created, and
7671 : : * so is on our local cache, so the GetMembers call is fast.
7672 : : */
7673 : : static void
5010 7674 : 76820 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
7675 : : uint16 *new_infomask2)
7676 : : {
7677 : : int nmembers;
7678 : : MultiXactMember *members;
7679 : : int i;
4884 bruce@momjian.us 7680 : 76820 : uint16 bits = HEAP_XMAX_IS_MULTI;
7681 : 76820 : uint16 bits2 = 0;
7682 : 76820 : bool has_update = false;
7683 : 76820 : LockTupleMode strongest = LockTupleKeyShare;
7684 : :
7685 : : /*
7686 : : * We only use this in multis we just created, so they cannot be values
7687 : : * pre-pg_upgrade.
7688 : : */
4458 alvherre@alvh.no-ip. 7689 : 76820 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7690 : :
5010 7691 [ + + ]: 1472669 : for (i = 0; i < nmembers; i++)
7692 : : {
7693 : : LockTupleMode mode;
7694 : :
7695 : : /*
7696 : : * Remember the strongest lock mode held by any member of the
7697 : : * multixact.
7698 : : */
5002 7699 : 1395849 : mode = TUPLOCK_from_mxstatus(members[i].status);
7700 [ + + ]: 1395849 : if (mode > strongest)
7701 : 2902 : strongest = mode;
7702 : :
7703 : : /* See what other bits we need */
5010 7704 [ + + + + : 1395849 : switch (members[i].status)
- ]
7705 : : {
7706 : 1393425 : case MultiXactStatusForKeyShare:
7707 : : case MultiXactStatusForShare:
7708 : : case MultiXactStatusForNoKeyUpdate:
7709 : 1393425 : break;
7710 : :
7711 : 53 : case MultiXactStatusForUpdate:
7712 : 53 : bits2 |= HEAP_KEYS_UPDATED;
7713 : 53 : break;
7714 : :
7715 : 2361 : case MultiXactStatusNoKeyUpdate:
7716 : 2361 : has_update = true;
7717 : 2361 : break;
7718 : :
7719 : 10 : case MultiXactStatusUpdate:
7720 : 10 : bits2 |= HEAP_KEYS_UPDATED;
7721 : 10 : has_update = true;
7722 : 10 : break;
7723 : : }
7724 : : }
7725 : :
5002 7726 [ + + + + ]: 76820 : if (strongest == LockTupleExclusive ||
7727 : : strongest == LockTupleNoKeyExclusive)
7728 : 2452 : bits |= HEAP_XMAX_EXCL_LOCK;
7729 [ + + ]: 74368 : else if (strongest == LockTupleShare)
7730 : 447 : bits |= HEAP_XMAX_SHR_LOCK;
7731 [ + - ]: 73921 : else if (strongest == LockTupleKeyShare)
7732 : 73921 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7733 : :
5010 7734 [ + + ]: 76820 : if (!has_update)
7735 : 74449 : bits |= HEAP_XMAX_LOCK_ONLY;
7736 : :
7737 [ + - ]: 76820 : if (nmembers > 0)
7738 : 76820 : pfree(members);
7739 : :
7740 : 76820 : *new_infomask = bits;
7741 : 76820 : *new_infomask2 = bits2;
7742 : 76820 : }
7743 : :
7744 : : /*
7745 : : * MultiXactIdGetUpdateXid
7746 : : *
7747 : : * Given a multixact Xmax and corresponding infomask, which does not have the
7748 : : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7749 : : * transaction.
7750 : : *
7751 : : * Caller is expected to check the status of the updating transaction, if
7752 : : * necessary.
7753 : : */
7754 : : static TransactionId
7755 : 162093 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7756 : : {
4884 bruce@momjian.us 7757 : 162093 : TransactionId update_xact = InvalidTransactionId;
7758 : : MultiXactMember *members;
7759 : : int nmembers;
7760 : :
5010 alvherre@alvh.no-ip. 7761 [ - + ]: 162093 : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7762 [ - + ]: 162093 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7763 : :
7764 : : /*
7765 : : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7766 : : * pre-pg_upgrade.
7767 : : */
4458 7768 : 162093 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7769 : :
5010 7770 [ + - ]: 162093 : if (nmembers > 0)
7771 : : {
7772 : : int i;
7773 : :
7774 [ + + ]: 3235164 : for (i = 0; i < nmembers; i++)
7775 : : {
7776 : : /* Ignore lockers */
4700 7777 [ + + ]: 3073071 : if (!ISUPDATE_from_mxstatus(members[i].status))
5010 7778 : 2910978 : continue;
7779 : :
7780 : : /* there can be at most one updater */
7781 [ - + ]: 162093 : Assert(update_xact == InvalidTransactionId);
7782 : 162093 : update_xact = members[i].xid;
7783 : : #ifndef USE_ASSERT_CHECKING
7784 : :
7785 : : /*
7786 : : * in an assert-enabled build, walk the whole array to ensure
7787 : : * there's no other updater.
7788 : : */
7789 : : break;
7790 : : #endif
7791 : : }
7792 : :
7793 : 162093 : pfree(members);
7794 : : }
7795 : :
7796 : 162093 : return update_xact;
7797 : : }
7798 : :
7799 : : /*
7800 : : * HeapTupleGetUpdateXid
7801 : : * As above, but use a HeapTupleHeader
7802 : : *
7803 : : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7804 : : * checking the hint bits.
7805 : : */
7806 : : TransactionId
627 peter@eisentraut.org 7807 : 159953 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
7808 : : {
7809 : 159953 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
7810 : 159953 : tup->t_infomask);
7811 : : }
7812 : :
7813 : : /*
7814 : : * Does the given multixact conflict with the current transaction grabbing a
7815 : : * tuple lock of the given strength?
7816 : : *
7817 : : * The passed infomask pairs up with the given multixact in the tuple header.
7818 : : *
7819 : : * If current_is_member is not NULL, it is set to 'true' if the current
7820 : : * transaction is a member of the given multixact.
7821 : : */
7822 : : static bool
4308 alvherre@alvh.no-ip. 7823 : 218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7824 : : LockTupleMode lockmode, bool *current_is_member)
7825 : : {
7826 : : int nmembers;
7827 : : MultiXactMember *members;
4160 bruce@momjian.us 7828 : 218 : bool result = false;
7829 : 218 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7830 : :
3762 alvherre@alvh.no-ip. 7831 [ - + ]: 218 : if (HEAP_LOCKED_UPGRADED(infomask))
3762 alvherre@alvh.no-ip. 7832 :UBC 0 : return false;
7833 : :
3762 alvherre@alvh.no-ip. 7834 :CBC 218 : nmembers = GetMultiXactIdMembers(multi, &members, false,
4308 7835 : 218 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7836 [ + - ]: 218 : if (nmembers >= 0)
7837 : : {
7838 : : int i;
7839 : :
7840 [ + + ]: 2682 : for (i = 0; i < nmembers; i++)
7841 : : {
7842 : : TransactionId memxid;
7843 : : LOCKMODE memlockmode;
7844 : :
2673 7845 [ + + + + : 2471 : if (result && (current_is_member == NULL || *current_is_member))
+ - ]
7846 : : break;
7847 : :
7848 : 2464 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7849 : :
7850 : : /* ignore members from current xact (but track their presence) */
2675 7851 : 2464 : memxid = members[i].xid;
7852 [ + + ]: 2464 : if (TransactionIdIsCurrentTransactionId(memxid))
7853 : : {
2673 7854 [ + + ]: 92 : if (current_is_member != NULL)
7855 : 78 : *current_is_member = true;
7856 : 92 : continue;
7857 : : }
7858 [ + + ]: 2372 : else if (result)
7859 : 8 : continue;
7860 : :
7861 : : /* ignore members that don't conflict with the lock we want */
7862 [ + + ]: 2364 : if (!DoLockModesConflict(memlockmode, wanted))
2675 7863 : 2325 : continue;
7864 : :
4308 7865 [ + + ]: 39 : if (ISUPDATE_from_mxstatus(members[i].status))
7866 : : {
7867 : : /* ignore aborted updaters */
7868 [ + + ]: 17 : if (TransactionIdDidAbort(memxid))
7869 : 1 : continue;
7870 : : }
7871 : : else
7872 : : {
7873 : : /* ignore lockers-only that are no longer in progress */
7874 [ + + ]: 22 : if (!TransactionIdIsInProgress(memxid))
7875 : 7 : continue;
7876 : : }
7877 : :
7878 : : /*
7879 : : * Whatever remains are either live lockers that conflict with our
7880 : : * wanted lock, and updaters that are not aborted. Those conflict
7881 : : * with what we want. Set up to return true, but keep going to
7882 : : * look for the current transaction among the multixact members,
7883 : : * if needed.
7884 : : */
7885 : 31 : result = true;
7886 : : }
7887 : 218 : pfree(members);
7888 : : }
7889 : :
7890 : 218 : return result;
7891 : : }
7892 : :
7893 : : /*
7894 : : * Do_MultiXactIdWait
7895 : : * Actual implementation for the two functions below.
7896 : : *
7897 : : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7898 : : * needed to ensure we only sleep on conflicting members, and the infomask is
7899 : : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7900 : : * indicates whether to use conditional lock acquisition, to allow callers to
7901 : : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7902 : : * context information for error messages. 'remaining', if not NULL, receives
7903 : : * the number of members that are still running, including any (non-aborted)
7904 : : * subtransactions of our own transaction. 'logLockFailure' indicates whether
7905 : : * to log details when a lock acquisition fails with 'nowait' enabled.
7906 : : *
7907 : : * We do this by sleeping on each member using XactLockTableWait. Any
7908 : : * members that belong to the current backend are *not* waited for, however;
7909 : : * this would not merely be useless but would lead to Assert failure inside
7910 : : * XactLockTableWait. By the time this returns, it is certain that all
7911 : : * transactions *of other backends* that were members of the MultiXactId
7912 : : * that conflict with the requested status are dead (and no new ones can have
7913 : : * been added, since it is not legal to add members to an existing
7914 : : * MultiXactId).
7915 : : *
7916 : : * But by the time we finish sleeping, someone else may have changed the Xmax
7917 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7918 : : *
7919 : : * Note that in case we return false, the number of remaining members is
7920 : : * not to be trusted.
7921 : : */
7922 : : static bool
5010 7923 : 61 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7924 : : uint16 infomask, bool nowait,
7925 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7926 : : int *remaining, bool logLockFailure)
7927 : : {
7928 : 61 : bool result = true;
7929 : : MultiXactMember *members;
7930 : : int nmembers;
7931 : 61 : int remain = 0;
7932 : :
7933 : : /* for pre-pg_upgrade tuples, no need to sleep at all */
3762 7934 [ + - ]: 61 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7935 : 61 : GetMultiXactIdMembers(multi, &members, false,
7936 : 61 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7937 : :
5010 7938 [ + - ]: 61 : if (nmembers >= 0)
7939 : : {
7940 : : int i;
7941 : :
7942 [ + + ]: 191 : for (i = 0; i < nmembers; i++)
7943 : : {
7944 : 136 : TransactionId memxid = members[i].xid;
7945 : 136 : MultiXactStatus memstatus = members[i].status;
7946 : :
7947 [ + + ]: 136 : if (TransactionIdIsCurrentTransactionId(memxid))
7948 : : {
7949 : 25 : remain++;
7950 : 25 : continue;
7951 : : }
7952 : :
7953 [ + + ]: 111 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7954 : 111 : LOCKMODE_from_mxstatus(status)))
7955 : : {
7956 [ + + + - ]: 22 : if (remaining && TransactionIdIsInProgress(memxid))
7957 : 8 : remain++;
7958 : 22 : continue;
7959 : : }
7960 : :
7961 : : /*
7962 : : * This member conflicts with our multi, so we have to sleep (or
7963 : : * return failure, if asked to avoid waiting.)
7964 : : *
7965 : : * Note that we don't set up an error context callback ourselves,
7966 : : * but instead we pass the info down to XactLockTableWait. This
7967 : : * might seem a bit wasteful because the context is set up and
7968 : : * tore down for each member of the multixact, but in reality it
7969 : : * should be barely noticeable, and it avoids duplicate code.
7970 : : */
7971 [ + + ]: 89 : if (nowait)
7972 : : {
577 fujii@postgresql.org 7973 : 6 : result = ConditionalXactLockTableWait(memxid, logLockFailure);
5010 alvherre@alvh.no-ip. 7974 [ + - ]: 6 : if (!result)
7975 : 6 : break;
7976 : : }
7977 : : else
4590 7978 : 83 : XactLockTableWait(memxid, rel, ctid, oper);
7979 : : }
7980 : :
5010 7981 : 61 : pfree(members);
7982 : : }
7983 : :
7984 [ + + ]: 61 : if (remaining)
7985 : 10 : *remaining = remain;
7986 : :
7987 : 61 : return result;
7988 : : }
7989 : :
7990 : : /*
7991 : : * MultiXactIdWait
7992 : : * Sleep on a MultiXactId.
7993 : : *
7994 : : * By the time we finish sleeping, someone else may have changed the Xmax
7995 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7996 : : *
7997 : : * We return (in *remaining, if not NULL) the number of members that are still
7998 : : * running, including any (non-aborted) subtransactions of our own transaction.
7999 : : */
8000 : : static void
4590 8001 : 55 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
8002 : : Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
8003 : : int *remaining)
8004 : : {
8005 : 55 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
8006 : : rel, ctid, oper, remaining, false);
5010 8007 : 55 : }
8008 : :
8009 : : /*
8010 : : * ConditionalMultiXactIdWait
8011 : : * As above, but only lock if we can get the lock without blocking.
8012 : : *
8013 : : * By the time we finish sleeping, someone else may have changed the Xmax
8014 : : * of the containing tuple, so the caller needs to iterate on us somehow.
8015 : : *
8016 : : * If the multixact is now all gone, return true. Returns false if some
8017 : : * transactions might still be running.
8018 : : *
8019 : : * We return (in *remaining, if not NULL) the number of members that are still
8020 : : * running, including any (non-aborted) subtransactions of our own transaction.
8021 : : */
8022 : : static bool
8023 : 6 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
8024 : : uint16 infomask, Relation rel, int *remaining,
8025 : : bool logLockFailure)
8026 : : {
4590 8027 : 6 : return Do_MultiXactIdWait(multi, status, infomask, true,
8028 : : rel, NULL, XLTW_None, remaining, logLockFailure);
8029 : : }
8030 : :
8031 : : /*
8032 : : * heap_tuple_needs_eventual_freeze
8033 : : *
8034 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
8035 : : * will eventually require freezing (if tuple isn't removed by pruning first).
8036 : : */
8037 : : bool
3877 rhaas@postgresql.org 8038 : 2211492 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
8039 : : {
8040 : : TransactionId xid;
8041 : :
8042 : : /*
8043 : : * If xmin is a normal transaction ID, this tuple is definitely not
8044 : : * frozen.
8045 : : */
8046 : 2211492 : xid = HeapTupleHeaderGetXmin(tuple);
8047 [ + + ]: 2211492 : if (TransactionIdIsNormal(xid))
8048 : 50104 : return true;
8049 : :
8050 : : /*
8051 : : * If xmax is a valid xact or multixact, this tuple is also not frozen.
8052 : : */
8053 [ + + ]: 2161388 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
8054 : : {
8055 : : MultiXactId multi;
8056 : :
8057 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8058 [ + - ]: 2 : if (MultiXactIdIsValid(multi))
8059 : 2 : return true;
8060 : : }
8061 : : else
8062 : : {
8063 : 2161386 : xid = HeapTupleHeaderGetRawXmax(tuple);
8064 [ + + ]: 2161386 : if (TransactionIdIsNormal(xid))
8065 : 41 : return true;
8066 : : }
8067 : :
8068 [ - + ]: 2161345 : if (tuple->t_infomask & HEAP_MOVED)
8069 : : {
3877 rhaas@postgresql.org 8070 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
8071 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8072 : 0 : return true;
8073 : : }
8074 : :
3877 rhaas@postgresql.org 8075 :CBC 2161345 : return false;
8076 : : }
8077 : :
8078 : : /*
8079 : : * heap_tuple_should_freeze
8080 : : *
8081 : : * Return value indicates if heap_prepare_freeze_tuple sibling function would
8082 : : * (or should) force freezing of the heap page that contains caller's tuple.
8083 : : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
8084 : : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
8085 : : *
8086 : : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
8087 : : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
8088 : : * Our working assumption is that caller won't decide to freeze this tuple.
8089 : : * It's up to caller to only ratchet back its own top-level trackers after the
8090 : : * point that it fully commits to not freezing the tuple/page in question.
8091 : : */
8092 : : bool
1384 pg@bowt.ie 8093 : 3263435 : heap_tuple_should_freeze(HeapTupleHeader tuple,
8094 : : const struct VacuumCutoffs *cutoffs,
8095 : : TransactionId *NoFreezePageRelfrozenXid,
8096 : : MultiXactId *NoFreezePageRelminMxid)
8097 : : {
8098 : : TransactionId xid;
8099 : : MultiXactId multi;
1390 8100 : 3263435 : bool freeze = false;
8101 : :
8102 : : /* First deal with xmin */
5453 rhaas@postgresql.org 8103 : 3263435 : xid = HeapTupleHeaderGetXmin(tuple);
1653 pg@bowt.ie 8104 [ + + ]: 3263435 : if (TransactionIdIsNormal(xid))
8105 : : {
1390 8106 [ - + ]: 3262901 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1384 8107 [ + + ]: 3262901 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8108 : 24245 : *NoFreezePageRelfrozenXid = xid;
1390 8109 [ + + ]: 3262901 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8110 : 20723 : freeze = true;
8111 : : }
8112 : :
8113 : : /* Now deal with xmax */
1653 8114 : 3263435 : xid = InvalidTransactionId;
8115 : 3263435 : multi = InvalidMultiXactId;
8116 [ + + ]: 3263435 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
4701 alvherre@alvh.no-ip. 8117 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
8118 : : else
1653 pg@bowt.ie 8119 : 3263433 : xid = HeapTupleHeaderGetRawXmax(tuple);
8120 : :
8121 [ + + ]: 3263435 : if (TransactionIdIsNormal(xid))
8122 : : {
1390 8123 [ - + ]: 398779 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
8124 : : /* xmax is a non-permanent XID */
1384 8125 [ + + ]: 398779 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8126 : 16 : *NoFreezePageRelfrozenXid = xid;
1390 8127 [ + + ]: 398779 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8128 : 21 : freeze = true;
8129 : : }
1653 8130 [ + + ]: 2864656 : else if (!MultiXactIdIsValid(multi))
8131 : : {
8132 : : /* xmax is a permanent XID or invalid MultiXactId/XID */
8133 : : }
8134 [ - + ]: 2 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
8135 : : {
8136 : : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
1384 pg@bowt.ie 8137 [ # # ]:UBC 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8138 : 0 : *NoFreezePageRelminMxid = multi;
8139 : : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
1390 8140 : 0 : freeze = true;
8141 : : }
8142 : : else
8143 : : {
8144 : : /* xmax is a MultiXactId that may have an updater XID */
8145 : : MultiXactMember *members;
8146 : : int nmembers;
8147 : :
1390 pg@bowt.ie 8148 [ - + ]:CBC 2 : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
1384 8149 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8150 : 2 : *NoFreezePageRelminMxid = multi;
1390 8151 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
8152 : 2 : freeze = true;
8153 : :
8154 : : /* need to check whether any member of the mxact is old */
1653 8155 : 2 : nmembers = GetMultiXactIdMembers(multi, &members, false,
8156 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
8157 : :
8158 [ + + ]: 5 : for (int i = 0; i < nmembers; i++)
8159 : : {
8160 : 3 : xid = members[i].xid;
1390 8161 [ - + ]: 3 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1384 8162 [ - + ]: 3 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
1384 pg@bowt.ie 8163 :UBC 0 : *NoFreezePageRelfrozenXid = xid;
1390 pg@bowt.ie 8164 [ - + ]:CBC 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
1390 pg@bowt.ie 8165 :UBC 0 : freeze = true;
8166 : : }
1653 pg@bowt.ie 8167 [ + + ]:CBC 2 : if (nmembers > 0)
8168 : 1 : pfree(members);
8169 : : }
8170 : :
5453 rhaas@postgresql.org 8171 [ - + ]: 3263435 : if (tuple->t_infomask & HEAP_MOVED)
8172 : : {
5453 rhaas@postgresql.org 8173 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
1653 pg@bowt.ie 8174 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
8175 : : {
1390 8176 [ # # ]: 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
1384 8177 [ # # ]: 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8178 : 0 : *NoFreezePageRelfrozenXid = xid;
8179 : : /* heap_prepare_freeze_tuple forces xvac freezing */
1390 8180 : 0 : freeze = true;
8181 : : }
8182 : : }
8183 : :
1390 pg@bowt.ie 8184 :CBC 3263435 : return freeze;
8185 : : }
8186 : :
8187 : : /*
8188 : : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
8189 : : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
8190 : : * that caller is in the process of physically removing, e.g. via HOT pruning
8191 : : * or index deletion.
8192 : : *
8193 : : * Caller must initialize its value to InvalidTransactionId, which is
8194 : : * generally interpreted as "definitely no need for a recovery conflict".
8195 : : * Final value must reflect all heap tuples that caller will physically remove
8196 : : * (or remove TID references to) via its ongoing pruning/deletion operation.
8197 : : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
8198 : : * caller's WAL record) by REDO routine when it replays caller's operation.
8199 : : */
8200 : : void
1425 8201 : 4086373 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
8202 : : TransactionId *snapshotConflictHorizon)
8203 : : {
6141 simon@2ndQuadrant.co 8204 : 4086373 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
5010 alvherre@alvh.no-ip. 8205 : 4086373 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
6141 simon@2ndQuadrant.co 8206 : 4086373 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
8207 : :
6090 tgl@sss.pgh.pa.us 8208 [ - + ]: 4086373 : if (tuple->t_infomask & HEAP_MOVED)
8209 : : {
1425 pg@bowt.ie 8210 [ # # ]:UBC 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
8211 : 0 : *snapshotConflictHorizon = xvac;
8212 : : }
8213 : :
8214 : : /*
8215 : : * Ignore tuples inserted by an aborted transaction or if the tuple was
8216 : : * updated/deleted by the inserting transaction.
8217 : : *
8218 : : * Look for a committed hint bit, or if no xmin bit is set, check clog.
8219 : : */
4677 rhaas@postgresql.org 8220 [ + + ]:CBC 4086373 : if (HeapTupleHeaderXminCommitted(tuple) ||
8221 [ + + + - ]: 147416 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
8222 : : {
5786 simon@2ndQuadrant.co 8223 [ + + + + ]: 7719037 : if (xmax != xmin &&
1425 pg@bowt.ie 8224 : 3757628 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
8225 : 132184 : *snapshotConflictHorizon = xmax;
8226 : : }
6141 simon@2ndQuadrant.co 8227 : 4086373 : }
8228 : :
8229 : : #ifdef USE_PREFETCH
8230 : : /*
8231 : : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
8232 : : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
8233 : : * we can prefetch, and which have already been prefetched; each call to this
8234 : : * function picks up where the previous call left off.
8235 : : *
8236 : : * Note: we expect the deltids array to be sorted in an order that groups TIDs
8237 : : * by heap block, with all TIDs for each block appearing together in exactly
8238 : : * one group.
8239 : : */
8240 : : static void
2098 pg@bowt.ie 8241 : 24305 : index_delete_prefetch_buffer(Relation rel,
8242 : : IndexDeletePrefetchState *prefetch_state,
8243 : : int prefetch_count)
8244 : : {
2757 andres@anarazel.de 8245 : 24305 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
8246 : 24305 : int count = 0;
8247 : : int i;
2098 pg@bowt.ie 8248 : 24305 : int ndeltids = prefetch_state->ndeltids;
8249 : 24305 : TM_IndexDelete *deltids = prefetch_state->deltids;
8250 : :
2757 andres@anarazel.de 8251 : 24305 : for (i = prefetch_state->next_item;
2098 pg@bowt.ie 8252 [ + + + + ]: 876258 : i < ndeltids && count < prefetch_count;
2757 andres@anarazel.de 8253 : 851953 : i++)
8254 : : {
2098 pg@bowt.ie 8255 : 851953 : ItemPointer htid = &deltids[i].tid;
8256 : :
2757 andres@anarazel.de 8257 [ + + + + ]: 1696415 : if (cur_hblkno == InvalidBlockNumber ||
8258 : 844462 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
8259 : : {
8260 : 22446 : cur_hblkno = ItemPointerGetBlockNumber(htid);
8261 : 22446 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
8262 : 22446 : count++;
8263 : : }
8264 : : }
8265 : :
8266 : : /*
8267 : : * Save the prefetch position so that next time we can continue from that
8268 : : * position.
8269 : : */
8270 : 24305 : prefetch_state->next_item = i;
8271 : 24305 : prefetch_state->cur_hblkno = cur_hblkno;
8272 : 24305 : }
8273 : : #endif
8274 : :
8275 : : /*
8276 : : * Helper function for heap_index_delete_tuples. Checks for index corruption
8277 : : * involving an invalid TID in index AM caller's index page.
8278 : : *
8279 : : * This is an ideal place for these checks. The index AM must hold a buffer
8280 : : * lock on the index page containing the TIDs we examine here, so we don't
8281 : : * have to worry about concurrent VACUUMs at all. We can be sure that the
8282 : : * index is corrupt when htid points directly to an LP_UNUSED item or
8283 : : * heap-only tuple, which is not the case during standard index scans.
8284 : : */
8285 : : static inline void
1803 pg@bowt.ie 8286 : 700707 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
8287 : : Page page, OffsetNumber maxoff,
8288 : : const ItemPointerData *htid, TM_IndexStatus *istatus)
8289 : : {
8290 : 700707 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8291 : : ItemId iid;
8292 : :
8293 [ + - + - : 700707 : Assert(OffsetNumberIsValid(istatus->idxoffnum));
- + ]
8294 : :
8295 [ - + ]: 700707 : if (unlikely(indexpagehoffnum > maxoff))
1803 pg@bowt.ie 8296 [ # # ]:UBC 0 : ereport(ERROR,
8297 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8298 : : 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\"",
8299 : : ItemPointerGetBlockNumber(htid),
8300 : : indexpagehoffnum,
8301 : : istatus->idxoffnum, delstate->iblknum,
8302 : : RelationGetRelationName(delstate->irel))));
8303 : :
1803 pg@bowt.ie 8304 :CBC 700707 : iid = PageGetItemId(page, indexpagehoffnum);
8305 [ - + ]: 700707 : if (unlikely(!ItemIdIsUsed(iid)))
1803 pg@bowt.ie 8306 [ # # ]:UBC 0 : ereport(ERROR,
8307 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8308 : : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8309 : : ItemPointerGetBlockNumber(htid),
8310 : : indexpagehoffnum,
8311 : : istatus->idxoffnum, delstate->iblknum,
8312 : : RelationGetRelationName(delstate->irel))));
8313 : :
1803 pg@bowt.ie 8314 [ + + ]:CBC 700707 : if (ItemIdHasStorage(iid))
8315 : : {
8316 : : HeapTupleHeader htup;
8317 : :
8318 [ - + ]: 450735 : Assert(ItemIdIsNormal(iid));
8319 : 450735 : htup = (HeapTupleHeader) PageGetItem(page, iid);
8320 : :
8321 [ - + ]: 450735 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
1803 pg@bowt.ie 8322 [ # # ]:UBC 0 : ereport(ERROR,
8323 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8324 : : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8325 : : ItemPointerGetBlockNumber(htid),
8326 : : indexpagehoffnum,
8327 : : istatus->idxoffnum, delstate->iblknum,
8328 : : RelationGetRelationName(delstate->irel))));
8329 : : }
1803 pg@bowt.ie 8330 :CBC 700707 : }
8331 : :
8332 : : /*
8333 : : * heapam implementation of tableam's index_delete_tuples interface.
8334 : : *
8335 : : * This helper function is called by index AMs during index tuple deletion.
8336 : : * See tableam header comments for an explanation of the interface implemented
8337 : : * here and a general theory of operation. Note that each call here is either
8338 : : * a simple index deletion call, or a bottom-up index deletion call.
8339 : : *
8340 : : * It's possible for this to generate a fair amount of I/O, since we may be
8341 : : * deleting hundreds of tuples from a single index block. To amortize that
8342 : : * cost to some degree, this uses prefetching and combines repeat accesses to
8343 : : * the same heap block.
8344 : : */
8345 : : TransactionId
2098 8346 : 7491 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
8347 : : {
8348 : : /* Initial assumption is that earlier pruning took care of conflict */
1425 8349 : 7491 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
2112 8350 : 7491 : BlockNumber blkno = InvalidBlockNumber;
2757 andres@anarazel.de 8351 : 7491 : Buffer buf = InvalidBuffer;
2112 pg@bowt.ie 8352 : 7491 : Page page = NULL;
8353 : 7491 : OffsetNumber maxoff = InvalidOffsetNumber;
8354 : : TransactionId priorXmax;
8355 : : #ifdef USE_PREFETCH
8356 : : IndexDeletePrefetchState prefetch_state;
8357 : : int prefetch_distance;
8358 : : #endif
8359 : : SnapshotData SnapshotNonVacuumable;
2098 8360 : 7491 : int finalndeltids = 0,
8361 : 7491 : nblocksaccessed = 0;
8362 : :
8363 : : /* State that's only used in bottom-up index deletion case */
8364 : 7491 : int nblocksfavorable = 0;
8365 : 7491 : int curtargetfreespace = delstate->bottomupfreespace,
8366 : 7491 : lastfreespace = 0,
8367 : 7491 : actualfreespace = 0;
8368 : 7491 : bool bottomup_final_block = false;
8369 : :
8370 : 7491 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8371 : :
8372 : : /* Sort caller's deltids array by TID for further processing */
8373 : 7491 : index_delete_sort(delstate);
8374 : :
8375 : : /*
8376 : : * Bottom-up case: resort deltids array in an order attuned to where the
8377 : : * greatest number of promising TIDs are to be found, and determine how
8378 : : * many blocks from the start of sorted array should be considered
8379 : : * favorable. This will also shrink the deltids array in order to
8380 : : * eliminate completely unfavorable blocks up front.
8381 : : */
8382 [ + + ]: 7491 : if (delstate->bottomup)
8383 : 2916 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
8384 : :
8385 : : #ifdef USE_PREFETCH
8386 : : /* Initialize prefetch state. */
2757 andres@anarazel.de 8387 : 7491 : prefetch_state.cur_hblkno = InvalidBlockNumber;
8388 : 7491 : prefetch_state.next_item = 0;
2098 pg@bowt.ie 8389 : 7491 : prefetch_state.ndeltids = delstate->ndeltids;
8390 : 7491 : prefetch_state.deltids = delstate->deltids;
8391 : :
8392 : : /*
8393 : : * Determine the prefetch distance that we will attempt to maintain.
8394 : : *
8395 : : * Since the caller holds a buffer lock somewhere in rel, we'd better make
8396 : : * sure that isn't a catalog relation before we call code that does
8397 : : * syscache lookups, to avoid risk of deadlock.
8398 : : */
2750 tmunro@postgresql.or 8399 [ + + ]: 7491 : if (IsCatalogRelation(rel))
2401 8400 : 5214 : prefetch_distance = maintenance_io_concurrency;
8401 : : else
8402 : : prefetch_distance =
8403 : 2277 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
8404 : :
8405 : : /* Cap initial prefetch distance for bottom-up deletion caller */
2098 pg@bowt.ie 8406 [ + + ]: 7491 : if (delstate->bottomup)
8407 : : {
8408 [ - + ]: 2916 : Assert(nblocksfavorable >= 1);
8409 [ - + ]: 2916 : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8410 : 2916 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8411 : : }
8412 : :
8413 : : /* Start prefetching. */
8414 : 7491 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8415 : : #endif
8416 : :
8417 : : /* Iterate over deltids, determine which to delete, check their horizon */
8418 [ - + ]: 7491 : Assert(delstate->ndeltids > 0);
8419 [ + + ]: 708198 : for (int i = 0; i < delstate->ndeltids; i++)
8420 : : {
8421 : 703623 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8422 : 703623 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8423 : 703623 : ItemPointer htid = &ideltid->tid;
8424 : : OffsetNumber offnum;
8425 : :
8426 : : /*
8427 : : * Read buffer, and perform required extra steps each time a new block
8428 : : * is encountered. Avoid refetching if it's the same block as the one
8429 : : * from the last htid.
8430 : : */
2112 8431 [ + + + + ]: 1399755 : if (blkno == InvalidBlockNumber ||
8432 : 696132 : ItemPointerGetBlockNumber(htid) != blkno)
8433 : : {
8434 : : /*
8435 : : * Consider giving up early for bottom-up index deletion caller
8436 : : * first. (Only prefetch next-next block afterwards, when it
8437 : : * becomes clear that we're at least going to access the next
8438 : : * block in line.)
8439 : : *
8440 : : * Sometimes the first block frees so much space for bottom-up
8441 : : * caller that the deletion process can end without accessing any
8442 : : * more blocks. It is usually necessary to access 2 or 3 blocks
8443 : : * per bottom-up deletion operation, though.
8444 : : */
2098 8445 [ + + ]: 19730 : if (delstate->bottomup)
8446 : : {
8447 : : /*
8448 : : * We often allow caller to delete a few additional items
8449 : : * whose entries we reached after the point that space target
8450 : : * from caller was satisfied. The cost of accessing the page
8451 : : * was already paid at that point, so it made sense to finish
8452 : : * it off. When that happened, we finalize everything here
8453 : : * (by finishing off the whole bottom-up deletion operation
8454 : : * without needlessly paying the cost of accessing any more
8455 : : * blocks).
8456 : : */
8457 [ + + ]: 6262 : if (bottomup_final_block)
8458 : 179 : break;
8459 : :
8460 : : /*
8461 : : * Give up when we didn't enable our caller to free any
8462 : : * additional space as a result of processing the page that we
8463 : : * just finished up with. This rule is the main way in which
8464 : : * we keep the cost of bottom-up deletion under control.
8465 : : */
8466 [ + + + + ]: 6083 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8467 : 2737 : break;
8468 : 3346 : lastfreespace = actualfreespace; /* for next time */
8469 : :
8470 : : /*
8471 : : * Deletion operation (which is bottom-up) will definitely
8472 : : * access the next block in line. Prepare for that now.
8473 : : *
8474 : : * Decay target free space so that we don't hang on for too
8475 : : * long with a marginal case. (Space target is only truly
8476 : : * helpful when it allows us to recognize that we don't need
8477 : : * to access more than 1 or 2 blocks to satisfy caller due to
8478 : : * agreeable workload characteristics.)
8479 : : *
8480 : : * We are a bit more patient when we encounter contiguous
8481 : : * blocks, though: these are treated as favorable blocks. The
8482 : : * decay process is only applied when the next block in line
8483 : : * is not a favorable/contiguous block. This is not an
8484 : : * exception to the general rule; we still insist on finding
8485 : : * at least one deletable item per block accessed. See
8486 : : * bottomup_nblocksfavorable() for full details of the theory
8487 : : * behind favorable blocks and heap block locality in general.
8488 : : *
8489 : : * Note: The first block in line is always treated as a
8490 : : * favorable block, so the earliest possible point that the
8491 : : * decay can be applied is just before we access the second
8492 : : * block in line. The Assert() verifies this for us.
8493 : : */
8494 [ + + - + ]: 3346 : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8495 [ + + ]: 3346 : if (nblocksfavorable > 0)
8496 : 3142 : nblocksfavorable--;
8497 : : else
8498 : 204 : curtargetfreespace /= 2;
8499 : : }
8500 : :
8501 : : /* release old buffer */
8502 [ + + ]: 16814 : if (BufferIsValid(buf))
8503 : 9323 : UnlockReleaseBuffer(buf);
8504 : :
8505 : 16814 : blkno = ItemPointerGetBlockNumber(htid);
2112 8506 : 16814 : buf = ReadBuffer(rel, blkno);
2098 8507 : 16814 : nblocksaccessed++;
8508 [ + + - + ]: 16814 : Assert(!delstate->bottomup ||
8509 : : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8510 : :
8511 : : #ifdef USE_PREFETCH
8512 : :
8513 : : /*
8514 : : * To maintain the prefetch distance, prefetch one more page for
8515 : : * each page we read.
8516 : : */
8517 : 16814 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8518 : : #endif
8519 : :
2112 8520 : 16814 : LockBuffer(buf, BUFFER_LOCK_SHARE);
8521 : :
8522 : 16814 : page = BufferGetPage(buf);
8523 : 16814 : maxoff = PageGetMaxOffsetNumber(page);
8524 : : }
8525 : :
8526 : : /*
8527 : : * In passing, detect index corruption involving an index page with a
8528 : : * TID that points to a location in the heap that couldn't possibly be
8529 : : * correct. We only do this with actual TIDs from caller's index page
8530 : : * (not items reached by traversing through a HOT chain).
8531 : : */
1803 8532 : 700707 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8533 : :
2098 8534 [ + + ]: 700707 : if (istatus->knowndeletable)
8535 [ + - - + ]: 155735 : Assert(!delstate->bottomup && !istatus->promising);
8536 : : else
8537 : : {
8538 : 544972 : ItemPointerData tmp = *htid;
8539 : : HeapTupleData heapTuple;
8540 : :
8541 : : /* Are any tuples from this HOT chain non-vacuumable? */
8542 [ + + ]: 544972 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8543 : : &heapTuple, NULL, true))
8544 : 341313 : continue; /* can't delete entry */
8545 : :
8546 : : /* Caller will delete, since whole HOT chain is vacuumable */
8547 : 203659 : istatus->knowndeletable = true;
8548 : :
8549 : : /* Maintain index free space info for bottom-up deletion case */
8550 [ + + ]: 203659 : if (delstate->bottomup)
8551 : : {
8552 [ - + ]: 10934 : Assert(istatus->freespace > 0);
8553 : 10934 : actualfreespace += istatus->freespace;
8554 [ + + ]: 10934 : if (actualfreespace >= curtargetfreespace)
8555 : 2649 : bottomup_final_block = true;
8556 : : }
8557 : : }
8558 : :
8559 : : /*
8560 : : * Maintain snapshotConflictHorizon value for deletion operation as a
8561 : : * whole by advancing current value using heap tuple headers. This is
8562 : : * loosely based on the logic for pruning a HOT chain.
8563 : : */
2112 8564 : 359394 : offnum = ItemPointerGetOffsetNumber(htid);
8565 : 359394 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8566 : : for (;;)
2757 andres@anarazel.de 8567 : 21804 : {
8568 : : ItemId lp;
8569 : : HeapTupleHeader htup;
8570 : :
8571 : : /* Sanity check (pure paranoia) */
1846 pg@bowt.ie 8572 [ - + ]: 381198 : if (offnum < FirstOffsetNumber)
1846 pg@bowt.ie 8573 :UBC 0 : break;
8574 : :
8575 : : /*
8576 : : * An offset past the end of page's line pointer array is possible
8577 : : * when the array was truncated
8578 : : */
1846 pg@bowt.ie 8579 [ - + ]:CBC 381198 : if (offnum > maxoff)
2112 pg@bowt.ie 8580 :UBC 0 : break;
8581 : :
2112 pg@bowt.ie 8582 :CBC 381198 : lp = PageGetItemId(page, offnum);
8583 [ + + ]: 381198 : if (ItemIdIsRedirected(lp))
8584 : : {
8585 : 9634 : offnum = ItemIdGetRedirect(lp);
8586 : 9634 : continue;
8587 : : }
8588 : :
8589 : : /*
8590 : : * We'll often encounter LP_DEAD line pointers (especially with an
8591 : : * entry marked knowndeletable by our caller up front). No heap
8592 : : * tuple headers get examined for an htid that leads us to an
8593 : : * LP_DEAD item. This is okay because the earlier pruning
8594 : : * operation that made the line pointer LP_DEAD in the first place
8595 : : * must have considered the original tuple header as part of
8596 : : * generating its own snapshotConflictHorizon value.
8597 : : *
8598 : : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8599 : : * the same strategy that index vacuuming uses in all cases. Index
8600 : : * VACUUM WAL records don't even have a snapshotConflictHorizon
8601 : : * field of their own for this reason.
8602 : : */
8603 [ + + ]: 371564 : if (!ItemIdIsNormal(lp))
8604 : 219333 : break;
8605 : :
8606 : 152231 : htup = (HeapTupleHeader) PageGetItem(page, lp);
8607 : :
8608 : : /*
8609 : : * Check the tuple XMIN against prior XMAX, if any
8610 : : */
8611 [ + + - + ]: 164401 : if (TransactionIdIsValid(priorXmax) &&
8612 : 12170 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
2112 pg@bowt.ie 8613 :UBC 0 : break;
8614 : :
1425 pg@bowt.ie 8615 :CBC 152231 : HeapTupleHeaderAdvanceConflictHorizon(htup,
8616 : : &snapshotConflictHorizon);
8617 : :
8618 : : /*
8619 : : * If the tuple is not HOT-updated, then we are at the end of this
8620 : : * HOT-chain. No need to visit later tuples from the same update
8621 : : * chain (they get their own index entries) -- just move on to
8622 : : * next htid from index AM caller.
8623 : : */
2112 8624 [ + + ]: 152231 : if (!HeapTupleHeaderIsHotUpdated(htup))
8625 : 140061 : break;
8626 : :
8627 : : /* Advance to next HOT chain member */
8628 [ - + ]: 12170 : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8629 : 12170 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8630 : 12170 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8631 : : }
8632 : :
8633 : : /* Enable further/final shrinking of deltids for caller */
2098 8634 : 359394 : finalndeltids = i + 1;
8635 : : }
8636 : :
8637 : 7491 : UnlockReleaseBuffer(buf);
8638 : :
8639 : : /*
8640 : : * Shrink deltids array to exclude non-deletable entries at the end. This
8641 : : * is not just a minor optimization. Final deltids array size might be
8642 : : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8643 : : * ndeltids being zero in all cases with zero total deletable entries.
8644 : : */
8645 [ + + - + ]: 7491 : Assert(finalndeltids > 0 || delstate->bottomup);
8646 : 7491 : delstate->ndeltids = finalndeltids;
8647 : :
1425 8648 : 7491 : return snapshotConflictHorizon;
8649 : : }
8650 : :
8651 : : /*
8652 : : * Specialized inlineable comparison function for index_delete_sort()
8653 : : */
8654 : : static inline int
2098 8655 : 17633079 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
8656 : : {
8657 : 17633079 : ItemPointer tid1 = &deltid1->tid;
8658 : 17633079 : ItemPointer tid2 = &deltid2->tid;
8659 : :
8660 : : {
8661 : 17633079 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
8662 : 17633079 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
8663 : :
8664 [ + + ]: 17633079 : if (blk1 != blk2)
8665 [ + + ]: 7238402 : return (blk1 < blk2) ? -1 : 1;
8666 : : }
8667 : : {
8668 : 10394677 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
8669 : 10394677 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
8670 : :
8671 [ + - ]: 10394677 : if (pos1 != pos2)
8672 [ + + ]: 10394677 : return (pos1 < pos2) ? -1 : 1;
8673 : : }
8674 : :
1809 pg@bowt.ie 8675 :UBC 0 : Assert(false);
8676 : :
8677 : : return 0;
8678 : : }
8679 : :
8680 : : /*
8681 : : * Sort deltids array from delstate by TID. This prepares it for further
8682 : : * processing by heap_index_delete_tuples().
8683 : : *
8684 : : * This operation becomes a noticeable consumer of CPU cycles with some
8685 : : * workloads, so we go to the trouble of specialization/micro optimization.
8686 : : * We use shellsort for this because it's easy to specialize, compiles to
8687 : : * relatively few instructions, and is adaptive to presorted inputs/subsets
8688 : : * (which are typical here).
8689 : : */
8690 : : static void
2098 pg@bowt.ie 8691 :CBC 7491 : index_delete_sort(TM_IndexDeleteOp *delstate)
8692 : : {
8693 : 7491 : TM_IndexDelete *deltids = delstate->deltids;
8694 : 7491 : int ndeltids = delstate->ndeltids;
8695 : :
8696 : : /*
8697 : : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8698 : : *
8699 : : * This implementation is fast with array sizes up to ~4500. This covers
8700 : : * all supported BLCKSZ values.
8701 : : */
8702 : 7491 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8703 : :
8704 : : /* Think carefully before changing anything here -- keep swaps cheap */
8705 : : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8706 : : "element size exceeds 8 bytes");
8707 : :
93 peter@eisentraut.org 8708 [ + + ]:GNC 74910 : for (size_t g = 0; g < lengthof(gaps); g++)
8709 : : {
705 dgustafsson@postgres 8710 [ + + ]:CBC 10589544 : for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8711 : : {
2098 pg@bowt.ie 8712 : 10522125 : TM_IndexDelete d = deltids[i];
8713 : 10522125 : int j = i;
8714 : :
8715 [ + + + + ]: 18136008 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8716 : : {
8717 : 7613883 : deltids[j] = deltids[j - hi];
8718 : 7613883 : j -= hi;
8719 : : }
8720 : 10522125 : deltids[j] = d;
8721 : : }
8722 : : }
8723 : 7491 : }
8724 : :
8725 : : /*
8726 : : * Returns how many blocks should be considered favorable/contiguous for a
8727 : : * bottom-up index deletion pass. This is a number of heap blocks that starts
8728 : : * from and includes the first block in line.
8729 : : *
8730 : : * There is always at least one favorable block during bottom-up index
8731 : : * deletion. In the worst case (i.e. with totally random heap blocks) the
8732 : : * first block in line (the only favorable block) can be thought of as a
8733 : : * degenerate array of contiguous blocks that consists of a single block.
8734 : : * heap_index_delete_tuples() will expect this.
8735 : : *
8736 : : * Caller passes blockgroups, a description of the final order that deltids
8737 : : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8738 : : * processing. Note that deltids need not actually be sorted just yet (caller
8739 : : * only passes deltids to us so that we can interpret blockgroups).
8740 : : *
8741 : : * You might guess that the existence of contiguous blocks cannot matter much,
8742 : : * since in general the main factor that determines which blocks we visit is
8743 : : * the number of promising TIDs, which is a fixed hint from the index AM.
8744 : : * We're not really targeting the general case, though -- the actual goal is
8745 : : * to adapt our behavior to a wide variety of naturally occurring conditions.
8746 : : * The effects of most of the heuristics we apply are only noticeable in the
8747 : : * aggregate, over time and across many _related_ bottom-up index deletion
8748 : : * passes.
8749 : : *
8750 : : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8751 : : * workloads where heap blocks visited during bottom-up index deletion can be
8752 : : * accessed contiguously, in the sense that each newly visited block is the
8753 : : * neighbor of the block that bottom-up deletion just finished processing (or
8754 : : * close enough to it). It will likely be cheaper to access more favorable
8755 : : * blocks sooner rather than later (e.g. in this pass, not across a series of
8756 : : * related bottom-up passes). Either way it is probably only a matter of time
8757 : : * (or a matter of further correlated version churn) before all blocks that
8758 : : * appear together as a single large batch of favorable blocks get accessed by
8759 : : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8760 : : * appear almost constantly or not even once (it all depends on per-index
8761 : : * workload characteristics).
8762 : : *
8763 : : * Note that the blockgroups sort order applies a power-of-two bucketing
8764 : : * scheme that creates opportunities for contiguous groups of blocks to get
8765 : : * batched together, at least with workloads that are naturally amenable to
8766 : : * being driven by heap block locality. This doesn't just enhance the spatial
8767 : : * locality of bottom-up heap block processing in the obvious way. It also
8768 : : * enables temporal locality of access, since sorting by heap block number
8769 : : * naturally tends to make the bottom-up processing order deterministic.
8770 : : *
8771 : : * Consider the following example to get a sense of how temporal locality
8772 : : * might matter: There is a heap relation with several indexes, each of which
8773 : : * is low to medium cardinality. It is subject to constant non-HOT updates.
8774 : : * The updates are skewed (in one part of the primary key, perhaps). None of
8775 : : * the indexes are logically modified by the UPDATE statements (if they were
8776 : : * then bottom-up index deletion would not be triggered in the first place).
8777 : : * Naturally, each new round of index tuples (for each heap tuple that gets a
8778 : : * heap_update() call) will have the same heap TID in each and every index.
8779 : : * Since these indexes are low cardinality and never get logically modified,
8780 : : * heapam processing during bottom-up deletion passes will access heap blocks
8781 : : * in approximately sequential order. Temporal locality of access occurs due
8782 : : * to bottom-up deletion passes behaving very similarly across each of the
8783 : : * indexes at any given moment. This keeps the number of buffer misses needed
8784 : : * to visit heap blocks to a minimum.
8785 : : */
8786 : : static int
8787 : 2916 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8788 : : TM_IndexDelete *deltids)
8789 : : {
8790 : 2916 : int64 lastblock = -1;
8791 : 2916 : int nblocksfavorable = 0;
8792 : :
8793 [ - + ]: 2916 : Assert(nblockgroups >= 1);
8794 [ - + ]: 2916 : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8795 : :
8796 : : /*
8797 : : * We tolerate heap blocks that will be accessed only slightly out of
8798 : : * physical order. Small blips occur when a pair of almost-contiguous
8799 : : * blocks happen to fall into different buckets (perhaps due only to a
8800 : : * small difference in npromisingtids that the bucketing scheme didn't
8801 : : * quite manage to ignore). We effectively ignore these blips by applying
8802 : : * a small tolerance. The precise tolerance we use is a little arbitrary,
8803 : : * but it works well enough in practice.
8804 : : */
8805 [ + + ]: 8939 : for (int b = 0; b < nblockgroups; b++)
8806 : : {
8807 : 8634 : IndexDeleteCounts *group = blockgroups + b;
8808 : 8634 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8809 : 8634 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8810 : :
8811 [ + + ]: 8634 : if (lastblock != -1 &&
8812 [ + + ]: 5718 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8813 [ + + ]: 5029 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8814 : : break;
8815 : :
8816 : 6023 : nblocksfavorable++;
8817 : 6023 : lastblock = block;
8818 : : }
8819 : :
8820 : : /* Always indicate that there is at least 1 favorable block */
8821 [ - + ]: 2916 : Assert(nblocksfavorable >= 1);
8822 : :
8823 : 2916 : return nblocksfavorable;
8824 : : }
8825 : :
8826 : : /*
8827 : : * qsort comparison function for bottomup_sort_and_shrink()
8828 : : */
8829 : : static int
8830 : 264688 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8831 : : {
8832 : 264688 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8833 : 264688 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8834 : :
8835 : : /*
8836 : : * Most significant field is npromisingtids (which we invert the order of
8837 : : * so as to sort in desc order).
8838 : : *
8839 : : * Caller should have already normalized npromisingtids fields into
8840 : : * power-of-two values (buckets).
8841 : : */
8842 [ + + ]: 264688 : if (group1->npromisingtids > group2->npromisingtids)
8843 : 12189 : return -1;
8844 [ + + ]: 252499 : if (group1->npromisingtids < group2->npromisingtids)
8845 : 15572 : return 1;
8846 : :
8847 : : /*
8848 : : * Tiebreak: desc ntids sort order.
8849 : : *
8850 : : * We cannot expect power-of-two values for ntids fields. We should
8851 : : * behave as if they were already rounded up for us instead.
8852 : : */
8853 [ + + ]: 236927 : if (group1->ntids != group2->ntids)
8854 : : {
8855 : 173769 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8856 : 173769 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8857 : :
8858 [ + + ]: 173769 : if (ntids1 > ntids2)
8859 : 25684 : return -1;
8860 [ + + ]: 148085 : if (ntids1 < ntids2)
8861 : 32422 : return 1;
8862 : : }
8863 : :
8864 : : /*
8865 : : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8866 : : * block in deltids array) order.
8867 : : *
8868 : : * This is equivalent to sorting in ascending heap block number order
8869 : : * (among otherwise equal subsets of the array). This approach allows us
8870 : : * to avoid accessing the out-of-line TID. (We rely on the assumption
8871 : : * that the deltids array was sorted in ascending heap TID order when
8872 : : * these offsets to the first TID from each heap block group were formed.)
8873 : : */
8874 [ + + ]: 178821 : if (group1->ifirsttid > group2->ifirsttid)
8875 : 87566 : return 1;
8876 [ + - ]: 91255 : if (group1->ifirsttid < group2->ifirsttid)
8877 : 91255 : return -1;
8878 : :
2098 pg@bowt.ie 8879 :UBC 0 : pg_unreachable();
8880 : :
8881 : : return 0;
8882 : : }
8883 : :
8884 : : /*
8885 : : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8886 : : *
8887 : : * Sorts deltids array in the order needed for useful processing by bottom-up
8888 : : * deletion. The array should already be sorted in TID order when we're
8889 : : * called. The sort process groups heap TIDs from deltids into heap block
8890 : : * groupings. Earlier/more-promising groups/blocks are usually those that are
8891 : : * known to have the most "promising" TIDs.
8892 : : *
8893 : : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8894 : : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8895 : : * return. This often means that deltids will be shrunk to a small fraction
8896 : : * of its original size (we eliminate many heap blocks from consideration for
8897 : : * caller up front).
8898 : : *
8899 : : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8900 : : * for a definition and full details.
8901 : : */
8902 : : static int
2098 pg@bowt.ie 8903 :CBC 2916 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8904 : : {
8905 : : IndexDeleteCounts *blockgroups;
8906 : : TM_IndexDelete *reordereddeltids;
8907 : 2916 : BlockNumber curblock = InvalidBlockNumber;
8908 : 2916 : int nblockgroups = 0;
8909 : 2916 : int ncopied = 0;
8910 : 2916 : int nblocksfavorable = 0;
8911 : :
8912 [ - + ]: 2916 : Assert(delstate->bottomup);
8913 [ - + ]: 2916 : Assert(delstate->ndeltids > 0);
8914 : :
8915 : : /* Calculate per-heap-block count of TIDs */
306 michael@paquier.xyz 8916 : 2916 : blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
2098 pg@bowt.ie 8917 [ + + ]: 1381324 : for (int i = 0; i < delstate->ndeltids; i++)
8918 : : {
8919 : 1378408 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8920 : 1378408 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8921 : 1378408 : ItemPointer htid = &ideltid->tid;
8922 : 1378408 : bool promising = istatus->promising;
8923 : :
8924 [ + + ]: 1378408 : if (curblock != ItemPointerGetBlockNumber(htid))
8925 : : {
8926 : : /* New block group */
8927 : 52123 : nblockgroups++;
8928 : :
8929 [ + + - + ]: 52123 : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8930 : : !BlockNumberIsValid(curblock));
8931 : :
8932 : 52123 : curblock = ItemPointerGetBlockNumber(htid);
8933 : 52123 : blockgroups[nblockgroups - 1].ifirsttid = i;
8934 : 52123 : blockgroups[nblockgroups - 1].ntids = 1;
8935 : 52123 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8936 : : }
8937 : : else
8938 : : {
8939 : 1326285 : blockgroups[nblockgroups - 1].ntids++;
8940 : : }
8941 : :
8942 [ + + ]: 1378408 : if (promising)
8943 : 260763 : blockgroups[nblockgroups - 1].npromisingtids++;
8944 : : }
8945 : :
8946 : : /*
8947 : : * We're about ready to sort block groups to determine the optimal order
8948 : : * for visiting heap blocks. But before we do, round the number of
8949 : : * promising tuples for each block group up to the next power-of-two,
8950 : : * unless it is very low (less than 4), in which case we round up to 4.
8951 : : * npromisingtids is far too noisy to trust when choosing between a pair
8952 : : * of block groups that both have very low values.
8953 : : *
8954 : : * This scheme divides heap blocks/block groups into buckets. Each bucket
8955 : : * contains blocks that have _approximately_ the same number of promising
8956 : : * TIDs as each other. The goal is to ignore relatively small differences
8957 : : * in the total number of promising entries, so that the whole process can
8958 : : * give a little weight to heapam factors (like heap block locality)
8959 : : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8960 : : * would be foolish to interpret small differences in npromisingtids
8961 : : * values as anything more than noise.
8962 : : *
8963 : : * We tiebreak on nhtids when sorting block group subsets that have the
8964 : : * same npromisingtids, but this has the same issues as npromisingtids,
8965 : : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8966 : : * only reason that we don't fix nhtids in the same way here too is that
8967 : : * we'll need accurate nhtids values after the sort. We handle nhtids
8968 : : * bucketization dynamically instead (in the sort comparator).
8969 : : *
8970 : : * See bottomup_nblocksfavorable() for a full explanation of when and how
8971 : : * heap locality/favorable blocks can significantly influence when and how
8972 : : * heap blocks are accessed.
8973 : : */
8974 [ + + ]: 55039 : for (int b = 0; b < nblockgroups; b++)
8975 : : {
8976 : 52123 : IndexDeleteCounts *group = blockgroups + b;
8977 : :
8978 : : /* Better off falling back on nhtids with low npromisingtids */
8979 [ + + ]: 52123 : if (group->npromisingtids <= 4)
8980 : 43302 : group->npromisingtids = 4;
8981 : : else
8982 : 8821 : group->npromisingtids =
8983 : 8821 : pg_nextpower2_32((uint32) group->npromisingtids);
8984 : : }
8985 : :
8986 : : /* Sort groups and rearrange caller's deltids array */
8987 : 2916 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8988 : : bottomup_sort_and_shrink_cmp);
56 michael@paquier.xyz 8989 :GNC 2916 : reordereddeltids = palloc_array(TM_IndexDelete, delstate->ndeltids);
8990 : :
2098 pg@bowt.ie 8991 :CBC 2916 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8992 : : /* Determine number of favorable blocks at the start of final deltids */
8993 : 2916 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8994 : : delstate->deltids);
8995 : :
8996 [ + + ]: 18913 : for (int b = 0; b < nblockgroups; b++)
8997 : : {
8998 : 15997 : IndexDeleteCounts *group = blockgroups + b;
8999 : 15997 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
9000 : :
9001 : 15997 : memcpy(reordereddeltids + ncopied, firstdtid,
9002 : 15997 : sizeof(TM_IndexDelete) * group->ntids);
9003 : 15997 : ncopied += group->ntids;
9004 : : }
9005 : :
9006 : : /* Copy final grouped and sorted TIDs back into start of caller's array */
9007 : 2916 : memcpy(delstate->deltids, reordereddeltids,
9008 : : sizeof(TM_IndexDelete) * ncopied);
9009 : 2916 : delstate->ndeltids = ncopied;
9010 : :
9011 : 2916 : pfree(reordereddeltids);
9012 : 2916 : pfree(blockgroups);
9013 : :
9014 : 2916 : return nblocksfavorable;
9015 : : }
9016 : :
9017 : : /*
9018 : : * Perform XLogInsert for a heap-update operation. Caller must already
9019 : : * have modified the buffer(s) and marked them dirty.
9020 : : */
9021 : : static XLogRecPtr
89 melanieplageman@gmai 9022 : 2383366 : log_heap_update(Relation reln, Buffer oldbuf, Buffer vmbuffer_old,
9023 : : Buffer newbuf, Buffer vmbuffer_new,
9024 : : HeapTuple oldtup, HeapTuple newtup,
9025 : : HeapTuple old_key_tuple,
9026 : : bool all_visible_cleared, bool new_all_visible_cleared,
9027 : : bool walLogical)
9028 : : {
9029 : : xl_heap_update xlrec;
9030 : : xl_heap_header xlhdr;
9031 : : xl_heap_header xlhdr_idx;
9032 : : uint8 info;
9033 : : uint16 prefix_suffix[2];
4597 heikki.linnakangas@i 9034 : 2383366 : uint16 prefixlen = 0,
9035 : 2383366 : suffixlen = 0;
9036 : : XLogRecPtr recptr;
3827 kgrittn@postgresql.o 9037 : 2383366 : Page page = BufferGetPage(newbuf);
189 alvherre@kurilemu.de 9038 [ + + + + : 2383366 : bool need_tuple_data = walLogical && RelationIsLogicallyLogged(reln);
+ + + - -
+ - - - -
+ - + + ]
9039 : : bool init;
9040 : : int bufflags;
9041 : :
9042 : : /* Caller should not call me on a non-WAL-logged relation */
5782 rhaas@postgresql.org 9043 [ + - + + : 2383366 : Assert(RelationNeedsWAL(reln));
+ - - + ]
9044 : :
4344 heikki.linnakangas@i 9045 : 2383366 : XLogBeginInsert();
9046 : :
6090 tgl@sss.pgh.pa.us 9047 [ + + ]: 2383366 : if (HeapTupleIsHeapOnly(newtup))
6962 9048 : 165348 : info = XLOG_HEAP_HOT_UPDATE;
9049 : : else
9050 : 2218018 : info = XLOG_HEAP_UPDATE;
9051 : :
9052 : : /*
9053 : : * If the old and new tuple are on the same page, we only need to log the
9054 : : * parts of the new tuple that were changed. That saves on the amount of
9055 : : * WAL we need to write. Currently, we just count any unchanged bytes in
9056 : : * the beginning and end of the tuple. That's quick to check, and
9057 : : * perfectly covers the common case that only one field is updated.
9058 : : *
9059 : : * We could do this even if the old and new tuple are on different pages,
9060 : : * but only if we don't make a full-page image of the old page, which is
9061 : : * difficult to know in advance. Also, if the old tuple is corrupt for
9062 : : * some reason, it would allow the corruption to propagate the new page,
9063 : : * so it seems best to avoid. Under the general assumption that most
9064 : : * updates tend to create the new tuple version on the same page, there
9065 : : * isn't much to be gained by doing this across pages anyway.
9066 : : *
9067 : : * Skip this if we're taking a full-page image of the new page, as we
9068 : : * don't include the new tuple in the WAL record in that case. Also
9069 : : * disable if effective_wal_level='logical', as logical decoding needs to
9070 : : * be able to read the new tuple in whole from the WAL record alone.
9071 : : */
4597 heikki.linnakangas@i 9072 [ + + + + ]: 2383366 : if (oldbuf == newbuf && !need_tuple_data &&
9073 [ + + ]: 169318 : !XLogCheckBufferNeedsBackup(newbuf))
9074 : : {
9075 : 168779 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
9076 : 168779 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
9077 : 168779 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
9078 : 168779 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
9079 : :
9080 : : /* Check for common prefix between old and new tuple */
9081 [ + + ]: 13939684 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
9082 : : {
9083 [ + + ]: 13910637 : if (newp[prefixlen] != oldp[prefixlen])
9084 : 139732 : break;
9085 : : }
9086 : :
9087 : : /*
9088 : : * Storing the length of the prefix takes 2 bytes, so we need to save
9089 : : * at least 3 bytes or there's no point.
9090 : : */
9091 [ + + ]: 168779 : if (prefixlen < 3)
9092 : 22824 : prefixlen = 0;
9093 : :
9094 : : /* Same for suffix */
9095 [ + + ]: 6037579 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
9096 : : {
9097 [ + + ]: 6008180 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
9098 : 139380 : break;
9099 : : }
9100 [ + + ]: 168779 : if (suffixlen < 3)
9101 : 42111 : suffixlen = 0;
9102 : : }
9103 : :
9104 : : /* Prepare main WAL data chain */
4689 rhaas@postgresql.org 9105 : 2383366 : xlrec.flags = 0;
9106 [ + + ]: 2383366 : if (all_visible_cleared)
4175 andres@anarazel.de 9107 : 2507 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
4689 rhaas@postgresql.org 9108 [ + + ]: 2383366 : if (new_all_visible_cleared)
4175 andres@anarazel.de 9109 : 1463 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
4597 heikki.linnakangas@i 9110 [ + + ]: 2383366 : if (prefixlen > 0)
4175 andres@anarazel.de 9111 : 145955 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
4597 heikki.linnakangas@i 9112 [ + + ]: 2383366 : if (suffixlen > 0)
4175 andres@anarazel.de 9113 : 126668 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
4344 heikki.linnakangas@i 9114 [ + + ]: 2383366 : if (need_tuple_data)
9115 : : {
4175 andres@anarazel.de 9116 : 47074 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
4344 heikki.linnakangas@i 9117 [ + + ]: 47074 : if (old_key_tuple)
9118 : : {
9119 [ + + ]: 159 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
4175 andres@anarazel.de 9120 : 67 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
9121 : : else
9122 : 92 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
9123 : : }
9124 : : }
9125 : :
9126 : : /* If new tuple is the single and first tuple on page... */
4597 heikki.linnakangas@i 9127 [ + + + + ]: 2396594 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
9128 : 13228 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
9129 : : {
9130 : 12725 : info |= XLOG_HEAP_INIT_PAGE;
4344 9131 : 12725 : init = true;
9132 : : }
9133 : : else
9134 : 2370641 : init = false;
9135 : :
9136 : : /* Prepare WAL data for the old page */
9137 : 2383366 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
9138 : 2383366 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
9139 : 4766732 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
9140 : 2383366 : oldtup->t_data->t_infomask2);
9141 : :
9142 : : /* Prepare WAL data for the new page */
9143 : 2383366 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
9144 : 2383366 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
9145 : :
9146 : 2383366 : bufflags = REGBUF_STANDARD;
9147 [ + + ]: 2383366 : if (init)
9148 : 12725 : bufflags |= REGBUF_WILL_INIT;
9149 [ + + ]: 2383366 : if (need_tuple_data)
9150 : 47074 : bufflags |= REGBUF_KEEP_DATA;
9151 : :
89 melanieplageman@gmai 9152 : 2383366 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_NEW, newbuf, bufflags);
4344 heikki.linnakangas@i 9153 [ + + ]: 2383366 : if (oldbuf != newbuf)
89 melanieplageman@gmai 9154 : 2202054 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_OLD, oldbuf, REGBUF_STANDARD);
9155 : :
608 peter@eisentraut.org 9156 : 2383366 : XLogRegisterData(&xlrec, SizeOfHeapUpdate);
9157 : :
9158 : : /*
9159 : : * Prepare WAL data for the new tuple.
9160 : : */
4597 heikki.linnakangas@i 9161 [ + + + + ]: 2383366 : if (prefixlen > 0 || suffixlen > 0)
9162 : : {
9163 [ + + + + ]: 168215 : if (prefixlen > 0 && suffixlen > 0)
9164 : : {
9165 : 104408 : prefix_suffix[0] = prefixlen;
9166 : 104408 : prefix_suffix[1] = suffixlen;
89 melanieplageman@gmai 9167 : 104408 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefix_suffix,
9168 : : sizeof(uint16) * 2);
9169 : : }
4597 heikki.linnakangas@i 9170 [ + + ]: 63807 : else if (prefixlen > 0)
9171 : : {
89 melanieplageman@gmai 9172 : 41547 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefixlen,
9173 : : sizeof(uint16));
9174 : : }
9175 : : else
9176 : : {
9177 : 22260 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &suffixlen,
9178 : : sizeof(uint16));
9179 : : }
9180 : : }
9181 : :
4344 heikki.linnakangas@i 9182 : 2383366 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
9183 : 2383366 : xlhdr.t_infomask = newtup->t_data->t_infomask;
9184 : 2383366 : xlhdr.t_hoff = newtup->t_data->t_hoff;
4251 tgl@sss.pgh.pa.us 9185 [ - + ]: 2383366 : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
9186 : :
9187 : : /*
9188 : : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9189 : : *
9190 : : * The 'data' doesn't include the common prefix or suffix.
9191 : : */
89 melanieplageman@gmai 9192 : 2383366 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &xlhdr, SizeOfHeapHeader);
4597 heikki.linnakangas@i 9193 [ + + ]: 2383366 : if (prefixlen == 0)
9194 : : {
89 melanieplageman@gmai 9195 : 2237411 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
608 peter@eisentraut.org 9196 : 2237411 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3400 tgl@sss.pgh.pa.us 9197 : 2237411 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
9198 : : }
9199 : : else
9200 : : {
9201 : : /*
9202 : : * Have to write the null bitmap and data after the common prefix as
9203 : : * two separate rdata entries.
9204 : : */
9205 : : /* bitmap [+ padding] [+ oid] */
4251 9206 [ + - ]: 145955 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9207 : : {
89 melanieplageman@gmai 9208 : 145955 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
608 peter@eisentraut.org 9209 : 145955 : (char *) newtup->t_data + SizeofHeapTupleHeader,
3400 tgl@sss.pgh.pa.us 9210 : 145955 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
9211 : : }
9212 : :
9213 : : /* data after common prefix */
89 melanieplageman@gmai 9214 : 145955 : XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
608 peter@eisentraut.org 9215 : 145955 : (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
3400 tgl@sss.pgh.pa.us 9216 : 145955 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9217 : : }
9218 : :
9219 : : /* We need to log a tuple identity */
4344 heikki.linnakangas@i 9220 [ + + + + ]: 2383366 : if (need_tuple_data && old_key_tuple)
9221 : : {
9222 : : /* don't really need this, but its more comfy to decode */
9223 : 159 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9224 : 159 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9225 : 159 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9226 : :
608 peter@eisentraut.org 9227 : 159 : XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
9228 : :
9229 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
4251 tgl@sss.pgh.pa.us 9230 : 159 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
9231 : 159 : old_key_tuple->t_len - SizeofHeapTupleHeader);
9232 : : }
9233 : :
9234 : : /*
9235 : : * Register VM buffers. If the old and new heap pages' VM bits are on the
9236 : : * same VM page and both their VM bits were cleared, the caller passes
9237 : : * only vmbuffer_new (mirroring the heap page convention where block 0 =
9238 : : * new is always registered).
9239 : : */
89 melanieplageman@gmai 9240 [ + + + + : 2383366 : Assert((BufferIsInvalid(vmbuffer_old) && BufferIsInvalid(vmbuffer_new)) ||
- + ]
9241 : : (vmbuffer_old != vmbuffer_new));
9242 : :
9243 [ + + ]: 2383366 : if (BufferIsValid(vmbuffer_new))
9244 : 1463 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_NEW, vmbuffer_new, 0);
9245 : :
9246 [ + + ]: 2383366 : if (BufferIsValid(vmbuffer_old))
9247 : 2326 : XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_OLD, vmbuffer_old, 0);
9248 : :
9249 : : /* filtering by origin on a row level is much more efficient */
3581 andres@anarazel.de 9250 : 2383366 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
9251 : :
4344 heikki.linnakangas@i 9252 : 2383366 : recptr = XLogInsert(RM_HEAP_ID, info);
9253 : :
7579 neilc@samurai.com 9254 : 2383366 : return recptr;
9255 : : }
9256 : :
9257 : : /*
9258 : : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
9259 : : *
9260 : : * This is only used when effective_wal_level is logical, and only for
9261 : : * catalog tuples.
9262 : : */
9263 : : static XLogRecPtr
4689 rhaas@postgresql.org 9264 : 27982 : log_heap_new_cid(Relation relation, HeapTuple tup)
9265 : : {
9266 : : xl_heap_new_cid xlrec;
9267 : :
9268 : : XLogRecPtr recptr;
9269 : 27982 : HeapTupleHeader hdr = tup->t_data;
9270 : :
9271 [ - + ]: 27982 : Assert(ItemPointerIsValid(&tup->t_self));
9272 [ - + ]: 27982 : Assert(tup->t_tableOid != InvalidOid);
9273 : :
9274 : 27982 : xlrec.top_xid = GetTopTransactionId();
1559 9275 : 27982 : xlrec.target_locator = relation->rd_locator;
4344 heikki.linnakangas@i 9276 : 27982 : xlrec.target_tid = tup->t_self;
9277 : :
9278 : : /*
9279 : : * If the tuple got inserted & deleted in the same TX we definitely have a
9280 : : * combo CID, set cmin and cmax.
9281 : : */
4689 rhaas@postgresql.org 9282 [ + + ]: 27982 : if (hdr->t_infomask & HEAP_COMBOCID)
9283 : : {
9284 [ - + ]: 2448 : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
4677 9285 [ - + ]: 2448 : Assert(!HeapTupleHeaderXminInvalid(hdr));
4689 9286 : 2448 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9287 : 2448 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9288 : 2448 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9289 : : }
9290 : : /* No combo CID, so only cmin or cmax can be set by this TX */
9291 : : else
9292 : : {
9293 : : /*
9294 : : * Tuple inserted.
9295 : : *
9296 : : * We need to check for LOCK ONLY because multixacts might be
9297 : : * transferred to the new tuple in case of FOR KEY SHARE updates in
9298 : : * which case there will be an xmax, although the tuple just got
9299 : : * inserted.
9300 : : */
9301 [ + + + + ]: 33439 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9302 : 7905 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
9303 : : {
9304 : 17630 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
9305 : 17630 : xlrec.cmax = InvalidCommandId;
9306 : : }
9307 : : /* Tuple from a different tx updated or deleted. */
9308 : : else
9309 : : {
9310 : 7904 : xlrec.cmin = InvalidCommandId;
9311 : 7904 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
9312 : : }
9313 : 25534 : xlrec.combocid = InvalidCommandId;
9314 : : }
9315 : :
9316 : : /*
9317 : : * Note that we don't need to register the buffer here, because this
9318 : : * operation does not modify the page. The insert/update/delete that
9319 : : * called us certainly did, but that's WAL-logged separately.
9320 : : */
4344 heikki.linnakangas@i 9321 : 27982 : XLogBeginInsert();
608 peter@eisentraut.org 9322 : 27982 : XLogRegisterData(&xlrec, SizeOfHeapNewCid);
9323 : :
9324 : : /* will be looked at irrespective of origin */
9325 : :
4344 heikki.linnakangas@i 9326 : 27982 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9327 : :
4689 rhaas@postgresql.org 9328 : 27982 : return recptr;
9329 : : }
9330 : :
9331 : : /*
9332 : : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9333 : : * the old tuple in an UPDATE or DELETE.
9334 : : *
9335 : : * Returns NULL if there's no need to log an identity or if there's no suitable
9336 : : * key defined.
9337 : : *
9338 : : * Pass key_required true if any replica identity columns changed value, or if
9339 : : * any of them have any external data. Delete must always pass true.
9340 : : *
9341 : : * *copy is set to true if the returned tuple is a modified copy rather than
9342 : : * the same tuple that was passed in.
9343 : : */
9344 : : static HeapTuple
1701 akapila@postgresql.o 9345 : 4245418 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
9346 : : bool *copy)
9347 : : {
4689 rhaas@postgresql.org 9348 : 4245418 : TupleDesc desc = RelationGetDescr(relation);
9349 : 4245418 : char replident = relation->rd_rel->relreplident;
9350 : : Bitmapset *idattrs;
9351 : : HeapTuple key_tuple;
9352 : : bool nulls[MaxHeapAttributeNumber];
9353 : : Datum values[MaxHeapAttributeNumber];
9354 : :
9355 : 4245418 : *copy = false;
9356 : :
9357 [ + + + + : 4245418 : if (!RelationIsLogicallyLogged(relation))
+ + - + -
- - - + -
+ + ]
9358 : 4144866 : return NULL;
9359 : :
9360 [ + + ]: 100552 : if (replident == REPLICA_IDENTITY_NOTHING)
9361 : 388 : return NULL;
9362 : :
9363 [ + + ]: 100164 : if (replident == REPLICA_IDENTITY_FULL)
9364 : : {
9365 : : /*
9366 : : * When logging the entire old tuple, it very well could contain
9367 : : * toasted columns. If so, force them to be inlined.
9368 : : */
9369 [ + + ]: 199 : if (HeapTupleHasExternal(tp))
9370 : : {
9371 : 4 : *copy = true;
2597 tgl@sss.pgh.pa.us 9372 : 4 : tp = toast_flatten_tuple(tp, desc);
9373 : : }
4689 rhaas@postgresql.org 9374 : 199 : return tp;
9375 : : }
9376 : :
9377 : : /* if the key isn't required and we're only logging the key, we're done */
1701 akapila@postgresql.o 9378 [ + + ]: 99965 : if (!key_required)
4689 rhaas@postgresql.org 9379 : 46955 : return NULL;
9380 : :
9381 : : /* find out the replica identity columns */
2597 tgl@sss.pgh.pa.us 9382 : 53010 : idattrs = RelationGetIndexAttrBitmap(relation,
9383 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
9384 : :
9385 : : /*
9386 : : * If there's no defined replica identity columns, treat as !key_required.
9387 : : * (This case should not be reachable from heap_update, since that should
9388 : : * calculate key_required accurately. But heap_delete just passes
9389 : : * constant true for key_required, so we can hit this case in deletes.)
9390 : : */
9391 [ + + ]: 53010 : if (bms_is_empty(idattrs))
9392 : 6022 : return NULL;
9393 : :
9394 : : /*
9395 : : * Construct a new tuple containing only the replica identity columns,
9396 : : * with nulls elsewhere. While we're at it, assert that the replica
9397 : : * identity columns aren't null.
9398 : : */
9399 : 46988 : heap_deform_tuple(tp, desc, values, nulls);
9400 : :
9401 [ + + ]: 150984 : for (int i = 0; i < desc->natts; i++)
9402 : : {
9403 [ + + ]: 103996 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
9404 : : idattrs))
9405 [ - + ]: 47000 : Assert(!nulls[i]);
9406 : : else
9407 : 56996 : nulls[i] = true;
9408 : : }
9409 : :
4689 rhaas@postgresql.org 9410 : 46988 : key_tuple = heap_form_tuple(desc, values, nulls);
9411 : 46988 : *copy = true;
9412 : :
2597 tgl@sss.pgh.pa.us 9413 : 46988 : bms_free(idattrs);
9414 : :
9415 : : /*
9416 : : * If the tuple, which by here only contains indexed columns, still has
9417 : : * toasted columns, force them to be inlined. This is somewhat unlikely
9418 : : * since there's limits on the size of indexed columns, so we don't
9419 : : * duplicate toast_flatten_tuple()s functionality in the above loop over
9420 : : * the indexed columns, even if it would be more efficient.
9421 : : */
4689 rhaas@postgresql.org 9422 [ + + ]: 46988 : if (HeapTupleHasExternal(key_tuple))
9423 : : {
4542 bruce@momjian.us 9424 : 4 : HeapTuple oldtup = key_tuple;
9425 : :
2597 tgl@sss.pgh.pa.us 9426 : 4 : key_tuple = toast_flatten_tuple(oldtup, desc);
4689 rhaas@postgresql.org 9427 : 4 : heap_freetuple(oldtup);
9428 : : }
9429 : :
9430 : 46988 : return key_tuple;
9431 : : }
9432 : :
9433 : : /*
9434 : : * HeapCheckForSerializableConflictOut
9435 : : * We are reading a tuple. If it's not visible, there may be a
9436 : : * rw-conflict out with the inserter. Otherwise, if it is visible to us
9437 : : * but has been deleted, there may be a rw-conflict out with the deleter.
9438 : : *
9439 : : * We will determine the top level xid of the writing transaction with which
9440 : : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9441 : : * for overlap with our own transaction.
9442 : : *
9443 : : * This function should be called just about anywhere in heapam.c where a
9444 : : * tuple has been read. The caller must hold at least a shared lock on the
9445 : : * buffer, because this function might set hint bits on the tuple. There is
9446 : : * currently no known reason to call this function from an index AM.
9447 : : */
9448 : : void
2449 tmunro@postgresql.or 9449 : 40874183 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
9450 : : HeapTuple tuple, Buffer buffer,
9451 : : Snapshot snapshot)
9452 : : {
9453 : : TransactionId xid;
9454 : : HTSV_Result htsvResult;
9455 : :
9456 [ + + ]: 40874183 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9457 : 40866204 : return;
9458 : :
9459 : : /*
9460 : : * Check to see whether the tuple has been written to by a concurrent
9461 : : * transaction, either to create it not visible to us, or to delete it
9462 : : * while it is visible to us. The "visible" bool indicates whether the
9463 : : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9464 : : * is going on with it.
9465 : : *
9466 : : * In the event of a concurrently inserted tuple that also happens to have
9467 : : * been concurrently updated (by a separate transaction), the xmin of the
9468 : : * tuple will be used -- not the updater's xid.
9469 : : */
9470 : 7979 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9471 [ + + + + : 7979 : switch (htsvResult)
- ]
9472 : : {
9473 : 7151 : case HEAPTUPLE_LIVE:
9474 [ + + ]: 7151 : if (visible)
9475 : 7129 : return;
9476 : 22 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9477 : 22 : break;
9478 : 364 : case HEAPTUPLE_RECENTLY_DEAD:
9479 : : case HEAPTUPLE_DELETE_IN_PROGRESS:
2314 pg@bowt.ie 9480 [ + + ]: 364 : if (visible)
9481 : 289 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9482 : : else
9483 : 75 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9484 : :
9485 [ + + ]: 364 : if (TransactionIdPrecedes(xid, TransactionXmin))
9486 : : {
9487 : : /* This is like the HEAPTUPLE_DEAD case */
9488 [ - + ]: 67 : Assert(!visible);
9489 : 67 : return;
9490 : : }
2449 tmunro@postgresql.or 9491 : 297 : break;
9492 : 345 : case HEAPTUPLE_INSERT_IN_PROGRESS:
9493 : 345 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9494 : 345 : break;
9495 : 119 : case HEAPTUPLE_DEAD:
2314 pg@bowt.ie 9496 [ - + ]: 119 : Assert(!visible);
2449 tmunro@postgresql.or 9497 : 119 : return;
2449 tmunro@postgresql.or 9498 :UBC 0 : default:
9499 : :
9500 : : /*
9501 : : * The only way to get to this default clause is if a new value is
9502 : : * added to the enum type without adding it to this switch
9503 : : * statement. That's a bug, so elog.
9504 : : */
9505 [ # # ]: 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9506 : :
9507 : : /*
9508 : : * In spite of having all enum values covered and calling elog on
9509 : : * this default, some compilers think this is a code path which
9510 : : * allows xid to be used below without initialization. Silence
9511 : : * that warning.
9512 : : */
9513 : : xid = InvalidTransactionId;
9514 : : }
9515 : :
2449 tmunro@postgresql.or 9516 [ - + ]:CBC 664 : Assert(TransactionIdIsValid(xid));
9517 [ - + ]: 664 : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
9518 : :
9519 : : /*
9520 : : * Find top level xid. Bail out if xid is too early to be a conflict, or
9521 : : * if it's our own xid.
9522 : : */
9523 [ + + ]: 664 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
9524 : 82 : return;
9525 : 582 : xid = SubTransGetTopmostTransaction(xid);
9526 [ - + ]: 582 : if (TransactionIdPrecedes(xid, TransactionXmin))
2449 tmunro@postgresql.or 9527 :UBC 0 : return;
9528 : :
2449 tmunro@postgresql.or 9529 :CBC 582 : CheckForSerializableConflictOut(relation, xid, snapshot);
9530 : : }
|