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-2025, 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 "pgstat.h"
47 : : #include "port/pg_bitutils.h"
48 : : #include "storage/lmgr.h"
49 : : #include "storage/predicate.h"
50 : : #include "storage/procarray.h"
51 : : #include "utils/datum.h"
52 : : #include "utils/injection_point.h"
53 : : #include "utils/inval.h"
54 : : #include "utils/spccache.h"
55 : : #include "utils/syscache.h"
56 : :
57 : :
58 : : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
59 : : TransactionId xid, CommandId cid, int options);
60 : : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
61 : : Buffer newbuf, HeapTuple oldtup,
62 : : HeapTuple newtup, HeapTuple old_key_tuple,
63 : : bool all_visible_cleared, bool new_all_visible_cleared);
64 : : #ifdef USE_ASSERT_CHECKING
65 : : static void check_lock_if_inplace_updateable_rel(Relation relation,
66 : : ItemPointer otid,
67 : : HeapTuple newtup);
68 : : static void check_inplace_rel_lock(HeapTuple oldtup);
69 : : #endif
70 : : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
71 : : Bitmapset *interesting_cols,
72 : : Bitmapset *external_cols,
73 : : HeapTuple oldtup, HeapTuple newtup,
74 : : bool *has_external);
75 : : static bool heap_acquire_tuplock(Relation relation, ItemPointer tid,
76 : : LockTupleMode mode, LockWaitPolicy wait_policy,
77 : : bool *have_tuple_lock);
78 : : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
79 : : BlockNumber block,
80 : : ScanDirection dir);
81 : : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
82 : : ScanDirection dir);
83 : : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
84 : : uint16 old_infomask2, TransactionId add_to_xmax,
85 : : LockTupleMode mode, bool is_update,
86 : : TransactionId *result_xmax, uint16 *result_infomask,
87 : : uint16 *result_infomask2);
88 : : static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple,
89 : : ItemPointer ctid, TransactionId xid,
90 : : LockTupleMode mode);
91 : : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
92 : : uint16 *new_infomask2);
93 : : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
94 : : uint16 t_infomask);
95 : : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
96 : : LockTupleMode lockmode, bool *current_is_member);
97 : : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
98 : : Relation rel, ItemPointer ctid, XLTW_Oper oper,
99 : : int *remaining);
100 : : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
101 : : uint16 infomask, Relation rel, int *remaining,
102 : : bool logLockFailure);
103 : : static void index_delete_sort(TM_IndexDeleteOp *delstate);
104 : : static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
105 : : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
106 : : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
107 : : bool *copy);
108 : :
109 : :
110 : : /*
111 : : * Each tuple lock mode has a corresponding heavyweight lock, and one or two
112 : : * corresponding MultiXactStatuses (one to merely lock tuples, another one to
113 : : * update them). This table (and the macros below) helps us determine the
114 : : * heavyweight lock mode and MultiXactStatus values to use for any particular
115 : : * tuple lock strength.
116 : : *
117 : : * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
118 : : *
119 : : * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
120 : : * instead.
121 : : */
122 : : static const struct
123 : : {
124 : : LOCKMODE hwlock;
125 : : int lockstatus;
126 : : int updstatus;
127 : : }
128 : :
129 : : tupleLockExtraInfo[MaxLockTupleMode + 1] =
130 : : {
131 : : { /* LockTupleKeyShare */
132 : : AccessShareLock,
133 : : MultiXactStatusForKeyShare,
134 : : -1 /* KeyShare does not allow updating tuples */
135 : : },
136 : : { /* LockTupleShare */
137 : : RowShareLock,
138 : : MultiXactStatusForShare,
139 : : -1 /* Share does not allow updating tuples */
140 : : },
141 : : { /* LockTupleNoKeyExclusive */
142 : : ExclusiveLock,
143 : : MultiXactStatusForNoKeyUpdate,
144 : : MultiXactStatusNoKeyUpdate
145 : : },
146 : : { /* LockTupleExclusive */
147 : : AccessExclusiveLock,
148 : : MultiXactStatusForUpdate,
149 : : MultiXactStatusUpdate
150 : : }
151 : : };
152 : :
153 : : /* Get the LOCKMODE for a given MultiXactStatus */
154 : : #define LOCKMODE_from_mxstatus(status) \
155 : : (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
156 : :
157 : : /*
158 : : * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
159 : : * This is more readable than having every caller translate it to lock.h's
160 : : * LOCKMODE.
161 : : */
162 : : #define LockTupleTuplock(rel, tup, mode) \
163 : : LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
164 : : #define UnlockTupleTuplock(rel, tup, mode) \
165 : : UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
166 : : #define ConditionalLockTupleTuplock(rel, tup, mode, log) \
167 : : ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
168 : :
169 : : #ifdef USE_PREFETCH
170 : : /*
171 : : * heap_index_delete_tuples and index_delete_prefetch_buffer use this
172 : : * structure to coordinate prefetching activity
173 : : */
174 : : typedef struct
175 : : {
176 : : BlockNumber cur_hblkno;
177 : : int next_item;
178 : : int ndeltids;
179 : : TM_IndexDelete *deltids;
180 : : } IndexDeletePrefetchState;
181 : : #endif
182 : :
183 : : /* heap_index_delete_tuples bottom-up index deletion costing constants */
184 : : #define BOTTOMUP_MAX_NBLOCKS 6
185 : : #define BOTTOMUP_TOLERANCE_NBLOCKS 3
186 : :
187 : : /*
188 : : * heap_index_delete_tuples uses this when determining which heap blocks it
189 : : * must visit to help its bottom-up index deletion caller
190 : : */
191 : : typedef struct IndexDeleteCounts
192 : : {
193 : : int16 npromisingtids; /* Number of "promising" TIDs in group */
194 : : int16 ntids; /* Number of TIDs in group */
195 : : int16 ifirsttid; /* Offset to group's first deltid */
196 : : } IndexDeleteCounts;
197 : :
198 : : /*
199 : : * This table maps tuple lock strength values for each particular
200 : : * MultiXactStatus value.
201 : : */
202 : : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
203 : : {
204 : : LockTupleKeyShare, /* ForKeyShare */
205 : : LockTupleShare, /* ForShare */
206 : : LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
207 : : LockTupleExclusive, /* ForUpdate */
208 : : LockTupleNoKeyExclusive, /* NoKeyUpdate */
209 : : LockTupleExclusive /* Update */
210 : : };
211 : :
212 : : /* Get the LockTupleMode for a given MultiXactStatus */
213 : : #define TUPLOCK_from_mxstatus(status) \
214 : : (MultiXactStatusLock[(status)])
215 : :
216 : : /*
217 : : * Check that we have a valid snapshot if we might need TOAST access.
218 : : */
219 : : static inline void
99 nathan@postgresql.or 220 :CBC 10459813 : AssertHasSnapshotForToast(Relation rel)
221 : : {
222 : : #ifdef USE_ASSERT_CHECKING
223 : :
224 : : /* bootstrap mode in particular breaks this rule */
225 [ + + ]: 10459813 : if (!IsNormalProcessingMode())
226 : 584900 : return;
227 : :
228 : : /* if the relation doesn't have a TOAST table, we are good */
229 [ + + ]: 9874913 : if (!OidIsValid(rel->rd_rel->reltoastrelid))
230 : 5083577 : return;
231 : :
232 [ - + ]: 4791336 : Assert(HaveRegisteredOrActiveSnapshot());
233 : :
234 : : #endif /* USE_ASSERT_CHECKING */
235 : : }
236 : :
237 : : /* ----------------------------------------------------------------
238 : : * heap support routines
239 : : * ----------------------------------------------------------------
240 : : */
241 : :
242 : : /*
243 : : * Streaming read API callback for parallel sequential scans. Returns the next
244 : : * block the caller wants from the read stream or InvalidBlockNumber when done.
245 : : */
246 : : static BlockNumber
516 tmunro@postgresql.or 247 : 100852 : heap_scan_stream_read_next_parallel(ReadStream *stream,
248 : : void *callback_private_data,
249 : : void *per_buffer_data)
250 : : {
251 : 100852 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
252 : :
253 [ - + ]: 100852 : Assert(ScanDirectionIsForward(scan->rs_dir));
254 [ - + ]: 100852 : Assert(scan->rs_base.rs_parallel);
255 : :
256 [ + + ]: 100852 : if (unlikely(!scan->rs_inited))
257 : : {
258 : : /* parallel scan */
259 : 1560 : table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
260 : 1560 : scan->rs_parallelworkerdata,
261 : 1560 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
262 : :
263 : : /* may return InvalidBlockNumber if there are no more blocks */
264 : 3120 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
265 : 1560 : scan->rs_parallelworkerdata,
266 : 1560 : (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
267 : 1560 : scan->rs_inited = true;
268 : : }
269 : : else
270 : : {
271 : 99292 : scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
272 : 99292 : scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
273 : 99292 : scan->rs_base.rs_parallel);
274 : : }
275 : :
276 : 100852 : return scan->rs_prefetch_block;
277 : : }
278 : :
279 : : /*
280 : : * Streaming read API callback for serial sequential and TID range scans.
281 : : * Returns the next block the caller wants from the read stream or
282 : : * InvalidBlockNumber when done.
283 : : */
284 : : static BlockNumber
285 : 3487370 : heap_scan_stream_read_next_serial(ReadStream *stream,
286 : : void *callback_private_data,
287 : : void *per_buffer_data)
288 : : {
289 : 3487370 : HeapScanDesc scan = (HeapScanDesc) callback_private_data;
290 : :
291 [ + + ]: 3487370 : if (unlikely(!scan->rs_inited))
292 : : {
293 : 948465 : scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
294 : 948465 : scan->rs_inited = true;
295 : : }
296 : : else
297 : 2538905 : scan->rs_prefetch_block = heapgettup_advance_block(scan,
298 : : scan->rs_prefetch_block,
299 : : scan->rs_dir);
300 : :
301 : 3487370 : return scan->rs_prefetch_block;
302 : : }
303 : :
304 : : /*
305 : : * Read stream API callback for bitmap heap scans.
306 : : * Returns the next block the caller wants from the read stream or
307 : : * InvalidBlockNumber when done.
308 : : */
309 : : static BlockNumber
175 melanieplageman@gmai 310 : 208737 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
311 : : void *per_buffer_data)
312 : : {
313 : 208737 : TBMIterateResult *tbmres = per_buffer_data;
314 : 208737 : BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
315 : 208737 : HeapScanDesc hscan = (HeapScanDesc) bscan;
316 : 208737 : TableScanDesc sscan = &hscan->rs_base;
317 : :
318 : : for (;;)
319 : : {
320 [ - + ]: 208737 : CHECK_FOR_INTERRUPTS();
321 : :
322 : : /* no more entries in the bitmap */
323 [ + + ]: 208737 : if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
324 : 10023 : return InvalidBlockNumber;
325 : :
326 : : /*
327 : : * Ignore any claimed entries past what we think is the end of the
328 : : * relation. It may have been extended after the start of our scan (we
329 : : * only hold an AccessShareLock, and it could be inserts from this
330 : : * backend). We don't take this optimization in SERIALIZABLE
331 : : * isolation though, as we need to examine all invisible tuples
332 : : * reachable by the index.
333 : : */
334 [ + + ]: 198714 : if (!IsolationIsSerializable() &&
335 [ - + ]: 198611 : tbmres->blockno >= hscan->rs_nblocks)
175 melanieplageman@gmai 336 :UBC 0 : continue;
337 : :
175 melanieplageman@gmai 338 :CBC 198714 : return tbmres->blockno;
339 : : }
340 : :
341 : : /* not reachable */
342 : : Assert(false);
343 : : }
344 : :
345 : : /* ----------------
346 : : * initscan - scan code common to heap_beginscan and heap_rescan
347 : : * ----------------
348 : : */
349 : : static void
3696 tgl@sss.pgh.pa.us 350 : 969699 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
351 : : {
2371 andres@anarazel.de 352 : 969699 : ParallelBlockTableScanDesc bpscan = NULL;
353 : : bool allow_strat;
354 : : bool allow_sync;
355 : :
356 : : /*
357 : : * Determine the number of blocks we have to scan.
358 : : *
359 : : * It is sufficient to do this once at scan start, since any tuples added
360 : : * while the scan is in progress will be invisible to my snapshot anyway.
361 : : * (That is not true when using a non-MVCC snapshot. However, we couldn't
362 : : * guarantee to return tuples added after scan start anyway, since they
363 : : * might go into pages we already scanned. To guarantee consistent
364 : : * results for a non-MVCC snapshot, the caller must hold some higher-level
365 : : * lock that ensures the interesting tuple(s) won't change.)
366 : : */
367 [ + + ]: 969699 : if (scan->rs_base.rs_parallel != NULL)
368 : : {
369 : 2013 : bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
370 : 2013 : scan->rs_nblocks = bpscan->phs_nblocks;
371 : : }
372 : : else
373 : 967686 : scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
374 : :
375 : : /*
376 : : * If the table is large relative to NBuffers, use a bulk-read access
377 : : * strategy and enable synchronized scanning (see syncscan.c). Although
378 : : * the thresholds for these features could be different, we make them the
379 : : * same so that there are only two behaviors to tune rather than four.
380 : : * (However, some callers need to be able to disable one or both of these
381 : : * behaviors, independently of the size of the table; also there is a GUC
382 : : * variable that can disable synchronized scanning.)
383 : : *
384 : : * Note that table_block_parallelscan_initialize has a very similar test;
385 : : * if you change this, consider changing that one, too.
386 : : */
387 [ + + ]: 969697 : if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
6664 tgl@sss.pgh.pa.us 388 [ + + ]: 962503 : scan->rs_nblocks > NBuffers / 4)
389 : : {
2302 andres@anarazel.de 390 : 13889 : allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
391 : 13889 : allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
392 : : }
393 : : else
6445 tgl@sss.pgh.pa.us 394 : 955808 : allow_strat = allow_sync = false;
395 : :
396 [ + + ]: 969697 : if (allow_strat)
397 : : {
398 : : /* During a rescan, keep the previous strategy object. */
6674 399 [ + + ]: 12426 : if (scan->rs_strategy == NULL)
400 : 12243 : scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
401 : : }
402 : : else
403 : : {
404 [ - + ]: 957271 : if (scan->rs_strategy != NULL)
6674 tgl@sss.pgh.pa.us 405 :UBC 0 : FreeAccessStrategy(scan->rs_strategy);
6674 tgl@sss.pgh.pa.us 406 :CBC 957271 : scan->rs_strategy = NULL;
407 : : }
408 : :
2371 andres@anarazel.de 409 [ + + ]: 969697 : if (scan->rs_base.rs_parallel != NULL)
410 : : {
411 : : /* For parallel scan, believe whatever ParallelTableScanDesc says. */
2302 412 [ + + ]: 2013 : if (scan->rs_base.rs_parallel->phs_syncscan)
413 : 2 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
414 : : else
415 : 2011 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
416 : : }
3613 rhaas@postgresql.org 417 [ + + ]: 967684 : else if (keep_startblock)
418 : : {
419 : : /*
420 : : * When rescanning, we want to keep the previous startblock setting,
421 : : * so that rewinding a cursor doesn't generate surprising results.
422 : : * Reset the active syncscan setting, though.
423 : : */
2302 andres@anarazel.de 424 [ + + + + ]: 611346 : if (allow_sync && synchronize_seqscans)
425 : 50 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
426 : : else
427 : 611296 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
428 : : }
5932 tgl@sss.pgh.pa.us 429 [ + + + + ]: 356338 : else if (allow_sync && synchronize_seqscans)
430 : : {
2302 andres@anarazel.de 431 : 73 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
2371 432 : 73 : scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
433 : : }
434 : : else
435 : : {
2302 436 : 356265 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
6665 tgl@sss.pgh.pa.us 437 : 356265 : scan->rs_startblock = 0;
438 : : }
439 : :
3956 alvherre@alvh.no-ip. 440 : 969697 : scan->rs_numblocks = InvalidBlockNumber;
7224 tgl@sss.pgh.pa.us 441 : 969697 : scan->rs_inited = false;
8855 442 : 969697 : scan->rs_ctup.t_data = NULL;
7224 443 : 969697 : ItemPointerSetInvalid(&scan->rs_ctup.t_self);
8855 444 : 969697 : scan->rs_cbuf = InvalidBuffer;
7224 445 : 969697 : scan->rs_cblock = InvalidBlockNumber;
262 melanieplageman@gmai 446 : 969697 : scan->rs_ntuples = 0;
447 : 969697 : scan->rs_cindex = 0;
448 : :
449 : : /*
450 : : * Initialize to ForwardScanDirection because it is most common and
451 : : * because heap scans go forward before going backward (e.g. CURSORs).
452 : : */
516 tmunro@postgresql.or 453 : 969697 : scan->rs_dir = ForwardScanDirection;
454 : 969697 : scan->rs_prefetch_block = InvalidBlockNumber;
455 : :
456 : : /* page-at-a-time fields are always invalid when not rs_inited */
457 : :
458 : : /*
459 : : * copy the scan key, if appropriate
460 : : */
1283 tgl@sss.pgh.pa.us 461 [ + + + + ]: 969697 : if (key != NULL && scan->rs_base.rs_nkeys > 0)
2371 andres@anarazel.de 462 : 205156 : memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
463 : :
464 : : /*
465 : : * Currently, we only have a stats counter for sequential heap scans (but
466 : : * e.g for bitmap scans the underlying bitmap index scans will be counted,
467 : : * and for sample scans we update stats for tuple fetches).
468 : : */
2302 469 [ + + ]: 969697 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
2371 470 [ + + + + : 949646 : pgstat_count_heap_scan(scan->rs_base.rs_rd);
+ + ]
10651 scrappy@hub.org 471 : 969697 : }
472 : :
473 : : /*
474 : : * heap_setscanlimits - restrict range of a heapscan
475 : : *
476 : : * startBlk is the page to start at
477 : : * numBlks is number of pages to scan (InvalidBlockNumber means "all")
478 : : */
479 : : void
2371 andres@anarazel.de 480 : 2794 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
481 : : {
482 : 2794 : HeapScanDesc scan = (HeapScanDesc) sscan;
483 : :
3700 tgl@sss.pgh.pa.us 484 [ - + ]: 2794 : Assert(!scan->rs_inited); /* else too late to change */
485 : : /* else rs_startblock is significant */
2302 andres@anarazel.de 486 [ - + ]: 2794 : Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
487 : :
488 : : /* Check startBlk is valid (but allow case of zero blocks...) */
3700 tgl@sss.pgh.pa.us 489 [ + + - + ]: 2794 : Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
490 : :
3956 alvherre@alvh.no-ip. 491 : 2794 : scan->rs_startblock = startBlk;
492 : 2794 : scan->rs_numblocks = numBlks;
493 : 2794 : }
494 : :
495 : : /*
496 : : * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
497 : : * multiple times, with constant arguments for all_visible,
498 : : * check_serializable.
499 : : */
500 : : pg_attribute_always_inline
501 : : static int
517 andres@anarazel.de 502 : 2528195 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
503 : : Page page, Buffer buffer,
504 : : BlockNumber block, int lines,
505 : : bool all_visible, bool check_serializable)
506 : : {
518 507 : 2528195 : int ntup = 0;
508 : : OffsetNumber lineoff;
509 : :
510 [ + + ]: 126600457 : for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
511 : : {
512 : 124072270 : ItemId lpp = PageGetItemId(page, lineoff);
513 : : HeapTupleData loctup;
514 : : bool valid;
515 : :
516 [ + + ]: 124072270 : if (!ItemIdIsNormal(lpp))
517 : 22507755 : continue;
518 : :
519 : 101564515 : loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
520 : 101564515 : loctup.t_len = ItemIdGetLength(lpp);
521 : 101564515 : loctup.t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
522 : 101564515 : ItemPointerSet(&(loctup.t_self), block, lineoff);
523 : :
524 [ + + ]: 101564515 : if (all_visible)
525 : 38731298 : valid = true;
526 : : else
527 : 62833217 : valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
528 : :
529 [ + + ]: 101564515 : if (check_serializable)
530 : 1405 : HeapCheckForSerializableConflictOut(valid, scan->rs_base.rs_rd,
531 : : &loctup, buffer, snapshot);
532 : :
533 [ + + ]: 101564507 : if (valid)
534 : : {
535 : 95022391 : scan->rs_vistuples[ntup] = lineoff;
536 : 95022391 : ntup++;
537 : : }
538 : : }
539 : :
540 [ - + ]: 2528187 : Assert(ntup <= MaxHeapTuplesPerPage);
541 : :
542 : 2528187 : return ntup;
543 : : }
544 : :
545 : : /*
546 : : * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
547 : : *
548 : : * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
549 : : * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
550 : : */
551 : : void
520 drowley@postgresql.o 552 : 2528195 : heap_prepare_pagescan(TableScanDesc sscan)
553 : : {
2371 andres@anarazel.de 554 : 2528195 : HeapScanDesc scan = (HeapScanDesc) sscan;
520 drowley@postgresql.o 555 : 2528195 : Buffer buffer = scan->rs_cbuf;
556 : 2528195 : BlockNumber block = scan->rs_cblock;
557 : : Snapshot snapshot;
558 : : Page page;
559 : : int lines;
560 : : bool all_visible;
561 : : bool check_serializable;
562 : :
563 [ - + ]: 2528195 : Assert(BufferGetBlockNumber(buffer) == block);
564 : :
565 : : /* ensure we're not accidentally being used when not in pagemode */
566 [ - + ]: 2528195 : Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
2371 andres@anarazel.de 567 : 2528195 : snapshot = scan->rs_base.rs_snapshot;
568 : :
569 : : /*
570 : : * Prune and repair fragmentation for the whole page, if possible.
571 : : */
572 : 2528195 : heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
573 : :
574 : : /*
575 : : * We must hold share lock on the buffer content while examining tuple
576 : : * visibility. Afterwards, however, the tuples we have found to be
577 : : * visible are guaranteed good as long as we hold the buffer pin.
578 : : */
7224 tgl@sss.pgh.pa.us 579 : 2528195 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
580 : :
1025 peter@eisentraut.org 581 : 2528195 : page = BufferGetPage(buffer);
582 : 2528195 : lines = PageGetMaxOffsetNumber(page);
583 : :
584 : : /*
585 : : * If the all-visible flag indicates that all tuples on the page are
586 : : * visible to everyone, we can skip the per-tuple visibility tests.
587 : : *
588 : : * Note: In hot standby, a tuple that's already visible to all
589 : : * transactions on the primary might still be invisible to a read-only
590 : : * transaction in the standby. We partly handle this problem by tracking
591 : : * the minimum xmin of visible tuples as the cut-off XID while marking a
592 : : * page all-visible on the primary and WAL log that along with the
593 : : * visibility map SET operation. In hot standby, we wait for (or abort)
594 : : * all transactions that can potentially may not see one or more tuples on
595 : : * the page. That's how index-only scans work fine in hot standby. A
596 : : * crucial difference between index-only scans and heap scans is that the
597 : : * index-only scan completely relies on the visibility map where as heap
598 : : * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
599 : : * the page-level flag can be trusted in the same way, because it might
600 : : * get propagated somehow without being explicitly WAL-logged, e.g. via a
601 : : * full page write. Until we can prove that beyond doubt, let's check each
602 : : * tuple for visibility the hard way.
603 : : */
604 [ + + + + ]: 2528195 : all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
605 : : check_serializable =
518 andres@anarazel.de 606 : 2528195 : CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
607 : :
608 : : /*
609 : : * We call page_collect_tuples() with constant arguments, to get the
610 : : * compiler to constant fold the constant arguments. Separate calls with
611 : : * constant arguments, rather than variables, are needed on several
612 : : * compilers to actually perform constant folding.
613 : : */
614 [ + + ]: 2528195 : if (likely(all_visible))
615 : : {
616 [ + - ]: 935345 : if (likely(!check_serializable))
517 617 : 935345 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
618 : : block, lines, true, false);
619 : : else
517 andres@anarazel.de 620 :UBC 0 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
621 : : block, lines, true, true);
622 : : }
623 : : else
624 : : {
518 andres@anarazel.de 625 [ + + ]:CBC 1592850 : if (likely(!check_serializable))
517 626 : 1592231 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
627 : : block, lines, false, false);
628 : : else
629 : 619 : scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
630 : : block, lines, false, true);
631 : : }
632 : :
7224 tgl@sss.pgh.pa.us 633 : 2528187 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
634 : 2528187 : }
635 : :
636 : : /*
637 : : * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
638 : : *
639 : : * Read the next block of the scan relation from the read stream and save it
640 : : * in the scan descriptor. It is already pinned.
641 : : */
642 : : static inline void
520 drowley@postgresql.o 643 : 3415381 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
644 : : {
516 tmunro@postgresql.or 645 [ - + ]: 3415381 : Assert(scan->rs_read_stream);
646 : :
647 : : /* release previous scan buffer, if any */
520 drowley@postgresql.o 648 [ + + ]: 3415381 : if (BufferIsValid(scan->rs_cbuf))
649 : : {
650 : 2465355 : ReleaseBuffer(scan->rs_cbuf);
651 : 2465355 : scan->rs_cbuf = InvalidBuffer;
652 : : }
653 : :
654 : : /*
655 : : * Be sure to check for interrupts at least once per page. Checks at
656 : : * higher code levels won't be able to stop a seqscan that encounters many
657 : : * pages' worth of consecutive dead tuples.
658 : : */
659 [ + + ]: 3415381 : CHECK_FOR_INTERRUPTS();
660 : :
661 : : /*
662 : : * If the scan direction is changing, reset the prefetch block to the
663 : : * current block. Otherwise, we will incorrectly prefetch the blocks
664 : : * between the prefetch block and the current block again before
665 : : * prefetching blocks in the new, correct scan direction.
666 : : */
516 tmunro@postgresql.or 667 [ + + ]: 3415379 : if (unlikely(scan->rs_dir != dir))
668 : : {
669 : 76 : scan->rs_prefetch_block = scan->rs_cblock;
670 : 76 : read_stream_reset(scan->rs_read_stream);
671 : : }
672 : :
673 : 3415379 : scan->rs_dir = dir;
674 : :
675 : 3415379 : scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
676 [ + + ]: 3415357 : if (BufferIsValid(scan->rs_cbuf))
677 : 2618081 : scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
520 drowley@postgresql.o 678 : 3415357 : }
679 : :
680 : : /*
681 : : * heapgettup_initial_block - return the first BlockNumber to scan
682 : : *
683 : : * Returns InvalidBlockNumber when there are no blocks to scan. This can
684 : : * occur with empty tables and in parallel scans when parallel workers get all
685 : : * of the pages before we can get a chance to get our first page.
686 : : */
687 : : static pg_noinline BlockNumber
947 688 : 948465 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
689 : : {
690 [ - + ]: 948465 : Assert(!scan->rs_inited);
516 tmunro@postgresql.or 691 [ - + ]: 948465 : Assert(scan->rs_base.rs_parallel == NULL);
692 : :
693 : : /* When there are no pages to scan, return InvalidBlockNumber */
947 drowley@postgresql.o 694 [ + + + + ]: 948465 : if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
695 : 467435 : return InvalidBlockNumber;
696 : :
697 [ + + ]: 481030 : if (ScanDirectionIsForward(dir))
698 : : {
516 tmunro@postgresql.or 699 : 480999 : return scan->rs_startblock;
700 : : }
701 : : else
702 : : {
703 : : /*
704 : : * Disable reporting to syncscan logic in a backwards scan; it's not
705 : : * very likely anyone else is doing the same thing at the same time,
706 : : * and much more likely that we'll just bollix things for forward
707 : : * scanners.
708 : : */
947 drowley@postgresql.o 709 : 31 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
710 : :
711 : : /*
712 : : * Start from last page of the scan. Ensure we take into account
713 : : * rs_numblocks if it's been adjusted by heap_setscanlimits().
714 : : */
715 [ + + ]: 31 : if (scan->rs_numblocks != InvalidBlockNumber)
716 : 3 : return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
717 : :
718 [ - + ]: 28 : if (scan->rs_startblock > 0)
947 drowley@postgresql.o 719 :UBC 0 : return scan->rs_startblock - 1;
720 : :
947 drowley@postgresql.o 721 :CBC 28 : return scan->rs_nblocks - 1;
722 : : }
723 : : }
724 : :
725 : :
726 : : /*
727 : : * heapgettup_start_page - helper function for heapgettup()
728 : : *
729 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
730 : : * to the number of tuples on this page. Also set *lineoff to the first
731 : : * offset to scan with forward scans getting the first offset and backward
732 : : * getting the final offset on the page.
733 : : */
734 : : static Page
946 735 : 94161 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
736 : : OffsetNumber *lineoff)
737 : : {
738 : : Page page;
739 : :
740 [ - + ]: 94161 : Assert(scan->rs_inited);
741 [ - + ]: 94161 : Assert(BufferIsValid(scan->rs_cbuf));
742 : :
743 : : /* Caller is responsible for ensuring buffer is locked if needed */
744 : 94161 : page = BufferGetPage(scan->rs_cbuf);
745 : :
942 746 : 94161 : *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
747 : :
946 748 [ + - ]: 94161 : if (ScanDirectionIsForward(dir))
749 : 94161 : *lineoff = FirstOffsetNumber;
750 : : else
946 drowley@postgresql.o 751 :UBC 0 : *lineoff = (OffsetNumber) (*linesleft);
752 : :
753 : : /* lineoff now references the physically previous or next tid */
946 drowley@postgresql.o 754 :CBC 94161 : return page;
755 : : }
756 : :
757 : :
758 : : /*
759 : : * heapgettup_continue_page - helper function for heapgettup()
760 : : *
761 : : * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
762 : : * to the number of tuples left to scan on this page. Also set *lineoff to
763 : : * the next offset to scan according to the ScanDirection in 'dir'.
764 : : */
765 : : static inline Page
766 : 7826863 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
767 : : OffsetNumber *lineoff)
768 : : {
769 : : Page page;
770 : :
771 [ - + ]: 7826863 : Assert(scan->rs_inited);
772 [ - + ]: 7826863 : Assert(BufferIsValid(scan->rs_cbuf));
773 : :
774 : : /* Caller is responsible for ensuring buffer is locked if needed */
775 : 7826863 : page = BufferGetPage(scan->rs_cbuf);
776 : :
777 [ + - ]: 7826863 : if (ScanDirectionIsForward(dir))
778 : : {
779 : 7826863 : *lineoff = OffsetNumberNext(scan->rs_coffset);
780 : 7826863 : *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
781 : : }
782 : : else
783 : : {
784 : : /*
785 : : * The previous returned tuple may have been vacuumed since the
786 : : * previous scan when we use a non-MVCC snapshot, so we must
787 : : * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
788 : : */
946 drowley@postgresql.o 789 [ # # ]:UBC 0 : *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
790 : 0 : *linesleft = *lineoff;
791 : : }
792 : :
793 : : /* lineoff now references the physically previous or next tid */
946 drowley@postgresql.o 794 :CBC 7826863 : return page;
795 : : }
796 : :
797 : : /*
798 : : * heapgettup_advance_block - helper for heap_fetch_next_buffer()
799 : : *
800 : : * Given the current block number, the scan direction, and various information
801 : : * contained in the scan descriptor, calculate the BlockNumber to scan next
802 : : * and return it. If there are no further blocks to scan, return
803 : : * InvalidBlockNumber to indicate this fact to the caller.
804 : : *
805 : : * This should not be called to determine the initial block number -- only for
806 : : * subsequent blocks.
807 : : *
808 : : * This also adjusts rs_numblocks when a limit has been imposed by
809 : : * heap_setscanlimits().
810 : : */
811 : : static inline BlockNumber
812 : 2538905 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
813 : : {
516 tmunro@postgresql.or 814 [ - + ]: 2538905 : Assert(scan->rs_base.rs_parallel == NULL);
815 : :
816 [ + + ]: 2538905 : if (likely(ScanDirectionIsForward(dir)))
817 : : {
818 : 2538847 : block++;
819 : :
820 : : /* wrap back to the start of the heap */
821 [ + + ]: 2538847 : if (block >= scan->rs_nblocks)
822 : 385843 : block = 0;
823 : :
824 : : /*
825 : : * Report our new scan position for synchronization purposes. We don't
826 : : * do that when moving backwards, however. That would just mess up any
827 : : * other forward-moving scanners.
828 : : *
829 : : * Note: we do this before checking for end of scan so that the final
830 : : * state of the position hint is back at the start of the rel. That's
831 : : * not strictly necessary, but otherwise when you run the same query
832 : : * multiple times the starting position would shift a little bit
833 : : * backwards on every invocation, which is confusing. We don't
834 : : * guarantee any specific ordering in general, though.
835 : : */
836 [ + + ]: 2538847 : if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
837 : 11349 : ss_report_location(scan->rs_base.rs_rd, block);
838 : :
839 : : /* we're done if we're back at where we started */
840 [ + + ]: 2538847 : if (block == scan->rs_startblock)
841 : 385802 : return InvalidBlockNumber;
842 : :
843 : : /* check if the limit imposed by heap_setscanlimits() is met */
844 [ + + ]: 2153045 : if (scan->rs_numblocks != InvalidBlockNumber)
845 : : {
846 [ + + ]: 2466 : if (--scan->rs_numblocks == 0)
847 : 1532 : return InvalidBlockNumber;
848 : : }
849 : :
850 : 2151513 : return block;
851 : : }
852 : : else
853 : : {
854 : : /* we're done if the last block is the start position */
946 drowley@postgresql.o 855 [ + - ]: 58 : if (block == scan->rs_startblock)
856 : 58 : return InvalidBlockNumber;
857 : :
858 : : /* check if the limit imposed by heap_setscanlimits() is met */
946 drowley@postgresql.o 859 [ # # ]:UBC 0 : if (scan->rs_numblocks != InvalidBlockNumber)
860 : : {
861 [ # # ]: 0 : if (--scan->rs_numblocks == 0)
862 : 0 : return InvalidBlockNumber;
863 : : }
864 : :
865 : : /* wrap to the end of the heap when the last page was page 0 */
866 [ # # ]: 0 : if (block == 0)
867 : 0 : block = scan->rs_nblocks;
868 : :
869 : 0 : block--;
870 : :
871 : 0 : return block;
872 : : }
873 : : }
874 : :
875 : : /* ----------------
876 : : * heapgettup - fetch next heap tuple
877 : : *
878 : : * Initialize the scan if not already done; then advance to the next
879 : : * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
880 : : * or set scan->rs_ctup.t_data = NULL if no more tuples.
881 : : *
882 : : * Note: the reason nkeys/key are passed separately, even though they are
883 : : * kept in the scan descriptor, is that the caller may not want us to check
884 : : * the scankeys.
885 : : *
886 : : * Note: when we fall off the end of the scan in either direction, we
887 : : * reset rs_inited. This means that a further request with the same
888 : : * scan direction will restart the scan, which is a bit odd, but a
889 : : * request with the opposite scan direction will start a fresh scan
890 : : * in the proper direction. The latter is required behavior for cursors,
891 : : * while the former case is generally undefined behavior in Postgres
892 : : * so we don't care too much.
893 : : * ----------------
894 : : */
895 : : static void
7224 tgl@sss.pgh.pa.us 896 :CBC 7847017 : heapgettup(HeapScanDesc scan,
897 : : ScanDirection dir,
898 : : int nkeys,
899 : : ScanKey key)
900 : : {
901 : 7847017 : HeapTuple tuple = &(scan->rs_ctup);
902 : : Page page;
903 : : OffsetNumber lineoff;
904 : : int linesleft;
905 : :
520 drowley@postgresql.o 906 [ + + ]: 7847017 : if (likely(scan->rs_inited))
907 : : {
908 : : /* continue from previously returned page/tuple */
946 909 : 7826863 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
910 : 7826863 : page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
942 911 : 7826863 : goto continue_page;
912 : : }
913 : :
914 : : /*
915 : : * advance the scan until we find a qualifying tuple or run out of stuff
916 : : * to scan
917 : : */
918 : : while (true)
919 : : {
520 920 : 114165 : heap_fetch_next_buffer(scan, dir);
921 : :
922 : : /* did we run out of blocks to scan? */
923 [ + + ]: 114165 : if (!BufferIsValid(scan->rs_cbuf))
924 : 20004 : break;
925 : :
926 [ - + ]: 94161 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
927 : :
942 928 : 94161 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
929 : 94161 : page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
930 : 7921024 : continue_page:
931 : :
932 : : /*
933 : : * Only continue scanning the page while we have lines left.
934 : : *
935 : : * Note that this protects us from accessing line pointers past
936 : : * PageGetMaxOffsetNumber(); both for forward scans when we resume the
937 : : * table scan, and for when we start scanning a new page.
938 : : */
939 [ + + ]: 7956604 : for (; linesleft > 0; linesleft--, lineoff += dir)
940 : : {
941 : : bool visible;
942 : 7862593 : ItemId lpp = PageGetItemId(page, lineoff);
943 : :
944 [ + + ]: 7862593 : if (!ItemIdIsNormal(lpp))
945 : 30351 : continue;
946 : :
947 : 7832242 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
948 : 7832242 : tuple->t_len = ItemIdGetLength(lpp);
520 949 : 7832242 : ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
950 : :
942 951 : 7832242 : visible = HeapTupleSatisfiesVisibility(tuple,
952 : : scan->rs_base.rs_snapshot,
953 : : scan->rs_cbuf);
954 : :
955 : 7832242 : HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
956 : : tuple, scan->rs_cbuf,
957 : : scan->rs_base.rs_snapshot);
958 : :
959 : : /* skip tuples not visible to this snapshot */
960 [ + + ]: 7832242 : if (!visible)
961 : 5229 : continue;
962 : :
963 : : /* skip any tuples that don't match the scan key */
964 [ - + ]: 7827013 : if (key != NULL &&
942 drowley@postgresql.o 965 [ # # ]:UBC 0 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
966 : : nkeys, key))
967 : 0 : continue;
968 : :
942 drowley@postgresql.o 969 :CBC 7827013 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
970 : 7827013 : scan->rs_coffset = lineoff;
971 : 7827013 : return;
972 : : }
973 : :
974 : : /*
975 : : * if we get here, it means we've exhausted the items on this page and
976 : : * it's time to move to the next.
977 : : */
7224 tgl@sss.pgh.pa.us 978 : 94011 : LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
979 : : }
980 : :
981 : : /* end of scan */
942 drowley@postgresql.o 982 [ - + ]: 20004 : if (BufferIsValid(scan->rs_cbuf))
942 drowley@postgresql.o 983 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
984 : :
942 drowley@postgresql.o 985 :CBC 20004 : scan->rs_cbuf = InvalidBuffer;
986 : 20004 : scan->rs_cblock = InvalidBlockNumber;
516 tmunro@postgresql.or 987 : 20004 : scan->rs_prefetch_block = InvalidBlockNumber;
942 drowley@postgresql.o 988 : 20004 : tuple->t_data = NULL;
989 : 20004 : scan->rs_inited = false;
990 : : }
991 : :
992 : : /* ----------------
993 : : * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
994 : : *
995 : : * Same API as heapgettup, but used in page-at-a-time mode
996 : : *
997 : : * The internal logic is much the same as heapgettup's too, but there are some
998 : : * differences: we do not take the buffer content lock (that only needs to
999 : : * happen inside heap_prepare_pagescan), and we iterate through just the
1000 : : * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
1001 : : * that lineindex is 0-based, where the corresponding loop variable lineoff in
1002 : : * heapgettup is 1-based.
1003 : : * ----------------
1004 : : */
1005 : : static void
7224 tgl@sss.pgh.pa.us 1006 : 48040056 : heapgettup_pagemode(HeapScanDesc scan,
1007 : : ScanDirection dir,
1008 : : int nkeys,
1009 : : ScanKey key)
1010 : : {
1011 : 48040056 : HeapTuple tuple = &(scan->rs_ctup);
1012 : : Page page;
1013 : : uint32 lineindex;
1014 : : uint32 linesleft;
1015 : :
520 drowley@postgresql.o 1016 [ + + ]: 48040056 : if (likely(scan->rs_inited))
1017 : : {
1018 : : /* continue from previously returned page/tuple */
946 1019 : 47110184 : page = BufferGetPage(scan->rs_cbuf);
1020 : :
1021 : 47110184 : lineindex = scan->rs_cindex + dir;
1022 [ + + ]: 47110184 : if (ScanDirectionIsForward(dir))
1023 : 47109856 : linesleft = scan->rs_ntuples - lineindex;
1024 : : else
1025 : 328 : linesleft = scan->rs_cindex;
1026 : : /* lineindex now references the next or previous visible tid */
1027 : :
942 1028 : 47110184 : goto continue_page;
1029 : : }
1030 : :
1031 : : /*
1032 : : * advance the scan until we find a qualifying tuple or run out of stuff
1033 : : * to scan
1034 : : */
1035 : : while (true)
1036 : : {
520 1037 : 3301216 : heap_fetch_next_buffer(scan, dir);
1038 : :
1039 : : /* did we run out of blocks to scan? */
1040 [ + + ]: 3301192 : if (!BufferIsValid(scan->rs_cbuf))
1041 : 777272 : break;
1042 : :
1043 [ - + ]: 2523920 : Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
1044 : :
1045 : : /* prune the page and determine visible tuple offsets */
1046 : 2523920 : heap_prepare_pagescan((TableScanDesc) scan);
942 1047 : 2523912 : page = BufferGetPage(scan->rs_cbuf);
1048 : 2523912 : linesleft = scan->rs_ntuples;
1049 [ + + ]: 2523912 : lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1050 : :
1051 : : /* block is the same for all tuples, set it once outside the loop */
158 heikki.linnakangas@i 1052 : 2523912 : ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1053 : :
1054 : : /* lineindex now references the next or previous visible tid */
942 drowley@postgresql.o 1055 : 49634096 : continue_page:
1056 : :
1057 [ + + ]: 94354266 : for (; linesleft > 0; linesleft--, lineindex += dir)
1058 : : {
1059 : : ItemId lpp;
1060 : : OffsetNumber lineoff;
1061 : :
262 melanieplageman@gmai 1062 [ - + ]: 91982922 : Assert(lineindex <= scan->rs_ntuples);
7224 tgl@sss.pgh.pa.us 1063 : 91982922 : lineoff = scan->rs_vistuples[lineindex];
1025 peter@eisentraut.org 1064 : 91982922 : lpp = PageGetItemId(page, lineoff);
6569 tgl@sss.pgh.pa.us 1065 [ - + ]: 91982922 : Assert(ItemIdIsNormal(lpp));
1066 : :
1025 peter@eisentraut.org 1067 : 91982922 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
7224 tgl@sss.pgh.pa.us 1068 : 91982922 : tuple->t_len = ItemIdGetLength(lpp);
158 heikki.linnakangas@i 1069 : 91982922 : ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1070 : :
1071 : : /* skip any tuples that don't match the scan key */
942 drowley@postgresql.o 1072 [ + + ]: 91982922 : if (key != NULL &&
1073 [ + + ]: 45030486 : !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1074 : : nkeys, key))
1075 : 44720170 : continue;
1076 : :
1077 : 47262752 : scan->rs_cindex = lineindex;
1078 : 47262752 : return;
1079 : : }
1080 : : }
1081 : :
1082 : : /* end of scan */
1083 [ - + ]: 777272 : if (BufferIsValid(scan->rs_cbuf))
942 drowley@postgresql.o 1084 :UBC 0 : ReleaseBuffer(scan->rs_cbuf);
942 drowley@postgresql.o 1085 :CBC 777272 : scan->rs_cbuf = InvalidBuffer;
1086 : 777272 : scan->rs_cblock = InvalidBlockNumber;
516 tmunro@postgresql.or 1087 : 777272 : scan->rs_prefetch_block = InvalidBlockNumber;
942 drowley@postgresql.o 1088 : 777272 : tuple->t_data = NULL;
1089 : 777272 : scan->rs_inited = false;
1090 : : }
1091 : :
1092 : :
1093 : : /* ----------------------------------------------------------------
1094 : : * heap access method interface
1095 : : * ----------------------------------------------------------------
1096 : : */
1097 : :
1098 : :
1099 : : TableScanDesc
8510 tgl@sss.pgh.pa.us 1100 : 358299 : heap_beginscan(Relation relation, Snapshot snapshot,
1101 : : int nkeys, ScanKey key,
1102 : : ParallelTableScanDesc parallel_scan,
1103 : : uint32 flags)
1104 : : {
1105 : : HeapScanDesc scan;
1106 : :
1107 : : /*
1108 : : * increment relation ref count while scanning relation
1109 : : *
1110 : : * This is just to make really sure the relcache entry won't go away while
1111 : : * the scan has a pointer to it. Caller should be holding the rel open
1112 : : * anyway, so this is redundant in all normal scenarios...
1113 : : */
9068 1114 : 358299 : RelationIncrementReferenceCount(relation);
1115 : :
1116 : : /*
1117 : : * allocate and initialize scan descriptor
1118 : : */
233 melanieplageman@gmai 1119 [ + + ]: 358299 : if (flags & SO_TYPE_BITMAPSCAN)
1120 : : {
1121 : 7901 : BitmapHeapScanDesc bscan = palloc(sizeof(BitmapHeapScanDescData));
1122 : :
1123 : : /*
1124 : : * Bitmap Heap scans do not have any fields that a normal Heap Scan
1125 : : * does not have, so no special initializations required here.
1126 : : */
1127 : 7901 : scan = (HeapScanDesc) bscan;
1128 : : }
1129 : : else
1130 : 350398 : scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1131 : :
2371 andres@anarazel.de 1132 : 358299 : scan->rs_base.rs_rd = relation;
1133 : 358299 : scan->rs_base.rs_snapshot = snapshot;
1134 : 358299 : scan->rs_base.rs_nkeys = nkeys;
2302 1135 : 358299 : scan->rs_base.rs_flags = flags;
2371 1136 : 358299 : scan->rs_base.rs_parallel = parallel_scan;
2302 1137 : 358299 : scan->rs_strategy = NULL; /* set in initscan */
175 melanieplageman@gmai 1138 : 358299 : scan->rs_cbuf = InvalidBuffer;
1139 : :
1140 : : /*
1141 : : * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1142 : : */
2302 andres@anarazel.de 1143 [ + + + + : 358299 : if (!(snapshot && IsMVCCSnapshot(snapshot)))
+ + ]
1144 : 28733 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1145 : :
1146 : : /* Check that a historic snapshot is not used for non-catalog tables */
15 heikki.linnakangas@i 1147 [ + + ]:GNC 358299 : if (snapshot &&
1148 [ + + ]: 349722 : IsHistoricMVCCSnapshot(snapshot) &&
1149 [ + - + - : 644 : !RelationIsAccessibleInLogicalDecoding(relation))
- + - - -
- - + - -
- - - - -
- - - ]
1150 : : {
15 heikki.linnakangas@i 1151 [ # # ]:UNC 0 : ereport(ERROR,
1152 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1153 : : errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1154 : : RelationGetRelationName(relation))));
1155 : : }
1156 : :
1157 : : /*
1158 : : * For seqscan and sample scans in a serializable transaction, acquire a
1159 : : * predicate lock on the entire relation. This is required not only to
1160 : : * lock all the matching tuples, but also to conflict with new insertions
1161 : : * into the table. In an indexscan, we take page locks on the index pages
1162 : : * covering the range specified in the scan qual, but in a heap scan there
1163 : : * is nothing more fine-grained to lock. A bitmap scan is a different
1164 : : * story, there we have already scanned the index and locked the index
1165 : : * pages covering the predicate. But in that case we still have to lock
1166 : : * any matching heap tuples. For sample scan we could optimize the locking
1167 : : * to be at least page-level granularity, but we'd need to add per-tuple
1168 : : * locking for that.
1169 : : */
2302 andres@anarazel.de 1170 [ + + ]:CBC 358299 : if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
1171 : : {
1172 : : /*
1173 : : * Ensure a missing snapshot is noticed reliably, even if the
1174 : : * isolation mode means predicate locking isn't performed (and
1175 : : * therefore the snapshot isn't used here).
1176 : : */
1177 [ - + ]: 340511 : Assert(snapshot);
5183 heikki.linnakangas@i 1178 : 340511 : PredicateLockRelation(relation, snapshot);
1179 : : }
1180 : :
1181 : : /* we only need to set this up once */
7224 tgl@sss.pgh.pa.us 1182 : 358299 : scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1183 : :
1184 : : /*
1185 : : * Allocate memory to keep track of page allocation for parallel workers
1186 : : * when doing a parallel scan.
1187 : : */
1621 drowley@postgresql.o 1188 [ + + ]: 358299 : if (parallel_scan != NULL)
1189 : 1959 : scan->rs_parallelworkerdata = palloc(sizeof(ParallelBlockTableScanWorkerData));
1190 : : else
1191 : 356340 : scan->rs_parallelworkerdata = NULL;
1192 : :
1193 : : /*
1194 : : * we do this here instead of in initscan() because heap_rescan also calls
1195 : : * initscan() and we don't want to allocate memory again
1196 : : */
8510 tgl@sss.pgh.pa.us 1197 [ + + ]: 358299 : if (nkeys > 0)
2371 andres@anarazel.de 1198 : 205156 : scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1199 : : else
1200 : 153143 : scan->rs_base.rs_key = NULL;
1201 : :
5932 tgl@sss.pgh.pa.us 1202 : 358299 : initscan(scan, key, false);
1203 : :
516 tmunro@postgresql.or 1204 : 358297 : scan->rs_read_stream = NULL;
1205 : :
1206 : : /*
1207 : : * Set up a read stream for sequential scans and TID range scans. This
1208 : : * should be done after initscan() because initscan() allocates the
1209 : : * BufferAccessStrategy object passed to the read stream API.
1210 : : */
1211 [ + + ]: 358297 : if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1212 [ + + ]: 17861 : scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
1213 : 341359 : {
1214 : : ReadStreamBlockNumberCB cb;
1215 : :
1216 [ + + ]: 341359 : if (scan->rs_base.rs_parallel)
1217 : 1959 : cb = heap_scan_stream_read_next_parallel;
1218 : : else
1219 : 339400 : cb = heap_scan_stream_read_next_serial;
1220 : :
1221 : : /* ---
1222 : : * It is safe to use batchmode as the only locks taken by `cb`
1223 : : * are never taken while waiting for IO:
1224 : : * - SyncScanLock is used in the non-parallel case
1225 : : * - in the parallel case, only spinlocks and atomics are used
1226 : : * ---
1227 : : */
160 andres@anarazel.de 1228 : 341359 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
1229 : : READ_STREAM_USE_BATCHING,
1230 : : scan->rs_strategy,
1231 : : scan->rs_base.rs_rd,
1232 : : MAIN_FORKNUM,
1233 : : cb,
1234 : : scan,
1235 : : 0);
1236 : : }
175 melanieplageman@gmai 1237 [ + + ]: 16938 : else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1238 : : {
156 1239 : 7901 : scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
1240 : : READ_STREAM_USE_BATCHING,
1241 : : scan->rs_strategy,
1242 : : scan->rs_base.rs_rd,
1243 : : MAIN_FORKNUM,
1244 : : bitmapheap_stream_read_next,
1245 : : scan,
1246 : : sizeof(TBMIterateResult));
1247 : : }
1248 : :
1249 : :
2371 andres@anarazel.de 1250 : 358297 : return (TableScanDesc) scan;
1251 : : }
1252 : :
1253 : : void
1254 : 611400 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1255 : : bool allow_strat, bool allow_sync, bool allow_pagemode)
1256 : : {
1257 : 611400 : HeapScanDesc scan = (HeapScanDesc) sscan;
1258 : :
1259 [ + + ]: 611400 : if (set_params)
1260 : : {
2302 1261 [ + - ]: 15 : if (allow_strat)
1262 : 15 : scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1263 : : else
2302 andres@anarazel.de 1264 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1265 : :
2302 andres@anarazel.de 1266 [ + + ]:CBC 15 : if (allow_sync)
1267 : 6 : scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1268 : : else
1269 : 9 : scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1270 : :
1271 [ + - + - ]: 15 : if (allow_pagemode && scan->rs_base.rs_snapshot &&
1272 [ - + - - ]: 15 : IsMVCCSnapshot(scan->rs_base.rs_snapshot))
1273 : 15 : scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
1274 : : else
2302 andres@anarazel.de 1275 :UBC 0 : scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1276 : : }
1277 : :
1278 : : /*
1279 : : * unpin scan buffers
1280 : : */
8855 tgl@sss.pgh.pa.us 1281 [ + + ]:CBC 611400 : if (BufferIsValid(scan->rs_cbuf))
1282 : : {
1283 : 1697 : ReleaseBuffer(scan->rs_cbuf);
175 melanieplageman@gmai 1284 : 1697 : scan->rs_cbuf = InvalidBuffer;
1285 : : }
1286 : :
1287 : : /*
1288 : : * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1289 : : * additional data vs a normal HeapScan
1290 : : */
1291 : :
1292 : : /*
1293 : : * The read stream is reset on rescan. This must be done before
1294 : : * initscan(), as some state referred to by read_stream_reset() is reset
1295 : : * in initscan().
1296 : : */
516 tmunro@postgresql.or 1297 [ + + ]: 611400 : if (scan->rs_read_stream)
1298 : 611382 : read_stream_reset(scan->rs_read_stream);
1299 : :
1300 : : /*
1301 : : * reinitialize scan descriptor
1302 : : */
5932 tgl@sss.pgh.pa.us 1303 : 611400 : initscan(scan, key, true);
10651 scrappy@hub.org 1304 : 611400 : }
1305 : :
1306 : : void
2371 andres@anarazel.de 1307 : 355971 : heap_endscan(TableScanDesc sscan)
1308 : : {
1309 : 355971 : HeapScanDesc scan = (HeapScanDesc) sscan;
1310 : :
1311 : : /* Note: no locking manipulations needed */
1312 : :
1313 : : /*
1314 : : * unpin scan buffers
1315 : : */
8855 tgl@sss.pgh.pa.us 1316 [ + + ]: 355971 : if (BufferIsValid(scan->rs_cbuf))
1317 : 149420 : ReleaseBuffer(scan->rs_cbuf);
1318 : :
1319 : : /*
1320 : : * Must free the read stream before freeing the BufferAccessStrategy.
1321 : : */
516 tmunro@postgresql.or 1322 [ + + ]: 355971 : if (scan->rs_read_stream)
1323 : 346988 : read_stream_end(scan->rs_read_stream);
1324 : :
1325 : : /*
1326 : : * decrement relation reference count and free scan descriptor storage
1327 : : */
2371 andres@anarazel.de 1328 : 355971 : RelationDecrementReferenceCount(scan->rs_base.rs_rd);
1329 : :
1330 [ + + ]: 355971 : if (scan->rs_base.rs_key)
1331 : 205126 : pfree(scan->rs_base.rs_key);
1332 : :
6674 tgl@sss.pgh.pa.us 1333 [ + + ]: 355971 : if (scan->rs_strategy != NULL)
1334 : 12233 : FreeAccessStrategy(scan->rs_strategy);
1335 : :
1621 drowley@postgresql.o 1336 [ + + ]: 355971 : if (scan->rs_parallelworkerdata != NULL)
1337 : 1959 : pfree(scan->rs_parallelworkerdata);
1338 : :
2302 andres@anarazel.de 1339 [ + + ]: 355971 : if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
2371 1340 : 30248 : UnregisterSnapshot(scan->rs_base.rs_snapshot);
1341 : :
9485 tgl@sss.pgh.pa.us 1342 : 355971 : pfree(scan);
10651 scrappy@hub.org 1343 : 355971 : }
1344 : :
1345 : : HeapTuple
2371 andres@anarazel.de 1346 : 9044853 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
1347 : : {
1348 : 9044853 : HeapScanDesc scan = (HeapScanDesc) sscan;
1349 : :
1350 : : /*
1351 : : * This is still widely used directly, without going through table AM, so
1352 : : * add a safety check. It's possible we should, at a later point,
1353 : : * downgrade this to an assert. The reason for checking the AM routine,
1354 : : * rather than the AM oid, is that this allows to write regression tests
1355 : : * that create another AM reusing the heap handler.
1356 : : */
1357 [ - + ]: 9044853 : if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
2371 andres@anarazel.de 1358 [ # # ]:UBC 0 : ereport(ERROR,
1359 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1360 : : errmsg_internal("only heap AM is supported")));
1361 : :
1362 : : /*
1363 : : * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1364 : : * for catalog or regular tables. See detailed comments in xact.c where
1365 : : * these variables are declared. Normally we have such a check at tableam
1366 : : * level API but this is called from many places so we need to ensure it
1367 : : * here.
1368 : : */
1855 akapila@postgresql.o 1369 [ - + - - :CBC 9044853 : if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
- + ]
1855 akapila@postgresql.o 1370 [ # # ]:UBC 0 : elog(ERROR, "unexpected heap_getnext call during logical decoding");
1371 : :
1372 : : /* Note: no locking manipulations needed */
1373 : :
2302 andres@anarazel.de 1374 [ + + ]:CBC 9044853 : if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
7137 neilc@samurai.com 1375 : 1678115 : heapgettup_pagemode(scan, direction,
2371 andres@anarazel.de 1376 : 1678115 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1377 : : else
1378 : 7366738 : heapgettup(scan, direction,
1379 : 7366738 : scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1380 : :
7224 tgl@sss.pgh.pa.us 1381 [ + + ]: 9044853 : if (scan->rs_ctup.t_data == NULL)
8510 1382 : 56168 : return NULL;
1383 : :
1384 : : /*
1385 : : * if we get here it means we have a new current scan tuple, so point to
1386 : : * the proper return buffer and return the tuple.
1387 : : */
1388 : :
2371 andres@anarazel.de 1389 [ - + - - : 8988685 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - ]
1390 : :
1391 : 8988685 : return &scan->rs_ctup;
1392 : : }
1393 : :
1394 : : bool
1395 : 46838284 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
1396 : : {
1397 : 46838284 : HeapScanDesc scan = (HeapScanDesc) sscan;
1398 : :
1399 : : /* Note: no locking manipulations needed */
1400 : :
2302 1401 [ + + ]: 46838284 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1402 : 46358005 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1403 : : else
1404 : 480279 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1405 : :
2371 1406 [ + + ]: 46838258 : if (scan->rs_ctup.t_data == NULL)
1407 : : {
1408 : 741061 : ExecClearTuple(slot);
1409 : 741061 : return false;
1410 : : }
1411 : :
1412 : : /*
1413 : : * if we get here it means we have a new current scan tuple, so point to
1414 : : * the proper return buffer and return the tuple.
1415 : : */
1416 : :
1417 [ + + - + : 46097197 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ + ]
1418 : :
1419 : 46097197 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1420 : : scan->rs_cbuf);
1421 : 46097197 : return true;
1422 : : }
1423 : :
1424 : : void
1652 drowley@postgresql.o 1425 : 956 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
1426 : : ItemPointer maxtid)
1427 : : {
1428 : 956 : HeapScanDesc scan = (HeapScanDesc) sscan;
1429 : : BlockNumber startBlk;
1430 : : BlockNumber numBlks;
1431 : : ItemPointerData highestItem;
1432 : : ItemPointerData lowestItem;
1433 : :
1434 : : /*
1435 : : * For relations without any pages, we can simply leave the TID range
1436 : : * unset. There will be no tuples to scan, therefore no tuples outside
1437 : : * the given TID range.
1438 : : */
1439 [ + + ]: 956 : if (scan->rs_nblocks == 0)
1440 : 24 : return;
1441 : :
1442 : : /*
1443 : : * Set up some ItemPointers which point to the first and last possible
1444 : : * tuples in the heap.
1445 : : */
1446 : 950 : ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1447 : 950 : ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1448 : :
1449 : : /*
1450 : : * If the given maximum TID is below the highest possible TID in the
1451 : : * relation, then restrict the range to that, otherwise we scan to the end
1452 : : * of the relation.
1453 : : */
1454 [ + + ]: 950 : if (ItemPointerCompare(maxtid, &highestItem) < 0)
1455 : 66 : ItemPointerCopy(maxtid, &highestItem);
1456 : :
1457 : : /*
1458 : : * If the given minimum TID is above the lowest possible TID in the
1459 : : * relation, then restrict the range to only scan for TIDs above that.
1460 : : */
1461 [ + + ]: 950 : if (ItemPointerCompare(mintid, &lowestItem) > 0)
1462 : 881 : ItemPointerCopy(mintid, &lowestItem);
1463 : :
1464 : : /*
1465 : : * Check for an empty range and protect from would be negative results
1466 : : * from the numBlks calculation below.
1467 : : */
1468 [ + + ]: 950 : if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1469 : : {
1470 : : /* Set an empty range of blocks to scan */
1471 : 18 : heap_setscanlimits(sscan, 0, 0);
1472 : 18 : return;
1473 : : }
1474 : :
1475 : : /*
1476 : : * Calculate the first block and the number of blocks we must scan. We
1477 : : * could be more aggressive here and perform some more validation to try
1478 : : * and further narrow the scope of blocks to scan by checking if the
1479 : : * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1480 : : * advance startBlk by one. Likewise, if highestItem has an offset of 0
1481 : : * we could scan one fewer blocks. However, such an optimization does not
1482 : : * seem worth troubling over, currently.
1483 : : */
1484 : 932 : startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1485 : :
1486 : 932 : numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1487 : 932 : ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1488 : :
1489 : : /* Set the start block and number of blocks to scan */
1490 : 932 : heap_setscanlimits(sscan, startBlk, numBlks);
1491 : :
1492 : : /* Finally, set the TID range in sscan */
316 melanieplageman@gmai 1493 : 932 : ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1494 : 932 : ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1495 : : }
1496 : :
1497 : : bool
1652 drowley@postgresql.o 1498 : 3843 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
1499 : : TupleTableSlot *slot)
1500 : : {
1501 : 3843 : HeapScanDesc scan = (HeapScanDesc) sscan;
316 melanieplageman@gmai 1502 : 3843 : ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
1503 : 3843 : ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
1504 : :
1505 : : /* Note: no locking manipulations needed */
1506 : : for (;;)
1507 : : {
1652 drowley@postgresql.o 1508 [ + - ]: 3936 : if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1509 : 3936 : heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1510 : : else
1652 drowley@postgresql.o 1511 :UBC 0 : heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1512 : :
1652 drowley@postgresql.o 1513 [ + + ]:CBC 3930 : if (scan->rs_ctup.t_data == NULL)
1514 : : {
1515 : 47 : ExecClearTuple(slot);
1516 : 47 : return false;
1517 : : }
1518 : :
1519 : : /*
1520 : : * heap_set_tidrange will have used heap_setscanlimits to limit the
1521 : : * range of pages we scan to only ones that can contain the TID range
1522 : : * we're scanning for. Here we must filter out any tuples from these
1523 : : * pages that are outside of that range.
1524 : : */
1525 [ + + ]: 3883 : if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1526 : : {
1527 : 93 : ExecClearTuple(slot);
1528 : :
1529 : : /*
1530 : : * When scanning backwards, the TIDs will be in descending order.
1531 : : * Future tuples in this direction will be lower still, so we can
1532 : : * just return false to indicate there will be no more tuples.
1533 : : */
1534 [ - + ]: 93 : if (ScanDirectionIsBackward(direction))
1652 drowley@postgresql.o 1535 :UBC 0 : return false;
1536 : :
1652 drowley@postgresql.o 1537 :CBC 93 : continue;
1538 : : }
1539 : :
1540 : : /*
1541 : : * Likewise for the final page, we must filter out TIDs greater than
1542 : : * maxtid.
1543 : : */
1544 [ + + ]: 3790 : if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1545 : : {
1546 : 36 : ExecClearTuple(slot);
1547 : :
1548 : : /*
1549 : : * When scanning forward, the TIDs will be in ascending order.
1550 : : * Future tuples in this direction will be higher still, so we can
1551 : : * just return false to indicate there will be no more tuples.
1552 : : */
1553 [ + - ]: 36 : if (ScanDirectionIsForward(direction))
1554 : 36 : return false;
1652 drowley@postgresql.o 1555 :UBC 0 : continue;
1556 : : }
1557 : :
1652 drowley@postgresql.o 1558 :CBC 3754 : break;
1559 : : }
1560 : :
1561 : : /*
1562 : : * if we get here it means we have a new current scan tuple, so point to
1563 : : * the proper return buffer and return the tuple.
1564 : : */
1565 [ - + - - : 3754 : pgstat_count_heap_getnext(scan->rs_base.rs_rd);
+ - ]
1566 : :
1567 : 3754 : ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1568 : 3754 : return true;
1569 : : }
1570 : :
1571 : : /*
1572 : : * heap_fetch - retrieve tuple with given tid
1573 : : *
1574 : : * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1575 : : * the tuple, fill in the remaining fields of *tuple, and check the tuple
1576 : : * against the specified snapshot.
1577 : : *
1578 : : * If successful (tuple found and passes snapshot time qual), then *userbuf
1579 : : * is set to the buffer holding the tuple and true is returned. The caller
1580 : : * must unpin the buffer when done with the tuple.
1581 : : *
1582 : : * If the tuple is not found (ie, item number references a deleted slot),
1583 : : * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1584 : : * and false is returned.
1585 : : *
1586 : : * If the tuple is found but fails the time qual check, then the behavior
1587 : : * depends on the keep_buf parameter. If keep_buf is false, the results
1588 : : * are the same as for the tuple-not-found case. If keep_buf is true,
1589 : : * then tuple->t_data and *userbuf are returned as for the success case,
1590 : : * and again the caller must unpin the buffer; but false is returned.
1591 : : *
1592 : : * heap_fetch does not follow HOT chains: only the exact TID requested will
1593 : : * be fetched.
1594 : : *
1595 : : * It is somewhat inconsistent that we ereport() on invalid block number but
1596 : : * return false on invalid item number. There are a couple of reasons though.
1597 : : * One is that the caller can relatively easily check the block number for
1598 : : * validity, but cannot check the item number without reading the page
1599 : : * himself. Another is that when we are following a t_ctid link, we can be
1600 : : * reasonably confident that the page number is valid (since VACUUM shouldn't
1601 : : * truncate off the destination page without having killed the referencing
1602 : : * tuple first), but the item number might well not be good.
1603 : : */
1604 : : bool
10651 scrappy@hub.org 1605 : 177901 : heap_fetch(Relation relation,
1606 : : Snapshot snapshot,
1607 : : HeapTuple tuple,
1608 : : Buffer *userbuf,
1609 : : bool keep_buf)
1610 : : {
8506 tgl@sss.pgh.pa.us 1611 : 177901 : ItemPointer tid = &(tuple->t_self);
1612 : : ItemId lp;
1613 : : Buffer buffer;
1614 : : Page page;
1615 : : OffsetNumber offnum;
1616 : : bool valid;
1617 : :
1618 : : /*
1619 : : * Fetch and pin the appropriate page of the relation.
1620 : : */
6365 1621 : 177901 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1622 : :
1623 : : /*
1624 : : * Need share lock on buffer to examine tuple commit status.
1625 : : */
9762 vadim4o@yahoo.com 1626 : 177892 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3426 kgrittn@postgresql.o 1627 : 177892 : page = BufferGetPage(buffer);
1628 : :
1629 : : /*
1630 : : * We'd better check for out-of-range offnum in case of VACUUM since the
1631 : : * TID was obtained.
1632 : : */
10226 bruce@momjian.us 1633 : 177892 : offnum = ItemPointerGetOffsetNumber(tid);
6264 tgl@sss.pgh.pa.us 1634 [ + - + + ]: 177892 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1635 : : {
7468 1636 : 3 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2359 andres@anarazel.de 1637 : 3 : ReleaseBuffer(buffer);
1638 : 3 : *userbuf = InvalidBuffer;
7468 tgl@sss.pgh.pa.us 1639 : 3 : tuple->t_data = NULL;
1640 : 3 : return false;
1641 : : }
1642 : :
1643 : : /*
1644 : : * get the item line pointer corresponding to the requested tid
1645 : : */
6264 1646 : 177889 : lp = PageGetItemId(page, offnum);
1647 : :
1648 : : /*
1649 : : * Must check for deleted tuple.
1650 : : */
6569 1651 [ + + ]: 177889 : if (!ItemIdIsNormal(lp))
1652 : : {
9195 vadim4o@yahoo.com 1653 : 345 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2359 andres@anarazel.de 1654 : 345 : ReleaseBuffer(buffer);
1655 : 345 : *userbuf = InvalidBuffer;
8506 tgl@sss.pgh.pa.us 1656 : 345 : tuple->t_data = NULL;
1657 : 345 : return false;
1658 : : }
1659 : :
1660 : : /*
1661 : : * fill in *tuple fields
1662 : : */
6264 1663 : 177544 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
9780 vadim4o@yahoo.com 1664 : 177544 : tuple->t_len = ItemIdGetLength(lp);
7322 tgl@sss.pgh.pa.us 1665 : 177544 : tuple->t_tableOid = RelationGetRelid(relation);
1666 : :
1667 : : /*
1668 : : * check tuple visibility, then release lock
1669 : : */
7224 1670 : 177544 : valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1671 : :
5325 heikki.linnakangas@i 1672 [ + + ]: 177544 : if (valid)
2048 tmunro@postgresql.or 1673 : 177492 : PredicateLockTID(relation, &(tuple->t_self), snapshot,
1674 : 177492 : HeapTupleHeaderGetXmin(tuple->t_data));
1675 : :
1676 : 177544 : HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1677 : :
5300 heikki.linnakangas@i 1678 : 177544 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1679 : :
8506 tgl@sss.pgh.pa.us 1680 [ + + ]: 177544 : if (valid)
1681 : : {
1682 : : /*
1683 : : * All checks passed, so return the tuple as valid. Caller is now
1684 : : * responsible for releasing the buffer.
1685 : : */
9479 1686 : 177492 : *userbuf = buffer;
1687 : :
8506 1688 : 177492 : return true;
1689 : : }
1690 : :
1691 : : /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1242 1692 [ + + ]: 52 : if (keep_buf)
1693 : 34 : *userbuf = buffer;
1694 : : else
1695 : : {
1696 : 18 : ReleaseBuffer(buffer);
1697 : 18 : *userbuf = InvalidBuffer;
1698 : 18 : tuple->t_data = NULL;
1699 : : }
1700 : :
8506 1701 : 52 : return false;
1702 : : }
1703 : :
1704 : : /*
1705 : : * heap_hot_search_buffer - search HOT chain for tuple satisfying snapshot
1706 : : *
1707 : : * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1708 : : * of a HOT chain), and buffer is the buffer holding this tuple. We search
1709 : : * for the first chain member satisfying the given snapshot. If one is
1710 : : * found, we update *tid to reference that tuple's offset number, and
1711 : : * return true. If no match, return false without modifying *tid.
1712 : : *
1713 : : * heapTuple is a caller-supplied buffer. When a match is found, we return
1714 : : * the tuple here, in addition to updating *tid. If no match is found, the
1715 : : * contents of this buffer on return are undefined.
1716 : : *
1717 : : * If all_dead is not NULL, we check non-visible tuples to see if they are
1718 : : * globally dead; *all_dead is set true if all members of the HOT chain
1719 : : * are vacuumable, false if not.
1720 : : *
1721 : : * Unlike heap_fetch, the caller must already have pin and (at least) share
1722 : : * lock on the buffer; it is still pinned/locked at exit.
1723 : : */
1724 : : bool
5325 heikki.linnakangas@i 1725 : 20845509 : heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
1726 : : Snapshot snapshot, HeapTuple heapTuple,
1727 : : bool *all_dead, bool first_call)
1728 : : {
1025 peter@eisentraut.org 1729 : 20845509 : Page page = BufferGetPage(buffer);
6561 tgl@sss.pgh.pa.us 1730 : 20845509 : TransactionId prev_xmax = InvalidTransactionId;
1731 : : BlockNumber blkno;
1732 : : OffsetNumber offnum;
1733 : : bool at_chain_start;
1734 : : bool valid;
1735 : : bool skip;
1851 andres@anarazel.de 1736 : 20845509 : GlobalVisState *vistest = NULL;
1737 : :
1738 : : /* If this is not the first call, previous call returned a (live!) tuple */
6561 tgl@sss.pgh.pa.us 1739 [ + + ]: 20845509 : if (all_dead)
5185 rhaas@postgresql.org 1740 : 17643719 : *all_dead = first_call;
1741 : :
2222 heikki.linnakangas@i 1742 : 20845509 : blkno = ItemPointerGetBlockNumber(tid);
6561 tgl@sss.pgh.pa.us 1743 : 20845509 : offnum = ItemPointerGetOffsetNumber(tid);
5185 rhaas@postgresql.org 1744 : 20845509 : at_chain_start = first_call;
1745 : 20845509 : skip = !first_call;
1746 : :
1747 : : /* XXX: we should assert that a snapshot is pushed or registered */
1851 andres@anarazel.de 1748 [ - + ]: 20845509 : Assert(TransactionIdIsValid(RecentXmin));
2222 heikki.linnakangas@i 1749 [ + - ]: 20845509 : Assert(BufferGetBlockNumber(buffer) == blkno);
1750 : :
1751 : : /* Scan through possible multiple members of HOT-chain */
1752 : : for (;;)
6561 tgl@sss.pgh.pa.us 1753 : 1471347 : {
1754 : : ItemId lp;
1755 : :
1756 : : /* check for bogus TID */
1025 peter@eisentraut.org 1757 [ + - + - ]: 22316856 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1758 : : break;
1759 : :
1760 : 22316856 : lp = PageGetItemId(page, offnum);
1761 : :
1762 : : /* check for unused, dead, or redirected items */
6561 tgl@sss.pgh.pa.us 1763 [ + + ]: 22316856 : if (!ItemIdIsNormal(lp))
1764 : : {
1765 : : /* We should only see a redirect at start of chain */
1766 [ + + + - ]: 745207 : if (ItemIdIsRedirected(lp) && at_chain_start)
1767 : : {
1768 : : /* Follow the redirect */
1769 : 406489 : offnum = ItemIdGetRedirect(lp);
1770 : 406489 : at_chain_start = false;
1771 : 406489 : continue;
1772 : : }
1773 : : /* else must be end of chain */
1774 : 338718 : break;
1775 : : }
1776 : :
1777 : : /*
1778 : : * Update heapTuple to point to the element of the HOT chain we're
1779 : : * currently investigating. Having t_self set correctly is important
1780 : : * because the SSI checks and the *Satisfies routine for historical
1781 : : * MVCC snapshots need the correct tid to decide about the visibility.
1782 : : */
1025 peter@eisentraut.org 1783 : 21571649 : heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
5185 rhaas@postgresql.org 1784 : 21571649 : heapTuple->t_len = ItemIdGetLength(lp);
4429 1785 : 21571649 : heapTuple->t_tableOid = RelationGetRelid(relation);
2222 heikki.linnakangas@i 1786 : 21571649 : ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1787 : :
1788 : : /*
1789 : : * Shouldn't see a HEAP_ONLY tuple at chain start.
1790 : : */
5185 rhaas@postgresql.org 1791 [ + + - + ]: 21571649 : if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
6561 tgl@sss.pgh.pa.us 1792 :UBC 0 : break;
1793 : :
1794 : : /*
1795 : : * The xmin should match the previous xmax value, else chain is
1796 : : * broken.
1797 : : */
6561 tgl@sss.pgh.pa.us 1798 [ + + - + ]:CBC 22636507 : if (TransactionIdIsValid(prev_xmax) &&
2865 alvherre@alvh.no-ip. 1799 : 1064858 : !TransactionIdEquals(prev_xmax,
1800 : : HeapTupleHeaderGetXmin(heapTuple->t_data)))
6561 tgl@sss.pgh.pa.us 1801 :UBC 0 : break;
1802 : :
1803 : : /*
1804 : : * When first_call is true (and thus, skip is initially false) we'll
1805 : : * return the first tuple we find. But on later passes, heapTuple
1806 : : * will initially be pointing to the tuple we returned last time.
1807 : : * Returning it again would be incorrect (and would loop forever), so
1808 : : * we skip it and return the next match we find.
1809 : : */
5185 rhaas@postgresql.org 1810 [ + + ]:CBC 21571649 : if (!skip)
1811 : : {
1812 : : /* If it's visible per the snapshot, we must return it */
1813 : 21490615 : valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
2048 tmunro@postgresql.or 1814 : 21490615 : HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1815 : : buffer, snapshot);
1816 : :
5185 rhaas@postgresql.org 1817 [ + + ]: 21490610 : if (valid)
1818 : : {
1819 : 14311412 : ItemPointerSetOffsetNumber(tid, offnum);
2048 tmunro@postgresql.or 1820 : 14311412 : PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1821 : 14311412 : HeapTupleHeaderGetXmin(heapTuple->t_data));
5185 rhaas@postgresql.org 1822 [ + + ]: 14311412 : if (all_dead)
1823 : 11385464 : *all_dead = false;
1824 : 14311412 : return true;
1825 : : }
1826 : : }
1827 : 7260232 : skip = false;
1828 : :
1829 : : /*
1830 : : * If we can't see it, maybe no one else can either. At caller
1831 : : * request, check whether all chain members are dead to all
1832 : : * transactions.
1833 : : *
1834 : : * Note: if you change the criterion here for what is "dead", fix the
1835 : : * planner's get_actual_variable_range() function to match.
1836 : : */
1851 andres@anarazel.de 1837 [ + + + + ]: 7260232 : if (all_dead && *all_dead)
1838 : : {
1839 [ + + ]: 6421769 : if (!vistest)
1840 : 6301133 : vistest = GlobalVisTestFor(relation);
1841 : :
1842 [ + + ]: 6421769 : if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1843 : 6071599 : *all_dead = false;
1844 : : }
1845 : :
1846 : : /*
1847 : : * Check to see if HOT chain continues past this tuple; if so fetch
1848 : : * the next offnum and loop around.
1849 : : */
5185 rhaas@postgresql.org 1850 [ + + ]: 7260232 : if (HeapTupleIsHotUpdated(heapTuple))
1851 : : {
1852 [ - + ]: 1064858 : Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
1853 : : blkno);
1854 : 1064858 : offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
6561 tgl@sss.pgh.pa.us 1855 : 1064858 : at_chain_start = false;
4609 alvherre@alvh.no-ip. 1856 : 1064858 : prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1857 : : }
1858 : : else
6505 bruce@momjian.us 1859 : 6195374 : break; /* end of chain */
1860 : : }
1861 : :
5213 heikki.linnakangas@i 1862 : 6534092 : return false;
1863 : : }
1864 : :
1865 : : /*
1866 : : * heap_get_latest_tid - get the latest tid of a specified tuple
1867 : : *
1868 : : * Actually, this gets the latest version that is visible according to the
1869 : : * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1870 : : * possibly uncommitted version.
1871 : : *
1872 : : * *tid is both an input and an output parameter: it is updated to
1873 : : * show the latest version of the row. Note that it will not be changed
1874 : : * if no version of the row passes the snapshot test.
1875 : : */
1876 : : void
2304 andres@anarazel.de 1877 : 150 : heap_get_latest_tid(TableScanDesc sscan,
1878 : : ItemPointer tid)
1879 : : {
2299 tgl@sss.pgh.pa.us 1880 : 150 : Relation relation = sscan->rs_rd;
1881 : 150 : Snapshot snapshot = sscan->rs_snapshot;
1882 : : ItemPointerData ctid;
1883 : : TransactionId priorXmax;
1884 : :
1885 : : /*
1886 : : * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1887 : : * Assume that t_ctid links are valid however - there shouldn't be invalid
1888 : : * ones in the table.
1889 : : */
2304 andres@anarazel.de 1890 [ - + ]: 150 : Assert(ItemPointerIsValid(tid));
1891 : :
1892 : : /*
1893 : : * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1894 : : * need to examine, and *tid is the TID we will return if ctid turns out
1895 : : * to be bogus.
1896 : : *
1897 : : * Note that we will loop until we reach the end of the t_ctid chain.
1898 : : * Depending on the snapshot passed, there might be at most one visible
1899 : : * version of the row, but we don't try to optimize for that.
1900 : : */
7322 tgl@sss.pgh.pa.us 1901 : 150 : ctid = *tid;
1902 : 150 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1903 : : for (;;)
1904 : 45 : {
1905 : : Buffer buffer;
1906 : : Page page;
1907 : : OffsetNumber offnum;
1908 : : ItemId lp;
1909 : : HeapTupleData tp;
1910 : : bool valid;
1911 : :
1912 : : /*
1913 : : * Read, pin, and lock the page.
1914 : : */
1915 : 195 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1916 : 195 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
3426 kgrittn@postgresql.o 1917 : 195 : page = BufferGetPage(buffer);
1918 : :
1919 : : /*
1920 : : * Check for bogus item number. This is not treated as an error
1921 : : * condition because it can happen while following a t_ctid link. We
1922 : : * just assume that the prior tid is OK and return it unchanged.
1923 : : */
7322 tgl@sss.pgh.pa.us 1924 : 195 : offnum = ItemPointerGetOffsetNumber(&ctid);
6264 1925 [ + - - + ]: 195 : if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1926 : : {
7099 tgl@sss.pgh.pa.us 1927 :UBC 0 : UnlockReleaseBuffer(buffer);
7322 1928 : 0 : break;
1929 : : }
6264 tgl@sss.pgh.pa.us 1930 :CBC 195 : lp = PageGetItemId(page, offnum);
6569 1931 [ - + ]: 195 : if (!ItemIdIsNormal(lp))
1932 : : {
7099 tgl@sss.pgh.pa.us 1933 :UBC 0 : UnlockReleaseBuffer(buffer);
7322 1934 : 0 : break;
1935 : : }
1936 : :
1937 : : /* OK to access the tuple */
7322 tgl@sss.pgh.pa.us 1938 :CBC 195 : tp.t_self = ctid;
6264 1939 : 195 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
7322 1940 : 195 : tp.t_len = ItemIdGetLength(lp);
4429 rhaas@postgresql.org 1941 : 195 : tp.t_tableOid = RelationGetRelid(relation);
1942 : :
1943 : : /*
1944 : : * After following a t_ctid link, we might arrive at an unrelated
1945 : : * tuple. Check for XMIN match.
1946 : : */
7322 tgl@sss.pgh.pa.us 1947 [ + + - + ]: 240 : if (TransactionIdIsValid(priorXmax) &&
2865 alvherre@alvh.no-ip. 1948 : 45 : !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1949 : : {
7099 tgl@sss.pgh.pa.us 1950 :UBC 0 : UnlockReleaseBuffer(buffer);
7322 1951 : 0 : break;
1952 : : }
1953 : :
1954 : : /*
1955 : : * Check tuple visibility; if visible, set it as the new result
1956 : : * candidate.
1957 : : */
7224 tgl@sss.pgh.pa.us 1958 :CBC 195 : valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2048 tmunro@postgresql.or 1959 : 195 : HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
7322 tgl@sss.pgh.pa.us 1960 [ + + ]: 195 : if (valid)
1961 : 138 : *tid = ctid;
1962 : :
1963 : : /*
1964 : : * If there's a valid t_ctid link, follow it, else we're done.
1965 : : */
4609 alvherre@alvh.no-ip. 1966 [ + + + + ]: 276 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1967 [ + - ]: 138 : HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
2709 andres@anarazel.de 1968 [ + + ]: 114 : HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
7322 tgl@sss.pgh.pa.us 1969 : 57 : ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1970 : : {
7099 1971 : 150 : UnlockReleaseBuffer(buffer);
7322 1972 : 150 : break;
1973 : : }
1974 : :
1975 : 45 : ctid = tp.t_data->t_ctid;
4609 alvherre@alvh.no-ip. 1976 : 45 : priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
7099 tgl@sss.pgh.pa.us 1977 : 45 : UnlockReleaseBuffer(buffer);
1978 : : } /* end of loop */
9462 inoue@tpf.co.jp 1979 : 150 : }
1980 : :
1981 : :
1982 : : /*
1983 : : * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1984 : : *
1985 : : * This is called after we have waited for the XMAX transaction to terminate.
1986 : : * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1987 : : * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1988 : : * hint bit if possible --- but beware that that may not yet be possible,
1989 : : * if the transaction committed asynchronously.
1990 : : *
1991 : : * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1992 : : * even if it commits.
1993 : : *
1994 : : * Hence callers should look only at XMAX_INVALID.
1995 : : *
1996 : : * Note this is not allowed for tuples whose xmax is a multixact.
1997 : : */
1998 : : static void
6598 tgl@sss.pgh.pa.us 1999 : 182 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
2000 : : {
4609 alvherre@alvh.no-ip. 2001 [ - + ]: 182 : Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
2002 [ - + ]: 182 : Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
2003 : :
6598 tgl@sss.pgh.pa.us 2004 [ + - ]: 182 : if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
2005 : : {
4609 alvherre@alvh.no-ip. 2006 [ + + + + ]: 331 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
2007 : 149 : TransactionIdDidCommit(xid))
6598 tgl@sss.pgh.pa.us 2008 : 123 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
2009 : : xid);
2010 : : else
2011 : 59 : HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
2012 : : InvalidTransactionId);
2013 : : }
2014 : 182 : }
2015 : :
2016 : :
2017 : : /*
2018 : : * GetBulkInsertState - prepare status object for a bulk insert
2019 : : */
2020 : : BulkInsertState
6148 2021 : 2324 : GetBulkInsertState(void)
2022 : : {
2023 : : BulkInsertState bistate;
2024 : :
2025 : 2324 : bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
2026 : 2324 : bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
2027 : 2324 : bistate->current_buf = InvalidBuffer;
884 andres@anarazel.de 2028 : 2324 : bistate->next_free = InvalidBlockNumber;
2029 : 2324 : bistate->last_free = InvalidBlockNumber;
754 2030 : 2324 : bistate->already_extended_by = 0;
6148 tgl@sss.pgh.pa.us 2031 : 2324 : return bistate;
2032 : : }
2033 : :
2034 : : /*
2035 : : * FreeBulkInsertState - clean up after finishing a bulk insert
2036 : : */
2037 : : void
2038 : 2181 : FreeBulkInsertState(BulkInsertState bistate)
2039 : : {
2040 [ + + ]: 2181 : if (bistate->current_buf != InvalidBuffer)
5931 bruce@momjian.us 2041 : 1741 : ReleaseBuffer(bistate->current_buf);
6148 tgl@sss.pgh.pa.us 2042 : 2181 : FreeAccessStrategy(bistate->strategy);
2043 : 2181 : pfree(bistate);
2044 : 2181 : }
2045 : :
2046 : : /*
2047 : : * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
2048 : : */
2049 : : void
3147 rhaas@postgresql.org 2050 : 80758 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
2051 : : {
2052 [ + + ]: 80758 : if (bistate->current_buf != InvalidBuffer)
2053 : 30021 : ReleaseBuffer(bistate->current_buf);
2054 : 80758 : bistate->current_buf = InvalidBuffer;
2055 : :
2056 : : /*
2057 : : * Despite the name, we also reset bulk relation extension state.
2058 : : * Otherwise we can end up erroring out due to looking for free space in
2059 : : * ->next_free of one partition, even though ->next_free was set when
2060 : : * extending another partition. It could obviously also be bad for
2061 : : * efficiency to look at existing blocks at offsets from another
2062 : : * partition, even if we don't error out.
2063 : : */
694 andres@anarazel.de 2064 : 80758 : bistate->next_free = InvalidBlockNumber;
2065 : 80758 : bistate->last_free = InvalidBlockNumber;
3147 rhaas@postgresql.org 2066 : 80758 : }
2067 : :
2068 : :
2069 : : /*
2070 : : * heap_insert - insert tuple into a heap
2071 : : *
2072 : : * The new tuple is stamped with current transaction ID and the specified
2073 : : * command ID.
2074 : : *
2075 : : * See table_tuple_insert for comments about most of the input flags, except
2076 : : * that this routine directly takes a tuple rather than a slot.
2077 : : *
2078 : : * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
2079 : : * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
2080 : : * implement table_tuple_insert_speculative().
2081 : : *
2082 : : * On return the header fields of *tup are updated to match the stored tuple;
2083 : : * in particular tup->t_self receives the actual TID where the tuple was
2084 : : * stored. But note that any toasting of fields within the tuple data is NOT
2085 : : * reflected into *tup.
2086 : : */
2087 : : void
7383 tgl@sss.pgh.pa.us 2088 : 8389743 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2089 : : int options, BulkInsertState bistate)
2090 : : {
7660 2091 : 8389743 : TransactionId xid = GetCurrentTransactionId();
2092 : : HeapTuple heaptup;
2093 : : Buffer buffer;
5191 rhaas@postgresql.org 2094 : 8389743 : Buffer vmbuffer = InvalidBuffer;
6121 heikki.linnakangas@i 2095 : 8389743 : bool all_visible_cleared = false;
2096 : :
2097 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1580 tgl@sss.pgh.pa.us 2098 [ - + ]: 8389743 : Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
2099 : : RelationGetNumberOfAttributes(relation));
2100 : :
99 nathan@postgresql.or 2101 : 8389743 : AssertHasSnapshotForToast(relation);
2102 : :
2103 : : /*
2104 : : * Fill in tuple header fields and toast the tuple if necessary.
2105 : : *
2106 : : * Note: below this point, heaptup is the data we actually intend to store
2107 : : * into the relation; tup is the caller's original untoasted data.
2108 : : */
5050 heikki.linnakangas@i 2109 : 8389743 : heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2110 : :
2111 : : /*
2112 : : * Find buffer to insert this tuple into. If the page is all visible,
2113 : : * this will also pin the requisite visibility map page.
2114 : : */
3598 kgrittn@postgresql.o 2115 : 8389743 : buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2116 : : InvalidBuffer, options, bistate,
2117 : : &vmbuffer, NULL,
2118 : : 0);
2119 : :
2120 : : /*
2121 : : * We're about to do the actual insert -- but check for conflict first, to
2122 : : * avoid possibly having to roll back work we've just done.
2123 : : *
2124 : : * This is safe without a recheck as long as there is no possibility of
2125 : : * another process scanning the page between this check and the insert
2126 : : * being visible to the scan (i.e., an exclusive buffer content lock is
2127 : : * continuously held from this point until the tuple insert is visible).
2128 : : *
2129 : : * For a heap insert, we only need to check for table-level SSI locks. Our
2130 : : * new tuple can't possibly conflict with existing tuple locks, and heap
2131 : : * page locks are only consolidated versions of tuple locks; they do not
2132 : : * lock "gaps" as index page locks do. So we don't need to specify a
2133 : : * buffer when making the call, which makes for a faster check.
2134 : : */
2048 tmunro@postgresql.or 2135 : 8389743 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2136 : :
2137 : : /* NO EREPORT(ERROR) from here till changes are logged */
9003 tgl@sss.pgh.pa.us 2138 : 8389731 : START_CRIT_SECTION();
2139 : :
3774 andres@anarazel.de 2140 : 8389731 : RelationPutHeapTuple(relation, buffer, heaptup,
2141 : 8389731 : (options & HEAP_INSERT_SPECULATIVE) != 0);
2142 : :
1556 tomas.vondra@postgre 2143 [ + + ]: 8389731 : if (PageIsAllVisible(BufferGetPage(buffer)))
2144 : : {
6121 heikki.linnakangas@i 2145 : 7421 : all_visible_cleared = true;
3426 kgrittn@postgresql.o 2146 : 7421 : PageClearAllVisible(BufferGetPage(buffer));
5191 rhaas@postgresql.org 2147 : 7421 : visibilitymap_clear(relation,
2148 : 7421 : ItemPointerGetBlockNumber(&(heaptup->t_self)),
2149 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
2150 : : }
2151 : :
2152 : : /*
2153 : : * XXX Should we set PageSetPrunable on this page ?
2154 : : *
2155 : : * The inserting transaction may eventually abort thus making this tuple
2156 : : * DEAD and hence available for pruning. Though we don't want to optimize
2157 : : * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2158 : : * aborted tuple will never be pruned until next vacuum is triggered.
2159 : : *
2160 : : * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2161 : : */
2162 : :
7099 tgl@sss.pgh.pa.us 2163 : 8389731 : MarkBufferDirty(buffer);
2164 : :
2165 : : /* XLOG stuff */
1981 noah@leadboat.com 2166 [ + + + + : 8389731 : if (RelationNeedsWAL(relation))
+ + + + ]
2167 : : {
2168 : : xl_heap_insert xlrec;
2169 : : xl_heap_header xlhdr;
2170 : : XLogRecPtr recptr;
3426 kgrittn@postgresql.o 2171 : 7043747 : Page page = BufferGetPage(buffer);
8934 bruce@momjian.us 2172 : 7043747 : uint8 info = XLOG_HEAP_INSERT;
3943 heikki.linnakangas@i 2173 : 7043747 : int bufflags = 0;
2174 : :
2175 : : /*
2176 : : * If this is a catalog, we need to transmit combo CIDs to properly
2177 : : * decode, so log that as well.
2178 : : */
4288 rhaas@postgresql.org 2179 [ + + + - : 7043747 : if (RelationIsAccessibleInLogicalDecoding(relation))
- + - - -
- + + + +
- + - - +
+ ]
2180 : 3278 : log_heap_new_cid(relation, heaptup);
2181 : :
2182 : : /*
2183 : : * If this is the single and first tuple on page, we can reinit the
2184 : : * page instead of restoring the whole thing. Set flag, and hide
2185 : : * buffer references from XLogInsert.
2186 : : */
3943 heikki.linnakangas@i 2187 [ + + + + ]: 7132765 : if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2188 : 89018 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2189 : : {
2190 : 87809 : info |= XLOG_HEAP_INIT_PAGE;
2191 : 87809 : bufflags |= REGBUF_WILL_INIT;
2192 : : }
2193 : :
2194 : 7043747 : xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
3774 andres@anarazel.de 2195 : 7043747 : xlrec.flags = 0;
2196 [ + + ]: 7043747 : if (all_visible_cleared)
2197 : 7418 : xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
2198 [ + + ]: 7043747 : if (options & HEAP_INSERT_SPECULATIVE)
2199 : 2061 : xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
3943 heikki.linnakangas@i 2200 [ - + ]: 7043747 : Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2201 : :
2202 : : /*
2203 : : * For logical decoding, we need the tuple even if we're doing a full
2204 : : * page write, so make sure it's included even if we take a full-page
2205 : : * image. (XXX We could alternatively store a pointer into the FPW).
2206 : : */
2523 andres@anarazel.de 2207 [ + + + - : 7043747 : if (RelationIsLogicallyLogged(relation) &&
- + - - -
- + - +
+ ]
2208 [ + + ]: 249824 : !(options & HEAP_INSERT_NO_LOGICAL))
2209 : : {
3774 2210 : 249797 : xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
3943 heikki.linnakangas@i 2211 : 249797 : bufflags |= REGBUF_KEEP_DATA;
2212 : :
1855 akapila@postgresql.o 2213 [ + + ]: 249797 : if (IsToastRelation(relation))
2214 : 1786 : xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
2215 : : }
2216 : :
3943 heikki.linnakangas@i 2217 : 7043747 : XLogBeginInsert();
207 peter@eisentraut.org 2218 : 7043747 : XLogRegisterData(&xlrec, SizeOfHeapInsert);
2219 : :
3943 heikki.linnakangas@i 2220 : 7043747 : xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2221 : 7043747 : xlhdr.t_infomask = heaptup->t_data->t_infomask;
2222 : 7043747 : xlhdr.t_hoff = heaptup->t_data->t_hoff;
2223 : :
2224 : : /*
2225 : : * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2226 : : * write the whole page to the xlog, we don't need to store
2227 : : * xl_heap_header in the xlog.
2228 : : */
2229 : 7043747 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
207 peter@eisentraut.org 2230 : 7043747 : XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
2231 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
3943 heikki.linnakangas@i 2232 : 7043747 : XLogRegisterBufData(0,
3850 tgl@sss.pgh.pa.us 2233 : 7043747 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2234 : 7043747 : heaptup->t_len - SizeofHeapTupleHeader);
2235 : :
2236 : : /* filtering by origin on a row level is much more efficient */
3180 andres@anarazel.de 2237 : 7043747 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2238 : :
3943 heikki.linnakangas@i 2239 : 7043747 : recptr = XLogInsert(RM_HEAP_ID, info);
2240 : :
9018 vadim4o@yahoo.com 2241 : 7043747 : PageSetLSN(page, recptr);
2242 : : }
2243 : :
9003 tgl@sss.pgh.pa.us 2244 [ - + ]: 8389731 : END_CRIT_SECTION();
2245 : :
7099 2246 : 8389731 : UnlockReleaseBuffer(buffer);
5191 rhaas@postgresql.org 2247 [ + + ]: 8389731 : if (vmbuffer != InvalidBuffer)
2248 : 7702 : ReleaseBuffer(vmbuffer);
2249 : :
2250 : : /*
2251 : : * If tuple is cachable, mark it for invalidation from the caches in case
2252 : : * we abort. Note it is OK to do this after releasing the buffer, because
2253 : : * the heaptup data structure is all in local memory, not in the shared
2254 : : * buffer.
2255 : : */
5135 tgl@sss.pgh.pa.us 2256 : 8389731 : CacheInvalidateHeapTuple(relation, heaptup, NULL);
2257 : :
2258 : : /* Note: speculative insertions are counted too, even if aborted later */
5050 heikki.linnakangas@i 2259 : 8389731 : pgstat_count_heap_insert(relation, 1);
2260 : :
2261 : : /*
2262 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
2263 : : * back to the caller's image, too.
2264 : : */
7230 tgl@sss.pgh.pa.us 2265 [ + + ]: 8389731 : if (heaptup != tup)
2266 : : {
2267 : 18281 : tup->t_self = heaptup->t_self;
2268 : 18281 : heap_freetuple(heaptup);
2269 : : }
10651 scrappy@hub.org 2270 : 8389731 : }
2271 : :
2272 : : /*
2273 : : * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2274 : : * tuple header fields and toasts the tuple if necessary. Returns a toasted
2275 : : * version of the tuple if it was toasted, or the original tuple if not. Note
2276 : : * that in any case, the header fields are also set in the original tuple.
2277 : : */
2278 : : static HeapTuple
5050 heikki.linnakangas@i 2279 : 9948518 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2280 : : CommandId cid, int options)
2281 : : {
2282 : : /*
2283 : : * To allow parallel inserts, we need to ensure that they are safe to be
2284 : : * performed in workers. We have the infrastructure to allow parallel
2285 : : * inserts in general except for the cases where inserts generate a new
2286 : : * CommandId (eg. inserts into a table having a foreign key column).
2287 : : */
2893 rhaas@postgresql.org 2288 [ - + ]: 9948518 : if (IsParallelWorker())
3782 rhaas@postgresql.org 2289 [ # # ]:UBC 0 : ereport(ERROR,
2290 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2291 : : errmsg("cannot insert tuples in a parallel worker")));
2292 : :
5050 heikki.linnakangas@i 2293 :CBC 9948518 : tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2294 : 9948518 : tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2295 : 9948518 : tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
4276 rhaas@postgresql.org 2296 : 9948518 : HeapTupleHeaderSetXmin(tup->t_data, xid);
4661 simon@2ndQuadrant.co 2297 [ + + ]: 9948518 : if (options & HEAP_INSERT_FROZEN)
4276 rhaas@postgresql.org 2298 : 102096 : HeapTupleHeaderSetXminFrozen(tup->t_data);
2299 : :
5050 heikki.linnakangas@i 2300 : 9948518 : HeapTupleHeaderSetCmin(tup->t_data, cid);
2999 tgl@sss.pgh.pa.us 2301 : 9948518 : HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
5050 heikki.linnakangas@i 2302 : 9948518 : tup->t_tableOid = RelationGetRelid(relation);
2303 : :
2304 : : /*
2305 : : * If the new tuple is too big for storage or contains already toasted
2306 : : * out-of-line attributes from some other relation, invoke the toaster.
2307 : : */
4570 kgrittn@postgresql.o 2308 [ + + ]: 9948518 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2309 [ + + ]: 30660 : relation->rd_rel->relkind != RELKIND_MATVIEW)
2310 : : {
2311 : : /* toast table entries should never be recursively toasted */
5050 heikki.linnakangas@i 2312 [ - + ]: 30612 : Assert(!HeapTupleHasExternal(tup));
2313 : 30612 : return tup;
2314 : : }
2315 [ + + + + ]: 9917906 : else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2164 rhaas@postgresql.org 2316 : 18325 : return heap_toast_insert_or_update(relation, tup, NULL, options);
2317 : : else
5050 heikki.linnakangas@i 2318 : 9899581 : return tup;
2319 : : }
2320 : :
2321 : : /*
2322 : : * Helper for heap_multi_insert() that computes the number of entire pages
2323 : : * that inserting the remaining heaptuples requires. Used to determine how
2324 : : * much the relation needs to be extended by.
2325 : : */
2326 : : static int
884 andres@anarazel.de 2327 : 355411 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2328 : : {
2329 : 355411 : size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2330 : 355411 : int npages = 1;
2331 : :
2332 [ + + ]: 2596708 : for (int i = done; i < ntuples; i++)
2333 : : {
2334 : 2241297 : size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2335 : :
2336 [ + + ]: 2241297 : if (page_avail < tup_sz)
2337 : : {
2338 : 16345 : npages++;
2339 : 16345 : page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2340 : : }
2341 : 2241297 : page_avail -= tup_sz;
2342 : : }
2343 : :
2344 : 355411 : return npages;
2345 : : }
2346 : :
2347 : : /*
2348 : : * heap_multi_insert - insert multiple tuples into a heap
2349 : : *
2350 : : * This is like heap_insert(), but inserts multiple tuples in one operation.
2351 : : * That's faster than calling heap_insert() in a loop, because when multiple
2352 : : * tuples can be inserted on a single page, we can write just a single WAL
2353 : : * record covering all of them, and only need to lock/unlock the page once.
2354 : : *
2355 : : * Note: this leaks memory into the current memory context. You can create a
2356 : : * temporary context before calling this, if that's a problem.
2357 : : */
2358 : : void
2347 2359 : 348600 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2360 : : CommandId cid, int options, BulkInsertState bistate)
2361 : : {
5050 heikki.linnakangas@i 2362 : 348600 : TransactionId xid = GetCurrentTransactionId();
2363 : : HeapTuple *heaptuples;
2364 : : int i;
2365 : : int ndone;
2366 : : PGAlignedBlock scratch;
2367 : : Page page;
1693 tomas.vondra@postgre 2368 : 348600 : Buffer vmbuffer = InvalidBuffer;
2369 : : bool needwal;
2370 : : Size saveFreeSpace;
4288 rhaas@postgresql.org 2371 [ + + + - : 348600 : bool need_tuple_data = RelationIsLogicallyLogged(relation);
- + - - -
- + - +
+ ]
2372 [ + + + - : 348600 : bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
- + - - -
- + + - +
- - - - -
- ]
884 andres@anarazel.de 2373 : 348600 : bool starting_with_empty_page = false;
2374 : 348600 : int npages = 0;
2375 : 348600 : int npages_used = 0;
2376 : :
2377 : : /* currently not needed (thus unsupported) for heap_multi_insert() */
1044 peter@eisentraut.org 2378 [ - + ]: 348600 : Assert(!(options & HEAP_INSERT_NO_LOGICAL));
2379 : :
99 nathan@postgresql.or 2380 : 348600 : AssertHasSnapshotForToast(relation);
2381 : :
1981 noah@leadboat.com 2382 [ + + + + : 348600 : needwal = RelationNeedsWAL(relation);
+ + + + ]
513 akorotkov@postgresql 2383 [ + + ]: 348600 : saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2384 : : HEAP_DEFAULT_FILLFACTOR);
2385 : :
2386 : : /* Toast and set header data in all the slots */
5050 heikki.linnakangas@i 2387 : 348600 : heaptuples = palloc(ntuples * sizeof(HeapTuple));
2388 [ + + ]: 1907375 : for (i = 0; i < ntuples; i++)
2389 : : {
2390 : : HeapTuple tuple;
2391 : :
2347 andres@anarazel.de 2392 : 1558775 : tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2393 : 1558775 : slots[i]->tts_tableOid = RelationGetRelid(relation);
2394 : 1558775 : tuple->t_tableOid = slots[i]->tts_tableOid;
2395 : 1558775 : heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2396 : : options);
2397 : : }
2398 : :
2399 : : /*
2400 : : * We're about to do the actual inserts -- but check for conflict first,
2401 : : * to minimize the possibility of having to roll back work we've just
2402 : : * done.
2403 : : *
2404 : : * A check here does not definitively prevent a serialization anomaly;
2405 : : * that check MUST be done at least past the point of acquiring an
2406 : : * exclusive buffer content lock on every buffer that will be affected,
2407 : : * and MAY be done after all inserts are reflected in the buffers and
2408 : : * those locks are released; otherwise there is a race condition. Since
2409 : : * multiple buffers can be locked and unlocked in the loop below, and it
2410 : : * would not be feasible to identify and lock all of those buffers before
2411 : : * the loop, we must do a final check at the end.
2412 : : *
2413 : : * The check here could be omitted with no loss of correctness; it is
2414 : : * present strictly as an optimization.
2415 : : *
2416 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2417 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2418 : : * page locks are only consolidated versions of tuple locks; they do not
2419 : : * lock "gaps" as index page locks do. So we don't need to specify a
2420 : : * buffer when making the call, which makes for a faster check.
2421 : : */
2048 tmunro@postgresql.or 2422 : 348600 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2423 : :
5050 heikki.linnakangas@i 2424 : 348600 : ndone = 0;
2425 [ + + ]: 712504 : while (ndone < ntuples)
2426 : : {
2427 : : Buffer buffer;
2428 : 363904 : bool all_visible_cleared = false;
1693 tomas.vondra@postgre 2429 : 363904 : bool all_frozen_set = false;
2430 : : int nthispage;
2431 : :
4093 rhaas@postgresql.org 2432 [ - + ]: 363904 : CHECK_FOR_INTERRUPTS();
2433 : :
2434 : : /*
2435 : : * Compute number of pages needed to fit the to-be-inserted tuples in
2436 : : * the worst case. This will be used to determine how much to extend
2437 : : * the relation by in RelationGetBufferForTuple(), if needed. If we
2438 : : * filled a prior page from scratch, we can just update our last
2439 : : * computation, but if we started with a partially filled page,
2440 : : * recompute from scratch, the number of potentially required pages
2441 : : * can vary due to tuples needing to fit onto the page, page headers
2442 : : * etc.
2443 : : */
884 andres@anarazel.de 2444 [ + + + + ]: 363904 : if (ndone == 0 || !starting_with_empty_page)
2445 : : {
2446 : 355411 : npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2447 : : saveFreeSpace);
2448 : 355411 : npages_used = 0;
2449 : : }
2450 : : else
2451 : 8493 : npages_used++;
2452 : :
2453 : : /*
2454 : : * Find buffer where at least the next tuple will fit. If the page is
2455 : : * all-visible, this will also pin the requisite visibility map page.
2456 : : *
2457 : : * Also pin visibility map page if COPY FREEZE inserts tuples into an
2458 : : * empty page. See all_frozen_set below.
2459 : : */
5050 heikki.linnakangas@i 2460 : 363904 : buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2461 : : InvalidBuffer, options, bistate,
2462 : : &vmbuffer, NULL,
2463 : : npages - npages_used);
3426 kgrittn@postgresql.o 2464 : 363904 : page = BufferGetPage(buffer);
2465 : :
1693 tomas.vondra@postgre 2466 : 363904 : starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2467 : :
2468 [ + + + + ]: 363904 : if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2469 : 1661 : all_frozen_set = true;
2470 : :
2471 : : /* NO EREPORT(ERROR) from here till changes are logged */
5050 heikki.linnakangas@i 2472 : 363904 : START_CRIT_SECTION();
2473 : :
2474 : : /*
2475 : : * RelationGetBufferForTuple has ensured that the first tuple fits.
2476 : : * Put that on the page, and then as many other tuples as fit.
2477 : : */
3774 andres@anarazel.de 2478 : 363904 : RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2479 : :
2480 : : /*
2481 : : * For logical decoding we need combo CIDs to properly decode the
2482 : : * catalog.
2483 : : */
2020 michael@paquier.xyz 2484 [ + + + + ]: 363904 : if (needwal && need_cids)
2485 : 4804 : log_heap_new_cid(relation, heaptuples[ndone]);
2486 : :
4651 heikki.linnakangas@i 2487 [ + + ]: 1558775 : for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2488 : : {
5050 2489 : 1210175 : HeapTuple heaptup = heaptuples[ndone + nthispage];
2490 : :
4861 2491 [ + + ]: 1210175 : if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
5050 2492 : 15304 : break;
2493 : :
3774 andres@anarazel.de 2494 : 1194871 : RelationPutHeapTuple(relation, buffer, heaptup, false);
2495 : :
2496 : : /*
2497 : : * For logical decoding we need combo CIDs to properly decode the
2498 : : * catalog.
2499 : : */
3943 heikki.linnakangas@i 2500 [ + + + + ]: 1194871 : if (needwal && need_cids)
2501 : 4537 : log_heap_new_cid(relation, heaptup);
2502 : : }
2503 : :
2504 : : /*
2505 : : * If the page is all visible, need to clear that, unless we're only
2506 : : * going to add further frozen rows to it.
2507 : : *
2508 : : * If we're only adding already frozen rows to a previously empty
2509 : : * page, mark it as all-visible.
2510 : : */
1693 tomas.vondra@postgre 2511 [ + + + + ]: 363904 : if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2512 : : {
4839 rhaas@postgresql.org 2513 : 3872 : all_visible_cleared = true;
2514 : 3872 : PageClearAllVisible(page);
2515 : 3872 : visibilitymap_clear(relation,
2516 : : BufferGetBlockNumber(buffer),
2517 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
2518 : : }
1693 tomas.vondra@postgre 2519 [ + + ]: 360032 : else if (all_frozen_set)
2520 : 1661 : PageSetAllVisible(page);
2521 : :
2522 : : /*
2523 : : * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2524 : : */
2525 : :
5050 heikki.linnakangas@i 2526 : 363904 : MarkBufferDirty(buffer);
2527 : :
2528 : : /* XLOG stuff */
2529 [ + + ]: 363904 : if (needwal)
2530 : : {
2531 : : XLogRecPtr recptr;
2532 : : xl_heap_multi_insert *xlrec;
2533 : 359538 : uint8 info = XLOG_HEAP2_MULTI_INSERT;
2534 : : char *tupledata;
2535 : : int totaldatalen;
2562 tgl@sss.pgh.pa.us 2536 : 359538 : char *scratchptr = scratch.data;
2537 : : bool init;
3943 heikki.linnakangas@i 2538 : 359538 : int bufflags = 0;
2539 : :
2540 : : /*
2541 : : * If the page was previously empty, we can reinit the page
2542 : : * instead of restoring the whole thing.
2543 : : */
1693 tomas.vondra@postgre 2544 : 359538 : init = starting_with_empty_page;
2545 : :
2546 : : /* allocate xl_heap_multi_insert struct from the scratch area */
5050 heikki.linnakangas@i 2547 : 359538 : xlrec = (xl_heap_multi_insert *) scratchptr;
2548 : 359538 : scratchptr += SizeOfHeapMultiInsert;
2549 : :
2550 : : /*
2551 : : * Allocate offsets array. Unless we're reinitializing the page,
2552 : : * in that case the tuples are stored in order starting at
2553 : : * FirstOffsetNumber and we don't need to store the offsets
2554 : : * explicitly.
2555 : : */
2556 [ + + ]: 359538 : if (!init)
2557 : 347406 : scratchptr += nthispage * sizeof(OffsetNumber);
2558 : :
2559 : : /* the rest of the scratch space is used for tuple data */
2560 : 359538 : tupledata = scratchptr;
2561 : :
2562 : : /* check that the mutually exclusive flags are not both set */
1578 tgl@sss.pgh.pa.us 2563 [ + + - + ]: 359538 : Assert(!(all_visible_cleared && all_frozen_set));
2564 : :
1693 tomas.vondra@postgre 2565 : 359538 : xlrec->flags = 0;
2566 [ + + ]: 359538 : if (all_visible_cleared)
2567 : 3872 : xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
2568 [ + + ]: 359538 : if (all_frozen_set)
2569 : 13 : xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
2570 : :
5050 heikki.linnakangas@i 2571 : 359538 : xlrec->ntuples = nthispage;
2572 : :
2573 : : /*
2574 : : * Write out an xl_multi_insert_tuple and the tuple data itself
2575 : : * for each tuple.
2576 : : */
2577 [ + + ]: 1612906 : for (i = 0; i < nthispage; i++)
2578 : : {
2579 : 1253368 : HeapTuple heaptup = heaptuples[ndone + i];
2580 : : xl_multi_insert_tuple *tuphdr;
2581 : : int datalen;
2582 : :
2583 [ + + ]: 1253368 : if (!init)
2584 : 735036 : xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2585 : : /* xl_multi_insert_tuple needs two-byte alignment. */
2586 : 1253368 : tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2587 : 1253368 : scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2588 : :
2589 : 1253368 : tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2590 : 1253368 : tuphdr->t_infomask = heaptup->t_data->t_infomask;
2591 : 1253368 : tuphdr->t_hoff = heaptup->t_data->t_hoff;
2592 : :
2593 : : /* write bitmap [+ padding] [+ oid] + data */
3850 tgl@sss.pgh.pa.us 2594 : 1253368 : datalen = heaptup->t_len - SizeofHeapTupleHeader;
5050 heikki.linnakangas@i 2595 : 1253368 : memcpy(scratchptr,
3850 tgl@sss.pgh.pa.us 2596 : 1253368 : (char *) heaptup->t_data + SizeofHeapTupleHeader,
2597 : : datalen);
5050 heikki.linnakangas@i 2598 : 1253368 : tuphdr->datalen = datalen;
2599 : 1253368 : scratchptr += datalen;
2600 : : }
2601 : 359538 : totaldatalen = scratchptr - tupledata;
2562 tgl@sss.pgh.pa.us 2602 [ - + ]: 359538 : Assert((scratchptr - scratch.data) < BLCKSZ);
2603 : :
4288 rhaas@postgresql.org 2604 [ + + ]: 359538 : if (need_tuple_data)
3774 andres@anarazel.de 2605 : 72 : xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
2606 : :
2607 : : /*
2608 : : * Signal that this is the last xl_heap_multi_insert record
2609 : : * emitted by this call to heap_multi_insert(). Needed for logical
2610 : : * decoding so it knows when to cleanup temporary data.
2611 : : */
3943 heikki.linnakangas@i 2612 [ + + ]: 359538 : if (ndone + nthispage == ntuples)
3774 andres@anarazel.de 2613 : 348085 : xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2614 : :
5050 heikki.linnakangas@i 2615 [ + + ]: 359538 : if (init)
2616 : : {
2617 : 12132 : info |= XLOG_HEAP_INIT_PAGE;
3943 2618 : 12132 : bufflags |= REGBUF_WILL_INIT;
2619 : : }
2620 : :
2621 : : /*
2622 : : * If we're doing logical decoding, include the new tuple data
2623 : : * even if we take a full-page image of the page.
2624 : : */
2625 [ + + ]: 359538 : if (need_tuple_data)
2626 : 72 : bufflags |= REGBUF_KEEP_DATA;
2627 : :
2628 : 359538 : XLogBeginInsert();
207 peter@eisentraut.org 2629 : 359538 : XLogRegisterData(xlrec, tupledata - scratch.data);
3943 heikki.linnakangas@i 2630 : 359538 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2631 : :
2632 : 359538 : XLogRegisterBufData(0, tupledata, totaldatalen);
2633 : :
2634 : : /* filtering by origin on a row level is much more efficient */
3180 andres@anarazel.de 2635 : 359538 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2636 : :
3943 heikki.linnakangas@i 2637 : 359538 : recptr = XLogInsert(RM_HEAP2_ID, info);
2638 : :
5050 2639 : 359538 : PageSetLSN(page, recptr);
2640 : : }
2641 : :
2642 [ - + ]: 363904 : END_CRIT_SECTION();
2643 : :
2644 : : /*
2645 : : * If we've frozen everything on the page, update the visibilitymap.
2646 : : * We're already holding pin on the vmbuffer.
2647 : : */
1693 tomas.vondra@postgre 2648 [ + + ]: 363904 : if (all_frozen_set)
2649 : : {
2650 [ - + ]: 1661 : Assert(PageIsAllVisible(page));
2651 [ - + ]: 1661 : Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
2652 : :
2653 : : /*
2654 : : * It's fine to use InvalidTransactionId here - this is only used
2655 : : * when HEAP_INSERT_FROZEN is specified, which intentionally
2656 : : * violates visibility rules.
2657 : : */
2658 : 1661 : visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
2659 : : InvalidXLogRecPtr, vmbuffer,
2660 : : InvalidTransactionId,
2661 : : VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
2662 : : }
2663 : :
2664 : 363904 : UnlockReleaseBuffer(buffer);
5050 heikki.linnakangas@i 2665 : 363904 : ndone += nthispage;
2666 : :
2667 : : /*
2668 : : * NB: Only release vmbuffer after inserting all tuples - it's fairly
2669 : : * likely that we'll insert into subsequent heap pages that are likely
2670 : : * to use the same vm page.
2671 : : */
2672 : : }
2673 : :
2674 : : /* We're done with inserting all tuples, so release the last vmbuffer. */
1693 tomas.vondra@postgre 2675 [ + + ]: 348600 : if (vmbuffer != InvalidBuffer)
2676 : 3956 : ReleaseBuffer(vmbuffer);
2677 : :
2678 : : /*
2679 : : * We're done with the actual inserts. Check for conflicts again, to
2680 : : * ensure that all rw-conflicts in to these inserts are detected. Without
2681 : : * this final check, a sequential scan of the heap may have locked the
2682 : : * table after the "before" check, missing one opportunity to detect the
2683 : : * conflict, and then scanned the table before the new tuples were there,
2684 : : * missing the other chance to detect the conflict.
2685 : : *
2686 : : * For heap inserts, we only need to check for table-level SSI locks. Our
2687 : : * new tuples can't possibly conflict with existing tuple locks, and heap
2688 : : * page locks are only consolidated versions of tuple locks; they do not
2689 : : * lock "gaps" as index page locks do. So we don't need to specify a
2690 : : * buffer when making the call.
2691 : : */
2048 tmunro@postgresql.or 2692 : 348600 : CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
2693 : :
2694 : : /*
2695 : : * If tuples are cachable, mark them for invalidation from the caches in
2696 : : * case we abort. Note it is OK to do this after releasing the buffer,
2697 : : * because the heaptuples data structure is all in local memory, not in
2698 : : * the shared buffer.
2699 : : */
4300 rhaas@postgresql.org 2700 [ + + ]: 348600 : if (IsCatalogRelation(relation))
2701 : : {
5050 heikki.linnakangas@i 2702 [ + + ]: 1204505 : for (i = 0; i < ntuples; i++)
2703 : 857218 : CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2704 : : }
2705 : :
2706 : : /* copy t_self fields back to the caller's slots */
4954 2707 [ + + ]: 1907375 : for (i = 0; i < ntuples; i++)
2347 andres@anarazel.de 2708 : 1558775 : slots[i]->tts_tid = heaptuples[i]->t_self;
2709 : :
5050 heikki.linnakangas@i 2710 : 348600 : pgstat_count_heap_insert(relation, ntuples);
2711 : 348600 : }
2712 : :
2713 : : /*
2714 : : * simple_heap_insert - insert a tuple
2715 : : *
2716 : : * Currently, this routine differs from heap_insert only in supplying
2717 : : * a default command ID and not allowing access to the speedup options.
2718 : : *
2719 : : * This should be used rather than using heap_insert directly in most places
2720 : : * where we are modifying system catalogs.
2721 : : */
2722 : : void
8509 tgl@sss.pgh.pa.us 2723 : 927073 : simple_heap_insert(Relation relation, HeapTuple tup)
2724 : : {
2482 andres@anarazel.de 2725 : 927073 : heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
8509 tgl@sss.pgh.pa.us 2726 : 927073 : }
2727 : :
2728 : : /*
2729 : : * Given infomask/infomask2, compute the bits that must be saved in the
2730 : : * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2731 : : * xl_heap_lock_updated WAL records.
2732 : : *
2733 : : * See fix_infomask_from_infobits.
2734 : : */
2735 : : static uint8
4609 alvherre@alvh.no-ip. 2736 : 1869330 : compute_infobits(uint16 infomask, uint16 infomask2)
2737 : : {
2738 : : return
2739 : 1869330 : ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2740 : 1869330 : ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2741 : 1869330 : ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2742 : : /* note we ignore HEAP_XMAX_SHR_LOCK here */
2743 : 3738660 : ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2744 : : ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2745 : 1869330 : XLHL_KEYS_UPDATED : 0);
2746 : : }
2747 : :
2748 : : /*
2749 : : * Given two versions of the same t_infomask for a tuple, compare them and
2750 : : * return whether the relevant status for a tuple Xmax has changed. This is
2751 : : * used after a buffer lock has been released and reacquired: we want to ensure
2752 : : * that the tuple state continues to be the same it was when we previously
2753 : : * examined it.
2754 : : *
2755 : : * Note the Xmax field itself must be compared separately.
2756 : : */
2757 : : static inline bool
4153 2758 : 5337 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2759 : : {
4141 bruce@momjian.us 2760 : 5337 : const uint16 interesting =
2761 : : HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2762 : :
4153 alvherre@alvh.no-ip. 2763 [ + + ]: 5337 : if ((new_infomask & interesting) != (old_infomask & interesting))
2764 : 12 : return true;
2765 : :
2766 : 5325 : return false;
2767 : : }
2768 : :
2769 : : /*
2770 : : * heap_delete - delete a tuple
2771 : : *
2772 : : * See table_tuple_delete() for an explanation of the parameters, except that
2773 : : * this routine directly takes a tuple rather than a slot.
2774 : : *
2775 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2776 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2777 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2778 : : * generated by another transaction).
2779 : : */
2780 : : TM_Result
8509 tgl@sss.pgh.pa.us 2781 : 1418482 : heap_delete(Relation relation, ItemPointer tid,
2782 : : CommandId cid, Snapshot crosscheck, bool wait,
2783 : : TM_FailureData *tmfd, bool changingPart)
2784 : : {
2785 : : TM_Result result;
7660 2786 : 1418482 : TransactionId xid = GetCurrentTransactionId();
2787 : : ItemId lp;
2788 : : HeapTupleData tp;
2789 : : Page page;
2790 : : BlockNumber block;
2791 : : Buffer buffer;
5191 rhaas@postgresql.org 2792 : 1418482 : Buffer vmbuffer = InvalidBuffer;
2793 : : TransactionId new_xmax;
2794 : : uint16 new_infomask,
2795 : : new_infomask2;
7434 tgl@sss.pgh.pa.us 2796 : 1418482 : bool have_tuple_lock = false;
2797 : : bool iscombo;
6121 heikki.linnakangas@i 2798 : 1418482 : bool all_visible_cleared = false;
4141 bruce@momjian.us 2799 : 1418482 : HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
4288 rhaas@postgresql.org 2800 : 1418482 : bool old_key_copied = false;
2801 : :
10226 bruce@momjian.us 2802 [ - + ]: 1418482 : Assert(ItemPointerIsValid(tid));
2803 : :
99 nathan@postgresql.or 2804 : 1418482 : AssertHasSnapshotForToast(relation);
2805 : :
2806 : : /*
2807 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
2808 : : * Other workers might need that combo CID for visibility checks, and we
2809 : : * have no provision for broadcasting it to them.
2810 : : */
3782 rhaas@postgresql.org 2811 [ - + ]: 1418482 : if (IsInParallelMode())
3782 rhaas@postgresql.org 2812 [ # # ]:UBC 0 : ereport(ERROR,
2813 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2814 : : errmsg("cannot delete tuples during a parallel operation")));
2815 : :
5191 rhaas@postgresql.org 2816 :CBC 1418482 : block = ItemPointerGetBlockNumber(tid);
2817 : 1418482 : buffer = ReadBuffer(relation, block);
3426 kgrittn@postgresql.o 2818 : 1418482 : page = BufferGetPage(buffer);
2819 : :
2820 : : /*
2821 : : * Before locking the buffer, pin the visibility map page if it appears to
2822 : : * be necessary. Since we haven't got the lock yet, someone else might be
2823 : : * in the middle of changing this, so we'll need to recheck after we have
2824 : : * the lock.
2825 : : */
5191 rhaas@postgresql.org 2826 [ + + ]: 1418482 : if (PageIsAllVisible(page))
2827 : 246 : visibilitymap_pin(relation, block, &vmbuffer);
2828 : :
9762 vadim4o@yahoo.com 2829 : 1418482 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2830 : :
1080 jdavis@postgresql.or 2831 : 1418482 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2832 [ - + ]: 1418482 : Assert(ItemIdIsNormal(lp));
2833 : :
2834 : 1418482 : tp.t_tableOid = RelationGetRelid(relation);
2835 : 1418482 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2836 : 1418482 : tp.t_len = ItemIdGetLength(lp);
2837 : 1418482 : tp.t_self = *tid;
2838 : :
2839 : 1 : l1:
2840 : :
2841 : : /*
2842 : : * If we didn't pin the visibility map page and the page has become all
2843 : : * visible while we were busy locking the buffer, we'll have to unlock and
2844 : : * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2845 : : * unfortunate, but hopefully shouldn't happen often.
2846 : : */
5191 rhaas@postgresql.org 2847 [ + + - + ]: 1418483 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2848 : : {
5191 rhaas@postgresql.org 2849 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2850 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
2851 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2852 : : }
2853 : :
4429 rhaas@postgresql.org 2854 :CBC 1418483 : result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2855 : :
2359 andres@anarazel.de 2856 [ - + ]: 1418483 : if (result == TM_Invisible)
2857 : : {
7099 tgl@sss.pgh.pa.us 2858 :UBC 0 : UnlockReleaseBuffer(buffer);
3688 2859 [ # # ]: 0 : ereport(ERROR,
2860 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2861 : : errmsg("attempted to delete invisible tuple")));
2862 : : }
513 akorotkov@postgresql 2863 [ + + + - ]:CBC 1418483 : else if (result == TM_BeingModified && wait)
2864 : : {
2865 : : TransactionId xwait;
2866 : : uint16 infomask;
2867 : :
2868 : : /* must copy state data before unlocking buffer */
4609 alvherre@alvh.no-ip. 2869 : 40547 : xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
7434 tgl@sss.pgh.pa.us 2870 : 40547 : infomask = tp.t_data->t_infomask;
2871 : :
2872 : : /*
2873 : : * Sleep until concurrent transaction ends -- except when there's a
2874 : : * single locker and it's our own transaction. Note we don't care
2875 : : * which lock mode the locker has, because we need the strongest one.
2876 : : *
2877 : : * Before sleeping, we need to acquire tuple lock to establish our
2878 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
2879 : : * release us when we are next-in-line for the tuple.
2880 : : *
2881 : : * If we are forced to "start over" below, we keep the tuple lock;
2882 : : * this arranges that we stay at the head of the line while rechecking
2883 : : * tuple state.
2884 : : */
7436 2885 [ + + ]: 40547 : if (infomask & HEAP_XMAX_IS_MULTI)
2886 : : {
2272 alvherre@alvh.no-ip. 2887 : 8 : bool current_is_member = false;
2888 : :
3802 2889 [ + - ]: 8 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2890 : : LockTupleExclusive, ¤t_is_member))
2891 : : {
2892 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2893 : :
2894 : : /*
2895 : : * Acquire the lock, if necessary (but skip it when we're
2896 : : * requesting a lock and already have one; avoids deadlock).
2897 : : */
2272 2898 [ + + ]: 8 : if (!current_is_member)
2899 : 6 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2900 : : LockWaitBlock, &have_tuple_lock);
2901 : :
2902 : : /* wait for multixact */
3802 2903 : 8 : MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2904 : : relation, &(tp.t_self), XLTW_Delete,
2905 : : NULL);
2906 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2907 : :
2908 : : /*
2909 : : * If xwait had just locked the tuple then some other xact
2910 : : * could update this tuple before we get to this point. Check
2911 : : * for xmax change, and start over if so.
2912 : : *
2913 : : * We also must start over if we didn't pin the VM page, and
2914 : : * the page has become all visible.
2915 : : */
1080 jdavis@postgresql.or 2916 [ + - + - : 16 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ - ]
2917 [ - + ]: 16 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
3802 alvherre@alvh.no-ip. 2918 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2919 : : xwait))
3802 alvherre@alvh.no-ip. 2920 :UBC 0 : goto l1;
2921 : : }
2922 : :
2923 : : /*
2924 : : * You might think the multixact is necessarily done here, but not
2925 : : * so: it could have surviving members, namely our own xact or
2926 : : * other subxacts of this backend. It is legal for us to delete
2927 : : * the tuple in either case, however (the latter case is
2928 : : * essentially a situation of upgrading our former shared lock to
2929 : : * exclusive). We don't bother changing the on-disk hint bits
2930 : : * since we are about to overwrite the xmax altogether.
2931 : : */
2932 : : }
3802 alvherre@alvh.no-ip. 2933 [ + + ]:CBC 40539 : else if (!TransactionIdIsCurrentTransactionId(xwait))
2934 : : {
2935 : : /*
2936 : : * Wait for regular transaction to end; but first, acquire tuple
2937 : : * lock.
2938 : : */
2939 : 43 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2940 : 43 : heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
2941 : : LockWaitBlock, &have_tuple_lock);
3867 heikki.linnakangas@i 2942 : 43 : XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
7436 tgl@sss.pgh.pa.us 2943 : 39 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2944 : :
2945 : : /*
2946 : : * xwait is done, but if xwait had just locked the tuple then some
2947 : : * other xact could update this tuple before we get to this point.
2948 : : * Check for xmax change, and start over if so.
2949 : : *
2950 : : * We also must start over if we didn't pin the VM page, and the
2951 : : * page has become all visible.
2952 : : */
1080 jdavis@postgresql.or 2953 [ + - + - : 78 : if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
+ + ]
2954 [ - + ]: 77 : xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
4609 alvherre@alvh.no-ip. 2955 : 38 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2956 : : xwait))
7436 tgl@sss.pgh.pa.us 2957 : 1 : goto l1;
2958 : :
2959 : : /* Otherwise check if it committed or aborted */
6598 2960 : 38 : UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2961 : : }
2962 : :
2963 : : /*
2964 : : * We may overwrite if previous xmax aborted, or if it committed but
2965 : : * only locked the tuple without updating it.
2966 : : */
4609 alvherre@alvh.no-ip. 2967 [ + + + + ]: 81070 : if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2968 [ + + ]: 40556 : HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2969 : 28 : HeapTupleHeaderIsOnlyLocked(tp.t_data))
2359 andres@anarazel.de 2970 : 40518 : result = TM_Ok;
1657 alvherre@alvh.no-ip. 2971 [ + + ]: 24 : else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2359 andres@anarazel.de 2972 : 20 : result = TM_Updated;
2973 : : else
2974 : 4 : result = TM_Deleted;
2975 : : }
2976 : :
2977 : : /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2978 [ + + ]: 1418478 : if (result != TM_Ok)
2979 : : {
2980 [ + + + + : 58 : Assert(result == TM_SelfModified ||
- + - - ]
2981 : : result == TM_Updated ||
2982 : : result == TM_Deleted ||
2983 : : result == TM_BeingModified);
7322 tgl@sss.pgh.pa.us 2984 [ - + ]: 58 : Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2359 andres@anarazel.de 2985 [ + + - + ]: 58 : Assert(result != TM_Updated ||
2986 : : !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2987 : : }
2988 : :
648 heikki.linnakangas@i 2989 [ + + + - ]: 1418478 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
2990 : : {
2991 : : /* Perform additional check for transaction-snapshot mode RI updates */
2992 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2993 : 1 : result = TM_Updated;
2994 : : }
2995 : :
2996 [ + + ]: 1418478 : if (result != TM_Ok)
2997 : : {
2359 andres@anarazel.de 2998 : 59 : tmfd->ctid = tp.t_data->t_ctid;
2999 : 59 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
3000 [ + + ]: 59 : if (result == TM_SelfModified)
3001 : 21 : tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
3002 : : else
3003 : 38 : tmfd->cmax = InvalidCommandId;
513 akorotkov@postgresql 3004 : 59 : UnlockReleaseBuffer(buffer);
7434 tgl@sss.pgh.pa.us 3005 [ + + ]: 59 : if (have_tuple_lock)
4609 alvherre@alvh.no-ip. 3006 : 24 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
5191 rhaas@postgresql.org 3007 [ - + ]: 59 : if (vmbuffer != InvalidBuffer)
5191 rhaas@postgresql.org 3008 :UBC 0 : ReleaseBuffer(vmbuffer);
9762 vadim4o@yahoo.com 3009 :CBC 59 : return result;
3010 : : }
3011 : :
3012 : : /*
3013 : : * We're about to do the actual delete -- check for conflict first, to
3014 : : * avoid possibly having to roll back work we've just done.
3015 : : *
3016 : : * This is safe without a recheck as long as there is no possibility of
3017 : : * another process scanning the page between this check and the delete
3018 : : * being visible to the scan (i.e., an exclusive buffer content lock is
3019 : : * continuously held from this point until the tuple delete is visible).
3020 : : */
2048 tmunro@postgresql.or 3021 : 1418419 : CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
3022 : :
3023 : : /* replace cid with a combo CID if necessary */
6784 tgl@sss.pgh.pa.us 3024 : 1418405 : HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
3025 : :
3026 : : /*
3027 : : * Compute replica identity tuple before entering the critical section so
3028 : : * we don't PANIC upon a memory allocation failure.
3029 : : */
4288 rhaas@postgresql.org 3030 : 1418405 : old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
3031 : :
3032 : : /*
3033 : : * If this is the first possibly-multixact-able operation in the current
3034 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
3035 : : * certain that the transaction will never become a member of any older
3036 : : * MultiXactIds than that. (We have to do this even if we end up just
3037 : : * using our own TransactionId below, since some other backend could
3038 : : * incorporate our XID into a MultiXact immediately afterwards.)
3039 : : */
4173 heikki.linnakangas@i 3040 : 1418405 : MultiXactIdSetOldestMember();
3041 : :
3042 : 1418405 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
3043 : 1418405 : tp.t_data->t_infomask, tp.t_data->t_infomask2,
3044 : : xid, LockTupleExclusive, true,
3045 : : &new_xmax, &new_infomask, &new_infomask2);
3046 : :
9003 tgl@sss.pgh.pa.us 3047 : 1418405 : START_CRIT_SECTION();
3048 : :
3049 : : /*
3050 : : * If this transaction commits, the tuple will become DEAD sooner or
3051 : : * later. Set flag that this page is a candidate for pruning once our xid
3052 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
3053 : : * the subsequent page pruning will be a no-op and the hint will be
3054 : : * cleared.
3055 : : */
6264 3056 [ - + + + : 1418405 : PageSetPrunable(page, xid);
+ + ]
3057 : :
6121 heikki.linnakangas@i 3058 [ + + ]: 1418405 : if (PageIsAllVisible(page))
3059 : : {
3060 : 246 : all_visible_cleared = true;
3061 : 246 : PageClearAllVisible(page);
5191 rhaas@postgresql.org 3062 : 246 : visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3063 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
3064 : : }
3065 : :
3066 : : /* store transaction information of xact deleting the tuple */
4609 alvherre@alvh.no-ip. 3067 : 1418405 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3068 : 1418405 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3069 : 1418405 : tp.t_data->t_infomask |= new_infomask;
3070 : 1418405 : tp.t_data->t_infomask2 |= new_infomask2;
6561 tgl@sss.pgh.pa.us 3071 : 1418405 : HeapTupleHeaderClearHotUpdated(tp.t_data);
4609 alvherre@alvh.no-ip. 3072 : 1418405 : HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
6784 tgl@sss.pgh.pa.us 3073 : 1418405 : HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3074 : : /* Make sure there is no forward chain link in t_ctid */
8425 3075 : 1418405 : tp.t_data->t_ctid = tp.t_self;
3076 : :
3077 : : /* Signal that this is actually a move into another partition */
2709 andres@anarazel.de 3078 [ + + ]: 1418405 : if (changingPart)
3079 : 484 : HeapTupleHeaderSetMovedPartitions(tp.t_data);
3080 : :
7099 tgl@sss.pgh.pa.us 3081 : 1418405 : MarkBufferDirty(buffer);
3082 : :
3083 : : /*
3084 : : * XLOG stuff
3085 : : *
3086 : : * NB: heap_abort_speculative() uses the same xlog record and replay
3087 : : * routines.
3088 : : */
5381 rhaas@postgresql.org 3089 [ + + + + : 1418405 : if (RelationNeedsWAL(relation))
+ + + + ]
3090 : : {
3091 : : xl_heap_delete xlrec;
3092 : : xl_heap_header xlhdr;
3093 : : XLogRecPtr recptr;
3094 : :
3095 : : /*
3096 : : * For logical decode we need combo CIDs to properly decode the
3097 : : * catalog
3098 : : */
4288 3099 [ + + + - : 1355786 : if (RelationIsAccessibleInLogicalDecoding(relation))
- + - - -
- + + - +
- - - - -
- ]
3100 : 6130 : log_heap_new_cid(relation, &tp);
3101 : :
2709 andres@anarazel.de 3102 : 1355786 : xlrec.flags = 0;
3103 [ + + ]: 1355786 : if (all_visible_cleared)
3104 : 246 : xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
3105 [ + + ]: 1355786 : if (changingPart)
3106 : 484 : xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
4609 alvherre@alvh.no-ip. 3107 : 2711572 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3108 : 1355786 : tp.t_data->t_infomask2);
3943 heikki.linnakangas@i 3109 : 1355786 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
4609 alvherre@alvh.no-ip. 3110 : 1355786 : xlrec.xmax = new_xmax;
3111 : :
3943 heikki.linnakangas@i 3112 [ + + ]: 1355786 : if (old_key_tuple != NULL)
3113 : : {
3114 [ + + ]: 47018 : if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3774 andres@anarazel.de 3115 : 130 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
3116 : : else
3117 : 46888 : xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
3118 : : }
3119 : :
3943 heikki.linnakangas@i 3120 : 1355786 : XLogBeginInsert();
207 peter@eisentraut.org 3121 : 1355786 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3122 : :
3943 heikki.linnakangas@i 3123 : 1355786 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3124 : :
3125 : : /*
3126 : : * Log replica identity of the deleted tuple if there is one
3127 : : */
4288 rhaas@postgresql.org 3128 [ + + ]: 1355786 : if (old_key_tuple != NULL)
3129 : : {
3130 : 47018 : xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3131 : 47018 : xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3132 : 47018 : xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3133 : :
207 peter@eisentraut.org 3134 : 47018 : XLogRegisterData(&xlhdr, SizeOfHeapHeader);
3943 heikki.linnakangas@i 3135 : 47018 : XLogRegisterData((char *) old_key_tuple->t_data
3136 : : + SizeofHeapTupleHeader,
3137 : 47018 : old_key_tuple->t_len
3138 : : - SizeofHeapTupleHeader);
3139 : : }
3140 : :
3141 : : /* filtering by origin on a row level is much more efficient */
3180 andres@anarazel.de 3142 : 1355786 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
3143 : :
3943 heikki.linnakangas@i 3144 : 1355786 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3145 : :
6264 tgl@sss.pgh.pa.us 3146 : 1355786 : PageSetLSN(page, recptr);
3147 : : }
3148 : :
9003 3149 [ - + ]: 1418405 : END_CRIT_SECTION();
3150 : :
9000 3151 : 1418405 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3152 : :
5191 rhaas@postgresql.org 3153 [ + + ]: 1418405 : if (vmbuffer != InvalidBuffer)
3154 : 246 : ReleaseBuffer(vmbuffer);
3155 : :
3156 : : /*
3157 : : * If the tuple has toasted out-of-line attributes, we need to delete
3158 : : * those items too. We have to do this before releasing the buffer
3159 : : * because we need to look at the contents of the tuple, but it's OK to
3160 : : * release the content lock on the buffer first.
3161 : : */
4570 kgrittn@postgresql.o 3162 [ + + ]: 1418405 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
3163 [ + + ]: 2422 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3164 : : {
3165 : : /* toast table entries should never be recursively toasted */
6731 tgl@sss.pgh.pa.us 3166 [ - + ]: 2412 : Assert(!HeapTupleHasExternal(&tp));
3167 : : }
3168 [ + + ]: 1415993 : else if (HeapTupleHasExternal(&tp))
2164 rhaas@postgresql.org 3169 : 299 : heap_toast_delete(relation, &tp, false);
3170 : :
3171 : : /*
3172 : : * Mark tuple for invalidation from system caches at next command
3173 : : * boundary. We have to do this before releasing the buffer because we
3174 : : * need to look at the contents of the tuple.
3175 : : */
5135 tgl@sss.pgh.pa.us 3176 : 1418405 : CacheInvalidateHeapTuple(relation, &tp, NULL);
3177 : :
3178 : : /* Now we can release the buffer */
513 akorotkov@postgresql 3179 : 1418405 : ReleaseBuffer(buffer);
3180 : :
3181 : : /*
3182 : : * Release the lmgr tuple lock, if we had it.
3183 : : */
7434 tgl@sss.pgh.pa.us 3184 [ + + ]: 1418405 : if (have_tuple_lock)
4609 alvherre@alvh.no-ip. 3185 : 20 : UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3186 : :
6677 tgl@sss.pgh.pa.us 3187 : 1418405 : pgstat_count_heap_delete(relation);
3188 : :
4288 rhaas@postgresql.org 3189 [ + + + + ]: 1418405 : if (old_key_tuple != NULL && old_key_copied)
3190 : 46889 : heap_freetuple(old_key_tuple);
3191 : :
2359 andres@anarazel.de 3192 : 1418405 : return TM_Ok;
3193 : : }
3194 : :
3195 : : /*
3196 : : * simple_heap_delete - delete a tuple
3197 : : *
3198 : : * This routine may be used to delete a tuple when concurrent updates of
3199 : : * the target tuple are not expected (for example, because we have a lock
3200 : : * on the relation associated with the tuple). Any failure is reported
3201 : : * via ereport().
3202 : : */
3203 : : void
8992 tgl@sss.pgh.pa.us 3204 : 609049 : simple_heap_delete(Relation relation, ItemPointer tid)
3205 : : {
3206 : : TM_Result result;
3207 : : TM_FailureData tmfd;
3208 : :
8027 3209 : 609049 : result = heap_delete(relation, tid,
3210 : : GetCurrentCommandId(true), InvalidSnapshot,
3211 : : true /* wait for commit */ ,
3212 : : &tmfd, false /* changingPart */ );
8992 3213 [ - + - - : 609049 : switch (result)
- ]
3214 : : {
2359 andres@anarazel.de 3215 :UBC 0 : case TM_SelfModified:
3216 : : /* Tuple was already updated in current command? */
8083 tgl@sss.pgh.pa.us 3217 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
3218 : : break;
3219 : :
2359 andres@anarazel.de 3220 :CBC 609049 : case TM_Ok:
3221 : : /* done successfully */
8992 tgl@sss.pgh.pa.us 3222 : 609049 : break;
3223 : :
2359 andres@anarazel.de 3224 :UBC 0 : case TM_Updated:
8083 tgl@sss.pgh.pa.us 3225 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
3226 : : break;
3227 : :
2359 andres@anarazel.de 3228 : 0 : case TM_Deleted:
3229 [ # # ]: 0 : elog(ERROR, "tuple concurrently deleted");
3230 : : break;
3231 : :
8992 tgl@sss.pgh.pa.us 3232 : 0 : default:
8083 3233 [ # # ]: 0 : elog(ERROR, "unrecognized heap_delete status: %u", result);
3234 : : break;
3235 : : }
8992 tgl@sss.pgh.pa.us 3236 :CBC 609049 : }
3237 : :
3238 : : /*
3239 : : * heap_update - replace a tuple
3240 : : *
3241 : : * See table_tuple_update() for an explanation of the parameters, except that
3242 : : * this routine directly takes a tuple rather than a slot.
3243 : : *
3244 : : * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3245 : : * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3246 : : * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3247 : : * generated by another transaction).
3248 : : */
3249 : : TM_Result
9418 bruce@momjian.us 3250 : 302988 : heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
3251 : : CommandId cid, Snapshot crosscheck, bool wait,
3252 : : TM_FailureData *tmfd, LockTupleMode *lockmode,
3253 : : TU_UpdateIndexes *update_indexes)
3254 : : {
3255 : : TM_Result result;
7660 tgl@sss.pgh.pa.us 3256 : 302988 : TransactionId xid = GetCurrentTransactionId();
3257 : : Bitmapset *hot_attrs;
3258 : : Bitmapset *sum_attrs;
3259 : : Bitmapset *key_attrs;
3260 : : Bitmapset *id_attrs;
3261 : : Bitmapset *interesting_attrs;
3262 : : Bitmapset *modified_attrs;
3263 : : ItemId lp;
3264 : : HeapTupleData oldtup;
3265 : : HeapTuple heaptup;
4288 rhaas@postgresql.org 3266 : 302988 : HeapTuple old_key_tuple = NULL;
3267 : 302988 : bool old_key_copied = false;
3268 : : Page page;
3269 : : BlockNumber block;
3270 : : MultiXactStatus mxact_status;
3271 : : Buffer buffer,
3272 : : newbuf,
5191 3273 : 302988 : vmbuffer = InvalidBuffer,
3274 : 302988 : vmbuffer_new = InvalidBuffer;
3275 : : bool need_toast;
3276 : : Size newtupsize,
3277 : : pagefree;
7434 tgl@sss.pgh.pa.us 3278 : 302988 : bool have_tuple_lock = false;
3279 : : bool iscombo;
6561 3280 : 302988 : bool use_hot_update = false;
901 tomas.vondra@postgre 3281 : 302988 : bool summarized_update = false;
3282 : : bool key_intact;
6121 heikki.linnakangas@i 3283 : 302988 : bool all_visible_cleared = false;
3284 : 302988 : bool all_visible_cleared_new = false;
3285 : : bool checked_lockers;
3286 : : bool locker_remains;
1300 akapila@postgresql.o 3287 : 302988 : bool id_has_external = false;
3288 : : TransactionId xmax_new_tuple,
3289 : : xmax_old_tuple;
3290 : : uint16 infomask_old_tuple,
3291 : : infomask2_old_tuple,
3292 : : infomask_new_tuple,
3293 : : infomask2_new_tuple;
3294 : :
10226 bruce@momjian.us 3295 [ - + ]: 302988 : Assert(ItemPointerIsValid(otid));
3296 : :
3297 : : /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1580 tgl@sss.pgh.pa.us 3298 [ - + ]: 302988 : Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
3299 : : RelationGetNumberOfAttributes(relation));
3300 : :
99 nathan@postgresql.or 3301 : 302988 : AssertHasSnapshotForToast(relation);
3302 : :
3303 : : /*
3304 : : * Forbid this during a parallel operation, lest it allocate a combo CID.
3305 : : * Other workers might need that combo CID for visibility checks, and we
3306 : : * have no provision for broadcasting it to them.
3307 : : */
3782 rhaas@postgresql.org 3308 [ - + ]: 302988 : if (IsInParallelMode())
3782 rhaas@postgresql.org 3309 [ # # ]:UBC 0 : ereport(ERROR,
3310 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3311 : : errmsg("cannot update tuples during a parallel operation")));
3312 : :
3313 : : #ifdef USE_ASSERT_CHECKING
347 noah@leadboat.com 3314 :CBC 302988 : check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3315 : : #endif
3316 : :
3317 : : /*
3318 : : * Fetch the list of attributes to be checked for various operations.
3319 : : *
3320 : : * For HOT considerations, this is wasted effort if we fail to update or
3321 : : * have to put the new tuple on a different page. But we must compute the
3322 : : * list before obtaining buffer lock --- in the worst case, if we are
3323 : : * doing an update on one of the relevant system catalogs, we could
3324 : : * deadlock if we try to fetch the list later. In any case, the relcache
3325 : : * caches the data so this is usually pretty cheap.
3326 : : *
3327 : : * We also need columns used by the replica identity and columns that are
3328 : : * considered the "key" of rows in the table.
3329 : : *
3330 : : * Note that we get copies of each bitmap, so we need not worry about
3331 : : * relcache flush happening midway through.
3332 : : */
901 tomas.vondra@postgre 3333 : 302988 : hot_attrs = RelationGetIndexAttrBitmap(relation,
3334 : : INDEX_ATTR_BITMAP_HOT_BLOCKING);
3335 : 302988 : sum_attrs = RelationGetIndexAttrBitmap(relation,
3336 : : INDEX_ATTR_BITMAP_SUMMARIZED);
4288 rhaas@postgresql.org 3337 : 302988 : key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3338 : 302988 : id_attrs = RelationGetIndexAttrBitmap(relation,
3339 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
1380 pg@bowt.ie 3340 : 302988 : interesting_attrs = NULL;
3341 : 302988 : interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
901 tomas.vondra@postgre 3342 : 302988 : interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
1380 pg@bowt.ie 3343 : 302988 : interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3344 : 302988 : interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3345 : :
5191 rhaas@postgresql.org 3346 : 302988 : block = ItemPointerGetBlockNumber(otid);
3347 : : INJECTION_POINT("heap_update-before-pin", NULL);
3348 : 302988 : buffer = ReadBuffer(relation, block);
3426 kgrittn@postgresql.o 3349 : 302988 : page = BufferGetPage(buffer);
3350 : :
3351 : : /*
3352 : : * Before locking the buffer, pin the visibility map page if it appears to
3353 : : * be necessary. Since we haven't got the lock yet, someone else might be
3354 : : * in the middle of changing this, so we'll need to recheck after we have
3355 : : * the lock.
3356 : : */
5191 rhaas@postgresql.org 3357 [ + + ]: 302988 : if (PageIsAllVisible(page))
3358 : 1557 : visibilitymap_pin(relation, block, &vmbuffer);
3359 : :
9762 vadim4o@yahoo.com 3360 : 302988 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3361 : :
6264 tgl@sss.pgh.pa.us 3362 : 302988 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3363 : :
3364 : : /*
3365 : : * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3366 : : * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3367 : : * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3368 : : * of which indicates concurrent pruning.
3369 : : *
3370 : : * Failing with TM_Updated would be most accurate. However, unlike other
3371 : : * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3372 : : * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3373 : : * does matter to SQL statements UPDATE and MERGE, those SQL statements
3374 : : * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3375 : : * TM_Updated and TM_Deleted affects only the wording of error messages.
3376 : : * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3377 : : * the specification of when tmfd->ctid is valid. Second, it creates
3378 : : * error log evidence that we took this branch.
3379 : : *
3380 : : * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3381 : : * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3382 : : * unrelated row, we'll fail with "duplicate key value violates unique".
3383 : : * XXX if otid is the live, newer version of the newtup row, we'll discard
3384 : : * changes originating in versions of this catalog row after the version
3385 : : * the caller got from syscache. See syscache-update-pruned.spec.
3386 : : */
224 noah@leadboat.com 3387 [ - + ]: 302988 : if (!ItemIdIsNormal(lp))
3388 : : {
224 noah@leadboat.com 3389 [ # # ]:UBC 0 : Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
3390 : :
3391 : 0 : UnlockReleaseBuffer(buffer);
3392 [ # # ]: 0 : Assert(!have_tuple_lock);
3393 [ # # ]: 0 : if (vmbuffer != InvalidBuffer)
3394 : 0 : ReleaseBuffer(vmbuffer);
3395 : 0 : tmfd->ctid = *otid;
3396 : 0 : tmfd->xmax = InvalidTransactionId;
3397 : 0 : tmfd->cmax = InvalidCommandId;
3398 : 0 : *update_indexes = TU_None;
3399 : :
3400 : 0 : bms_free(hot_attrs);
3401 : 0 : bms_free(sum_attrs);
3402 : 0 : bms_free(key_attrs);
3403 : 0 : bms_free(id_attrs);
3404 : : /* modified_attrs not yet initialized */
3405 : 0 : bms_free(interesting_attrs);
3406 : 0 : return TM_Deleted;
3407 : : }
3408 : :
3409 : : /*
3410 : : * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3411 : : * properly.
3412 : : */
4600 alvherre@alvh.no-ip. 3413 :CBC 302988 : oldtup.t_tableOid = RelationGetRelid(relation);
6264 tgl@sss.pgh.pa.us 3414 : 302988 : oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
9780 vadim4o@yahoo.com 3415 : 302988 : oldtup.t_len = ItemIdGetLength(lp);
3416 : 302988 : oldtup.t_self = *otid;
3417 : :
3418 : : /* the new tuple is ready, except for this: */
4600 alvherre@alvh.no-ip. 3419 : 302988 : newtup->t_tableOid = RelationGetRelid(relation);
3420 : :
3421 : : /*
3422 : : * Determine columns modified by the update. Additionally, identify
3423 : : * whether any of the unmodified replica identity key attributes in the
3424 : : * old tuple is externally stored or not. This is required because for
3425 : : * such attributes the flattened value won't be WAL logged as part of the
3426 : : * new tuple so we must include it as part of the old_key_tuple. See
3427 : : * ExtractReplicaIdentity.
3428 : : */
1300 akapila@postgresql.o 3429 : 302988 : modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3430 : : id_attrs, &oldtup,
3431 : : newtup, &id_has_external);
3432 : :
3433 : : /*
3434 : : * If we're not updating any "key" column, we can grab a weaker lock type.
3435 : : * This allows for more concurrency when we are running simultaneously
3436 : : * with foreign key checks.
3437 : : *
3438 : : * Note that if a column gets detoasted while executing the update, but
3439 : : * the value ends up being the same, this test will fail and we will use
3440 : : * the stronger lock. This is acceptable; the important case to optimize
3441 : : * is updates that don't manipulate key columns, not those that
3442 : : * serendipitously arrive at the same key values.
3443 : : */
3083 alvherre@alvh.no-ip. 3444 [ + + ]: 302988 : if (!bms_overlap(modified_attrs, key_attrs))
3445 : : {
2704 simon@2ndQuadrant.co 3446 : 298858 : *lockmode = LockTupleNoKeyExclusive;
4609 alvherre@alvh.no-ip. 3447 : 298858 : mxact_status = MultiXactStatusNoKeyUpdate;
3448 : 298858 : key_intact = true;
3449 : :
3450 : : /*
3451 : : * If this is the first possibly-multixact-able operation in the
3452 : : * current transaction, set my per-backend OldestMemberMXactId
3453 : : * setting. We can be certain that the transaction will never become a
3454 : : * member of any older MultiXactIds than that. (We have to do this
3455 : : * even if we end up just using our own TransactionId below, since
3456 : : * some other backend could incorporate our XID into a MultiXact
3457 : : * immediately afterwards.)
3458 : : */
3459 : 298858 : MultiXactIdSetOldestMember();
3460 : : }
3461 : : else
3462 : : {
2704 simon@2ndQuadrant.co 3463 : 4130 : *lockmode = LockTupleExclusive;
4609 alvherre@alvh.no-ip. 3464 : 4130 : mxact_status = MultiXactStatusUpdate;
3465 : 4130 : key_intact = false;
3466 : : }
3467 : :
3468 : : /*
3469 : : * Note: beyond this point, use oldtup not otid to refer to old tuple.
3470 : : * otid may very well point at newtup->t_self, which we will overwrite
3471 : : * with the new tuple's location, so there's great risk of confusion if we
3472 : : * use otid anymore.
3473 : : */
3474 : :
9762 vadim4o@yahoo.com 3475 : 1 : l2:
4609 alvherre@alvh.no-ip. 3476 : 302989 : checked_lockers = false;
3477 : 302989 : locker_remains = false;
4429 rhaas@postgresql.org 3478 : 302989 : result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3479 : :
3480 : : /* see below about the "no wait" case */
513 akorotkov@postgresql 3481 [ + + - + ]: 302989 : Assert(result != TM_BeingModified || wait);
3482 : :
2359 andres@anarazel.de 3483 [ - + ]: 302989 : if (result == TM_Invisible)
3484 : : {
7099 tgl@sss.pgh.pa.us 3485 :UBC 0 : UnlockReleaseBuffer(buffer);
3688 3486 [ # # ]: 0 : ereport(ERROR,
3487 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3488 : : errmsg("attempted to update invisible tuple")));
3489 : : }
513 akorotkov@postgresql 3490 [ + + + - ]:CBC 302989 : else if (result == TM_BeingModified && wait)
3491 : : {
3492 : : TransactionId xwait;
3493 : : uint16 infomask;
4609 alvherre@alvh.no-ip. 3494 : 35939 : bool can_continue = false;
3495 : :
3496 : : /*
3497 : : * XXX note that we don't consider the "no wait" case here. This
3498 : : * isn't a problem currently because no caller uses that case, but it
3499 : : * should be fixed if such a caller is introduced. It wasn't a
3500 : : * problem previously because this code would always wait, but now
3501 : : * that some tuple locks do not conflict with one of the lock modes we
3502 : : * use, it is possible that this case is interesting to handle
3503 : : * specially.
3504 : : *
3505 : : * This may cause failures with third-party code that calls
3506 : : * heap_update directly.
3507 : : */
3508 : :
3509 : : /* must copy state data before unlocking buffer */
3510 : 35939 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
7434 tgl@sss.pgh.pa.us 3511 : 35939 : infomask = oldtup.t_data->t_infomask;
3512 : :
3513 : : /*
3514 : : * Now we have to do something about the existing locker. If it's a
3515 : : * multi, sleep on it; we might be awakened before it is completely
3516 : : * gone (or even not sleep at all in some cases); we need to preserve
3517 : : * it as locker, unless it is gone completely.
3518 : : *
3519 : : * If it's not a multi, we need to check for sleeping conditions
3520 : : * before actually going to sleep. If the update doesn't conflict
3521 : : * with the locks, we just continue without sleeping (but making sure
3522 : : * it is preserved).
3523 : : *
3524 : : * Before sleeping, we need to acquire tuple lock to establish our
3525 : : * priority for the tuple (see heap_lock_tuple). LockTuple will
3526 : : * release us when we are next-in-line for the tuple. Note we must
3527 : : * not acquire the tuple lock until we're sure we're going to sleep;
3528 : : * otherwise we're open for race conditions with other transactions
3529 : : * holding the tuple lock which sleep on us.
3530 : : *
3531 : : * If we are forced to "start over" below, we keep the tuple lock;
3532 : : * this arranges that we stay at the head of the line while rechecking
3533 : : * tuple state.
3534 : : */
7436 3535 [ + + ]: 35939 : if (infomask & HEAP_XMAX_IS_MULTI)
3536 : : {
3537 : : TransactionId update_xact;
3538 : : int remain;
2272 alvherre@alvh.no-ip. 3539 : 60 : bool current_is_member = false;
3540 : :
3802 3541 [ + + ]: 60 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3542 : : *lockmode, ¤t_is_member))
3543 : : {
3544 : 8 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3545 : :
3546 : : /*
3547 : : * Acquire the lock, if necessary (but skip it when we're
3548 : : * requesting a lock and already have one; avoids deadlock).
3549 : : */
2272 3550 [ - + ]: 8 : if (!current_is_member)
2272 alvherre@alvh.no-ip. 3551 :UBC 0 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3552 : : LockWaitBlock, &have_tuple_lock);
3553 : :
3554 : : /* wait for multixact */
3802 alvherre@alvh.no-ip. 3555 :CBC 8 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3556 : : relation, &oldtup.t_self, XLTW_Update,
3557 : : &remain);
3558 : 8 : checked_lockers = true;
3559 : 8 : locker_remains = remain != 0;
3560 : 8 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3561 : :
3562 : : /*
3563 : : * If xwait had just locked the tuple then some other xact
3564 : : * could update this tuple before we get to this point. Check
3565 : : * for xmax change, and start over if so.
3566 : : */
3567 [ + - ]: 8 : if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3568 [ - + ]: 8 : infomask) ||
2999 tgl@sss.pgh.pa.us 3569 : 8 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3570 : : xwait))
3802 alvherre@alvh.no-ip. 3571 :UBC 0 : goto l2;
3572 : : }
3573 : :
3574 : : /*
3575 : : * Note that the multixact may not be done by now. It could have
3576 : : * surviving members; our own xact or other subxacts of this
3577 : : * backend, and also any other concurrent transaction that locked
3578 : : * the tuple with LockTupleKeyShare if we only got
3579 : : * LockTupleNoKeyExclusive. If this is the case, we have to be
3580 : : * careful to mark the updated tuple with the surviving members in
3581 : : * Xmax.
3582 : : *
3583 : : * Note that there could have been another update in the
3584 : : * MultiXact. In that case, we need to check whether it committed
3585 : : * or aborted. If it aborted we are safe to update it again;
3586 : : * otherwise there is an update conflict, and we have to return
3587 : : * TableTuple{Deleted, Updated} below.
3588 : : *
3589 : : * In the LockTupleExclusive case, we still need to preserve the
3590 : : * surviving members: those would include the tuple locks we had
3591 : : * before this one, which are important to keep in case this
3592 : : * subxact aborts.
3593 : : */
4609 alvherre@alvh.no-ip. 3594 [ + + ]:CBC 60 : if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3595 : 8 : update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3596 : : else
3802 3597 : 52 : update_xact = InvalidTransactionId;
3598 : :
3599 : : /*
3600 : : * There was no UPDATE in the MultiXact; or it aborted. No
3601 : : * TransactionIdIsInProgress() call needed here, since we called
3602 : : * MultiXactIdWait() above.
3603 : : */
4609 3604 [ + + + + ]: 68 : if (!TransactionIdIsValid(update_xact) ||
3605 : 8 : TransactionIdDidAbort(update_xact))
3606 : 53 : can_continue = true;
3607 : : }
3802 3608 [ + + ]: 35879 : else if (TransactionIdIsCurrentTransactionId(xwait))
3609 : : {
3610 : : /*
3611 : : * The only locker is ourselves; we can avoid grabbing the tuple
3612 : : * lock here, but must preserve our locking information.
3613 : : */
3614 : 35784 : checked_lockers = true;
3615 : 35784 : locker_remains = true;
3616 : 35784 : can_continue = true;
3617 : : }
3618 [ + + + + ]: 95 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3619 : : {
3620 : : /*
3621 : : * If it's just a key-share locker, and we're not changing the key
3622 : : * columns, we don't need to wait for it to end; but we need to
3623 : : * preserve it as locker.
3624 : : */
3625 : 29 : checked_lockers = true;
3626 : 29 : locker_remains = true;
3627 : 29 : can_continue = true;
3628 : : }
3629 : : else
3630 : : {
3631 : : /*
3632 : : * Wait for regular transaction to end; but first, acquire tuple
3633 : : * lock.
3634 : : */
3635 : 66 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2704 simon@2ndQuadrant.co 3636 : 66 : heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3637 : : LockWaitBlock, &have_tuple_lock);
3802 alvherre@alvh.no-ip. 3638 : 66 : XactLockTableWait(xwait, relation, &oldtup.t_self,
3639 : : XLTW_Update);
3640 : 66 : checked_lockers = true;
3641 : 66 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3642 : :
3643 : : /*
3644 : : * xwait is done, but if xwait had just locked the tuple then some
3645 : : * other xact could update this tuple before we get to this point.
3646 : : * Check for xmax change, and start over if so.
3647 : : */
3648 [ + + - + ]: 131 : if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3649 : 65 : !TransactionIdEquals(xwait,
3650 : : HeapTupleHeaderGetRawXmax(oldtup.t_data)))
3651 : 1 : goto l2;
3652 : :
3653 : : /* Otherwise check if it committed or aborted */
3654 : 65 : UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3655 [ + + ]: 65 : if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
4609 3656 : 15 : can_continue = true;
3657 : : }
3658 : :
2359 andres@anarazel.de 3659 [ + + ]: 35938 : if (can_continue)
3660 : 35881 : result = TM_Ok;
1657 alvherre@alvh.no-ip. 3661 [ + + ]: 57 : else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
2359 andres@anarazel.de 3662 : 52 : result = TM_Updated;
3663 : : else
3664 : 5 : result = TM_Deleted;
3665 : : }
3666 : :
3667 : : /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3668 [ + + ]: 302988 : if (result != TM_Ok)
3669 : : {
3670 [ + + + + : 153 : Assert(result == TM_SelfModified ||
- + - - ]
3671 : : result == TM_Updated ||
3672 : : result == TM_Deleted ||
3673 : : result == TM_BeingModified);
7322 tgl@sss.pgh.pa.us 3674 [ - + ]: 153 : Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
2359 andres@anarazel.de 3675 [ + + - + ]: 153 : Assert(result != TM_Updated ||
3676 : : !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3677 : : }
3678 : :
648 heikki.linnakangas@i 3679 [ + + + - ]: 302988 : if (crosscheck != InvalidSnapshot && result == TM_Ok)
3680 : : {
3681 : : /* Perform additional check for transaction-snapshot mode RI updates */
3682 [ + - ]: 1 : if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3683 : 1 : result = TM_Updated;
3684 : : }
3685 : :
3686 [ + + ]: 302988 : if (result != TM_Ok)
3687 : : {
2359 andres@anarazel.de 3688 : 154 : tmfd->ctid = oldtup.t_data->t_ctid;
3689 : 154 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3690 [ + + ]: 154 : if (result == TM_SelfModified)
3691 : 52 : tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3692 : : else
3693 : 102 : tmfd->cmax = InvalidCommandId;
513 akorotkov@postgresql 3694 : 154 : UnlockReleaseBuffer(buffer);
7434 tgl@sss.pgh.pa.us 3695 [ + + ]: 154 : if (have_tuple_lock)
2704 simon@2ndQuadrant.co 3696 : 50 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
5191 rhaas@postgresql.org 3697 [ - + ]: 154 : if (vmbuffer != InvalidBuffer)
5191 rhaas@postgresql.org 3698 :UBC 0 : ReleaseBuffer(vmbuffer);
901 tomas.vondra@postgre 3699 :CBC 154 : *update_indexes = TU_None;
3700 : :
6561 tgl@sss.pgh.pa.us 3701 : 154 : bms_free(hot_attrs);
901 tomas.vondra@postgre 3702 : 154 : bms_free(sum_attrs);
4609 alvherre@alvh.no-ip. 3703 : 154 : bms_free(key_attrs);
3300 tgl@sss.pgh.pa.us 3704 : 154 : bms_free(id_attrs);
3083 alvherre@alvh.no-ip. 3705 : 154 : bms_free(modified_attrs);
3706 : 154 : bms_free(interesting_attrs);
9762 vadim4o@yahoo.com 3707 : 154 : return result;
3708 : : }
3709 : :
3710 : : /*
3711 : : * If we didn't pin the visibility map page and the page has become all
3712 : : * visible while we were busy locking the buffer, or during some
3713 : : * subsequent window during which we had it unlocked, we'll have to unlock
3714 : : * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3715 : : * bit unfortunate, especially since we'll now have to recheck whether the
3716 : : * tuple has been locked or updated under us, but hopefully it won't
3717 : : * happen very often.
3718 : : */
5185 rhaas@postgresql.org 3719 [ + + - + ]: 302834 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3720 : : {
5185 rhaas@postgresql.org 3721 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3722 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
3723 : 0 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5093 3724 : 0 : goto l2;
3725 : : }
3726 : :
3727 : : /* Fill in transaction status data */
3728 : :
3729 : : /*
3730 : : * If the tuple we're updating is locked, we need to preserve the locking
3731 : : * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3732 : : */
4609 alvherre@alvh.no-ip. 3733 :CBC 302834 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3734 : 302834 : oldtup.t_data->t_infomask,
3735 : 302834 : oldtup.t_data->t_infomask2,
3736 : : xid, *lockmode, true,
3737 : : &xmax_old_tuple, &infomask_old_tuple,
3738 : : &infomask2_old_tuple);
3739 : :
3740 : : /*
3741 : : * And also prepare an Xmax value for the new copy of the tuple. If there
3742 : : * was no xmax previously, or there was one but all lockers are now gone,
3743 : : * then use InvalidTransactionId; otherwise, get the xmax from the old
3744 : : * tuple. (In rare cases that might also be InvalidTransactionId and yet
3745 : : * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3746 : : */
3747 [ + + + - ]: 338700 : if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3361 3748 [ + + ]: 71732 : HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
4609 3749 [ - + ]: 35814 : (checked_lockers && !locker_remains))
3750 : 266968 : xmax_new_tuple = InvalidTransactionId;
3751 : : else
3752 : 35866 : xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3753 : :
3754 [ + + ]: 302834 : if (!TransactionIdIsValid(xmax_new_tuple))
3755 : : {
3756 : 266968 : infomask_new_tuple = HEAP_XMAX_INVALID;
3757 : 266968 : infomask2_new_tuple = 0;
3758 : : }
3759 : : else
3760 : : {
3761 : : /*
3762 : : * If we found a valid Xmax for the new tuple, then the infomask bits
3763 : : * to use on the new tuple depend on what was there on the old one.
3764 : : * Note that since we're doing an update, the only possibility is that
3765 : : * the lockers had FOR KEY SHARE lock.
3766 : : */
3767 [ + + ]: 35866 : if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3768 : : {
3769 : 53 : GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3770 : : &infomask2_new_tuple);
3771 : : }
3772 : : else
3773 : : {
3774 : 35813 : infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3775 : 35813 : infomask2_new_tuple = 0;
3776 : : }
3777 : : }
3778 : :
3779 : : /*
3780 : : * Prepare the new tuple with the appropriate initial values of Xmin and
3781 : : * Xmax, as well as initial infomask bits as computed above.
3782 : : */
9780 vadim4o@yahoo.com 3783 : 302834 : newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
6561 tgl@sss.pgh.pa.us 3784 : 302834 : newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
7660 3785 : 302834 : HeapTupleHeaderSetXmin(newtup->t_data, xid);
8484 bruce@momjian.us 3786 : 302834 : HeapTupleHeaderSetCmin(newtup->t_data, cid);
4609 alvherre@alvh.no-ip. 3787 : 302834 : newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3788 : 302834 : newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3789 : 302834 : HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3790 : :
3791 : : /*
3792 : : * Replace cid with a combo CID if necessary. Note that we already put
3793 : : * the plain cid into the new tuple.
3794 : : */
6784 tgl@sss.pgh.pa.us 3795 : 302834 : HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3796 : :
3797 : : /*
3798 : : * If the toaster needs to be activated, OR if the new tuple will not fit
3799 : : * on the same page as the old, then we need to release the content lock
3800 : : * (but not the pin!) on the old tuple's buffer while we are off doing
3801 : : * TOAST and/or table-file-extension work. We must mark the old tuple to
3802 : : * show that it's locked, else other processes may try to update it
3803 : : * themselves.
3804 : : *
3805 : : * We need to invoke the toaster if there are already any out-of-line
3806 : : * toasted values present, or if the new tuple is over-threshold.
3807 : : */
4570 kgrittn@postgresql.o 3808 [ - + ]: 302834 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
4570 kgrittn@postgresql.o 3809 [ # # ]:UBC 0 : relation->rd_rel->relkind != RELKIND_MATVIEW)
3810 : : {
3811 : : /* toast table entries should never be recursively toasted */
6731 tgl@sss.pgh.pa.us 3812 [ # # ]: 0 : Assert(!HeapTupleHasExternal(&oldtup));
3813 [ # # ]: 0 : Assert(!HeapTupleHasExternal(newtup));
3814 : 0 : need_toast = false;
3815 : : }
3816 : : else
6731 tgl@sss.pgh.pa.us 3817 [ + + ]:CBC 908141 : need_toast = (HeapTupleHasExternal(&oldtup) ||
3818 [ + + ]: 605307 : HeapTupleHasExternal(newtup) ||
3819 [ + + ]: 302449 : newtup->t_len > TOAST_TUPLE_THRESHOLD);
3820 : :
6264 3821 : 302834 : pagefree = PageGetHeapFreeSpace(page);
3822 : :
6789 3823 : 302834 : newtupsize = MAXALIGN(newtup->t_len);
3824 : :
8879 3825 [ + + + + ]: 302834 : if (need_toast || newtupsize > pagefree)
9130 vadim4o@yahoo.com 3826 : 149313 : {
3827 : : TransactionId xmax_lock_old_tuple;
3828 : : uint16 infomask_lock_old_tuple,
3829 : : infomask2_lock_old_tuple;
3337 andres@anarazel.de 3830 : 149313 : bool cleared_all_frozen = false;
3831 : :
3832 : : /*
3833 : : * To prevent concurrent sessions from updating the tuple, we have to
3834 : : * temporarily mark it locked, while we release the page-level lock.
3835 : : *
3836 : : * To satisfy the rule that any xid potentially appearing in a buffer
3837 : : * written out to disk, we unfortunately have to WAL log this
3838 : : * temporary modification. We can reuse xl_heap_lock for this
3839 : : * purpose. If we crash/error before following through with the
3840 : : * actual update, xmax will be of an aborted transaction, allowing
3841 : : * other sessions to proceed.
3842 : : */
3843 : :
3844 : : /*
3845 : : * Compute xmax / infomask appropriate for locking the tuple. This has
3846 : : * to be done separately from the combo that's going to be used for
3847 : : * updating, because the potentially created multixact would otherwise
3848 : : * be wrong.
3849 : : */
3340 3850 : 149313 : compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3851 : 149313 : oldtup.t_data->t_infomask,
3852 : 149313 : oldtup.t_data->t_infomask2,
3853 : : xid, *lockmode, false,
3854 : : &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3855 : : &infomask2_lock_old_tuple);
3856 : :
3857 [ - + ]: 149313 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3858 : :
3859 : 149313 : START_CRIT_SECTION();
3860 : :
3861 : : /* Clear obsolete visibility flags ... */
4609 alvherre@alvh.no-ip. 3862 : 149313 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3863 : 149313 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6561 tgl@sss.pgh.pa.us 3864 : 149313 : HeapTupleClearHotUpdated(&oldtup);
3865 : : /* ... and store info about transaction updating this tuple */
3340 andres@anarazel.de 3866 [ - + ]: 149313 : Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3867 : 149313 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3868 : 149313 : oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3869 : 149313 : oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
6784 tgl@sss.pgh.pa.us 3870 : 149313 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3871 : :
3872 : : /* temporarily make it look not-updated, but locked */
7230 3873 : 149313 : oldtup.t_data->t_ctid = oldtup.t_self;
3874 : :
3875 : : /*
3876 : : * Clear all-frozen bit on visibility map if needed. We could
3877 : : * immediately reset ALL_VISIBLE, but given that the WAL logging
3878 : : * overhead would be unchanged, that doesn't seem necessarily
3879 : : * worthwhile.
3880 : : */
1607 3881 [ + + + + ]: 150203 : if (PageIsAllVisible(page) &&
3337 andres@anarazel.de 3882 : 890 : visibilitymap_clear(relation, block, vmbuffer,
3883 : : VISIBILITYMAP_ALL_FROZEN))
3884 : 721 : cleared_all_frozen = true;
3885 : :
3340 3886 : 149313 : MarkBufferDirty(buffer);
3887 : :
3888 [ + + + + : 149313 : if (RelationNeedsWAL(relation))
+ - + + ]
3889 : : {
3890 : : xl_heap_lock xlrec;
3891 : : XLogRecPtr recptr;
3892 : :
3893 : 139182 : XLogBeginInsert();
3894 : 139182 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3895 : :
3896 : 139182 : xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
879 pg@bowt.ie 3897 : 139182 : xlrec.xmax = xmax_lock_old_tuple;
3340 andres@anarazel.de 3898 : 278364 : xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3899 : 139182 : oldtup.t_data->t_infomask2);
3337 3900 : 139182 : xlrec.flags =
3901 : 139182 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
207 peter@eisentraut.org 3902 : 139182 : XLogRegisterData(&xlrec, SizeOfHeapLock);
3340 andres@anarazel.de 3903 : 139182 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3904 : 139182 : PageSetLSN(page, recptr);
3905 : : }
3906 : :
3907 [ - + ]: 149313 : END_CRIT_SECTION();
3908 : :
9130 vadim4o@yahoo.com 3909 : 149313 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3910 : :
3911 : : /*
3912 : : * Let the toaster do its thing, if needed.
3913 : : *
3914 : : * Note: below this point, heaptup is the data we actually intend to
3915 : : * store into the relation; newtup is the caller's original untoasted
3916 : : * data.
3917 : : */
9000 tgl@sss.pgh.pa.us 3918 [ + + ]: 149313 : if (need_toast)
3919 : : {
3920 : : /* Note we always use WAL and FSM during updates */
2164 rhaas@postgresql.org 3921 : 1689 : heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
7230 tgl@sss.pgh.pa.us 3922 : 1689 : newtupsize = MAXALIGN(heaptup->t_len);
3923 : : }
3924 : : else
3925 : 147624 : heaptup = newtup;
3926 : :
3927 : : /*
3928 : : * Now, do we need a new page for the tuple, or not? This is a bit
3929 : : * tricky since someone else could have added tuples to the page while
3930 : : * we weren't looking. We have to recheck the available space after
3931 : : * reacquiring the buffer lock. But don't bother to do that if the
3932 : : * former amount of free space is still not enough; it's unlikely
3933 : : * there's more free now than before.
3934 : : *
3935 : : * What's more, if we need to get a new page, we will need to acquire
3936 : : * buffer locks on both old and new pages. To avoid deadlock against
3937 : : * some other backend trying to get the same two locks in the other
3938 : : * order, we must be consistent about the order we get the locks in.
3939 : : * We use the rule "lock the lower-numbered page of the relation
3940 : : * first". To implement this, we must do RelationGetBufferForTuple
3941 : : * while not holding the lock on the old page, and we must rely on it
3942 : : * to get the locks on both pages in the correct order.
3943 : : *
3944 : : * Another consideration is that we need visibility map page pin(s) if
3945 : : * we will have to clear the all-visible flag on either page. If we
3946 : : * call RelationGetBufferForTuple, we rely on it to acquire any such
3947 : : * pins; but if we don't, we have to handle that here. Hence we need
3948 : : * a loop.
3949 : : */
3950 : : for (;;)
3951 : : {
1607 3952 [ + + ]: 149313 : if (newtupsize > pagefree)
3953 : : {
3954 : : /* It doesn't fit, must use RelationGetBufferForTuple. */
3955 : 148779 : newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3956 : : buffer, 0, NULL,
3957 : : &vmbuffer_new, &vmbuffer,
3958 : : 0);
3959 : : /* We're all done. */
3960 : 148779 : break;
3961 : : }
3962 : : /* Acquire VM page pin if needed and we don't have it. */
3963 [ + + - + ]: 534 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
1607 tgl@sss.pgh.pa.us 3964 :UBC 0 : visibilitymap_pin(relation, block, &vmbuffer);
3965 : : /* Re-acquire the lock on the old tuple's page. */
8879 tgl@sss.pgh.pa.us 3966 :CBC 534 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3967 : : /* Re-check using the up-to-date free space */
6264 3968 : 534 : pagefree = PageGetHeapFreeSpace(page);
1607 3969 [ + - ]: 534 : if (newtupsize > pagefree ||
3970 [ + + - + ]: 534 : (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3971 : : {
3972 : : /*
3973 : : * Rats, it doesn't fit anymore, or somebody just now set the
3974 : : * all-visible flag. We must now unlock and loop to avoid
3975 : : * deadlock. Fortunately, this path should seldom be taken.
3976 : : */
8879 tgl@sss.pgh.pa.us 3977 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3978 : : }
3979 : : else
3980 : : {
3981 : : /* We're all done. */
8879 tgl@sss.pgh.pa.us 3982 :CBC 534 : newbuf = buffer;
1607 3983 : 534 : break;
3984 : : }
3985 : : }
3986 : : }
3987 : : else
3988 : : {
3989 : : /* No TOAST work needed, and it'll fit on same page */
9000 3990 : 153521 : newbuf = buffer;
7230 3991 : 153521 : heaptup = newtup;
3992 : : }
3993 : :
3994 : : /*
3995 : : * We're about to do the actual update -- check for conflict first, to
3996 : : * avoid possibly having to roll back work we've just done.
3997 : : *
3998 : : * This is safe without a recheck as long as there is no possibility of
3999 : : * another process scanning the pages between this check and the update
4000 : : * being visible to the scan (i.e., exclusive buffer content lock(s) are
4001 : : * continuously held from this point until the tuple update is visible).
4002 : : *
4003 : : * For the new tuple the only check needed is at the relation level, but
4004 : : * since both tuples are in the same relation and the check for oldtup
4005 : : * will include checking the relation level, there is no benefit to a
4006 : : * separate check for the new tuple.
4007 : : */
1607 tmunro@postgresql.or 4008 : 302834 : CheckForSerializableConflictIn(relation, &oldtup.t_self,
4009 : : BufferGetBlockNumber(buffer));
4010 : :
4011 : : /*
4012 : : * At this point newbuf and buffer are both pinned and locked, and newbuf
4013 : : * has enough space for the new tuple. If they are the same buffer, only
4014 : : * one pin is held.
4015 : : */
4016 : :
6561 tgl@sss.pgh.pa.us 4017 [ + + ]: 302822 : if (newbuf == buffer)
4018 : : {
4019 : : /*
4020 : : * Since the new tuple is going into the same page, we might be able
4021 : : * to do a HOT update. Check if any of the index columns have been
4022 : : * changed.
4023 : : */
1380 pg@bowt.ie 4024 [ + + ]: 154043 : if (!bms_overlap(modified_attrs, hot_attrs))
4025 : : {
6561 tgl@sss.pgh.pa.us 4026 : 142118 : use_hot_update = true;
4027 : :
4028 : : /*
4029 : : * If none of the columns that are used in hot-blocking indexes
4030 : : * were updated, we can apply HOT, but we do still need to check
4031 : : * if we need to update the summarizing indexes, and update those
4032 : : * indexes if the columns were updated, or we may fail to detect
4033 : : * e.g. value bound changes in BRIN minmax indexes.
4034 : : */
901 tomas.vondra@postgre 4035 [ + + ]: 142118 : if (bms_overlap(modified_attrs, sum_attrs))
4036 : 1641 : summarized_update = true;
4037 : : }
4038 : : }
4039 : : else
4040 : : {
4041 : : /* Set a hint that the old page could use prune/defrag */
6264 tgl@sss.pgh.pa.us 4042 : 148779 : PageSetFull(page);
4043 : : }
4044 : :
4045 : : /*
4046 : : * Compute replica identity tuple before entering the critical section so
4047 : : * we don't PANIC upon a memory allocation failure.
4048 : : * ExtractReplicaIdentity() will return NULL if nothing needs to be
4049 : : * logged. Pass old key required as true only if the replica identity key
4050 : : * columns are modified or it has external data.
4051 : : */
3083 alvherre@alvh.no-ip. 4052 : 302822 : old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
1300 akapila@postgresql.o 4053 [ + + + + ]: 302822 : bms_overlap(modified_attrs, id_attrs) ||
4054 : : id_has_external,
4055 : : &old_key_copied);
4056 : :
4057 : : /* NO EREPORT(ERROR) from here till changes are logged */
9003 tgl@sss.pgh.pa.us 4058 : 302822 : START_CRIT_SECTION();
4059 : :
4060 : : /*
4061 : : * If this transaction commits, the old tuple will become DEAD sooner or
4062 : : * later. Set flag that this page is a candidate for pruning once our xid
4063 : : * falls below the OldestXmin horizon. If the transaction finally aborts,
4064 : : * the subsequent page pruning will be a no-op and the hint will be
4065 : : * cleared.
4066 : : *
4067 : : * XXX Should we set hint on newbuf as well? If the transaction aborts,
4068 : : * there would be a prunable tuple in the newbuf; but for now we choose
4069 : : * not to optimize for aborts. Note that heap_xlog_update must be kept in
4070 : : * sync if this decision changes.
4071 : : */
6264 4072 [ - + + + : 302822 : PageSetPrunable(page, xid);
+ + ]
4073 : :
6561 4074 [ + + ]: 302822 : if (use_hot_update)
4075 : : {
4076 : : /* Mark the old tuple as HOT-updated */
4077 : 142118 : HeapTupleSetHotUpdated(&oldtup);
4078 : : /* And mark the new tuple as heap-only */
4079 : 142118 : HeapTupleSetHeapOnly(heaptup);
4080 : : /* Mark the caller's copy too, in case different from heaptup */
4081 : 142118 : HeapTupleSetHeapOnly(newtup);
4082 : : }
4083 : : else
4084 : : {
4085 : : /* Make sure tuples are correctly marked as not-HOT */
4086 : 160704 : HeapTupleClearHotUpdated(&oldtup);
4087 : 160704 : HeapTupleClearHeapOnly(heaptup);
4088 : 160704 : HeapTupleClearHeapOnly(newtup);
4089 : : }
4090 : :
2999 4091 : 302822 : RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4092 : :
4093 : :
4094 : : /* Clear obsolete visibility flags, possibly set by ourselves above... */
3340 andres@anarazel.de 4095 : 302822 : oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4096 : 302822 : oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4097 : : /* ... and store info about transaction updating this tuple */
4098 [ - + ]: 302822 : Assert(TransactionIdIsValid(xmax_old_tuple));
4099 : 302822 : HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4100 : 302822 : oldtup.t_data->t_infomask |= infomask_old_tuple;
4101 : 302822 : oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4102 : 302822 : HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4103 : :
4104 : : /* record address of new tuple in t_ctid of old one */
7230 tgl@sss.pgh.pa.us 4105 : 302822 : oldtup.t_data->t_ctid = heaptup->t_self;
4106 : :
4107 : : /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
3426 kgrittn@postgresql.o 4108 [ + + ]: 302822 : if (PageIsAllVisible(BufferGetPage(buffer)))
4109 : : {
5857 tgl@sss.pgh.pa.us 4110 : 1557 : all_visible_cleared = true;
3426 kgrittn@postgresql.o 4111 : 1557 : PageClearAllVisible(BufferGetPage(buffer));
5185 rhaas@postgresql.org 4112 : 1557 : visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
4113 : : vmbuffer, VISIBILITYMAP_VALID_BITS);
4114 : : }
3426 kgrittn@postgresql.o 4115 [ + + + + ]: 302822 : if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
4116 : : {
5857 tgl@sss.pgh.pa.us 4117 : 1003 : all_visible_cleared_new = true;
3426 kgrittn@postgresql.o 4118 : 1003 : PageClearAllVisible(BufferGetPage(newbuf));
5185 rhaas@postgresql.org 4119 : 1003 : visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
4120 : : vmbuffer_new, VISIBILITYMAP_VALID_BITS);
4121 : : }
4122 : :
7099 tgl@sss.pgh.pa.us 4123 [ + + ]: 302822 : if (newbuf != buffer)
4124 : 148779 : MarkBufferDirty(newbuf);
4125 : 302822 : MarkBufferDirty(buffer);
4126 : :
4127 : : /* XLOG stuff */
5381 rhaas@postgresql.org 4128 [ + + + + : 302822 : if (RelationNeedsWAL(relation))
+ + + + ]
4129 : : {
4130 : : XLogRecPtr recptr;
4131 : :
4132 : : /*
4133 : : * For logical decoding we need combo CIDs to properly decode the
4134 : : * catalog.
4135 : : */
4288 4136 [ + + + - : 291460 : if (RelationIsAccessibleInLogicalDecoding(relation))
- + - - -
- + + - +
- - - - -
- ]
4137 : : {
4138 : 2530 : log_heap_new_cid(relation, &oldtup);
4139 : 2530 : log_heap_new_cid(relation, heaptup);
4140 : : }
4141 : :
4142 : 291460 : recptr = log_heap_update(relation, buffer,
4143 : : newbuf, &oldtup, heaptup,
4144 : : old_key_tuple,
4145 : : all_visible_cleared,
4146 : : all_visible_cleared_new);
9196 vadim4o@yahoo.com 4147 [ + + ]: 291460 : if (newbuf != buffer)
4148 : : {
3426 kgrittn@postgresql.o 4149 : 138654 : PageSetLSN(BufferGetPage(newbuf), recptr);
4150 : : }
4151 : 291460 : PageSetLSN(BufferGetPage(buffer), recptr);
4152 : : }
4153 : :
9003 tgl@sss.pgh.pa.us 4154 [ - + ]: 302822 : END_CRIT_SECTION();
4155 : :
9196 vadim4o@yahoo.com 4156 [ + + ]: 302822 : if (newbuf != buffer)
4157 : 148779 : LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
9762 4158 : 302822 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4159 : :
4160 : : /*
4161 : : * Mark old tuple for invalidation from system caches at next command
4162 : : * boundary, and mark the new tuple for invalidation in case we abort. We
4163 : : * have to do this before releasing the buffer because oldtup is in the
4164 : : * buffer. (heaptup is all in local memory, but it's necessary to process
4165 : : * both tuple versions in one call to inval.c so we can avoid redundant
4166 : : * sinval messages.)
4167 : : */
5135 tgl@sss.pgh.pa.us 4168 : 302822 : CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4169 : :
4170 : : /* Now we can release the buffer(s) */
9008 4171 [ + + ]: 302822 : if (newbuf != buffer)
7099 4172 : 148779 : ReleaseBuffer(newbuf);
513 akorotkov@postgresql 4173 : 302822 : ReleaseBuffer(buffer);
5191 rhaas@postgresql.org 4174 [ + + ]: 302822 : if (BufferIsValid(vmbuffer_new))
4175 : 1006 : ReleaseBuffer(vmbuffer_new);
4176 [ + + ]: 302822 : if (BufferIsValid(vmbuffer))
4177 : 1557 : ReleaseBuffer(vmbuffer);
4178 : :
4179 : : /*
4180 : : * Release the lmgr tuple lock, if we had it.
4181 : : */
7434 tgl@sss.pgh.pa.us 4182 [ + + ]: 302822 : if (have_tuple_lock)
2704 simon@2ndQuadrant.co 4183 : 15 : UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4184 : :
898 pg@bowt.ie 4185 : 302822 : pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4186 : :
4187 : : /*
4188 : : * If heaptup is a private copy, release it. Don't forget to copy t_self
4189 : : * back to the caller's image, too.
4190 : : */
7230 tgl@sss.pgh.pa.us 4191 [ + + ]: 302822 : if (heaptup != newtup)
4192 : : {
4193 : 1641 : newtup->t_self = heaptup->t_self;
4194 : 1641 : heap_freetuple(heaptup);
4195 : : }
4196 : :
4197 : : /*
4198 : : * If it is a HOT update, the update may still need to update summarized
4199 : : * indexes, lest we fail to update those summaries and get incorrect
4200 : : * results (for example, minmax bounds of the block may change with this
4201 : : * update).
4202 : : */
901 tomas.vondra@postgre 4203 [ + + ]: 302822 : if (use_hot_update)
4204 : : {
4205 [ + + ]: 142118 : if (summarized_update)
4206 : 1641 : *update_indexes = TU_Summarizing;
4207 : : else
4208 : 140477 : *update_indexes = TU_None;
4209 : : }
4210 : : else
4211 : 160704 : *update_indexes = TU_All;
4212 : :
4288 rhaas@postgresql.org 4213 [ + + + + ]: 302822 : if (old_key_tuple != NULL && old_key_copied)
4214 : 84 : heap_freetuple(old_key_tuple);
4215 : :
6561 tgl@sss.pgh.pa.us 4216 : 302822 : bms_free(hot_attrs);
901 tomas.vondra@postgre 4217 : 302822 : bms_free(sum_attrs);
4609 alvherre@alvh.no-ip. 4218 : 302822 : bms_free(key_attrs);
3300 tgl@sss.pgh.pa.us 4219 : 302822 : bms_free(id_attrs);
3083 alvherre@alvh.no-ip. 4220 : 302822 : bms_free(modified_attrs);
4221 : 302822 : bms_free(interesting_attrs);
4222 : :
2359 andres@anarazel.de 4223 : 302822 : return TM_Ok;
4224 : : }
4225 : :
4226 : : #ifdef USE_ASSERT_CHECKING
4227 : : /*
4228 : : * Confirm adequate lock held during heap_update(), per rules from
4229 : : * README.tuplock section "Locking to write inplace-updated tables".
4230 : : */
4231 : : static void
347 noah@leadboat.com 4232 : 302988 : check_lock_if_inplace_updateable_rel(Relation relation,
4233 : : ItemPointer otid,
4234 : : HeapTuple newtup)
4235 : : {
4236 : : /* LOCKTAG_TUPLE acceptable for any catalog */
4237 [ + + ]: 302988 : switch (RelationGetRelid(relation))
4238 : : {
4239 : 66333 : case RelationRelationId:
4240 : : case DatabaseRelationId:
4241 : : {
4242 : : LOCKTAG tuptag;
4243 : :
4244 : 66333 : SET_LOCKTAG_TUPLE(tuptag,
4245 : : relation->rd_lockInfo.lockRelId.dbId,
4246 : : relation->rd_lockInfo.lockRelId.relId,
4247 : : ItemPointerGetBlockNumber(otid),
4248 : : ItemPointerGetOffsetNumber(otid));
4249 [ + + ]: 66333 : if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
4250 : 29888 : return;
4251 : : }
4252 : 36445 : break;
4253 : 236655 : default:
4254 [ - + ]: 236655 : Assert(!IsInplaceUpdateRelation(relation));
4255 : 236655 : return;
4256 : : }
4257 : :
4258 [ + - - ]: 36445 : switch (RelationGetRelid(relation))
4259 : : {
4260 : 36445 : case RelationRelationId:
4261 : : {
4262 : : /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4263 : 36445 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
4264 : 36445 : Oid relid = classForm->oid;
4265 : : Oid dbid;
4266 : : LOCKTAG tag;
4267 : :
4268 [ + + ]: 36445 : if (IsSharedRelation(relid))
4269 : 44 : dbid = InvalidOid;
4270 : : else
4271 : 36401 : dbid = MyDatabaseId;
4272 : :
4273 [ + + ]: 36445 : if (classForm->relkind == RELKIND_INDEX)
4274 : : {
4275 : 1001 : Relation irel = index_open(relid, AccessShareLock);
4276 : :
4277 : 1001 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4278 : 1001 : index_close(irel, AccessShareLock);
4279 : : }
4280 : : else
4281 : 35444 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4282 : :
4283 [ + + ]: 36445 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4284 [ - + ]: 32969 : !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
347 noah@leadboat.com 4285 [ # # ]:UBC 0 : elog(WARNING,
4286 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4287 : : NameStr(classForm->relname),
4288 : : relid,
4289 : : classForm->relkind,
4290 : : ItemPointerGetBlockNumber(otid),
4291 : : ItemPointerGetOffsetNumber(otid));
4292 : : }
347 noah@leadboat.com 4293 :CBC 36445 : break;
347 noah@leadboat.com 4294 :UBC 0 : case DatabaseRelationId:
4295 : : {
4296 : : /* LOCKTAG_TUPLE required */
4297 : 0 : Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
4298 : :
4299 [ # # ]: 0 : elog(WARNING,
4300 : : "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4301 : : NameStr(dbForm->datname),
4302 : : dbForm->oid,
4303 : : ItemPointerGetBlockNumber(otid),
4304 : : ItemPointerGetOffsetNumber(otid));
4305 : : }
4306 : 0 : break;
4307 : : }
4308 : : }
4309 : :
4310 : : /*
4311 : : * Confirm adequate relation lock held, per rules from README.tuplock section
4312 : : * "Locking to write inplace-updated tables".
4313 : : */
4314 : : static void
347 noah@leadboat.com 4315 :CBC 89880 : check_inplace_rel_lock(HeapTuple oldtup)
4316 : : {
4317 : 89880 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
4318 : 89880 : Oid relid = classForm->oid;
4319 : : Oid dbid;
4320 : : LOCKTAG tag;
4321 : :
4322 [ + + ]: 89880 : if (IsSharedRelation(relid))
4323 : 8567 : dbid = InvalidOid;
4324 : : else
4325 : 81313 : dbid = MyDatabaseId;
4326 : :
4327 [ + + ]: 89880 : if (classForm->relkind == RELKIND_INDEX)
4328 : : {
4329 : 39158 : Relation irel = index_open(relid, AccessShareLock);
4330 : :
4331 : 39158 : SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4332 : 39158 : index_close(irel, AccessShareLock);
4333 : : }
4334 : : else
4335 : 50722 : SET_LOCKTAG_RELATION(tag, dbid, relid);
4336 : :
4337 [ - + ]: 89880 : if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
347 noah@leadboat.com 4338 [ # # ]:UBC 0 : elog(WARNING,
4339 : : "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4340 : : NameStr(classForm->relname),
4341 : : relid,
4342 : : classForm->relkind,
4343 : : ItemPointerGetBlockNumber(&oldtup->t_self),
4344 : : ItemPointerGetOffsetNumber(&oldtup->t_self));
347 noah@leadboat.com 4345 :CBC 89880 : }
4346 : : #endif
4347 : :
4348 : : /*
4349 : : * Check if the specified attribute's values are the same. Subroutine for
4350 : : * HeapDetermineColumnsInfo.
4351 : : */
4352 : : static bool
1300 akapila@postgresql.o 4353 : 730933 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4354 : : bool isnull1, bool isnull2)
4355 : : {
4356 : : /*
4357 : : * If one value is NULL and other is not, then they are certainly not
4358 : : * equal
4359 : : */
6561 tgl@sss.pgh.pa.us 4360 [ + + ]: 730933 : if (isnull1 != isnull2)
4361 : 45 : return false;
4362 : :
4363 : : /*
4364 : : * If both are NULL, they can be considered equal.
4365 : : */
4366 [ + + ]: 730888 : if (isnull1)
4367 : 4991 : return true;
4368 : :
4369 : : /*
4370 : : * We do simple binary comparison of the two datums. This may be overly
4371 : : * strict because there can be multiple binary representations for the
4372 : : * same logical value. But we should be OK as long as there are no false
4373 : : * positives. Using a type-specific equality operator is messy because
4374 : : * there could be multiple notions of equality in different operator
4375 : : * classes; furthermore, we cannot safely invoke user-defined functions
4376 : : * while holding exclusive buffer lock.
4377 : : */
4378 [ - + ]: 725897 : if (attrnum <= 0)
4379 : : {
4380 : : /* The only allowed system columns are OIDs, so do this */
6561 tgl@sss.pgh.pa.us 4381 :UBC 0 : return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4382 : : }
4383 : : else
4384 : : {
4385 : : CompactAttribute *att;
4386 : :
6561 tgl@sss.pgh.pa.us 4387 [ - + ]:CBC 725897 : Assert(attrnum <= tupdesc->natts);
260 drowley@postgresql.o 4388 : 725897 : att = TupleDescCompactAttr(tupdesc, attrnum - 1);
6561 tgl@sss.pgh.pa.us 4389 : 725897 : return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4390 : : }
4391 : : }
4392 : :
4393 : : /*
4394 : : * Check which columns are being updated.
4395 : : *
4396 : : * Given an updated tuple, determine (and return into the output bitmapset),
4397 : : * from those listed as interesting, the set of columns that changed.
4398 : : *
4399 : : * has_external indicates if any of the unmodified attributes (from those
4400 : : * listed as interesting) of the old tuple is a member of external_cols and is
4401 : : * stored externally.
4402 : : */
4403 : : static Bitmapset *
1300 akapila@postgresql.o 4404 : 302988 : HeapDetermineColumnsInfo(Relation relation,
4405 : : Bitmapset *interesting_cols,
4406 : : Bitmapset *external_cols,
4407 : : HeapTuple oldtup, HeapTuple newtup,
4408 : : bool *has_external)
4409 : : {
4410 : : int attidx;
3034 bruce@momjian.us 4411 : 302988 : Bitmapset *modified = NULL;
1300 akapila@postgresql.o 4412 : 302988 : TupleDesc tupdesc = RelationGetDescr(relation);
4413 : :
919 tgl@sss.pgh.pa.us 4414 : 302988 : attidx = -1;
4415 [ + + ]: 1033921 : while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4416 : : {
4417 : : /* attidx is zero-based, attrnum is the normal attribute number */
4418 : 730933 : AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
4419 : : Datum value1,
4420 : : value2;
4421 : : bool isnull1,
4422 : : isnull2;
4423 : :
4424 : : /*
4425 : : * If it's a whole-tuple reference, say "not equal". It's not really
4426 : : * worth supporting this case, since it could only succeed after a
4427 : : * no-op update, which is hardly a case worth optimizing for.
4428 : : */
1300 akapila@postgresql.o 4429 [ - + ]: 730933 : if (attrnum == 0)
4430 : : {
919 tgl@sss.pgh.pa.us 4431 :UBC 0 : modified = bms_add_member(modified, attidx);
1300 akapila@postgresql.o 4432 :CBC 698842 : continue;
4433 : : }
4434 : :
4435 : : /*
4436 : : * Likewise, automatically say "not equal" for any system attribute
4437 : : * other than tableOID; we cannot expect these to be consistent in a
4438 : : * HOT chain, or even to be set correctly yet in the new tuple.
4439 : : */
4440 [ - + ]: 730933 : if (attrnum < 0)
4441 : : {
1300 akapila@postgresql.o 4442 [ # # ]:UBC 0 : if (attrnum != TableOidAttributeNumber)
4443 : : {
919 tgl@sss.pgh.pa.us 4444 : 0 : modified = bms_add_member(modified, attidx);
1300 akapila@postgresql.o 4445 : 0 : continue;
4446 : : }
4447 : : }
4448 : :
4449 : : /*
4450 : : * Extract the corresponding values. XXX this is pretty inefficient
4451 : : * if there are many indexed columns. Should we do a single
4452 : : * heap_deform_tuple call on each tuple, instead? But that doesn't
4453 : : * work for system columns ...
4454 : : */
1300 akapila@postgresql.o 4455 :CBC 730933 : value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4456 : 730933 : value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4457 : :
4458 [ + + ]: 730933 : if (!heap_attr_equals(tupdesc, attrnum, value1,
4459 : : value2, isnull1, isnull2))
4460 : : {
919 tgl@sss.pgh.pa.us 4461 : 26710 : modified = bms_add_member(modified, attidx);
1300 akapila@postgresql.o 4462 : 26710 : continue;
4463 : : }
4464 : :
4465 : : /*
4466 : : * No need to check attributes that can't be stored externally. Note
4467 : : * that system attributes can't be stored externally.
4468 : : */
4469 [ + - + + ]: 704223 : if (attrnum < 0 || isnull1 ||
260 drowley@postgresql.o 4470 [ + + ]: 699232 : TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
1300 akapila@postgresql.o 4471 : 672132 : continue;
4472 : :
4473 : : /*
4474 : : * Check if the old tuple's attribute is stored externally and is a
4475 : : * member of external_cols.
4476 : : */
4477 [ + + + + ]: 32096 : if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
919 tgl@sss.pgh.pa.us 4478 : 5 : bms_is_member(attidx, external_cols))
1300 akapila@postgresql.o 4479 : 2 : *has_external = true;
4480 : : }
4481 : :
3083 alvherre@alvh.no-ip. 4482 : 302988 : return modified;
4483 : : }
4484 : :
4485 : : /*
4486 : : * simple_heap_update - replace a tuple
4487 : : *
4488 : : * This routine may be used to update a tuple when concurrent updates of
4489 : : * the target tuple are not expected (for example, because we have a lock
4490 : : * on the relation associated with the tuple). Any failure is reported
4491 : : * via ereport().
4492 : : */
4493 : : void
901 tomas.vondra@postgre 4494 : 109496 : simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup,
4495 : : TU_UpdateIndexes *update_indexes)
4496 : : {
4497 : : TM_Result result;
4498 : : TM_FailureData tmfd;
4499 : : LockTupleMode lockmode;
4500 : :
8027 tgl@sss.pgh.pa.us 4501 : 109496 : result = heap_update(relation, otid, tup,
4502 : : GetCurrentCommandId(true), InvalidSnapshot,
4503 : : true /* wait for commit */ ,
4504 : : &tmfd, &lockmode, update_indexes);
8992 4505 [ - + - - : 109496 : switch (result)
- ]
4506 : : {
2359 andres@anarazel.de 4507 :UBC 0 : case TM_SelfModified:
4508 : : /* Tuple was already updated in current command? */
8083 tgl@sss.pgh.pa.us 4509 [ # # ]: 0 : elog(ERROR, "tuple already updated by self");
4510 : : break;
4511 : :
2359 andres@anarazel.de 4512 :CBC 109496 : case TM_Ok:
4513 : : /* done successfully */
8992 tgl@sss.pgh.pa.us 4514 : 109496 : break;
4515 : :
2359 andres@anarazel.de 4516 :UBC 0 : case TM_Updated:
8083 tgl@sss.pgh.pa.us 4517 [ # # ]: 0 : elog(ERROR, "tuple concurrently updated");
4518 : : break;
4519 : :
2359 andres@anarazel.de 4520 : 0 : case TM_Deleted:
4521 [ # # ]: 0 : elog(ERROR, "tuple concurrently deleted");
4522 : : break;
4523 : :
8992 tgl@sss.pgh.pa.us 4524 : 0 : default:
8083 4525 [ # # ]: 0 : elog(ERROR, "unrecognized heap_update status: %u", result);
4526 : : break;
4527 : : }
8992 tgl@sss.pgh.pa.us 4528 :CBC 109496 : }
4529 : :
4530 : :
4531 : : /*
4532 : : * Return the MultiXactStatus corresponding to the given tuple lock mode.
4533 : : */
4534 : : static MultiXactStatus
4609 alvherre@alvh.no-ip. 4535 : 1214 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4536 : : {
4537 : : int retval;
4538 : :
4539 [ + + ]: 1214 : if (is_update)
4540 : 96 : retval = tupleLockExtraInfo[mode].updstatus;
4541 : : else
4542 : 1118 : retval = tupleLockExtraInfo[mode].lockstatus;
4543 : :
4544 [ - + ]: 1214 : if (retval == -1)
4609 alvherre@alvh.no-ip. 4545 [ # # # # ]:UBC 0 : elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4546 : : is_update ? "true" : "false");
4547 : :
4456 alvherre@alvh.no-ip. 4548 :CBC 1214 : return (MultiXactStatus) retval;
4549 : : }
4550 : :
4551 : : /*
4552 : : * heap_lock_tuple - lock a tuple in shared or exclusive mode
4553 : : *
4554 : : * Note that this acquires a buffer pin, which the caller must release.
4555 : : *
4556 : : * Input parameters:
4557 : : * relation: relation containing tuple (caller must hold suitable lock)
4558 : : * tid: TID of tuple to lock
4559 : : * cid: current command ID (used for visibility test, and stored into
4560 : : * tuple's cmax if lock is successful)
4561 : : * mode: indicates if shared or exclusive tuple lock is desired
4562 : : * wait_policy: what to do if tuple lock is not available
4563 : : * follow_updates: if true, follow the update chain to also lock descendant
4564 : : * tuples.
4565 : : *
4566 : : * Output parameters:
4567 : : * *tuple: all fields filled in
4568 : : * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4569 : : * *tmfd: filled in failure cases (see below)
4570 : : *
4571 : : * Function results are the same as the ones for table_tuple_lock().
4572 : : *
4573 : : * In the failure cases other than TM_Invisible, the routine fills
4574 : : * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4575 : : * if necessary), and t_cmax (the last only for TM_SelfModified,
4576 : : * since we cannot obtain cmax from a combo CID generated by another
4577 : : * transaction).
4578 : : * See comments for struct TM_FailureData for additional info.
4579 : : *
4580 : : * See README.tuplock for a thorough explanation of this mechanism.
4581 : : */
4582 : : TM_Result
513 akorotkov@postgresql 4583 : 84928 : heap_lock_tuple(Relation relation, HeapTuple tuple,
4584 : : CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4585 : : bool follow_updates,
4586 : : Buffer *buffer, TM_FailureData *tmfd)
4587 : : {
4588 : : TM_Result result;
4589 : 84928 : ItemPointer tid = &(tuple->t_self);
4590 : : ItemId lp;
4591 : : Page page;
3337 andres@anarazel.de 4592 : 84928 : Buffer vmbuffer = InvalidBuffer;
4593 : : BlockNumber block;
4594 : : TransactionId xid,
4595 : : xmax;
4596 : : uint16 old_infomask,
4597 : : new_infomask,
4598 : : new_infomask2;
3802 alvherre@alvh.no-ip. 4599 : 84928 : bool first_time = true;
2272 4600 : 84928 : bool skip_tuple_lock = false;
7434 tgl@sss.pgh.pa.us 4601 : 84928 : bool have_tuple_lock = false;
3337 andres@anarazel.de 4602 : 84928 : bool cleared_all_frozen = false;
4603 : :
513 akorotkov@postgresql 4604 : 84928 : *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3337 andres@anarazel.de 4605 : 84928 : block = ItemPointerGetBlockNumber(tid);
4606 : :
4607 : : /*
4608 : : * Before locking the buffer, pin the visibility map page if it appears to
4609 : : * be necessary. Since we haven't got the lock yet, someone else might be
4610 : : * in the middle of changing this, so we'll need to recheck after we have
4611 : : * the lock.
4612 : : */
513 akorotkov@postgresql 4613 [ + + ]: 84928 : if (PageIsAllVisible(BufferGetPage(*buffer)))
3337 andres@anarazel.de 4614 : 1662 : visibilitymap_pin(relation, block, &vmbuffer);
4615 : :
513 akorotkov@postgresql 4616 : 84928 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4617 : :
4618 : 84928 : page = BufferGetPage(*buffer);
6264 tgl@sss.pgh.pa.us 4619 : 84928 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6569 4620 [ - + ]: 84928 : Assert(ItemIdIsNormal(lp));
4621 : :
6264 4622 : 84928 : tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
9762 vadim4o@yahoo.com 4623 : 84928 : tuple->t_len = ItemIdGetLength(lp);
7322 tgl@sss.pgh.pa.us 4624 : 84928 : tuple->t_tableOid = RelationGetRelid(relation);
4625 : :
9762 vadim4o@yahoo.com 4626 : 11 : l3:
513 akorotkov@postgresql 4627 : 84939 : result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4628 : :
2359 andres@anarazel.de 4629 [ + + ]: 84939 : if (result == TM_Invisible)
4630 : : {
4631 : : /*
4632 : : * This is possible, but only when locking a tuple for ON CONFLICT
4633 : : * UPDATE. We return this value here rather than throwing an error in
4634 : : * order to give that case the opportunity to throw a more specific
4635 : : * error.
4636 : : */
4637 : 12 : result = TM_Invisible;
3337 4638 : 12 : goto out_locked;
4639 : : }
2359 4640 [ + + + + ]: 84927 : else if (result == TM_BeingModified ||
4641 [ + + ]: 77042 : result == TM_Updated ||
4642 : : result == TM_Deleted)
4643 : : {
4644 : : TransactionId xwait;
4645 : : uint16 infomask;
4646 : : uint16 infomask2;
4647 : : bool require_sleep;
4648 : : ItemPointerData t_ctid;
4649 : :
4650 : : /* must copy state data before unlocking buffer */
4609 alvherre@alvh.no-ip. 4651 : 7886 : xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
7434 tgl@sss.pgh.pa.us 4652 : 7886 : infomask = tuple->t_data->t_infomask;
4609 alvherre@alvh.no-ip. 4653 : 7886 : infomask2 = tuple->t_data->t_infomask2;
4654 : 7886 : ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4655 : :
513 akorotkov@postgresql 4656 : 7886 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4657 : :
4658 : : /*
4659 : : * If any subtransaction of the current top transaction already holds
4660 : : * a lock as strong as or stronger than what we're requesting, we
4661 : : * effectively hold the desired lock already. We *must* succeed
4662 : : * without trying to take the tuple lock, else we will deadlock
4663 : : * against anyone wanting to acquire a stronger lock.
4664 : : *
4665 : : * Note we only do this the first time we loop on the HTSU result;
4666 : : * there is no point in testing in subsequent passes, because
4667 : : * evidently our own transaction cannot have acquired a new lock after
4668 : : * the first time we checked.
4669 : : */
3802 alvherre@alvh.no-ip. 4670 [ + + ]: 7886 : if (first_time)
4671 : : {
4672 : 7877 : first_time = false;
4673 : :
4674 [ + + ]: 7877 : if (infomask & HEAP_XMAX_IS_MULTI)
4675 : : {
4676 : : int i;
4677 : : int nmembers;
4678 : : MultiXactMember *members;
4679 : :
4680 : : /*
4681 : : * We don't need to allow old multixacts here; if that had
4682 : : * been the case, HeapTupleSatisfiesUpdate would have returned
4683 : : * MayBeUpdated and we wouldn't be here.
4684 : : */
4685 : : nmembers =
4686 : 93 : GetMultiXactIdMembers(xwait, &members, false,
4687 : 93 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4688 : :
4689 [ + + ]: 284 : for (i = 0; i < nmembers; i++)
4690 : : {
4691 : : /* only consider members of our own transaction */
4692 [ + + ]: 205 : if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4693 : 156 : continue;
4694 : :
4695 [ + + ]: 49 : if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4696 : : {
4609 4697 : 14 : pfree(members);
2359 andres@anarazel.de 4698 : 14 : result = TM_Ok;
3337 4699 : 14 : goto out_unlocked;
4700 : : }
4701 : : else
4702 : : {
4703 : : /*
4704 : : * Disable acquisition of the heavyweight tuple lock.
4705 : : * Otherwise, when promoting a weaker lock, we might
4706 : : * deadlock with another locker that has acquired the
4707 : : * heavyweight tuple lock and is waiting for our
4708 : : * transaction to finish.
4709 : : *
4710 : : * Note that in this case we still need to wait for
4711 : : * the multixact if required, to avoid acquiring
4712 : : * conflicting locks.
4713 : : */
2272 alvherre@alvh.no-ip. 4714 : 35 : skip_tuple_lock = true;
4715 : : }
4716 : : }
4717 : :
3802 4718 [ + - ]: 79 : if (members)
4719 : 79 : pfree(members);
4720 : : }
4721 [ + + ]: 7784 : else if (TransactionIdIsCurrentTransactionId(xwait))
4722 : : {
4723 [ + + + + : 6549 : switch (mode)
- ]
4724 : : {
4725 : 163 : case LockTupleKeyShare:
4726 [ - + - - : 163 : Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
- - ]
4727 : : HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4728 : : HEAP_XMAX_IS_EXCL_LOCKED(infomask));
2359 andres@anarazel.de 4729 : 163 : result = TM_Ok;
3337 4730 : 163 : goto out_unlocked;
3802 alvherre@alvh.no-ip. 4731 : 20 : case LockTupleShare:
4732 [ + + - + ]: 26 : if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4733 : 6 : HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4734 : : {
2359 andres@anarazel.de 4735 : 14 : result = TM_Ok;
3337 4736 : 14 : goto out_unlocked;
4737 : : }
3802 alvherre@alvh.no-ip. 4738 : 6 : break;
4739 : 65 : case LockTupleNoKeyExclusive:
4740 [ + + ]: 65 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4741 : : {
2359 andres@anarazel.de 4742 : 53 : result = TM_Ok;
3337 4743 : 53 : goto out_unlocked;
4744 : : }
3802 alvherre@alvh.no-ip. 4745 : 12 : break;
4746 : 6301 : case LockTupleExclusive:
4747 [ + + ]: 6301 : if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4748 [ + + ]: 1261 : infomask2 & HEAP_KEYS_UPDATED)
4749 : : {
2359 andres@anarazel.de 4750 : 1240 : result = TM_Ok;
3337 4751 : 1240 : goto out_unlocked;
4752 : : }
3802 alvherre@alvh.no-ip. 4753 : 5061 : break;
4754 : : }
4755 : : }
4756 : : }
4757 : :
4758 : : /*
4759 : : * Initially assume that we will have to wait for the locking
4760 : : * transaction(s) to finish. We check various cases below in which
4761 : : * this can be turned off.
4762 : : */
4609 4763 : 6402 : require_sleep = true;
4764 [ + + ]: 6402 : if (mode == LockTupleKeyShare)
4765 : : {
4766 : : /*
4767 : : * If we're requesting KeyShare, and there's no update present, we
4768 : : * don't need to wait. Even if there is an update, we can still
4769 : : * continue if the key hasn't been modified.
4770 : : *
4771 : : * However, if there are updates, we need to walk the update chain
4772 : : * to mark future versions of the row as locked, too. That way,
4773 : : * if somebody deletes that future version, we're protected
4774 : : * against the key going away. This locking of future versions
4775 : : * could block momentarily, if a concurrent transaction is
4776 : : * deleting a key; or it could return a value to the effect that
4777 : : * the transaction deleting the key has already committed. So we
4778 : : * do this before re-locking the buffer; otherwise this would be
4779 : : * prone to deadlocks.
4780 : : *
4781 : : * Note that the TID we're locking was grabbed before we unlocked
4782 : : * the buffer. For it to change while we're not looking, the
4783 : : * other properties we're testing for below after re-locking the
4784 : : * buffer would also change, in which case we would restart this
4785 : : * loop above.
4786 : : */
4787 [ + + ]: 593 : if (!(infomask2 & HEAP_KEYS_UPDATED))
4788 : : {
4789 : : bool updated;
4790 : :
4791 : 562 : updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4792 : :
4793 : : /*
4794 : : * If there are updates, follow the update chain; bail out if
4795 : : * that cannot be done.
4796 : : */
4797 [ + - + + ]: 562 : if (follow_updates && updated)
4798 : : {
4799 : : TM_Result res;
4800 : :
4801 : 50 : res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4802 : : GetCurrentTransactionId(),
4803 : : mode);
2359 andres@anarazel.de 4804 [ + + ]: 50 : if (res != TM_Ok)
4805 : : {
4609 alvherre@alvh.no-ip. 4806 : 6 : result = res;
4807 : : /* recovery code expects to have buffer lock held */
513 akorotkov@postgresql 4808 : 6 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4609 alvherre@alvh.no-ip. 4809 : 185 : goto failed;
4810 : : }
4811 : : }
4812 : :
513 akorotkov@postgresql 4813 : 556 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4814 : :
4815 : : /*
4816 : : * Make sure it's still an appropriate lock, else start over.
4817 : : * Also, if it wasn't updated before we released the lock, but
4818 : : * is updated now, we start over too; the reason is that we
4819 : : * now need to follow the update chain to lock the new
4820 : : * versions.
4821 : : */
4609 alvherre@alvh.no-ip. 4822 [ + + ]: 556 : if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4823 [ + - ]: 43 : ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4824 [ - + ]: 43 : !updated))
4825 : 11 : goto l3;
4826 : :
4827 : : /* Things look okay, so we can skip sleeping */
4828 : 556 : require_sleep = false;
4829 : :
4830 : : /*
4831 : : * Note we allow Xmax to change here; other updaters/lockers
4832 : : * could have modified it before we grabbed the buffer lock.
4833 : : * However, this is not a problem, because with the recheck we
4834 : : * just did we ensure that they still don't conflict with the
4835 : : * lock we want.
4836 : : */
4837 : : }
4838 : : }
4839 [ + + ]: 5809 : else if (mode == LockTupleShare)
4840 : : {
4841 : : /*
4842 : : * If we're requesting Share, we can similarly avoid sleeping if
4843 : : * there's no update and no exclusive lock present.
4844 : : */
4845 [ + - ]: 442 : if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4846 [ + + ]: 442 : !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4847 : : {
513 akorotkov@postgresql 4848 : 436 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4849 : :
4850 : : /*
4851 : : * Make sure it's still an appropriate lock, else start over.
4852 : : * See above about allowing xmax to change.
4853 : : */
4609 alvherre@alvh.no-ip. 4854 [ + - - + ]: 872 : if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4855 : 436 : HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
4609 alvherre@alvh.no-ip. 4856 :UBC 0 : goto l3;
4609 alvherre@alvh.no-ip. 4857 :CBC 436 : require_sleep = false;
4858 : : }
4859 : : }
4860 [ + + ]: 5367 : else if (mode == LockTupleNoKeyExclusive)
4861 : : {
4862 : : /*
4863 : : * If we're requesting NoKeyExclusive, we might also be able to
4864 : : * avoid sleeping; just ensure that there no conflicting lock
4865 : : * already acquired.
4866 : : */
4867 [ + + ]: 159 : if (infomask & HEAP_XMAX_IS_MULTI)
4868 : : {
3907 4869 [ + + ]: 26 : if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4870 : : mode, NULL))
4871 : : {
4872 : : /*
4873 : : * No conflict, but if the xmax changed under us in the
4874 : : * meantime, start over.
4875 : : */
513 akorotkov@postgresql 4876 : 13 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3907 alvherre@alvh.no-ip. 4877 [ + - - + ]: 26 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4878 : 13 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4879 : : xwait))
3907 alvherre@alvh.no-ip. 4880 :UBC 0 : goto l3;
4881 : :
4882 : : /* otherwise, we're good */
3907 alvherre@alvh.no-ip. 4883 :CBC 13 : require_sleep = false;
4884 : : }
4885 : : }
4609 4886 [ + + ]: 133 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4887 : : {
513 akorotkov@postgresql 4888 : 18 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4889 : :
4890 : : /* if the xmax changed in the meantime, start over */
4153 alvherre@alvh.no-ip. 4891 [ + - - + ]: 36 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
2046 4892 : 18 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4893 : : xwait))
4609 alvherre@alvh.no-ip. 4894 :UBC 0 : goto l3;
4895 : : /* otherwise, we're good */
4609 alvherre@alvh.no-ip. 4896 :CBC 18 : require_sleep = false;
4897 : : }
4898 : : }
4899 : :
4900 : : /*
4901 : : * As a check independent from those above, we can also avoid sleeping
4902 : : * if the current transaction is the sole locker of the tuple. Note
4903 : : * that the strength of the lock already held is irrelevant; this is
4904 : : * not about recording the lock in Xmax (which will be done regardless
4905 : : * of this optimization, below). Also, note that the cases where we
4906 : : * hold a lock stronger than we are requesting are already handled
4907 : : * above by not doing anything.
4908 : : *
4909 : : * Note we only deal with the non-multixact case here; MultiXactIdWait
4910 : : * is well equipped to deal with this situation on its own.
4911 : : */
3802 4912 [ + + + + : 11728 : if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
+ + ]
4913 : 5332 : TransactionIdIsCurrentTransactionId(xwait))
4914 : : {
4915 : : /* ... but if the xmax changed in the meantime, start over */
513 akorotkov@postgresql 4916 : 5061 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3802 alvherre@alvh.no-ip. 4917 [ + - - + ]: 10122 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4918 : 5061 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4919 : : xwait))
3802 alvherre@alvh.no-ip. 4920 :UBC 0 : goto l3;
3802 alvherre@alvh.no-ip. 4921 [ - + ]:CBC 5061 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
4922 : 5061 : require_sleep = false;
4923 : : }
4924 : :
4925 : : /*
4926 : : * Time to sleep on the other transaction/multixact, if necessary.
4927 : : *
4928 : : * If the other transaction is an update/delete that's already
4929 : : * committed, then sleeping cannot possibly do any good: if we're
4930 : : * required to sleep, get out to raise an error instead.
4931 : : *
4932 : : * By here, we either have already acquired the buffer exclusive lock,
4933 : : * or we must wait for the locking transaction or multixact; so below
4934 : : * we ensure that we grab buffer lock after the sleep.
4935 : : */
2359 andres@anarazel.de 4936 [ + + + + : 6396 : if (require_sleep && (result == TM_Updated || result == TM_Deleted))
+ + ]
4937 : : {
513 akorotkov@postgresql 4938 : 141 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3340 alvherre@alvh.no-ip. 4939 : 141 : goto failed;
4940 : : }
4941 [ + + ]: 6255 : else if (require_sleep)
4942 : : {
4943 : : /*
4944 : : * Acquire tuple lock to establish our priority for the tuple, or
4945 : : * die trying. LockTuple will release us when we are next-in-line
4946 : : * for the tuple. We must do this even if we are share-locking,
4947 : : * but not if we already have a weaker lock on the tuple.
4948 : : *
4949 : : * If we are forced to "start over" below, we keep the tuple lock;
4950 : : * this arranges that we stay at the head of the line while
4951 : : * rechecking tuple state.
4952 : : */
2272 4953 [ + + ]: 171 : if (!skip_tuple_lock &&
4954 [ + + ]: 155 : !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4955 : : &have_tuple_lock))
4956 : : {
4957 : : /*
4958 : : * This can only happen if wait_policy is Skip and the lock
4959 : : * couldn't be obtained.
4960 : : */
2359 andres@anarazel.de 4961 : 1 : result = TM_WouldBlock;
4962 : : /* recovery code expects to have buffer lock held */
513 akorotkov@postgresql 4963 : 1 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3907 alvherre@alvh.no-ip. 4964 : 1 : goto failed;
4965 : : }
4966 : :
4609 4967 [ + + ]: 169 : if (infomask & HEAP_XMAX_IS_MULTI)
4968 : : {
4969 : 40 : MultiXactStatus status = get_mxact_status_for_lock(mode, false);
4970 : :
4971 : : /* We only ever lock tuples, never update them */
4972 [ - + ]: 40 : if (status >= MultiXactStatusNoKeyUpdate)
4609 alvherre@alvh.no-ip. 4973 [ # # ]:UBC 0 : elog(ERROR, "invalid lock mode in heap_lock_tuple");
4974 : :
4975 : : /* wait for multixact to end, or die trying */
3987 alvherre@alvh.no-ip. 4976 [ + + + - ]:CBC 40 : switch (wait_policy)
4977 : : {
4978 : 36 : case LockWaitBlock:
4979 : 36 : MultiXactIdWait((MultiXactId) xwait, status, infomask,
4980 : : relation, &tuple->t_self, XLTW_Lock, NULL);
4981 : 36 : break;
4982 : 2 : case LockWaitSkip:
4983 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4984 : : status, infomask, relation,
4985 : : NULL, false))
4986 : : {
2359 andres@anarazel.de 4987 : 2 : result = TM_WouldBlock;
4988 : : /* recovery code expects to have buffer lock held */
513 akorotkov@postgresql 4989 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3987 alvherre@alvh.no-ip. 4990 : 2 : goto failed;
4991 : : }
3987 alvherre@alvh.no-ip. 4992 :UBC 0 : break;
3987 alvherre@alvh.no-ip. 4993 :CBC 2 : case LockWaitError:
4994 [ + - ]: 2 : if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4995 : : status, infomask, relation,
4996 : : NULL, log_lock_failures))
4997 [ + - ]: 2 : ereport(ERROR,
4998 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4999 : : errmsg("could not obtain lock on row in relation \"%s\"",
5000 : : RelationGetRelationName(relation))));
5001 : :
3987 alvherre@alvh.no-ip. 5002 :UBC 0 : break;
5003 : : }
5004 : :
5005 : : /*
5006 : : * Of course, the multixact might not be done here: if we're
5007 : : * requesting a light lock mode, other transactions with light
5008 : : * locks could still be alive, as well as locks owned by our
5009 : : * own xact or other subxacts of this backend. We need to
5010 : : * preserve the surviving MultiXact members. Note that it
5011 : : * isn't absolutely necessary in the latter case, but doing so
5012 : : * is simpler.
5013 : : */
5014 : : }
5015 : : else
5016 : : {
5017 : : /* wait for regular transaction to end, or die trying */
3987 alvherre@alvh.no-ip. 5018 [ + + + - ]:CBC 129 : switch (wait_policy)
5019 : : {
5020 : 90 : case LockWaitBlock:
3867 heikki.linnakangas@i 5021 : 90 : XactLockTableWait(xwait, relation, &tuple->t_self,
5022 : : XLTW_Lock);
3987 alvherre@alvh.no-ip. 5023 : 90 : break;
5024 : 33 : case LockWaitSkip:
176 fujii@postgresql.org 5025 [ + - ]: 33 : if (!ConditionalXactLockTableWait(xwait, false))
5026 : : {
2359 andres@anarazel.de 5027 : 33 : result = TM_WouldBlock;
5028 : : /* recovery code expects to have buffer lock held */
513 akorotkov@postgresql 5029 : 33 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3987 alvherre@alvh.no-ip. 5030 : 33 : goto failed;
5031 : : }
3987 alvherre@alvh.no-ip. 5032 :UBC 0 : break;
3987 alvherre@alvh.no-ip. 5033 :CBC 6 : case LockWaitError:
95 fujii@postgresql.org 5034 [ + - ]: 6 : if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
3987 alvherre@alvh.no-ip. 5035 [ + - ]: 6 : ereport(ERROR,
5036 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5037 : : errmsg("could not obtain lock on row in relation \"%s\"",
5038 : : RelationGetRelationName(relation))));
3987 alvherre@alvh.no-ip. 5039 :UBC 0 : break;
5040 : : }
5041 : : }
5042 : :
5043 : : /* if there are updates, follow the update chain */
3802 alvherre@alvh.no-ip. 5044 [ + + + + ]:CBC 126 : if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
5045 : : {
5046 : : TM_Result res;
5047 : :
5048 : 41 : res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
5049 : : GetCurrentTransactionId(),
5050 : : mode);
2359 andres@anarazel.de 5051 [ + + ]: 41 : if (res != TM_Ok)
5052 : : {
3802 alvherre@alvh.no-ip. 5053 : 2 : result = res;
5054 : : /* recovery code expects to have buffer lock held */
513 akorotkov@postgresql 5055 : 2 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3802 alvherre@alvh.no-ip. 5056 : 2 : goto failed;
5057 : : }
5058 : : }
5059 : :
513 akorotkov@postgresql 5060 : 124 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
5061 : :
5062 : : /*
5063 : : * xwait is done, but if xwait had just locked the tuple then some
5064 : : * other xact could update this tuple before we get to this point.
5065 : : * Check for xmax change, and start over if so.
5066 : : */
3802 alvherre@alvh.no-ip. 5067 [ + + + + ]: 238 : if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5068 : 114 : !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
5069 : : xwait))
5070 : 11 : goto l3;
5071 : :
5072 [ + + ]: 113 : if (!(infomask & HEAP_XMAX_IS_MULTI))
5073 : : {
5074 : : /*
5075 : : * Otherwise check if it committed or aborted. Note we cannot
5076 : : * be here if the tuple was only locked by somebody who didn't
5077 : : * conflict with us; that would have been handled above. So
5078 : : * that transaction must necessarily be gone by now. But
5079 : : * don't check for this in the multixact case, because some
5080 : : * locker transactions might still be running.
5081 : : */
513 akorotkov@postgresql 5082 : 79 : UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5083 : : }
5084 : : }
5085 : :
5086 : : /* By here, we're certain that we hold buffer exclusive lock again */
5087 : :
5088 : : /*
5089 : : * We may lock if previous xmax aborted, or if it committed but only
5090 : : * locked the tuple without updating it; or if we didn't have to wait
5091 : : * at all for whatever reason.
5092 : : */
4609 alvherre@alvh.no-ip. 5093 [ + + ]: 6197 : if (!require_sleep ||
5094 [ + + + + ]: 196 : (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5095 [ + + ]: 150 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
5096 : 67 : HeapTupleHeaderIsOnlyLocked(tuple->t_data))
2359 andres@anarazel.de 5097 : 6138 : result = TM_Ok;
1657 alvherre@alvh.no-ip. 5098 [ + + ]: 59 : else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
2359 andres@anarazel.de 5099 : 47 : result = TM_Updated;
5100 : : else
5101 : 12 : result = TM_Deleted;
5102 : : }
5103 : :
4609 alvherre@alvh.no-ip. 5104 : 77041 : failed:
2359 andres@anarazel.de 5105 [ + + ]: 83423 : if (result != TM_Ok)
5106 : : {
5107 [ + + + + : 250 : Assert(result == TM_SelfModified || result == TM_Updated ||
+ + - + ]
5108 : : result == TM_Deleted || result == TM_WouldBlock);
5109 : :
5110 : : /*
5111 : : * When locking a tuple under LockWaitSkip semantics and we fail with
5112 : : * TM_WouldBlock above, it's possible for concurrent transactions to
5113 : : * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5114 : : * this assert is slightly different from the equivalent one in
5115 : : * heap_delete and heap_update.
5116 : : */
1341 alvherre@alvh.no-ip. 5117 [ + + - + ]: 250 : Assert((result == TM_WouldBlock) ||
5118 : : !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
2359 andres@anarazel.de 5119 [ + + - + ]: 250 : Assert(result != TM_Updated ||
5120 : : !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5121 : 250 : tmfd->ctid = tuple->t_data->t_ctid;
5122 : 250 : tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5123 [ + + ]: 250 : if (result == TM_SelfModified)
5124 : 6 : tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5125 : : else
5126 : 244 : tmfd->cmax = InvalidCommandId;
3337 5127 : 250 : goto out_locked;
5128 : : }
5129 : :
5130 : : /*
5131 : : * If we didn't pin the visibility map page and the page has become all
5132 : : * visible while we were busy locking the buffer, or during some
5133 : : * subsequent window during which we had it unlocked, we'll have to unlock
5134 : : * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5135 : : * unfortunate, especially since we'll now have to recheck whether the
5136 : : * tuple has been locked or updated under us, but hopefully it won't
5137 : : * happen very often.
5138 : : */
3320 5139 [ + + - + ]: 83173 : if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5140 : : {
513 akorotkov@postgresql 5141 :UBC 0 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3320 andres@anarazel.de 5142 : 0 : visibilitymap_pin(relation, block, &vmbuffer);
513 akorotkov@postgresql 5143 : 0 : LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3320 andres@anarazel.de 5144 : 0 : goto l3;
5145 : : }
5146 : :
4609 alvherre@alvh.no-ip. 5147 :CBC 83173 : xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5148 : 83173 : old_infomask = tuple->t_data->t_infomask;
5149 : :
5150 : : /*
5151 : : * If this is the first possibly-multixact-able operation in the current
5152 : : * transaction, set my per-backend OldestMemberMXactId setting. We can be
5153 : : * certain that the transaction will never become a member of any older
5154 : : * MultiXactIds than that. (We have to do this even if we end up just
5155 : : * using our own TransactionId below, since some other backend could
5156 : : * incorporate our XID into a MultiXact immediately afterwards.)
5157 : : */
5158 : 83173 : MultiXactIdSetOldestMember();
5159 : :
5160 : : /*
5161 : : * Compute the new xmax and infomask to store into the tuple. Note we do
5162 : : * not modify the tuple just yet, because that would leave it in the wrong
5163 : : * state if multixact.c elogs.
5164 : : */
5165 : 83173 : compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5166 : : GetCurrentTransactionId(), mode, false,
5167 : : &xid, &new_infomask, &new_infomask2);
5168 : :
7436 tgl@sss.pgh.pa.us 5169 : 83173 : START_CRIT_SECTION();
5170 : :
5171 : : /*
5172 : : * Store transaction information of xact locking the tuple.
5173 : : *
5174 : : * Note: Cmax is meaningless in this context, so don't set it; this avoids
5175 : : * possibly generating a useless combo CID. Moreover, if we're locking a
5176 : : * previously updated tuple, it's important to preserve the Cmax.
5177 : : *
5178 : : * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5179 : : * we would break the HOT chain.
5180 : : */
4609 alvherre@alvh.no-ip. 5181 : 83173 : tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5182 : 83173 : tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5183 : 83173 : tuple->t_data->t_infomask |= new_infomask;
5184 : 83173 : tuple->t_data->t_infomask2 |= new_infomask2;
5185 [ + + ]: 83173 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5186 : 83134 : HeapTupleHeaderClearHotUpdated(tuple->t_data);
7660 tgl@sss.pgh.pa.us 5187 : 83173 : HeapTupleHeaderSetXmax(tuple->t_data, xid);
5188 : :
5189 : : /*
5190 : : * Make sure there is no forward chain link in t_ctid. Note that in the
5191 : : * cases where the tuple has been updated, we must not overwrite t_ctid,
5192 : : * because it was set by the updater. Moreover, if the tuple has been
5193 : : * updated, we need to follow the update chain to lock the new versions of
5194 : : * the tuple as well.
5195 : : */
4609 alvherre@alvh.no-ip. 5196 [ + + ]: 83173 : if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5197 : 83134 : tuple->t_data->t_ctid = *tid;
5198 : :
5199 : : /* Clear only the all-frozen bit on visibility map if needed */
3337 andres@anarazel.de 5200 [ + + + + ]: 84835 : if (PageIsAllVisible(page) &&
5201 : 1662 : visibilitymap_clear(relation, block, vmbuffer,
5202 : : VISIBILITYMAP_ALL_FROZEN))
5203 : 14 : cleared_all_frozen = true;
5204 : :
5205 : :
513 akorotkov@postgresql 5206 : 83173 : MarkBufferDirty(*buffer);
5207 : :
5208 : : /*
5209 : : * XLOG stuff. You might think that we don't need an XLOG record because
5210 : : * there is no state change worth restoring after a crash. You would be
5211 : : * wrong however: we have just written either a TransactionId or a
5212 : : * MultiXactId that may never have been seen on disk before, and we need
5213 : : * to make sure that there are XLOG entries covering those ID numbers.
5214 : : * Else the same IDs might be re-used after a crash, which would be
5215 : : * disastrous if this page made it to disk before the crash. Essentially
5216 : : * we have to enforce the WAL log-before-data rule even in this case.
5217 : : * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5218 : : * entries for everything anyway.)
5219 : : */
5381 rhaas@postgresql.org 5220 [ + + + + : 83173 : if (RelationNeedsWAL(relation))
+ - + - ]
5221 : : {
5222 : : xl_heap_lock xlrec;
5223 : : XLogRecPtr recptr;
5224 : :
3943 heikki.linnakangas@i 5225 : 82829 : XLogBeginInsert();
513 akorotkov@postgresql 5226 : 82829 : XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
5227 : :
3943 heikki.linnakangas@i 5228 : 82829 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
879 pg@bowt.ie 5229 : 82829 : xlrec.xmax = xid;
4609 alvherre@alvh.no-ip. 5230 : 165658 : xlrec.infobits_set = compute_infobits(new_infomask,
5231 : 82829 : tuple->t_data->t_infomask2);
3337 andres@anarazel.de 5232 : 82829 : xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
207 peter@eisentraut.org 5233 : 82829 : XLogRegisterData(&xlrec, SizeOfHeapLock);
5234 : :
5235 : : /* we don't decode row locks atm, so no need to log the origin */
5236 : :
3943 heikki.linnakangas@i 5237 : 82829 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5238 : :
6264 tgl@sss.pgh.pa.us 5239 : 82829 : PageSetLSN(page, recptr);
5240 : : }
5241 : :
7436 5242 [ - + ]: 83173 : END_CRIT_SECTION();
5243 : :
2359 andres@anarazel.de 5244 : 83173 : result = TM_Ok;
5245 : :
3337 5246 : 83435 : out_locked:
513 akorotkov@postgresql 5247 : 83435 : LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
5248 : :
3337 andres@anarazel.de 5249 : 84919 : out_unlocked:
5250 [ + + ]: 84919 : if (BufferIsValid(vmbuffer))
5251 : 1662 : ReleaseBuffer(vmbuffer);
5252 : :
5253 : : /*
5254 : : * Don't update the visibility map here. Locking a tuple doesn't change
5255 : : * visibility info.
5256 : : */
5257 : :
5258 : : /*
5259 : : * Now that we have successfully marked the tuple as locked, we can
5260 : : * release the lmgr tuple lock, if we had it.
5261 : : */
7434 tgl@sss.pgh.pa.us 5262 [ + + ]: 84919 : if (have_tuple_lock)
4609 alvherre@alvh.no-ip. 5263 : 140 : UnlockTupleTuplock(relation, tid, mode);
5264 : :
3337 andres@anarazel.de 5265 : 84919 : return result;
5266 : : }
5267 : :
5268 : : /*
5269 : : * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5270 : : * its normal, Xmax-based tuple lock.
5271 : : *
5272 : : * have_tuple_lock is an input and output parameter: on input, it indicates
5273 : : * whether the lock has previously been acquired (and this function does
5274 : : * nothing in that case). If this function returns success, have_tuple_lock
5275 : : * has been flipped to true.
5276 : : *
5277 : : * Returns false if it was unable to obtain the lock; this can only happen if
5278 : : * wait_policy is Skip.
5279 : : */
5280 : : static bool
3907 alvherre@alvh.no-ip. 5281 : 270 : heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode,
5282 : : LockWaitPolicy wait_policy, bool *have_tuple_lock)
5283 : : {
5284 [ + + ]: 270 : if (*have_tuple_lock)
5285 : 9 : return true;
5286 : :
5287 [ + + + - ]: 261 : switch (wait_policy)
5288 : : {
5289 : 220 : case LockWaitBlock:
5290 : 220 : LockTupleTuplock(relation, tid, mode);
5291 : 220 : break;
5292 : :
5293 : 34 : case LockWaitSkip:
176 fujii@postgresql.org 5294 [ + + ]: 34 : if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
3907 alvherre@alvh.no-ip. 5295 : 1 : return false;
5296 : 33 : break;
5297 : :
5298 : 7 : case LockWaitError:
95 fujii@postgresql.org 5299 [ + + ]: 7 : if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
3907 alvherre@alvh.no-ip. 5300 [ + - ]: 1 : ereport(ERROR,
5301 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5302 : : errmsg("could not obtain lock on row in relation \"%s\"",
5303 : : RelationGetRelationName(relation))));
5304 : 6 : break;
5305 : : }
5306 : 259 : *have_tuple_lock = true;
5307 : :
5308 : 259 : return true;
5309 : : }
5310 : :
5311 : : /*
5312 : : * Given an original set of Xmax and infomask, and a transaction (identified by
5313 : : * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5314 : : * corresponding infomasks to use on the tuple.
5315 : : *
5316 : : * Note that this might have side effects such as creating a new MultiXactId.
5317 : : *
5318 : : * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5319 : : * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5320 : : * but it was not running anymore. There is a race condition, which is that the
5321 : : * MultiXactId may have finished since then, but that uncommon case is handled
5322 : : * either here, or within MultiXactIdExpand.
5323 : : *
5324 : : * There is a similar race condition possible when the old xmax was a regular
5325 : : * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5326 : : * window, but it's still possible to end up creating an unnecessary
5327 : : * MultiXactId. Fortunately this is harmless.
5328 : : */
5329 : : static void
4609 5330 : 1953788 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
5331 : : uint16 old_infomask2, TransactionId add_to_xmax,
5332 : : LockTupleMode mode, bool is_update,
5333 : : TransactionId *result_xmax, uint16 *result_infomask,
5334 : : uint16 *result_infomask2)
5335 : : {
5336 : : TransactionId new_xmax;
5337 : : uint16 new_infomask,
5338 : : new_infomask2;
5339 : :
4279 5340 [ + - ]: 1953788 : Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
5341 : :
4609 5342 : 2057747 : l5:
5343 : 2057747 : new_infomask = 0;
5344 : 2057747 : new_infomask2 = 0;
5345 [ + + ]: 2057747 : if (old_infomask & HEAP_XMAX_INVALID)
5346 : : {
5347 : : /*
5348 : : * No previous locker; we just insert our own TransactionId.
5349 : : *
5350 : : * Note that it's critical that this case be the first one checked,
5351 : : * because there are several blocks below that come back to this one
5352 : : * to implement certain optimizations; old_infomask might contain
5353 : : * other dirty bits in those cases, but we don't really care.
5354 : : */
5355 [ + + ]: 1952646 : if (is_update)
5356 : : {
5357 : 1721143 : new_xmax = add_to_xmax;
5358 [ + + ]: 1721143 : if (mode == LockTupleExclusive)
5359 : 1454573 : new_infomask2 |= HEAP_KEYS_UPDATED;
5360 : : }
5361 : : else
5362 : : {
5363 : 231503 : new_infomask |= HEAP_XMAX_LOCK_ONLY;
5364 [ + + + + : 231503 : switch (mode)
- ]
5365 : : {
5366 : 2518 : case LockTupleKeyShare:
5367 : 2518 : new_xmax = add_to_xmax;
5368 : 2518 : new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5369 : 2518 : break;
5370 : 739 : case LockTupleShare:
5371 : 739 : new_xmax = add_to_xmax;
5372 : 739 : new_infomask |= HEAP_XMAX_SHR_LOCK;
5373 : 739 : break;
5374 : 132556 : case LockTupleNoKeyExclusive:
5375 : 132556 : new_xmax = add_to_xmax;
5376 : 132556 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5377 : 132556 : break;
5378 : 95690 : case LockTupleExclusive:
5379 : 95690 : new_xmax = add_to_xmax;
5380 : 95690 : new_infomask |= HEAP_XMAX_EXCL_LOCK;
5381 : 95690 : new_infomask2 |= HEAP_KEYS_UPDATED;
5382 : 95690 : break;
4609 alvherre@alvh.no-ip. 5383 :UBC 0 : default:
5384 : 0 : new_xmax = InvalidTransactionId; /* silence compiler */
5385 [ # # ]: 0 : elog(ERROR, "invalid lock mode");
5386 : : }
5387 : : }
5388 : : }
4609 alvherre@alvh.no-ip. 5389 [ + + ]:CBC 105101 : else if (old_infomask & HEAP_XMAX_IS_MULTI)
5390 : : {
5391 : : MultiXactStatus new_status;
5392 : :
5393 : : /*
5394 : : * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5395 : : * cross-check.
5396 : : */
5397 [ - + ]: 132 : Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5398 : :
5399 : : /*
5400 : : * A multixact together with LOCK_ONLY set but neither lock bit set
5401 : : * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5402 : : * anymore. This check is critical for databases upgraded by
5403 : : * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5404 : : * that such multis are never passed.
5405 : : */
3361 5406 [ - + ]: 132 : if (HEAP_LOCKED_UPGRADED(old_infomask))
5407 : : {
4609 alvherre@alvh.no-ip. 5408 :UBC 0 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5409 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5410 : 0 : goto l5;
5411 : : }
5412 : :
5413 : : /*
5414 : : * If the XMAX is already a MultiXactId, then we need to expand it to
5415 : : * include add_to_xmax; but if all the members were lockers and are
5416 : : * all gone, we can do away with the IS_MULTI bit and just set
5417 : : * add_to_xmax as the only locker/updater. If all lockers are gone
5418 : : * and we have an updater that aborted, we can also do without a
5419 : : * multi.
5420 : : *
5421 : : * The cost of doing GetMultiXactIdMembers would be paid by
5422 : : * MultiXactIdExpand if we weren't to do this, so this check is not
5423 : : * incurring extra work anyhow.
5424 : : */
4057 alvherre@alvh.no-ip. 5425 [ + + ]:CBC 132 : if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5426 : : {
4609 5427 [ + + ]: 26 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
3802 5428 [ + - ]: 10 : !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
5429 : : old_infomask)))
5430 : : {
5431 : : /*
5432 : : * Reset these bits and restart; otherwise fall through to
5433 : : * create a new multi below.
5434 : : */
4609 5435 : 26 : old_infomask &= ~HEAP_XMAX_IS_MULTI;
5436 : 26 : old_infomask |= HEAP_XMAX_INVALID;
5437 : 26 : goto l5;
5438 : : }
5439 : : }
5440 : :
5441 : 106 : new_status = get_mxact_status_for_lock(mode, is_update);
5442 : :
5443 : 106 : new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5444 : : new_status);
5445 : 106 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5446 : : }
5447 [ + + ]: 104969 : else if (old_infomask & HEAP_XMAX_COMMITTED)
5448 : : {
5449 : : /*
5450 : : * It's a committed update, so we need to preserve him as updater of
5451 : : * the tuple.
5452 : : */
5453 : : MultiXactStatus status;
5454 : : MultiXactStatus new_status;
5455 : :
5456 [ - + ]: 13 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4609 alvherre@alvh.no-ip. 5457 :UBC 0 : status = MultiXactStatusUpdate;
5458 : : else
4609 alvherre@alvh.no-ip. 5459 :CBC 13 : status = MultiXactStatusNoKeyUpdate;
5460 : :
5461 : 13 : new_status = get_mxact_status_for_lock(mode, is_update);
5462 : :
5463 : : /*
5464 : : * since it's not running, it's obviously impossible for the old
5465 : : * updater to be identical to the current one, so we need not check
5466 : : * for that case as we do in the block above.
5467 : : */
5468 : 13 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5469 : 13 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5470 : : }
5471 [ + + ]: 104956 : else if (TransactionIdIsInProgress(xmax))
5472 : : {
5473 : : /*
5474 : : * If the XMAX is a valid, in-progress TransactionId, then we need to
5475 : : * create a new MultiXactId that includes both the old locker or
5476 : : * updater and our own TransactionId.
5477 : : */
5478 : : MultiXactStatus new_status;
5479 : : MultiXactStatus old_status;
5480 : : LockTupleMode old_mode;
5481 : :
5482 [ + + ]: 104947 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5483 : : {
5484 [ + + ]: 104921 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4279 5485 : 5624 : old_status = MultiXactStatusForKeyShare;
4609 5486 [ + + ]: 99297 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4279 5487 : 432 : old_status = MultiXactStatusForShare;
4609 5488 [ + - ]: 98865 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5489 : : {
5490 [ + + ]: 98865 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4279 5491 : 92768 : old_status = MultiXactStatusForUpdate;
5492 : : else
5493 : 6097 : old_status = MultiXactStatusForNoKeyUpdate;
5494 : : }
5495 : : else
5496 : : {
5497 : : /*
5498 : : * LOCK_ONLY can be present alone only when a page has been
5499 : : * upgraded by pg_upgrade. But in that case,
5500 : : * TransactionIdIsInProgress() should have returned false. We
5501 : : * assume it's no longer locked in this case.
5502 : : */
4609 alvherre@alvh.no-ip. 5503 [ # # ]:UBC 0 : elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5504 : 0 : old_infomask |= HEAP_XMAX_INVALID;
5505 : 0 : old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5506 : 0 : goto l5;
5507 : : }
5508 : : }
5509 : : else
5510 : : {
5511 : : /* it's an update, but which kind? */
4609 alvherre@alvh.no-ip. 5512 [ - + ]:CBC 26 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4279 alvherre@alvh.no-ip. 5513 :UBC 0 : old_status = MultiXactStatusUpdate;
5514 : : else
4279 alvherre@alvh.no-ip. 5515 :CBC 26 : old_status = MultiXactStatusNoKeyUpdate;
5516 : : }
5517 : :
5518 : 104947 : old_mode = TUPLOCK_from_mxstatus(old_status);
5519 : :
5520 : : /*
5521 : : * If the lock to be acquired is for the same TransactionId as the
5522 : : * existing lock, there's an optimization possible: consider only the
5523 : : * strongest of both locks as the only one present, and restart.
5524 : : */
4609 5525 [ + + ]: 104947 : if (xmax == add_to_xmax)
5526 : : {
5527 : : /*
5528 : : * Note that it's not possible for the original tuple to be
5529 : : * updated: we wouldn't be here because the tuple would have been
5530 : : * invisible and we wouldn't try to update it. As a subtlety,
5531 : : * this code can also run when traversing an update chain to lock
5532 : : * future versions of a tuple. But we wouldn't be here either,
5533 : : * because the add_to_xmax would be different from the original
5534 : : * updater.
5535 : : */
4279 5536 [ - + ]: 103925 : Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5537 : :
5538 : : /* acquire the strongest of both */
5539 [ + + ]: 103925 : if (mode < old_mode)
5540 : 52208 : mode = old_mode;
5541 : : /* mustn't touch is_update */
5542 : :
5543 : 103925 : old_infomask |= HEAP_XMAX_INVALID;
5544 : 103925 : goto l5;
5545 : : }
5546 : :
5547 : : /* otherwise, just fall back to creating a new multixact */
5548 : 1022 : new_status = get_mxact_status_for_lock(mode, is_update);
5549 : 1022 : new_xmax = MultiXactIdCreate(xmax, old_status,
5550 : : add_to_xmax, new_status);
4609 5551 : 1022 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5552 : : }
5553 [ + + + + ]: 14 : else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5554 : 5 : TransactionIdDidCommit(xmax))
5555 : 1 : {
5556 : : /*
5557 : : * It's a committed update, so we gotta preserve him as updater of the
5558 : : * tuple.
5559 : : */
5560 : : MultiXactStatus status;
5561 : : MultiXactStatus new_status;
5562 : :
5563 [ - + ]: 1 : if (old_infomask2 & HEAP_KEYS_UPDATED)
4609 alvherre@alvh.no-ip. 5564 :UBC 0 : status = MultiXactStatusUpdate;
5565 : : else
4609 alvherre@alvh.no-ip. 5566 :CBC 1 : status = MultiXactStatusNoKeyUpdate;
5567 : :
5568 : 1 : new_status = get_mxact_status_for_lock(mode, is_update);
5569 : :
5570 : : /*
5571 : : * since it's not running, it's obviously impossible for the old
5572 : : * updater to be identical to the current one, so we need not check
5573 : : * for that case as we do in the block above.
5574 : : */
5575 : 1 : new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5576 : 1 : GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5577 : : }
5578 : : else
5579 : : {
5580 : : /*
5581 : : * Can get here iff the locking/updating transaction was running when
5582 : : * the infomask was extracted from the tuple, but finished before
5583 : : * TransactionIdIsInProgress got to run. Deal with it as if there was
5584 : : * no locker at all in the first place.
5585 : : */
5586 : 8 : old_infomask |= HEAP_XMAX_INVALID;
5587 : 8 : goto l5;
5588 : : }
5589 : :
5590 : 1953788 : *result_infomask = new_infomask;
5591 : 1953788 : *result_infomask2 = new_infomask2;
5592 : 1953788 : *result_xmax = new_xmax;
5593 : 1953788 : }
5594 : :
5595 : : /*
5596 : : * Subroutine for heap_lock_updated_tuple_rec.
5597 : : *
5598 : : * Given a hypothetical multixact status held by the transaction identified
5599 : : * with the given xid, does the current transaction need to wait, fail, or can
5600 : : * it continue if it wanted to acquire a lock of the given mode? "needwait"
5601 : : * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5602 : : * returned. If the lock is already held by the current transaction, return
5603 : : * TM_SelfModified. In case of a conflict with another transaction, a
5604 : : * different HeapTupleSatisfiesUpdate return code is returned.
5605 : : *
5606 : : * The held status is said to be hypothetical because it might correspond to a
5607 : : * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5608 : : * way for simplicity of API.
5609 : : */
5610 : : static TM_Result
4301 5611 : 32 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5612 : : LockTupleMode mode, HeapTuple tup,
5613 : : bool *needwait)
5614 : : {
5615 : : MultiXactStatus wantedstatus;
5616 : :
5617 : 32 : *needwait = false;
5618 : 32 : wantedstatus = get_mxact_status_for_lock(mode, false);
5619 : :
5620 : : /*
5621 : : * Note: we *must* check TransactionIdIsInProgress before
5622 : : * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5623 : : * for an explanation.
5624 : : */
5625 [ - + ]: 32 : if (TransactionIdIsCurrentTransactionId(xid))
5626 : : {
5627 : : /*
5628 : : * The tuple has already been locked by our own transaction. This is
5629 : : * very rare but can happen if multiple transactions are trying to
5630 : : * lock an ancient version of the same tuple.
5631 : : */
2359 andres@anarazel.de 5632 :UBC 0 : return TM_SelfModified;
5633 : : }
4301 alvherre@alvh.no-ip. 5634 [ + + ]:CBC 32 : else if (TransactionIdIsInProgress(xid))
5635 : : {
5636 : : /*
5637 : : * If the locking transaction is running, what we do depends on
5638 : : * whether the lock modes conflict: if they do, then we must wait for
5639 : : * it to finish; otherwise we can fall through to lock this tuple
5640 : : * version without waiting.
5641 : : */
5642 [ + + ]: 16 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5643 : 16 : LOCKMODE_from_mxstatus(wantedstatus)))
5644 : : {
5645 : 8 : *needwait = true;
5646 : : }
5647 : :
5648 : : /*
5649 : : * If we set needwait above, then this value doesn't matter;
5650 : : * otherwise, this value signals to caller that it's okay to proceed.
5651 : : */
2359 andres@anarazel.de 5652 : 16 : return TM_Ok;
5653 : : }
4301 alvherre@alvh.no-ip. 5654 [ + + ]: 16 : else if (TransactionIdDidAbort(xid))
2359 andres@anarazel.de 5655 : 3 : return TM_Ok;
4301 alvherre@alvh.no-ip. 5656 [ + - ]: 13 : else if (TransactionIdDidCommit(xid))
5657 : : {
5658 : : /*
5659 : : * The other transaction committed. If it was only a locker, then the
5660 : : * lock is completely gone now and we can return success; but if it
5661 : : * was an update, then what we do depends on whether the two lock
5662 : : * modes conflict. If they conflict, then we must report error to
5663 : : * caller. But if they don't, we can fall through to allow the current
5664 : : * transaction to lock the tuple.
5665 : : *
5666 : : * Note: the reason we worry about ISUPDATE here is because as soon as
5667 : : * a transaction ends, all its locks are gone and meaningless, and
5668 : : * thus we can ignore them; whereas its updates persist. In the
5669 : : * TransactionIdIsInProgress case, above, we don't need to check
5670 : : * because we know the lock is still "alive" and thus a conflict needs
5671 : : * always be checked.
5672 : : */
4293 5673 [ + + ]: 13 : if (!ISUPDATE_from_mxstatus(status))
2359 andres@anarazel.de 5674 : 4 : return TM_Ok;
5675 : :
4301 alvherre@alvh.no-ip. 5676 [ + + ]: 9 : if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5677 : 9 : LOCKMODE_from_mxstatus(wantedstatus)))
5678 : : {
5679 : : /* bummer */
1657 5680 [ + + ]: 8 : if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
2359 andres@anarazel.de 5681 : 6 : return TM_Updated;
5682 : : else
5683 : 2 : return TM_Deleted;
5684 : : }
5685 : :
5686 : 1 : return TM_Ok;
5687 : : }
5688 : :
5689 : : /* Not in progress, not aborted, not committed -- must have crashed */
2359 andres@anarazel.de 5690 :UBC 0 : return TM_Ok;
5691 : : }
5692 : :
5693 : :
5694 : : /*
5695 : : * Recursive part of heap_lock_updated_tuple
5696 : : *
5697 : : * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5698 : : * xid with the given mode; if this tuple is updated, recurse to lock the new
5699 : : * version as well.
5700 : : */
5701 : : static TM_Result
4609 alvherre@alvh.no-ip. 5702 :CBC 81 : heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid,
5703 : : LockTupleMode mode)
5704 : : {
5705 : : TM_Result result;
5706 : : ItemPointerData tupid;
5707 : : HeapTupleData mytup;
5708 : : Buffer buf;
5709 : : uint16 new_infomask,
5710 : : new_infomask2,
5711 : : old_infomask,
5712 : : old_infomask2;
5713 : : TransactionId xmax,
5714 : : new_xmax;
4301 5715 : 81 : TransactionId priorXmax = InvalidTransactionId;
3337 andres@anarazel.de 5716 : 81 : bool cleared_all_frozen = false;
5717 : : bool pinned_desired_page;
5718 : 81 : Buffer vmbuffer = InvalidBuffer;
5719 : : BlockNumber block;
5720 : :
4609 alvherre@alvh.no-ip. 5721 : 81 : ItemPointerCopy(tid, &tupid);
5722 : :
5723 : : for (;;)
5724 : : {
5725 : 84 : new_infomask = 0;
5726 : 84 : new_xmax = InvalidTransactionId;
3337 andres@anarazel.de 5727 : 84 : block = ItemPointerGetBlockNumber(&tupid);
4609 alvherre@alvh.no-ip. 5728 : 84 : ItemPointerCopy(&tupid, &(mytup.t_self));
5729 : :
1242 tgl@sss.pgh.pa.us 5730 [ + - ]: 84 : if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5731 : : {
5732 : : /*
5733 : : * if we fail to find the updated version of the tuple, it's
5734 : : * because it was vacuumed/pruned away after its creator
5735 : : * transaction aborted. So behave as if we got to the end of the
5736 : : * chain, and there's no further tuple to lock: return success to
5737 : : * caller.
5738 : : */
2359 andres@anarazel.de 5739 :UBC 0 : result = TM_Ok;
2745 tgl@sss.pgh.pa.us 5740 : 0 : goto out_unlocked;
5741 : : }
5742 : :
4609 alvherre@alvh.no-ip. 5743 :CBC 84 : l4:
5744 [ - + ]: 92 : CHECK_FOR_INTERRUPTS();
5745 : :
5746 : : /*
5747 : : * Before locking the buffer, pin the visibility map page if it
5748 : : * appears to be necessary. Since we haven't got the lock yet,
5749 : : * someone else might be in the middle of changing this, so we'll need
5750 : : * to recheck after we have the lock.
5751 : : */
3337 andres@anarazel.de 5752 [ - + ]: 92 : if (PageIsAllVisible(BufferGetPage(buf)))
5753 : : {
3337 andres@anarazel.de 5754 :UBC 0 : visibilitymap_pin(rel, block, &vmbuffer);
2745 tgl@sss.pgh.pa.us 5755 : 0 : pinned_desired_page = true;
5756 : : }
5757 : : else
2745 tgl@sss.pgh.pa.us 5758 :CBC 92 : pinned_desired_page = false;
5759 : :
4609 alvherre@alvh.no-ip. 5760 : 92 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5761 : :
5762 : : /*
5763 : : * If we didn't pin the visibility map page and the page has become
5764 : : * all visible while we were busy locking the buffer, we'll have to
5765 : : * unlock and re-lock, to avoid holding the buffer lock across I/O.
5766 : : * That's a bit unfortunate, but hopefully shouldn't happen often.
5767 : : *
5768 : : * Note: in some paths through this function, we will reach here
5769 : : * holding a pin on a vm page that may or may not be the one matching
5770 : : * this page. If this page isn't all-visible, we won't use the vm
5771 : : * page, but we hold onto such a pin till the end of the function.
5772 : : */
2745 tgl@sss.pgh.pa.us 5773 [ + - - + ]: 92 : if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5774 : : {
3320 andres@anarazel.de 5775 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5776 : 0 : visibilitymap_pin(rel, block, &vmbuffer);
5777 : 0 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5778 : : }
5779 : :
5780 : : /*
5781 : : * Check the tuple XMIN against prior XMAX, if any. If we reached the
5782 : : * end of the chain, we're done, so return success.
5783 : : */
4301 alvherre@alvh.no-ip. 5784 [ + + - + ]:CBC 95 : if (TransactionIdIsValid(priorXmax) &&
2865 5785 : 3 : !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5786 : : priorXmax))
5787 : : {
2359 andres@anarazel.de 5788 :UBC 0 : result = TM_Ok;
3337 5789 : 0 : goto out_locked;
5790 : : }
5791 : :
5792 : : /*
5793 : : * Also check Xmin: if this tuple was created by an aborted
5794 : : * (sub)transaction, then we already locked the last live one in the
5795 : : * chain, thus we're done, so return success.
5796 : : */
3284 alvherre@alvh.no-ip. 5797 [ + + ]:CBC 92 : if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
5798 : : {
2359 andres@anarazel.de 5799 : 13 : result = TM_Ok;
2745 tgl@sss.pgh.pa.us 5800 : 13 : goto out_locked;
5801 : : }
5802 : :
4609 alvherre@alvh.no-ip. 5803 : 79 : old_infomask = mytup.t_data->t_infomask;
4301 5804 : 79 : old_infomask2 = mytup.t_data->t_infomask2;
4609 5805 : 79 : xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5806 : :
5807 : : /*
5808 : : * If this tuple version has been updated or locked by some concurrent
5809 : : * transaction(s), what we do depends on whether our lock mode
5810 : : * conflicts with what those other transactions hold, and also on the
5811 : : * status of them.
5812 : : */
4301 5813 [ + + ]: 79 : if (!(old_infomask & HEAP_XMAX_INVALID))
5814 : : {
5815 : : TransactionId rawxmax;
5816 : : bool needwait;
5817 : :
5818 : 30 : rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5819 [ + + ]: 30 : if (old_infomask & HEAP_XMAX_IS_MULTI)
5820 : : {
5821 : : int nmembers;
5822 : : int i;
5823 : : MultiXactMember *members;
5824 : :
5825 : : /*
5826 : : * We don't need a test for pg_upgrade'd tuples: this is only
5827 : : * applied to tuples after the first in an update chain. Said
5828 : : * first tuple in the chain may well be locked-in-9.2-and-
5829 : : * pg_upgraded, but that one was already locked by our caller,
5830 : : * not us; and any subsequent ones cannot be because our
5831 : : * caller must necessarily have obtained a snapshot later than
5832 : : * the pg_upgrade itself.
5833 : : */
3361 5834 [ - + ]: 1 : Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
5835 : :
4057 5836 : 1 : nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
2999 tgl@sss.pgh.pa.us 5837 : 1 : HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4301 alvherre@alvh.no-ip. 5838 [ + + ]: 4 : for (i = 0; i < nmembers; i++)
5839 : : {
3337 andres@anarazel.de 5840 : 3 : result = test_lockmode_for_conflict(members[i].status,
5841 : 3 : members[i].xid,
5842 : : mode,
5843 : : &mytup,
5844 : : &needwait);
5845 : :
5846 : : /*
5847 : : * If the tuple was already locked by ourselves in a
5848 : : * previous iteration of this (say heap_lock_tuple was
5849 : : * forced to restart the locking loop because of a change
5850 : : * in xmax), then we hold the lock already on this tuple
5851 : : * version and we don't need to do anything; and this is
5852 : : * not an error condition either. We just need to skip
5853 : : * this tuple and continue locking the next version in the
5854 : : * update chain.
5855 : : */
2359 5856 [ - + ]: 3 : if (result == TM_SelfModified)
5857 : : {
2964 alvherre@alvh.no-ip. 5858 :UBC 0 : pfree(members);
5859 : 0 : goto next;
5860 : : }
5861 : :
4301 alvherre@alvh.no-ip. 5862 [ - + ]:CBC 3 : if (needwait)
5863 : : {
4301 alvherre@alvh.no-ip. 5864 :UBC 0 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
4189 5865 : 0 : XactLockTableWait(members[i].xid, rel,
5866 : : &mytup.t_self,
5867 : : XLTW_LockUpdated);
4301 5868 : 0 : pfree(members);
5869 : 0 : goto l4;
5870 : : }
2359 andres@anarazel.de 5871 [ - + ]:CBC 3 : if (result != TM_Ok)
5872 : : {
4301 alvherre@alvh.no-ip. 5873 :UBC 0 : pfree(members);
3337 andres@anarazel.de 5874 : 0 : goto out_locked;
5875 : : }
5876 : : }
4301 alvherre@alvh.no-ip. 5877 [ + - ]:CBC 1 : if (members)
5878 : 1 : pfree(members);
5879 : : }
5880 : : else
5881 : : {
5882 : : MultiXactStatus status;
5883 : :
5884 : : /*
5885 : : * For a non-multi Xmax, we first need to compute the
5886 : : * corresponding MultiXactStatus by using the infomask bits.
5887 : : */
5888 [ + + ]: 29 : if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5889 : : {
5890 [ + - ]: 10 : if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5891 : 10 : status = MultiXactStatusForKeyShare;
4301 alvherre@alvh.no-ip. 5892 [ # # ]:UBC 0 : else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5893 : 0 : status = MultiXactStatusForShare;
5894 [ # # ]: 0 : else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5895 : : {
5896 [ # # ]: 0 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5897 : 0 : status = MultiXactStatusForUpdate;
5898 : : else
5899 : 0 : status = MultiXactStatusForNoKeyUpdate;
5900 : : }
5901 : : else
5902 : : {
5903 : : /*
5904 : : * LOCK_ONLY present alone (a pg_upgraded tuple marked
5905 : : * as share-locked in the old cluster) shouldn't be
5906 : : * seen in the middle of an update chain.
5907 : : */
5908 [ # # ]: 0 : elog(ERROR, "invalid lock status in tuple");
5909 : : }
5910 : : }
5911 : : else
5912 : : {
5913 : : /* it's an update, but which kind? */
4301 alvherre@alvh.no-ip. 5914 [ + + ]:CBC 19 : if (old_infomask2 & HEAP_KEYS_UPDATED)
5915 : 14 : status = MultiXactStatusUpdate;
5916 : : else
5917 : 5 : status = MultiXactStatusNoKeyUpdate;
5918 : : }
5919 : :
3337 andres@anarazel.de 5920 : 29 : result = test_lockmode_for_conflict(status, rawxmax, mode,
5921 : : &mytup, &needwait);
5922 : :
5923 : : /*
5924 : : * If the tuple was already locked by ourselves in a previous
5925 : : * iteration of this (say heap_lock_tuple was forced to
5926 : : * restart the locking loop because of a change in xmax), then
5927 : : * we hold the lock already on this tuple version and we don't
5928 : : * need to do anything; and this is not an error condition
5929 : : * either. We just need to skip this tuple and continue
5930 : : * locking the next version in the update chain.
5931 : : */
2359 5932 [ - + ]: 29 : if (result == TM_SelfModified)
2964 alvherre@alvh.no-ip. 5933 :UBC 0 : goto next;
5934 : :
4301 alvherre@alvh.no-ip. 5935 [ + + ]:CBC 29 : if (needwait)
5936 : : {
5937 : 8 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
3867 heikki.linnakangas@i 5938 : 8 : XactLockTableWait(rawxmax, rel, &mytup.t_self,
5939 : : XLTW_LockUpdated);
4301 alvherre@alvh.no-ip. 5940 : 8 : goto l4;
5941 : : }
2359 andres@anarazel.de 5942 [ + + ]: 21 : if (result != TM_Ok)
5943 : : {
3337 5944 : 8 : goto out_locked;
5945 : : }
5946 : : }
5947 : : }
5948 : :
5949 : : /* compute the new Xmax and infomask values for the tuple ... */
4609 alvherre@alvh.no-ip. 5950 : 63 : compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5951 : : xid, mode, false,
5952 : : &new_xmax, &new_infomask, &new_infomask2);
5953 : :
3337 andres@anarazel.de 5954 [ - + - - ]: 63 : if (PageIsAllVisible(BufferGetPage(buf)) &&
3337 andres@anarazel.de 5955 :UBC 0 : visibilitymap_clear(rel, block, vmbuffer,
5956 : : VISIBILITYMAP_ALL_FROZEN))
5957 : 0 : cleared_all_frozen = true;
5958 : :
4609 alvherre@alvh.no-ip. 5959 :CBC 63 : START_CRIT_SECTION();
5960 : :
5961 : : /* ... and set them */
5962 : 63 : HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5963 : 63 : mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5964 : 63 : mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5965 : 63 : mytup.t_data->t_infomask |= new_infomask;
5966 : 63 : mytup.t_data->t_infomask2 |= new_infomask2;
5967 : :
5968 : 63 : MarkBufferDirty(buf);
5969 : :
5970 : : /* XLOG stuff */
5971 [ + - - + : 63 : if (RelationNeedsWAL(rel))
- - - - ]
5972 : : {
5973 : : xl_heap_lock_updated xlrec;
5974 : : XLogRecPtr recptr;
3426 kgrittn@postgresql.o 5975 : 63 : Page page = BufferGetPage(buf);
5976 : :
3943 heikki.linnakangas@i 5977 : 63 : XLogBeginInsert();
5978 : 63 : XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
5979 : :
5980 : 63 : xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
4609 alvherre@alvh.no-ip. 5981 : 63 : xlrec.xmax = new_xmax;
5982 : 63 : xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
3337 andres@anarazel.de 5983 : 63 : xlrec.flags =
5984 : 63 : cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5985 : :
207 peter@eisentraut.org 5986 : 63 : XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
5987 : :
3943 heikki.linnakangas@i 5988 : 63 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5989 : :
4609 alvherre@alvh.no-ip. 5990 : 63 : PageSetLSN(page, recptr);
5991 : : }
5992 : :
5993 [ - + ]: 63 : END_CRIT_SECTION();
5994 : :
2964 5995 : 63 : next:
5996 : : /* if we find the end of update chain, we're done. */
4609 5997 [ + - + - ]: 126 : if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
2709 andres@anarazel.de 5998 [ + + ]: 126 : HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
4483 bruce@momjian.us 5999 [ + + ]: 67 : ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
4609 alvherre@alvh.no-ip. 6000 : 4 : HeapTupleHeaderIsOnlyLocked(mytup.t_data))
6001 : : {
2359 andres@anarazel.de 6002 : 60 : result = TM_Ok;
3337 6003 : 60 : goto out_locked;
6004 : : }
6005 : :
6006 : : /* tail recursion */
4301 alvherre@alvh.no-ip. 6007 : 3 : priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
4609 6008 : 3 : ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6009 : 3 : UnlockReleaseBuffer(buf);
6010 : : }
6011 : :
6012 : : result = TM_Ok;
6013 : :
3337 andres@anarazel.de 6014 : 81 : out_locked:
6015 : 81 : UnlockReleaseBuffer(buf);
6016 : :
2745 tgl@sss.pgh.pa.us 6017 : 81 : out_unlocked:
3337 andres@anarazel.de 6018 [ - + ]: 81 : if (vmbuffer != InvalidBuffer)
3337 andres@anarazel.de 6019 :UBC 0 : ReleaseBuffer(vmbuffer);
6020 : :
3337 andres@anarazel.de 6021 :CBC 81 : return result;
6022 : : }
6023 : :
6024 : : /*
6025 : : * heap_lock_updated_tuple
6026 : : * Follow update chain when locking an updated tuple, acquiring locks (row
6027 : : * marks) on the updated versions.
6028 : : *
6029 : : * The initial tuple is assumed to be already locked.
6030 : : *
6031 : : * This function doesn't check visibility, it just unconditionally marks the
6032 : : * tuple(s) as locked. If any tuple in the updated chain is being deleted
6033 : : * concurrently (or updated with the key being modified), sleep until the
6034 : : * transaction doing it is finished.
6035 : : *
6036 : : * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6037 : : * when we have to wait for other transactions to release them, as opposed to
6038 : : * what heap_lock_tuple does. The reason is that having more than one
6039 : : * transaction walking the chain is probably uncommon enough that risk of
6040 : : * starvation is not likely: one of the preconditions for being here is that
6041 : : * the snapshot in use predates the update that created this tuple (because we
6042 : : * started at an earlier version of the tuple), but at the same time such a
6043 : : * transaction cannot be using repeatable read or serializable isolation
6044 : : * levels, because that would lead to a serializability failure.
6045 : : */
6046 : : static TM_Result
4609 alvherre@alvh.no-ip. 6047 : 91 : heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid,
6048 : : TransactionId xid, LockTupleMode mode)
6049 : : {
6050 : : /*
6051 : : * If the tuple has not been updated, or has moved into another partition
6052 : : * (effectively a delete) stop here.
6053 : : */
2709 andres@anarazel.de 6054 [ + + ]: 91 : if (!HeapTupleHeaderIndicatesMovedPartitions(tuple->t_data) &&
6055 [ + + ]: 89 : !ItemPointerEquals(&tuple->t_self, ctid))
6056 : : {
6057 : : /*
6058 : : * If this is the first possibly-multixact-able operation in the
6059 : : * current transaction, set my per-backend OldestMemberMXactId
6060 : : * setting. We can be certain that the transaction will never become a
6061 : : * member of any older MultiXactIds than that. (We have to do this
6062 : : * even if we end up just using our own TransactionId below, since
6063 : : * some other backend could incorporate our XID into a MultiXact
6064 : : * immediately afterwards.)
6065 : : */
4609 alvherre@alvh.no-ip. 6066 : 81 : MultiXactIdSetOldestMember();
6067 : :
6068 : 81 : return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
6069 : : }
6070 : :
6071 : : /* nothing to lock */
2359 andres@anarazel.de 6072 : 10 : return TM_Ok;
6073 : : }
6074 : :
6075 : : /*
6076 : : * heap_finish_speculative - mark speculative insertion as successful
6077 : : *
6078 : : * To successfully finish a speculative insertion we have to clear speculative
6079 : : * token from tuple. To do so the t_ctid field, which will contain a
6080 : : * speculative token value, is modified in place to point to the tuple itself,
6081 : : * which is characteristic of a newly inserted ordinary tuple.
6082 : : *
6083 : : * NB: It is not ok to commit without either finishing or aborting a
6084 : : * speculative insertion. We could treat speculative tuples of committed
6085 : : * transactions implicitly as completed, but then we would have to be prepared
6086 : : * to deal with speculative tokens on committed tuples. That wouldn't be
6087 : : * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6088 : : * but clearing the token at completion isn't very expensive either.
6089 : : * An explicit confirmation WAL record also makes logical decoding simpler.
6090 : : */
6091 : : void
6092 : 2062 : heap_finish_speculative(Relation relation, ItemPointer tid)
6093 : : {
6094 : : Buffer buffer;
6095 : : Page page;
6096 : : OffsetNumber offnum;
3774 6097 : 2062 : ItemId lp = NULL;
6098 : : HeapTupleHeader htup;
6099 : :
2359 6100 : 2062 : buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3774 6101 : 2062 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
8 peter@eisentraut.org 6102 :GNC 2062 : page = BufferGetPage(buffer);
6103 : :
2359 andres@anarazel.de 6104 :CBC 2062 : offnum = ItemPointerGetOffsetNumber(tid);
3774 6105 [ + - ]: 2062 : if (PageGetMaxOffsetNumber(page) >= offnum)
6106 : 2062 : lp = PageGetItemId(page, offnum);
6107 : :
6108 [ + - - + ]: 2062 : if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
3579 andres@anarazel.de 6109 [ # # ]:UBC 0 : elog(ERROR, "invalid lp");
6110 : :
3774 andres@anarazel.de 6111 :CBC 2062 : htup = (HeapTupleHeader) PageGetItem(page, lp);
6112 : :
6113 : : /* NO EREPORT(ERROR) from here till changes are logged */
6114 : 2062 : START_CRIT_SECTION();
6115 : :
2359 6116 [ - + ]: 2062 : Assert(HeapTupleHeaderIsSpeculative(htup));
6117 : :
3774 6118 : 2062 : MarkBufferDirty(buffer);
6119 : :
6120 : : /*
6121 : : * Replace the speculative insertion token with a real t_ctid, pointing to
6122 : : * itself like it does on regular tuples.
6123 : : */
2359 6124 : 2062 : htup->t_ctid = *tid;
6125 : :
6126 : : /* XLOG stuff */
3774 6127 [ + + + + : 2062 : if (RelationNeedsWAL(relation))
+ - + - ]
6128 : : {
6129 : : xl_heap_confirm xlrec;
6130 : : XLogRecPtr recptr;
6131 : :
2359 6132 : 2053 : xlrec.offnum = ItemPointerGetOffsetNumber(tid);
6133 : :
3774 6134 : 2053 : XLogBeginInsert();
6135 : :
6136 : : /* We want the same filtering on this as on a plain insert */
3180 6137 : 2053 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6138 : :
207 peter@eisentraut.org 6139 : 2053 : XLogRegisterData(&xlrec, SizeOfHeapConfirm);
3774 andres@anarazel.de 6140 : 2053 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6141 : :
6142 : 2053 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6143 : :
6144 : 2053 : PageSetLSN(page, recptr);
6145 : : }
6146 : :
6147 [ - + ]: 2062 : END_CRIT_SECTION();
6148 : :
6149 : 2062 : UnlockReleaseBuffer(buffer);
6150 : 2062 : }
6151 : :
6152 : : /*
6153 : : * heap_abort_speculative - kill a speculatively inserted tuple
6154 : : *
6155 : : * Marks a tuple that was speculatively inserted in the same command as dead,
6156 : : * by setting its xmin as invalid. That makes it immediately appear as dead
6157 : : * to all transactions, including our own. In particular, it makes
6158 : : * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6159 : : * inserting a duplicate key value won't unnecessarily wait for our whole
6160 : : * transaction to finish (it'll just wait for our speculative insertion to
6161 : : * finish).
6162 : : *
6163 : : * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6164 : : * that arise due to a mutual dependency that is not user visible. By
6165 : : * definition, unprincipled deadlocks cannot be prevented by the user
6166 : : * reordering lock acquisition in client code, because the implementation level
6167 : : * lock acquisitions are not under the user's direct control. If speculative
6168 : : * inserters did not take this precaution, then under high concurrency they
6169 : : * could deadlock with each other, which would not be acceptable.
6170 : : *
6171 : : * This is somewhat redundant with heap_delete, but we prefer to have a
6172 : : * dedicated routine with stripped down requirements. Note that this is also
6173 : : * used to delete the TOAST tuples created during speculative insertion.
6174 : : *
6175 : : * This routine does not affect logical decoding as it only looks at
6176 : : * confirmation records.
6177 : : */
6178 : : void
2359 6179 : 10 : heap_abort_speculative(Relation relation, ItemPointer tid)
6180 : : {
3774 6181 : 10 : TransactionId xid = GetCurrentTransactionId();
6182 : : ItemId lp;
6183 : : HeapTupleData tp;
6184 : : Page page;
6185 : : BlockNumber block;
6186 : : Buffer buffer;
6187 : :
6188 [ - + ]: 10 : Assert(ItemPointerIsValid(tid));
6189 : :
6190 : 10 : block = ItemPointerGetBlockNumber(tid);
6191 : 10 : buffer = ReadBuffer(relation, block);
3426 kgrittn@postgresql.o 6192 : 10 : page = BufferGetPage(buffer);
6193 : :
3774 andres@anarazel.de 6194 : 10 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6195 : :
6196 : : /*
6197 : : * Page can't be all visible, we just inserted into it, and are still
6198 : : * running.
6199 : : */
6200 [ - + ]: 10 : Assert(!PageIsAllVisible(page));
6201 : :
6202 : 10 : lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6203 [ - + ]: 10 : Assert(ItemIdIsNormal(lp));
6204 : :
6205 : 10 : tp.t_tableOid = RelationGetRelid(relation);
6206 : 10 : tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6207 : 10 : tp.t_len = ItemIdGetLength(lp);
6208 : 10 : tp.t_self = *tid;
6209 : :
6210 : : /*
6211 : : * Sanity check that the tuple really is a speculatively inserted tuple,
6212 : : * inserted by us.
6213 : : */
6214 [ - + ]: 10 : if (tp.t_data->t_choice.t_heap.t_xmin != xid)
3774 andres@anarazel.de 6215 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a tuple inserted by another transaction");
3307 andres@anarazel.de 6216 [ + + - + ]:CBC 10 : if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
3774 andres@anarazel.de 6217 [ # # ]:UBC 0 : elog(ERROR, "attempted to kill a non-speculative tuple");
3774 andres@anarazel.de 6218 [ - + ]:CBC 10 : Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
6219 : :
6220 : : /*
6221 : : * No need to check for serializable conflicts here. There is never a
6222 : : * need for a combo CID, either. No need to extract replica identity, or
6223 : : * do anything special with infomask bits.
6224 : : */
6225 : :
6226 : 10 : START_CRIT_SECTION();
6227 : :
6228 : : /*
6229 : : * The tuple will become DEAD immediately. Flag that this page is a
6230 : : * candidate for pruning by setting xmin to TransactionXmin. While not
6231 : : * immediately prunable, it is the oldest xid we can cheaply determine
6232 : : * that's safe against wraparound / being older than the table's
6233 : : * relfrozenxid. To defend against the unlikely case of a new relation
6234 : : * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6235 : : * if so (vacuum can't subsequently move relfrozenxid to beyond
6236 : : * TransactionXmin, so there's no race here).
6237 : : */
1980 6238 [ - + ]: 10 : Assert(TransactionIdIsValid(TransactionXmin));
6239 : : {
495 noah@leadboat.com 6240 : 10 : TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6241 : : TransactionId prune_xid;
6242 : :
6243 [ - + ]: 10 : if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
495 noah@leadboat.com 6244 :UBC 0 : prune_xid = relfrozenxid;
6245 : : else
495 noah@leadboat.com 6246 :CBC 10 : prune_xid = TransactionXmin;
6247 [ - + + + : 10 : PageSetPrunable(page, prune_xid);
- + ]
6248 : : }
6249 : :
6250 : : /* store transaction information of xact deleting the tuple */
3774 andres@anarazel.de 6251 : 10 : tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
6252 : 10 : tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6253 : :
6254 : : /*
6255 : : * Set the tuple header xmin to InvalidTransactionId. This makes the
6256 : : * tuple immediately invisible everyone. (In particular, to any
6257 : : * transactions waiting on the speculative token, woken up later.)
6258 : : */
6259 : 10 : HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
6260 : :
6261 : : /* Clear the speculative insertion token too */
6262 : 10 : tp.t_data->t_ctid = tp.t_self;
6263 : :
6264 : 10 : MarkBufferDirty(buffer);
6265 : :
6266 : : /*
6267 : : * XLOG stuff
6268 : : *
6269 : : * The WAL records generated here match heap_delete(). The same recovery
6270 : : * routines are used.
6271 : : */
6272 [ + - - + : 10 : if (RelationNeedsWAL(relation))
- - - - ]
6273 : : {
6274 : : xl_heap_delete xlrec;
6275 : : XLogRecPtr recptr;
6276 : :
6277 : 10 : xlrec.flags = XLH_DELETE_IS_SUPER;
6278 : 20 : xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6279 : 10 : tp.t_data->t_infomask2);
6280 : 10 : xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
6281 : 10 : xlrec.xmax = xid;
6282 : :
6283 : 10 : XLogBeginInsert();
207 peter@eisentraut.org 6284 : 10 : XLogRegisterData(&xlrec, SizeOfHeapDelete);
3774 andres@anarazel.de 6285 : 10 : XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6286 : :
6287 : : /* No replica identity & replication origin logged */
6288 : :
6289 : 10 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6290 : :
6291 : 10 : PageSetLSN(page, recptr);
6292 : : }
6293 : :
6294 [ - + ]: 10 : END_CRIT_SECTION();
6295 : :
6296 : 10 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6297 : :
6298 [ + + ]: 10 : if (HeapTupleHasExternal(&tp))
6299 : : {
3307 6300 [ - + ]: 1 : Assert(!IsToastRelation(relation));
2164 rhaas@postgresql.org 6301 : 1 : heap_toast_delete(relation, &tp, true);
6302 : : }
6303 : :
6304 : : /*
6305 : : * Never need to mark tuple for invalidation, since catalogs don't support
6306 : : * speculative insertion
6307 : : */
6308 : :
6309 : : /* Now we can release the buffer */
3774 andres@anarazel.de 6310 : 10 : ReleaseBuffer(buffer);
6311 : :
6312 : : /* count deletion, as we counted the insertion too */
6313 : 10 : pgstat_count_heap_delete(relation);
6314 : 10 : }
6315 : :
6316 : : /*
6317 : : * heap_inplace_lock - protect inplace update from concurrent heap_update()
6318 : : *
6319 : : * Evaluate whether the tuple's state is compatible with a no-key update.
6320 : : * Current transaction rowmarks are fine, as is KEY SHARE from any
6321 : : * transaction. If compatible, return true with the buffer exclusive-locked,
6322 : : * and the caller must release that by calling
6323 : : * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6324 : : * an error. Otherwise, call release_callback(arg), wait for blocking
6325 : : * transactions to end, and return false.
6326 : : *
6327 : : * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6328 : : * DDL, this doesn't guarantee any particular predicate locking.
6329 : : *
6330 : : * One could modify this to return true for tuples with delete in progress,
6331 : : * All inplace updaters take a lock that conflicts with DROP. If explicit
6332 : : * "DELETE FROM pg_class" is in progress, we'll wait for it like we would an
6333 : : * update.
6334 : : *
6335 : : * Readers of inplace-updated fields expect changes to those fields are
6336 : : * durable. For example, vac_truncate_clog() reads datfrozenxid from
6337 : : * pg_database tuples via catalog snapshots. A future snapshot must not
6338 : : * return a lower datfrozenxid for the same database OID (lower in the
6339 : : * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6340 : : * tuple can start while we hold a lock on its buffer. In cases like
6341 : : * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6342 : : * to this transaction. ROLLBACK then is one case where it's okay to lose
6343 : : * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6344 : : * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6345 : : * committed tuple.)
6346 : : *
6347 : : * In principle, we could avoid waiting by overwriting every tuple in the
6348 : : * updated tuple chain. Reader expectations permit updating a tuple only if
6349 : : * it's aborted, is the tail of the chain, or we already updated the tuple
6350 : : * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6351 : : * order from tail to head. That would imply either (a) mutating all tuples
6352 : : * in one critical section or (b) accepting a chance of partial completion.
6353 : : * Partial completion of a relfrozenxid update would have the weird
6354 : : * consequence that the table's next VACUUM could see the table's relfrozenxid
6355 : : * move forward between vacuum_get_cutoffs() and finishing.
6356 : : */
6357 : : bool
347 noah@leadboat.com 6358 : 90832 : heap_inplace_lock(Relation relation,
6359 : : HeapTuple oldtup_ptr, Buffer buffer,
6360 : : void (*release_callback) (void *), void *arg)
6361 : : {
6362 : 90832 : HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6363 : : TM_Result result;
6364 : : bool ret;
6365 : :
6366 : : #ifdef USE_ASSERT_CHECKING
6367 [ + + ]: 90832 : if (RelationGetRelid(relation) == RelationRelationId)
6368 : 89880 : check_inplace_rel_lock(oldtup_ptr);
6369 : : #endif
6370 : :
6371 [ - + ]: 90832 : Assert(BufferIsValid(buffer));
6372 : :
6373 : : /*
6374 : : * Construct shared cache inval if necessary. Because we pass a tuple
6375 : : * version without our own inplace changes or inplace changes other
6376 : : * sessions complete while we wait for locks, inplace update mustn't
6377 : : * change catcache lookup keys. But we aren't bothering with index
6378 : : * updates either, so that's true a fortiori. After LockBuffer(), it
6379 : : * would be too late, because this might reach a
6380 : : * CatalogCacheInitializeCache() that locks "buffer".
6381 : : */
308 6382 : 90832 : CacheInvalidateHeapTupleInplace(relation, oldtup_ptr, NULL);
6383 : :
347 6384 : 90832 : LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6385 : 90832 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
6386 : :
6387 : : /*----------
6388 : : * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6389 : : *
6390 : : * - wait unconditionally
6391 : : * - already locked tuple above, since inplace needs that unconditionally
6392 : : * - don't recheck header after wait: simpler to defer to next iteration
6393 : : * - don't try to continue even if the updater aborts: likewise
6394 : : * - no crosscheck
6395 : : */
6396 : 90832 : result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6397 : : buffer);
6398 : :
6399 [ - + ]: 90832 : if (result == TM_Invisible)
6400 : : {
6401 : : /* no known way this can happen */
3782 rhaas@postgresql.org 6402 [ # # ]:UBC 0 : ereport(ERROR,
6403 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6404 : : errmsg_internal("attempted to overwrite invisible tuple")));
6405 : : }
347 noah@leadboat.com 6406 [ - + ]:CBC 90832 : else if (result == TM_SelfModified)
6407 : : {
6408 : : /*
6409 : : * CREATE INDEX might reach this if an expression is silly enough to
6410 : : * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6411 : : * statements might get here after a heap_update() of the same row, in
6412 : : * the absence of an intervening CommandCounterIncrement().
6413 : : */
347 noah@leadboat.com 6414 [ # # ]:UBC 0 : ereport(ERROR,
6415 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6416 : : errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6417 : : }
347 noah@leadboat.com 6418 [ + + ]:CBC 90832 : else if (result == TM_BeingModified)
6419 : : {
6420 : : TransactionId xwait;
6421 : : uint16 infomask;
6422 : :
6423 : 42 : xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6424 : 42 : infomask = oldtup.t_data->t_infomask;
6425 : :
6426 [ + + ]: 42 : if (infomask & HEAP_XMAX_IS_MULTI)
6427 : : {
6428 : 5 : LockTupleMode lockmode = LockTupleNoKeyExclusive;
6429 : 5 : MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
6430 : : int remain;
6431 : :
6432 [ + + ]: 5 : if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6433 : : lockmode, NULL))
6434 : : {
6435 : 2 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
312 6436 : 2 : release_callback(arg);
347 6437 : 2 : ret = false;
6438 : 2 : MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6439 : : relation, &oldtup.t_self, XLTW_Update,
6440 : : &remain);
6441 : : }
6442 : : else
6443 : 3 : ret = true;
6444 : : }
6445 [ + + ]: 37 : else if (TransactionIdIsCurrentTransactionId(xwait))
6446 : 1 : ret = true;
6447 [ + + ]: 36 : else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6448 : 1 : ret = true;
6449 : : else
6450 : : {
6451 : 35 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
312 6452 : 35 : release_callback(arg);
347 6453 : 35 : ret = false;
6454 : 35 : XactLockTableWait(xwait, relation, &oldtup.t_self,
6455 : : XLTW_Update);
6456 : : }
6457 : : }
6458 : : else
6459 : : {
6460 : 90790 : ret = (result == TM_Ok);
6461 [ - + ]: 90790 : if (!ret)
6462 : : {
347 noah@leadboat.com 6463 :UBC 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
312 6464 : 0 : release_callback(arg);
6465 : : }
6466 : : }
6467 : :
6468 : : /*
6469 : : * GetCatalogSnapshot() relies on invalidation messages to know when to
6470 : : * take a new snapshot. COMMIT of xwait is responsible for sending the
6471 : : * invalidation. We're not acquiring heavyweight locks sufficient to
6472 : : * block if not yet sent, so we must take a new snapshot to ensure a later
6473 : : * attempt has a fair chance. While we don't need this if xwait aborted,
6474 : : * don't bother optimizing that.
6475 : : */
347 noah@leadboat.com 6476 [ + + ]:CBC 90832 : if (!ret)
6477 : : {
6478 : 37 : UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
308 6479 : 37 : ForgetInplace_Inval();
347 6480 : 37 : InvalidateCatalogSnapshot();
6481 : : }
6482 : 90832 : return ret;
6483 : : }
6484 : :
6485 : : /*
6486 : : * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6487 : : *
6488 : : * The tuple cannot change size, and therefore its header fields and null
6489 : : * bitmap (if any) don't change either.
6490 : : *
6491 : : * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6492 : : */
6493 : : void
6494 : 62880 : heap_inplace_update_and_unlock(Relation relation,
6495 : : HeapTuple oldtup, HeapTuple tuple,
6496 : : Buffer buffer)
6497 : : {
6498 : 62880 : HeapTupleHeader htup = oldtup->t_data;
6499 : : uint32 oldlen;
6500 : : uint32 newlen;
6501 : : char *dst;
6502 : : char *src;
316 6503 : 62880 : int nmsgs = 0;
6504 : 62880 : SharedInvalidationMessage *invalMessages = NULL;
6505 : 62880 : bool RelcacheInitFileInval = false;
6506 : :
347 6507 [ - + ]: 62880 : Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6508 : 62880 : oldlen = oldtup->t_len - htup->t_hoff;
7059 tgl@sss.pgh.pa.us 6509 : 62880 : newlen = tuple->t_len - tuple->t_data->t_hoff;
6510 [ + - - + ]: 62880 : if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
3579 andres@anarazel.de 6511 [ # # ]:UBC 0 : elog(ERROR, "wrong tuple length");
6512 : :
316 noah@leadboat.com 6513 :CBC 62880 : dst = (char *) htup + htup->t_hoff;
6514 : 62880 : src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6515 : :
6516 : : /* Like RecordTransactionCommit(), log only if needed */
6517 [ + + ]: 62880 : if (XLogStandbyInfoActive())
6518 : 49388 : nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6519 : : &RelcacheInitFileInval);
6520 : :
6521 : : /*
6522 : : * Unlink relcache init files as needed. If unlinking, acquire
6523 : : * RelCacheInitLock until after associated invalidations. By doing this
6524 : : * in advance, if we checkpoint and then crash between inplace
6525 : : * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6526 : : * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6527 : : * neglect to PANIC on EIO.
6528 : : */
6529 : 62880 : PreInplace_Inval();
6530 : :
6531 : : /*----------
6532 : : * NO EREPORT(ERROR) from here till changes are complete
6533 : : *
6534 : : * Our buffer lock won't stop a reader having already pinned and checked
6535 : : * visibility for this tuple. Hence, we write WAL first, then mutate the
6536 : : * buffer. Like in MarkBufferDirtyHint() or RecordTransactionCommit(),
6537 : : * checkpoint delay makes that acceptable. With the usual order of
6538 : : * changes, a crash after memcpy() and before XLogInsert() could allow
6539 : : * datfrozenxid to overtake relfrozenxid:
6540 : : *
6541 : : * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6542 : : * ["R" is a VACUUM tbl]
6543 : : * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6544 : : * D: systable_getnext() returns pg_class tuple of tbl
6545 : : * R: memcpy() into pg_class tuple of tbl
6546 : : * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6547 : : * [crash]
6548 : : * [recovery restores datfrozenxid w/o relfrozenxid]
6549 : : *
6550 : : * Mimic MarkBufferDirtyHint() subroutine XLogSaveBufferForHint().
6551 : : * Specifically, use DELAY_CHKPT_START, and copy the buffer to the stack.
6552 : : * The stack copy facilitates a FPI of the post-mutation block before we
6553 : : * accept other sessions seeing it. DELAY_CHKPT_START allows us to
6554 : : * XLogInsert() before MarkBufferDirty(). Since XLogSaveBufferForHint()
6555 : : * can operate under BUFFER_LOCK_SHARED, it can't avoid DELAY_CHKPT_START.
6556 : : * This function, however, likely could avoid it with the following order
6557 : : * of operations: MarkBufferDirty(), XLogInsert(), memcpy(). Opt to use
6558 : : * DELAY_CHKPT_START here, too, as a way to have fewer distinct code
6559 : : * patterns to analyze. Inplace update isn't so frequent that it should
6560 : : * pursue the small optimization of skipping DELAY_CHKPT_START.
6561 : : */
6562 [ - + ]: 62880 : Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
6563 : 62880 : START_CRIT_SECTION();
6564 : 62880 : MyProc->delayChkptFlags |= DELAY_CHKPT_START;
6565 : :
6566 : : /* XLOG stuff */
5381 rhaas@postgresql.org 6567 [ + - + + : 62880 : if (RelationNeedsWAL(relation))
+ - + + ]
6568 : : {
6569 : : xl_heap_inplace xlrec;
6570 : : PGAlignedBlock copied_buffer;
316 noah@leadboat.com 6571 : 62872 : char *origdata = (char *) BufferGetBlock(buffer);
6572 : 62872 : Page page = BufferGetPage(buffer);
6573 : 62872 : uint16 lower = ((PageHeader) page)->pd_lower;
6574 : 62872 : uint16 upper = ((PageHeader) page)->pd_upper;
6575 : : uintptr_t dst_offset_in_block;
6576 : : RelFileLocator rlocator;
6577 : : ForkNumber forkno;
6578 : : BlockNumber blkno;
6579 : : XLogRecPtr recptr;
6580 : :
3943 heikki.linnakangas@i 6581 : 62872 : xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
316 noah@leadboat.com 6582 : 62872 : xlrec.dbId = MyDatabaseId;
6583 : 62872 : xlrec.tsId = MyDatabaseTableSpace;
6584 : 62872 : xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6585 : 62872 : xlrec.nmsgs = nmsgs;
6586 : :
3943 heikki.linnakangas@i 6587 : 62872 : XLogBeginInsert();
207 peter@eisentraut.org 6588 : 62872 : XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
316 noah@leadboat.com 6589 [ + + ]: 62872 : if (nmsgs != 0)
207 peter@eisentraut.org 6590 : 34738 : XLogRegisterData(invalMessages,
6591 : : nmsgs * sizeof(SharedInvalidationMessage));
6592 : :
6593 : : /* register block matching what buffer will look like after changes */
316 noah@leadboat.com 6594 : 62872 : memcpy(copied_buffer.data, origdata, lower);
6595 : 62872 : memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6596 : 62872 : dst_offset_in_block = dst - origdata;
6597 : 62872 : memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6598 : 62872 : BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6599 [ - + ]: 62872 : Assert(forkno == MAIN_FORKNUM);
6600 : 62872 : XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6601 : : REGBUF_STANDARD);
6602 : 62872 : XLogRegisterBufData(0, src, newlen);
6603 : :
6604 : : /* inplace updates aren't decoded atm, don't log the origin */
6605 : :
3943 heikki.linnakangas@i 6606 : 62872 : recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6607 : :
316 noah@leadboat.com 6608 : 62872 : PageSetLSN(page, recptr);
6609 : : }
6610 : :
6611 : 62880 : memcpy(dst, src, newlen);
6612 : :
6613 : 62880 : MarkBufferDirty(buffer);
6614 : :
6615 : 62880 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6616 : :
6617 : : /*
6618 : : * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6619 : : * do this before UnlockTuple().
6620 : : *
6621 : : * If we're mutating a tuple visible only to this transaction, there's an
6622 : : * equivalent transactional inval from the action that created the tuple,
6623 : : * and this inval is superfluous.
6624 : : */
6625 : 62880 : AtInplace_Inval();
6626 : :
6627 : 62880 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
7059 tgl@sss.pgh.pa.us 6628 [ - + ]: 62880 : END_CRIT_SECTION();
316 noah@leadboat.com 6629 : 62880 : UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6630 : :
6631 : 62880 : AcceptInvalidationMessages(); /* local processing of just-sent inval */
6632 : :
6633 : : /*
6634 : : * Queue a transactional inval. The immediate invalidation we just sent
6635 : : * is the only one known to be necessary. To reduce risk from the
6636 : : * transition to immediate invalidation, continue sending a transactional
6637 : : * invalidation like we've long done. Third-party code might rely on it.
6638 : : */
7059 tgl@sss.pgh.pa.us 6639 [ + + ]: 62880 : if (!IsBootstrapProcessingMode())
5135 6640 : 48230 : CacheInvalidateHeapTuple(relation, tuple, NULL);
7059 6641 : 62880 : }
6642 : :
6643 : : /*
6644 : : * heap_inplace_unlock - reverse of heap_inplace_lock
6645 : : */
6646 : : void
347 noah@leadboat.com 6647 : 27915 : heap_inplace_unlock(Relation relation,
6648 : : HeapTuple oldtup, Buffer buffer)
6649 : : {
6650 : 27915 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6651 : 27915 : UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
308 6652 : 27915 : ForgetInplace_Inval();
347 6653 : 27915 : }
6654 : :
6655 : : #define FRM_NOOP 0x0001
6656 : : #define FRM_INVALIDATE_XMAX 0x0002
6657 : : #define FRM_RETURN_IS_XID 0x0004
6658 : : #define FRM_RETURN_IS_MULTI 0x0008
6659 : : #define FRM_MARK_COMMITTED 0x0010
6660 : :
6661 : : /*
6662 : : * FreezeMultiXactId
6663 : : * Determine what to do during freezing when a tuple is marked by a
6664 : : * MultiXactId.
6665 : : *
6666 : : * "flags" is an output value; it's used to tell caller what to do on return.
6667 : : * "pagefrz" is an input/output value, used to manage page level freezing.
6668 : : *
6669 : : * Possible values that we can set in "flags":
6670 : : * FRM_NOOP
6671 : : * don't do anything -- keep existing Xmax
6672 : : * FRM_INVALIDATE_XMAX
6673 : : * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6674 : : * FRM_RETURN_IS_XID
6675 : : * The Xid return value is a single update Xid to set as xmax.
6676 : : * FRM_MARK_COMMITTED
6677 : : * Xmax can be marked as HEAP_XMAX_COMMITTED
6678 : : * FRM_RETURN_IS_MULTI
6679 : : * The return value is a new MultiXactId to set as new Xmax.
6680 : : * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6681 : : *
6682 : : * Caller delegates control of page freezing to us. In practice we always
6683 : : * force freezing of caller's page unless FRM_NOOP processing is indicated.
6684 : : * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6685 : : * can never be left behind. We freely choose when and how to process each
6686 : : * Multi, without ever violating the cutoff postconditions for freezing.
6687 : : *
6688 : : * It's useful to remove Multis on a proactive timeline (relative to freezing
6689 : : * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6690 : : * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6691 : : * misses through eager processing.
6692 : : *
6693 : : * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6694 : : * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6695 : : * This can usually be put off, which is usually enough to avoid it altogether.
6696 : : * Allocating new multis during VACUUM should be avoided on general principle;
6697 : : * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6698 : : * its own special risks.
6699 : : *
6700 : : * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6701 : : * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6702 : : *
6703 : : * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6704 : : * have already forced page-level freezing, since that might incur the same
6705 : : * SLRU buffer misses that we specifically intended to avoid by freezing.
6706 : : */
6707 : : static TransactionId
4282 alvherre@alvh.no-ip. 6708 : 6 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
6709 : : const struct VacuumCutoffs *cutoffs, uint16 *flags,
6710 : : HeapPageFreeze *pagefrz)
6711 : : {
6712 : : TransactionId newxmax;
6713 : : MultiXactMember *members;
6714 : : int nmembers;
6715 : : bool need_replace;
6716 : : int nnewmembers;
6717 : : MultiXactMember *newmembers;
6718 : : bool has_lockers;
6719 : : TransactionId update_xid;
6720 : : bool update_committed;
6721 : : TransactionId FreezePageRelfrozenXid;
6722 : :
6723 : 6 : *flags = 0;
6724 : :
6725 : : /* We should only be called in Multis */
6726 [ - + ]: 6 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6727 : :
3361 6728 [ + - - + ]: 12 : if (!MultiXactIdIsValid(multi) ||
6729 : 6 : HEAP_LOCKED_UPGRADED(t_infomask))
6730 : : {
4282 alvherre@alvh.no-ip. 6731 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
983 pg@bowt.ie 6732 : 0 : pagefrz->freeze_required = true;
4282 alvherre@alvh.no-ip. 6733 : 0 : return InvalidTransactionId;
6734 : : }
989 pg@bowt.ie 6735 [ - + ]:CBC 6 : else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
2854 andres@anarazel.de 6736 [ # # ]:UBC 0 : ereport(ERROR,
6737 : : (errcode(ERRCODE_DATA_CORRUPTED),
6738 : : errmsg_internal("found multixact %u from before relminmxid %u",
6739 : : multi, cutoffs->relminmxid)));
983 pg@bowt.ie 6740 [ + + ]:CBC 6 : else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6741 : : {
6742 : : TransactionId update_xact;
6743 : :
6744 : : /*
6745 : : * This old multi cannot possibly have members still running, but
6746 : : * verify just in case. If it was a locker only, it can be removed
6747 : : * without any further consideration; but if it contained an update,
6748 : : * we might need to preserve it.
6749 : : */
2854 andres@anarazel.de 6750 [ - + ]: 4 : if (MultiXactIdIsRunning(multi,
6751 : 4 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
2854 andres@anarazel.de 6752 [ # # ]:UBC 0 : ereport(ERROR,
6753 : : (errcode(ERRCODE_DATA_CORRUPTED),
6754 : : errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6755 : : multi, cutoffs->OldestMxact)));
6756 : :
4282 alvherre@alvh.no-ip. 6757 [ + - ]:CBC 4 : if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6758 : : {
6759 : 4 : *flags |= FRM_INVALIDATE_XMAX;
983 pg@bowt.ie 6760 : 4 : pagefrz->freeze_required = true;
6761 : 4 : return InvalidTransactionId;
6762 : : }
6763 : :
6764 : : /* replace multi with single XID for its updater? */
983 pg@bowt.ie 6765 :UBC 0 : update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6766 [ # # ]: 0 : if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6767 [ # # ]: 0 : ereport(ERROR,
6768 : : (errcode(ERRCODE_DATA_CORRUPTED),
6769 : : errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6770 : : multi, update_xact,
6771 : : cutoffs->relfrozenxid)));
6772 [ # # ]: 0 : else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6773 : : {
6774 : : /*
6775 : : * Updater XID has to have aborted (otherwise the tuple would have
6776 : : * been pruned away instead, since updater XID is < OldestXmin).
6777 : : * Just remove xmax.
6778 : : */
977 6779 [ # # ]: 0 : if (TransactionIdDidCommit(update_xact))
983 6780 [ # # ]: 0 : ereport(ERROR,
6781 : : (errcode(ERRCODE_DATA_CORRUPTED),
6782 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6783 : : multi, update_xact,
6784 : : cutoffs->OldestXmin)));
6785 : 0 : *flags |= FRM_INVALIDATE_XMAX;
6786 : 0 : pagefrz->freeze_required = true;
6787 : 0 : return InvalidTransactionId;
6788 : : }
6789 : :
6790 : : /* Have to keep updater XID as new xmax */
6791 : 0 : *flags |= FRM_RETURN_IS_XID;
6792 : 0 : pagefrz->freeze_required = true;
6793 : 0 : return update_xact;
6794 : : }
6795 : :
6796 : : /*
6797 : : * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6798 : : * need to walk the whole members array to figure out what to do, if
6799 : : * anything.
6800 : : */
6801 : : nmembers =
3361 alvherre@alvh.no-ip. 6802 :CBC 2 : GetMultiXactIdMembers(multi, &members, false,
4057 6803 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
4282 6804 [ - + ]: 2 : if (nmembers <= 0)
6805 : : {
6806 : : /* Nothing worth keeping */
4282 alvherre@alvh.no-ip. 6807 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
983 pg@bowt.ie 6808 : 0 : pagefrz->freeze_required = true;
4282 alvherre@alvh.no-ip. 6809 : 0 : return InvalidTransactionId;
6810 : : }
6811 : :
6812 : : /*
6813 : : * The FRM_NOOP case is the only case where we might need to ratchet back
6814 : : * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6815 : : * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6816 : : * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6817 : : * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6818 : : * trackers managed by VACUUM being ratcheting back by xmax to the degree
6819 : : * required to make it safe to leave xmax undisturbed, independent of
6820 : : * whether or not page freezing is triggered somewhere else.
6821 : : *
6822 : : * Our policy is to force freezing in every case other than FRM_NOOP,
6823 : : * which obviates the need to maintain either set of trackers, anywhere.
6824 : : * Every other case will reliably execute a freeze plan for xmax that
6825 : : * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6826 : : * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6827 : : * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6828 : : * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6829 : : */
4282 alvherre@alvh.no-ip. 6830 :CBC 2 : need_replace = false;
983 pg@bowt.ie 6831 : 2 : FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
989 6832 [ + + ]: 4 : for (int i = 0; i < nmembers; i++)
6833 : : {
6834 : 3 : TransactionId xid = members[i].xid;
6835 : :
6836 [ - + ]: 3 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6837 : :
6838 [ + + ]: 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6839 : : {
6840 : : /* Can't violate the FreezeLimit postcondition */
4282 alvherre@alvh.no-ip. 6841 : 1 : need_replace = true;
6842 : 1 : break;
6843 : : }
983 pg@bowt.ie 6844 [ - + ]: 2 : if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
983 pg@bowt.ie 6845 :UBC 0 : FreezePageRelfrozenXid = xid;
6846 : : }
6847 : :
6848 : : /* Can't violate the MultiXactCutoff postcondition, either */
983 pg@bowt.ie 6849 [ + + ]:CBC 2 : if (!need_replace)
6850 : 1 : need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6851 : :
4282 alvherre@alvh.no-ip. 6852 [ + + ]: 2 : if (!need_replace)
6853 : : {
6854 : : /*
6855 : : * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6856 : : * both together to make it safe to retain this particular multi after
6857 : : * freezing its page
6858 : : */
6859 : 1 : *flags |= FRM_NOOP;
983 pg@bowt.ie 6860 : 1 : pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6861 [ - + ]: 1 : if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
983 pg@bowt.ie 6862 :UBC 0 : pagefrz->FreezePageRelminMxid = multi;
4282 alvherre@alvh.no-ip. 6863 :CBC 1 : pfree(members);
1252 pg@bowt.ie 6864 : 1 : return multi;
6865 : : }
6866 : :
6867 : : /*
6868 : : * Do a more thorough second pass over the multi to figure out which
6869 : : * member XIDs actually need to be kept. Checking the precise status of
6870 : : * individual members might even show that we don't need to keep anything.
6871 : : * That is quite possible even though the Multi must be >= OldestMxact,
6872 : : * since our second pass only keeps member XIDs when it's truly necessary;
6873 : : * even member XIDs >= OldestXmin often won't be kept by second pass.
6874 : : */
4282 alvherre@alvh.no-ip. 6875 : 1 : nnewmembers = 0;
6876 : 1 : newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6877 : 1 : has_lockers = false;
6878 : 1 : update_xid = InvalidTransactionId;
6879 : 1 : update_committed = false;
6880 : :
6881 : : /*
6882 : : * Determine whether to keep each member xid, or to ignore it instead
6883 : : */
989 pg@bowt.ie 6884 [ + + ]: 3 : for (int i = 0; i < nmembers; i++)
6885 : : {
6886 : 2 : TransactionId xid = members[i].xid;
6887 : 2 : MultiXactStatus mstatus = members[i].status;
6888 : :
6889 [ - + ]: 2 : Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6890 : :
6891 [ + - ]: 2 : if (!ISUPDATE_from_mxstatus(mstatus))
6892 : : {
6893 : : /*
6894 : : * Locker XID (not updater XID). We only keep lockers that are
6895 : : * still running.
6896 : : */
6897 [ + - + + ]: 4 : if (TransactionIdIsCurrentTransactionId(xid) ||
6898 : 2 : TransactionIdIsInProgress(xid))
6899 : : {
983 6900 [ - + ]: 1 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
983 pg@bowt.ie 6901 [ # # ]:UBC 0 : ereport(ERROR,
6902 : : (errcode(ERRCODE_DATA_CORRUPTED),
6903 : : errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6904 : : multi, xid,
6905 : : cutoffs->OldestXmin)));
989 pg@bowt.ie 6906 :CBC 1 : newmembers[nnewmembers++] = members[i];
6907 : 1 : has_lockers = true;
6908 : : }
6909 : :
6910 : 2 : continue;
6911 : : }
6912 : :
6913 : : /*
6914 : : * Updater XID (not locker XID). Should we keep it?
6915 : : *
6916 : : * Since the tuple wasn't totally removed when vacuum pruned, the
6917 : : * update Xid cannot possibly be older than OldestXmin cutoff unless
6918 : : * the updater XID aborted. If the updater transaction is known
6919 : : * aborted or crashed then it's okay to ignore it, otherwise not.
6920 : : *
6921 : : * In any case the Multi should never contain two updaters, whatever
6922 : : * their individual commit status. Check for that first, in passing.
6923 : : */
989 pg@bowt.ie 6924 [ # # ]:UBC 0 : if (TransactionIdIsValid(update_xid))
6925 [ # # ]: 0 : ereport(ERROR,
6926 : : (errcode(ERRCODE_DATA_CORRUPTED),
6927 : : errmsg_internal("multixact %u has two or more updating members",
6928 : : multi),
6929 : : errdetail_internal("First updater XID=%u second updater XID=%u.",
6930 : : update_xid, xid)));
6931 : :
6932 : : /*
6933 : : * As with all tuple visibility routines, it's critical to test
6934 : : * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6935 : : * race conditions explained in detail in heapam_visibility.c.
6936 : : */
6937 [ # # # # ]: 0 : if (TransactionIdIsCurrentTransactionId(xid) ||
6938 : 0 : TransactionIdIsInProgress(xid))
6939 : 0 : update_xid = xid;
6940 [ # # ]: 0 : else if (TransactionIdDidCommit(xid))
6941 : : {
6942 : : /*
6943 : : * The transaction committed, so we can tell caller to set
6944 : : * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6945 : : * transaction is not running.)
6946 : : */
6947 : 0 : update_committed = true;
6948 : 0 : update_xid = xid;
6949 : : }
6950 : : else
6951 : : {
6952 : : /*
6953 : : * Not in progress, not committed -- must be aborted or crashed;
6954 : : * we can ignore it.
6955 : : */
6956 : 0 : continue;
6957 : : }
6958 : :
6959 : : /*
6960 : : * We determined that updater must be kept -- add it to pending new
6961 : : * members list
6962 : : */
983 6963 [ # # ]: 0 : if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6964 [ # # ]: 0 : ereport(ERROR,
6965 : : (errcode(ERRCODE_DATA_CORRUPTED),
6966 : : errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6967 : : multi, xid, cutoffs->OldestXmin)));
989 6968 : 0 : newmembers[nnewmembers++] = members[i];
6969 : : }
6970 : :
4282 alvherre@alvh.no-ip. 6971 :CBC 1 : pfree(members);
6972 : :
6973 : : /*
6974 : : * Determine what to do with caller's multi based on information gathered
6975 : : * during our second pass
6976 : : */
6977 [ - + ]: 1 : if (nnewmembers == 0)
6978 : : {
6979 : : /* Nothing worth keeping */
4282 alvherre@alvh.no-ip. 6980 :UBC 0 : *flags |= FRM_INVALIDATE_XMAX;
989 pg@bowt.ie 6981 : 0 : newxmax = InvalidTransactionId;
6982 : : }
4282 alvherre@alvh.no-ip. 6983 [ - + - - ]:CBC 1 : else if (TransactionIdIsValid(update_xid) && !has_lockers)
6984 : : {
6985 : : /*
6986 : : * If there's a single member and it's an update, pass it back alone
6987 : : * without creating a new Multi. (XXX we could do this when there's a
6988 : : * single remaining locker, too, but that would complicate the API too
6989 : : * much; moreover, the case with the single updater is more
6990 : : * interesting, because those are longer-lived.)
6991 : : */
4282 alvherre@alvh.no-ip. 6992 [ # # ]:UBC 0 : Assert(nnewmembers == 1);
6993 : 0 : *flags |= FRM_RETURN_IS_XID;
6994 [ # # ]: 0 : if (update_committed)
6995 : 0 : *flags |= FRM_MARK_COMMITTED;
989 pg@bowt.ie 6996 : 0 : newxmax = update_xid;
6997 : : }
6998 : : else
6999 : : {
7000 : : /*
7001 : : * Create a new multixact with the surviving members of the previous
7002 : : * one, to set as new Xmax in the tuple
7003 : : */
989 pg@bowt.ie 7004 :CBC 1 : newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
4282 alvherre@alvh.no-ip. 7005 : 1 : *flags |= FRM_RETURN_IS_MULTI;
7006 : : }
7007 : :
7008 : 1 : pfree(newmembers);
7009 : :
983 pg@bowt.ie 7010 : 1 : pagefrz->freeze_required = true;
989 7011 : 1 : return newxmax;
7012 : : }
7013 : :
7014 : : /*
7015 : : * heap_prepare_freeze_tuple
7016 : : *
7017 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7018 : : * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
7019 : : * setup enough state (in the *frz output argument) to enable caller to
7020 : : * process this tuple as part of freezing its page, and return true. Return
7021 : : * false if nothing can be changed about the tuple right now.
7022 : : *
7023 : : * Also sets *totally_frozen to true if the tuple will be totally frozen once
7024 : : * caller executes returned freeze plan (or if the tuple was already totally
7025 : : * frozen by an earlier VACUUM). This indicates that there are no remaining
7026 : : * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
7027 : : *
7028 : : * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
7029 : : * tuple that we returned true for, and then execute freezing. Caller must
7030 : : * initialize pagefrz fields for page as a whole before first call here for
7031 : : * each heap page.
7032 : : *
7033 : : * VACUUM caller decides on whether or not to freeze the page as a whole.
7034 : : * We'll often prepare freeze plans for a page that caller just discards.
7035 : : * However, VACUUM doesn't always get to make a choice; it must freeze when
7036 : : * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7037 : : * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7038 : : * that VACUUM always follows that rule.
7039 : : *
7040 : : * We sometimes force freezing of xmax MultiXactId values long before it is
7041 : : * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7042 : : * It's worth processing MultiXactIds proactively when it is cheap to do so,
7043 : : * and it's convenient to make that happen by piggy-backing it on the "force
7044 : : * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7045 : : * because it is expensive right now (though only when it's still possible to
7046 : : * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7047 : : *
7048 : : * It is assumed that the caller has checked the tuple with
7049 : : * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7050 : : * (else we should be removing the tuple, not freezing it).
7051 : : *
7052 : : * NB: This function has side effects: it might allocate a new MultiXactId.
7053 : : * It will be set as tuple's new xmax when our *frz output is processed within
7054 : : * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7055 : : * then caller had better have an exclusive lock on it already.
7056 : : */
7057 : : bool
2854 andres@anarazel.de 7058 : 4465680 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
7059 : : const struct VacuumCutoffs *cutoffs,
7060 : : HeapPageFreeze *pagefrz,
7061 : : HeapTupleFreeze *frz, bool *totally_frozen)
7062 : : {
989 pg@bowt.ie 7063 : 4465680 : bool xmin_already_frozen = false,
7064 : 4465680 : xmax_already_frozen = false;
7065 : 4465680 : bool freeze_xmin = false,
7066 : 4465680 : replace_xvac = false,
7067 : 4465680 : replace_xmax = false,
7068 : 4465680 : freeze_xmax = false;
7069 : : TransactionId xid;
7070 : :
977 7071 : 4465680 : frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
4282 alvherre@alvh.no-ip. 7072 : 4465680 : frz->t_infomask2 = tuple->t_infomask2;
7073 : 4465680 : frz->t_infomask = tuple->t_infomask;
977 pg@bowt.ie 7074 : 4465680 : frz->frzflags = 0;
7075 : 4465680 : frz->checkflags = 0;
7076 : :
7077 : : /*
7078 : : * Process xmin, while keeping track of whether it's already frozen, or
7079 : : * will become frozen iff our freeze plan is executed by caller (could be
7080 : : * neither).
7081 : : */
6880 tgl@sss.pgh.pa.us 7082 : 4465680 : xid = HeapTupleHeaderGetXmin(tuple);
2319 alvherre@alvh.no-ip. 7083 [ + + ]: 4465680 : if (!TransactionIdIsNormal(xid))
989 pg@bowt.ie 7084 : 1327834 : xmin_already_frozen = true;
7085 : : else
7086 : : {
7087 [ - + ]: 3137846 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
2854 andres@anarazel.de 7088 [ # # ]:UBC 0 : ereport(ERROR,
7089 : : (errcode(ERRCODE_DATA_CORRUPTED),
7090 : : errmsg_internal("found xmin %u from before relfrozenxid %u",
7091 : : xid, cutoffs->relfrozenxid)));
7092 : :
7093 : : /* Will set freeze_xmin flags in freeze plan below */
983 pg@bowt.ie 7094 :CBC 3137846 : freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7095 : :
7096 : : /* Verify that xmin committed if and when freeze plan is executed */
977 7097 [ + + ]: 3137846 : if (freeze_xmin)
7098 : 2537977 : frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
7099 : : }
7100 : :
7101 : : /*
7102 : : * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7103 : : * as we support having MOVED_OFF/MOVED_IN tuples in the database
7104 : : */
989 7105 : 4465680 : xid = HeapTupleHeaderGetXvac(tuple);
7106 [ - + ]: 4465680 : if (TransactionIdIsNormal(xid))
7107 : : {
989 pg@bowt.ie 7108 [ # # ]:UBC 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7109 [ # # ]: 0 : Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7110 : :
7111 : : /*
7112 : : * For Xvac, we always freeze proactively. This allows totally_frozen
7113 : : * tracking to ignore xvac.
7114 : : */
983 7115 : 0 : replace_xvac = pagefrz->freeze_required = true;
7116 : :
7117 : : /* Will set replace_xvac flags in freeze plan below */
7118 : : }
7119 : :
7120 : : /* Now process xmax */
977 pg@bowt.ie 7121 :CBC 4465680 : xid = frz->xmax;
4300 alvherre@alvh.no-ip. 7122 [ + + ]: 4465680 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7123 : : {
7124 : : /* Raw xmax is a MultiXactId */
7125 : : TransactionId newxmax;
7126 : : uint16 flags;
7127 : :
7128 : : /*
7129 : : * We will either remove xmax completely (in the "freeze_xmax" path),
7130 : : * process xmax by replacing it (in the "replace_xmax" path), or
7131 : : * perform no-op xmax processing. The only constraint is that the
7132 : : * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7133 : : */
989 pg@bowt.ie 7134 : 6 : newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7135 : : &flags, pagefrz);
7136 : :
983 7137 [ + + ]: 6 : if (flags & FRM_NOOP)
7138 : : {
7139 : : /*
7140 : : * xmax is a MultiXactId, and nothing about it changes for now.
7141 : : * This is the only case where 'freeze_required' won't have been
7142 : : * set for us by FreezeMultiXactId, as well as the only case where
7143 : : * neither freeze_xmax nor replace_xmax are set (given a multi).
7144 : : *
7145 : : * This is a no-op, but the call to FreezeMultiXactId might have
7146 : : * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7147 : : * for us (the "freeze page" variants, specifically). That'll
7148 : : * make it safe for our caller to freeze the page later on, while
7149 : : * leaving this particular xmax undisturbed.
7150 : : *
7151 : : * FreezeMultiXactId is _not_ responsible for the "no freeze"
7152 : : * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7153 : : * job. A call to heap_tuple_should_freeze for this same tuple
7154 : : * will take place below if 'freeze_required' isn't set already.
7155 : : * (This repeats work from FreezeMultiXactId, but allows "no
7156 : : * freeze" tracker maintenance to happen in only one place.)
7157 : : */
7158 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7159 [ + - - + ]: 1 : Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7160 : : }
7161 [ - + ]: 5 : else if (flags & FRM_RETURN_IS_XID)
7162 : : {
7163 : : /*
7164 : : * xmax will become an updater Xid (original MultiXact's updater
7165 : : * member Xid will be carried forward as a simple Xid in Xmax).
7166 : : */
989 pg@bowt.ie 7167 [ # # ]:UBC 0 : Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7168 : :
7169 : : /*
7170 : : * NB -- some of these transformations are only valid because we
7171 : : * know the return Xid is a tuple updater (i.e. not merely a
7172 : : * locker.) Also note that the only reason we don't explicitly
7173 : : * worry about HEAP_KEYS_UPDATED is because it lives in
7174 : : * t_infomask2 rather than t_infomask.
7175 : : */
4282 alvherre@alvh.no-ip. 7176 : 0 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7177 : 0 : frz->xmax = newxmax;
7178 [ # # ]: 0 : if (flags & FRM_MARK_COMMITTED)
2984 teodor@sigaev.ru 7179 : 0 : frz->t_infomask |= HEAP_XMAX_COMMITTED;
989 pg@bowt.ie 7180 : 0 : replace_xmax = true;
7181 : : }
4282 alvherre@alvh.no-ip. 7182 [ + + ]:CBC 5 : else if (flags & FRM_RETURN_IS_MULTI)
7183 : : {
7184 : : uint16 newbits;
7185 : : uint16 newbits2;
7186 : :
7187 : : /*
7188 : : * xmax is an old MultiXactId that we have to replace with a new
7189 : : * MultiXactId, to carry forward two or more original member XIDs.
7190 : : */
989 pg@bowt.ie 7191 [ - + ]: 1 : Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7192 : :
7193 : : /*
7194 : : * We can't use GetMultiXactIdHintBits directly on the new multi
7195 : : * here; that routine initializes the masks to all zeroes, which
7196 : : * would lose other bits we need. Doing it this way ensures all
7197 : : * unrelated bits remain untouched.
7198 : : */
4282 alvherre@alvh.no-ip. 7199 : 1 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7200 : 1 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7201 : 1 : GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7202 : 1 : frz->t_infomask |= newbits;
7203 : 1 : frz->t_infomask2 |= newbits2;
7204 : 1 : frz->xmax = newxmax;
989 pg@bowt.ie 7205 : 1 : replace_xmax = true;
7206 : : }
7207 : : else
7208 : : {
7209 : : /*
7210 : : * Freeze plan for tuple "freezes xmax" in the strictest sense:
7211 : : * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7212 : : */
7213 [ - + ]: 4 : Assert(flags & FRM_INVALIDATE_XMAX);
1252 7214 [ - + ]: 4 : Assert(!TransactionIdIsValid(newxmax));
7215 : :
7216 : : /* Will set freeze_xmax flags in freeze plan below */
989 7217 : 4 : freeze_xmax = true;
7218 : : }
7219 : :
7220 : : /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
983 7221 [ - + - - : 6 : Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
- - ]
7222 : : }
3370 rhaas@postgresql.org 7223 [ + + ]: 4465674 : else if (TransactionIdIsNormal(xid))
7224 : : {
7225 : : /* Raw xmax is normal XID */
989 pg@bowt.ie 7226 [ - + ]: 265924 : if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
2854 andres@anarazel.de 7227 [ # # ]:UBC 0 : ereport(ERROR,
7228 : : (errcode(ERRCODE_DATA_CORRUPTED),
7229 : : errmsg_internal("found xmax %u from before relfrozenxid %u",
7230 : : xid, cutoffs->relfrozenxid)));
7231 : :
7232 : : /* Will set freeze_xmax flags in freeze plan below */
977 pg@bowt.ie 7233 :CBC 265924 : freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7234 : :
7235 : : /*
7236 : : * Verify that xmax aborted if and when freeze plan is executed,
7237 : : * provided it's from an update. (A lock-only xmax can be removed
7238 : : * independent of this, since the lock is released at xact end.)
7239 : : */
7240 [ + + + + ]: 265924 : if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7241 : 1512 : frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7242 : : }
1018 7243 [ + - ]: 4199750 : else if (!TransactionIdIsValid(xid))
7244 : : {
7245 : : /* Raw xmax is InvalidTransactionId XID */
7246 [ - + ]: 4199750 : Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
2682 alvherre@alvh.no-ip. 7247 : 4199750 : xmax_already_frozen = true;
7248 : : }
7249 : : else
2682 alvherre@alvh.no-ip. 7250 [ # # ]:UBC 0 : ereport(ERROR,
7251 : : (errcode(ERRCODE_DATA_CORRUPTED),
7252 : : errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7253 : : xid, tuple->t_infomask)));
7254 : :
989 pg@bowt.ie 7255 [ + + ]:CBC 4465680 : if (freeze_xmin)
7256 : : {
7257 [ - + ]: 2537977 : Assert(!xmin_already_frozen);
7258 : :
7259 : 2537977 : frz->t_infomask |= HEAP_XMIN_FROZEN;
7260 : : }
7261 [ - + ]: 4465680 : if (replace_xvac)
7262 : : {
7263 : : /*
7264 : : * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7265 : : * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7266 : : * transaction succeeded.
7267 : : */
983 pg@bowt.ie 7268 [ # # ]:UBC 0 : Assert(pagefrz->freeze_required);
989 7269 [ # # ]: 0 : if (tuple->t_infomask & HEAP_MOVED_OFF)
7270 : 0 : frz->frzflags |= XLH_INVALID_XVAC;
7271 : : else
7272 : 0 : frz->frzflags |= XLH_FREEZE_XVAC;
7273 : : }
989 pg@bowt.ie 7274 [ + + ]:CBC 4465680 : if (replace_xmax)
7275 : : {
7276 [ + - - + ]: 1 : Assert(!xmax_already_frozen && !freeze_xmax);
983 7277 [ - + ]: 1 : Assert(pagefrz->freeze_required);
7278 : :
7279 : : /* Already set replace_xmax flags in freeze plan earlier */
7280 : : }
4300 alvherre@alvh.no-ip. 7281 [ + + ]: 4465680 : if (freeze_xmax)
7282 : : {
989 pg@bowt.ie 7283 [ + - - + ]: 2473 : Assert(!xmax_already_frozen && !replace_xmax);
7284 : :
4282 alvherre@alvh.no-ip. 7285 : 2473 : frz->xmax = InvalidTransactionId;
7286 : :
7287 : : /*
7288 : : * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7289 : : * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7290 : : * Also get rid of the HEAP_KEYS_UPDATED bit.
7291 : : */
7292 : 2473 : frz->t_infomask &= ~HEAP_XMAX_BITS;
7293 : 2473 : frz->t_infomask |= HEAP_XMAX_INVALID;
7294 : 2473 : frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7295 : 2473 : frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7296 : : }
7297 : :
7298 : : /*
7299 : : * Determine if this tuple is already totally frozen, or will become
7300 : : * totally frozen (provided caller executes freeze plans for the page)
7301 : : */
989 pg@bowt.ie 7302 [ + + + + : 8329018 : *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
+ + ]
7303 [ + + ]: 3863338 : (freeze_xmax || xmax_already_frozen));
7304 : :
983 7305 [ + + + + : 4465680 : if (!pagefrz->freeze_required && !(xmin_already_frozen &&
+ + ]
7306 : : xmax_already_frozen))
7307 : : {
7308 : : /*
7309 : : * So far no previous tuple from the page made freezing mandatory.
7310 : : * Does this tuple force caller to freeze the entire page?
7311 : : */
7312 : 2017991 : pagefrz->freeze_required =
7313 : 2017991 : heap_tuple_should_freeze(tuple, cutoffs,
7314 : : &pagefrz->NoFreezePageRelfrozenXid,
7315 : : &pagefrz->NoFreezePageRelminMxid);
7316 : : }
7317 : :
7318 : : /* Tell caller if this tuple has a usable freeze plan set in *frz */
989 7319 [ + + + - : 4465680 : return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
+ - + + ]
7320 : : }
7321 : :
7322 : : /*
7323 : : * Perform xmin/xmax XID status sanity checks before actually executing freeze
7324 : : * plans.
7325 : : *
7326 : : * heap_prepare_freeze_tuple doesn't perform these checks directly because
7327 : : * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7328 : : * successive VACUUMs that each decide against freezing the same page.
7329 : : */
7330 : : void
521 heikki.linnakangas@i 7331 : 21054 : heap_pre_freeze_checks(Buffer buffer,
7332 : : HeapTupleFreeze *tuples, int ntuples)
7333 : : {
1026 pg@bowt.ie 7334 : 21054 : Page page = BufferGetPage(buffer);
7335 : :
977 7336 [ + + ]: 940830 : for (int i = 0; i < ntuples; i++)
7337 : : {
7338 : 919776 : HeapTupleFreeze *frz = tuples + i;
7339 : 919776 : ItemId itemid = PageGetItemId(page, frz->offset);
7340 : : HeapTupleHeader htup;
7341 : :
7342 : 919776 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
7343 : :
7344 : : /* Deliberately avoid relying on tuple hint bits here */
7345 [ + + ]: 919776 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7346 : : {
7347 : 919775 : TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
7348 : :
7349 [ - + ]: 919775 : Assert(!HeapTupleHeaderXminFrozen(htup));
7350 [ - + ]: 919775 : if (unlikely(!TransactionIdDidCommit(xmin)))
977 pg@bowt.ie 7351 [ # # ]:UBC 0 : ereport(ERROR,
7352 : : (errcode(ERRCODE_DATA_CORRUPTED),
7353 : : errmsg_internal("uncommitted xmin %u needs to be frozen",
7354 : : xmin)));
7355 : : }
7356 : :
7357 : : /*
7358 : : * TransactionIdDidAbort won't work reliably in the presence of XIDs
7359 : : * left behind by transactions that were in progress during a crash,
7360 : : * so we can only check that xmax didn't commit
7361 : : */
977 pg@bowt.ie 7362 [ + + ]:CBC 919776 : if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7363 : : {
7364 : 505 : TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
7365 : :
7366 [ - + ]: 505 : Assert(TransactionIdIsNormal(xmax));
7367 [ - + ]: 505 : if (unlikely(TransactionIdDidCommit(xmax)))
977 pg@bowt.ie 7368 [ # # ]:UBC 0 : ereport(ERROR,
7369 : : (errcode(ERRCODE_DATA_CORRUPTED),
7370 : : errmsg_internal("cannot freeze committed xmax %u",
7371 : : xmax)));
7372 : : }
7373 : : }
521 heikki.linnakangas@i 7374 :CBC 21054 : }
7375 : :
7376 : : /*
7377 : : * Helper which executes freezing of one or more heap tuples on a page on
7378 : : * behalf of caller. Caller passes an array of tuple plans from
7379 : : * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7380 : : * Must be called in a critical section that also marks the buffer dirty and,
7381 : : * if needed, emits WAL.
7382 : : */
7383 : : void
7384 : 21054 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
7385 : : {
7386 : 21054 : Page page = BufferGetPage(buffer);
7387 : :
1026 pg@bowt.ie 7388 [ + + ]: 940830 : for (int i = 0; i < ntuples; i++)
7389 : : {
977 7390 : 919776 : HeapTupleFreeze *frz = tuples + i;
7391 : 919776 : ItemId itemid = PageGetItemId(page, frz->offset);
7392 : : HeapTupleHeader htup;
7393 : :
1026 7394 : 919776 : htup = (HeapTupleHeader) PageGetItem(page, itemid);
977 7395 : 919776 : heap_execute_freeze_tuple(htup, frz);
7396 : : }
1026 7397 : 21054 : }
7398 : :
7399 : : /*
7400 : : * heap_freeze_tuple
7401 : : * Freeze tuple in place, without WAL logging.
7402 : : *
7403 : : * Useful for callers like CLUSTER that perform their own WAL logging.
7404 : : */
7405 : : bool
2854 andres@anarazel.de 7406 : 360163 : heap_freeze_tuple(HeapTupleHeader tuple,
7407 : : TransactionId relfrozenxid, TransactionId relminmxid,
7408 : : TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7409 : : {
7410 : : HeapTupleFreeze frz;
7411 : : bool do_freeze;
7412 : : bool totally_frozen;
7413 : : struct VacuumCutoffs cutoffs;
7414 : : HeapPageFreeze pagefrz;
7415 : :
989 pg@bowt.ie 7416 : 360163 : cutoffs.relfrozenxid = relfrozenxid;
7417 : 360163 : cutoffs.relminmxid = relminmxid;
7418 : 360163 : cutoffs.OldestXmin = FreezeLimit;
7419 : 360163 : cutoffs.OldestMxact = MultiXactCutoff;
7420 : 360163 : cutoffs.FreezeLimit = FreezeLimit;
7421 : 360163 : cutoffs.MultiXactCutoff = MultiXactCutoff;
7422 : :
983 7423 : 360163 : pagefrz.freeze_required = true;
7424 : 360163 : pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7425 : 360163 : pagefrz.FreezePageRelminMxid = MultiXactCutoff;
7426 : 360163 : pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7427 : 360163 : pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7428 : :
989 7429 : 360163 : do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7430 : : &pagefrz, &frz, &totally_frozen);
7431 : :
7432 : : /*
7433 : : * Note that because this is not a WAL-logged operation, we don't need to
7434 : : * fill in the offset in the freeze record.
7435 : : */
7436 : :
4282 alvherre@alvh.no-ip. 7437 [ + + ]: 360163 : if (do_freeze)
7438 : 255884 : heap_execute_freeze_tuple(tuple, &frz);
7439 : 360163 : return do_freeze;
7440 : : }
7441 : :
7442 : : /*
7443 : : * For a given MultiXactId, return the hint bits that should be set in the
7444 : : * tuple's infomask.
7445 : : *
7446 : : * Normally this should be called for a multixact that was just created, and
7447 : : * so is on our local cache, so the GetMembers call is fast.
7448 : : */
7449 : : static void
4609 7450 : 1196 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
7451 : : uint16 *new_infomask2)
7452 : : {
7453 : : int nmembers;
7454 : : MultiXactMember *members;
7455 : : int i;
4483 bruce@momjian.us 7456 : 1196 : uint16 bits = HEAP_XMAX_IS_MULTI;
7457 : 1196 : uint16 bits2 = 0;
7458 : 1196 : bool has_update = false;
7459 : 1196 : LockTupleMode strongest = LockTupleKeyShare;
7460 : :
7461 : : /*
7462 : : * We only use this in multis we just created, so they cannot be values
7463 : : * pre-pg_upgrade.
7464 : : */
4057 alvherre@alvh.no-ip. 7465 : 1196 : nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7466 : :
4609 7467 [ + + ]: 3671 : for (i = 0; i < nmembers; i++)
7468 : : {
7469 : : LockTupleMode mode;
7470 : :
7471 : : /*
7472 : : * Remember the strongest lock mode held by any member of the
7473 : : * multixact.
7474 : : */
4601 7475 : 2475 : mode = TUPLOCK_from_mxstatus(members[i].status);
7476 [ + + ]: 2475 : if (mode > strongest)
7477 : 660 : strongest = mode;
7478 : :
7479 : : /* See what other bits we need */
4609 7480 [ + + + + : 2475 : switch (members[i].status)
- ]
7481 : : {
7482 : 2284 : case MultiXactStatusForKeyShare:
7483 : : case MultiXactStatusForShare:
7484 : : case MultiXactStatusForNoKeyUpdate:
7485 : 2284 : break;
7486 : :
7487 : 52 : case MultiXactStatusForUpdate:
7488 : 52 : bits2 |= HEAP_KEYS_UPDATED;
7489 : 52 : break;
7490 : :
7491 : 129 : case MultiXactStatusNoKeyUpdate:
7492 : 129 : has_update = true;
7493 : 129 : break;
7494 : :
7495 : 10 : case MultiXactStatusUpdate:
7496 : 10 : bits2 |= HEAP_KEYS_UPDATED;
7497 : 10 : has_update = true;
7498 : 10 : break;
7499 : : }
7500 : : }
7501 : :
4601 7502 [ + + + + ]: 1196 : if (strongest == LockTupleExclusive ||
7503 : : strongest == LockTupleNoKeyExclusive)
7504 : 219 : bits |= HEAP_XMAX_EXCL_LOCK;
7505 [ + + ]: 977 : else if (strongest == LockTupleShare)
7506 : 438 : bits |= HEAP_XMAX_SHR_LOCK;
7507 [ + - ]: 539 : else if (strongest == LockTupleKeyShare)
7508 : 539 : bits |= HEAP_XMAX_KEYSHR_LOCK;
7509 : :
4609 7510 [ + + ]: 1196 : if (!has_update)
7511 : 1057 : bits |= HEAP_XMAX_LOCK_ONLY;
7512 : :
7513 [ + - ]: 1196 : if (nmembers > 0)
7514 : 1196 : pfree(members);
7515 : :
7516 : 1196 : *new_infomask = bits;
7517 : 1196 : *new_infomask2 = bits2;
7518 : 1196 : }
7519 : :
7520 : : /*
7521 : : * MultiXactIdGetUpdateXid
7522 : : *
7523 : : * Given a multixact Xmax and corresponding infomask, which does not have the
7524 : : * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7525 : : * transaction.
7526 : : *
7527 : : * Caller is expected to check the status of the updating transaction, if
7528 : : * necessary.
7529 : : */
7530 : : static TransactionId
7531 : 526 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
7532 : : {
4483 bruce@momjian.us 7533 : 526 : TransactionId update_xact = InvalidTransactionId;
7534 : : MultiXactMember *members;
7535 : : int nmembers;
7536 : :
4609 alvherre@alvh.no-ip. 7537 [ - + ]: 526 : Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7538 [ - + ]: 526 : Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7539 : :
7540 : : /*
7541 : : * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7542 : : * pre-pg_upgrade.
7543 : : */
4057 7544 : 526 : nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7545 : :
4609 7546 [ + - ]: 526 : if (nmembers > 0)
7547 : : {
7548 : : int i;
7549 : :
7550 [ + + ]: 1974 : for (i = 0; i < nmembers; i++)
7551 : : {
7552 : : /* Ignore lockers */
4299 7553 [ + + ]: 1448 : if (!ISUPDATE_from_mxstatus(members[i].status))
4609 7554 : 922 : continue;
7555 : :
7556 : : /* there can be at most one updater */
7557 [ - + ]: 526 : Assert(update_xact == InvalidTransactionId);
7558 : 526 : update_xact = members[i].xid;
7559 : : #ifndef USE_ASSERT_CHECKING
7560 : :
7561 : : /*
7562 : : * in an assert-enabled build, walk the whole array to ensure
7563 : : * there's no other updater.
7564 : : */
7565 : : break;
7566 : : #endif
7567 : : }
7568 : :
7569 : 526 : pfree(members);
7570 : : }
7571 : :
7572 : 526 : return update_xact;
7573 : : }
7574 : :
7575 : : /*
7576 : : * HeapTupleGetUpdateXid
7577 : : * As above, but use a HeapTupleHeader
7578 : : *
7579 : : * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7580 : : * checking the hint bits.
7581 : : */
7582 : : TransactionId
226 peter@eisentraut.org 7583 : 516 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
7584 : : {
7585 : 516 : return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
7586 : 516 : tup->t_infomask);
7587 : : }
7588 : :
7589 : : /*
7590 : : * Does the given multixact conflict with the current transaction grabbing a
7591 : : * tuple lock of the given strength?
7592 : : *
7593 : : * The passed infomask pairs up with the given multixact in the tuple header.
7594 : : *
7595 : : * If current_is_member is not NULL, it is set to 'true' if the current
7596 : : * transaction is a member of the given multixact.
7597 : : */
7598 : : static bool
3907 alvherre@alvh.no-ip. 7599 : 99 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
7600 : : LockTupleMode lockmode, bool *current_is_member)
7601 : : {
7602 : : int nmembers;
7603 : : MultiXactMember *members;
3759 bruce@momjian.us 7604 : 99 : bool result = false;
7605 : 99 : LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7606 : :
3361 alvherre@alvh.no-ip. 7607 [ - + ]: 99 : if (HEAP_LOCKED_UPGRADED(infomask))
3361 alvherre@alvh.no-ip. 7608 :UBC 0 : return false;
7609 : :
3361 alvherre@alvh.no-ip. 7610 :CBC 99 : nmembers = GetMultiXactIdMembers(multi, &members, false,
3907 7611 : 99 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7612 [ + - ]: 99 : if (nmembers >= 0)
7613 : : {
7614 : : int i;
7615 : :
7616 [ + + ]: 309 : for (i = 0; i < nmembers; i++)
7617 : : {
7618 : : TransactionId memxid;
7619 : : LOCKMODE memlockmode;
7620 : :
2272 7621 [ + + + + : 217 : if (result && (current_is_member == NULL || *current_is_member))
+ - ]
7622 : : break;
7623 : :
7624 : 210 : memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7625 : :
7626 : : /* ignore members from current xact (but track their presence) */
2274 7627 : 210 : memxid = members[i].xid;
7628 [ + + ]: 210 : if (TransactionIdIsCurrentTransactionId(memxid))
7629 : : {
2272 7630 [ + + ]: 92 : if (current_is_member != NULL)
7631 : 78 : *current_is_member = true;
7632 : 92 : continue;
7633 : : }
7634 [ + + ]: 118 : else if (result)
7635 : 8 : continue;
7636 : :
7637 : : /* ignore members that don't conflict with the lock we want */
7638 [ + + ]: 110 : if (!DoLockModesConflict(memlockmode, wanted))
2274 7639 : 71 : continue;
7640 : :
3907 7641 [ + + ]: 39 : if (ISUPDATE_from_mxstatus(members[i].status))
7642 : : {
7643 : : /* ignore aborted updaters */
7644 [ + + ]: 17 : if (TransactionIdDidAbort(memxid))
7645 : 1 : continue;
7646 : : }
7647 : : else
7648 : : {
7649 : : /* ignore lockers-only that are no longer in progress */
7650 [ + + ]: 22 : if (!TransactionIdIsInProgress(memxid))
7651 : 7 : continue;
7652 : : }
7653 : :
7654 : : /*
7655 : : * Whatever remains are either live lockers that conflict with our
7656 : : * wanted lock, and updaters that are not aborted. Those conflict
7657 : : * with what we want. Set up to return true, but keep going to
7658 : : * look for the current transaction among the multixact members,
7659 : : * if needed.
7660 : : */
7661 : 31 : result = true;
7662 : : }
7663 : 99 : pfree(members);
7664 : : }
7665 : :
7666 : 99 : return result;
7667 : : }
7668 : :
7669 : : /*
7670 : : * Do_MultiXactIdWait
7671 : : * Actual implementation for the two functions below.
7672 : : *
7673 : : * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7674 : : * needed to ensure we only sleep on conflicting members, and the infomask is
7675 : : * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7676 : : * indicates whether to use conditional lock acquisition, to allow callers to
7677 : : * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7678 : : * context information for error messages. 'remaining', if not NULL, receives
7679 : : * the number of members that are still running, including any (non-aborted)
7680 : : * subtransactions of our own transaction. 'logLockFailure' indicates whether
7681 : : * to log details when a lock acquisition fails with 'nowait' enabled.
7682 : : *
7683 : : * We do this by sleeping on each member using XactLockTableWait. Any
7684 : : * members that belong to the current backend are *not* waited for, however;
7685 : : * this would not merely be useless but would lead to Assert failure inside
7686 : : * XactLockTableWait. By the time this returns, it is certain that all
7687 : : * transactions *of other backends* that were members of the MultiXactId
7688 : : * that conflict with the requested status are dead (and no new ones can have
7689 : : * been added, since it is not legal to add members to an existing
7690 : : * MultiXactId).
7691 : : *
7692 : : * But by the time we finish sleeping, someone else may have changed the Xmax
7693 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7694 : : *
7695 : : * Note that in case we return false, the number of remaining members is
7696 : : * not to be trusted.
7697 : : */
7698 : : static bool
4609 7699 : 58 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7700 : : uint16 infomask, bool nowait,
7701 : : Relation rel, ItemPointer ctid, XLTW_Oper oper,
7702 : : int *remaining, bool logLockFailure)
7703 : : {
7704 : 58 : bool result = true;
7705 : : MultiXactMember *members;
7706 : : int nmembers;
7707 : 58 : int remain = 0;
7708 : :
7709 : : /* for pre-pg_upgrade tuples, no need to sleep at all */
3361 7710 [ + - ]: 58 : nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7711 : 58 : GetMultiXactIdMembers(multi, &members, false,
7712 : 58 : HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7713 : :
4609 7714 [ + - ]: 58 : if (nmembers >= 0)
7715 : : {
7716 : : int i;
7717 : :
7718 [ + + ]: 186 : for (i = 0; i < nmembers; i++)
7719 : : {
7720 : 132 : TransactionId memxid = members[i].xid;
7721 : 132 : MultiXactStatus memstatus = members[i].status;
7722 : :
7723 [ + + ]: 132 : if (TransactionIdIsCurrentTransactionId(memxid))
7724 : : {
7725 : 24 : remain++;
7726 : 24 : continue;
7727 : : }
7728 : :
7729 [ + + ]: 108 : if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
7730 : 108 : LOCKMODE_from_mxstatus(status)))
7731 : : {
7732 [ + + + - ]: 22 : if (remaining && TransactionIdIsInProgress(memxid))
7733 : 8 : remain++;
7734 : 22 : continue;
7735 : : }
7736 : :
7737 : : /*
7738 : : * This member conflicts with our multi, so we have to sleep (or
7739 : : * return failure, if asked to avoid waiting.)
7740 : : *
7741 : : * Note that we don't set up an error context callback ourselves,
7742 : : * but instead we pass the info down to XactLockTableWait. This
7743 : : * might seem a bit wasteful because the context is set up and
7744 : : * tore down for each member of the multixact, but in reality it
7745 : : * should be barely noticeable, and it avoids duplicate code.
7746 : : */
7747 [ + + ]: 86 : if (nowait)
7748 : : {
176 fujii@postgresql.org 7749 : 4 : result = ConditionalXactLockTableWait(memxid, logLockFailure);
4609 alvherre@alvh.no-ip. 7750 [ + - ]: 4 : if (!result)
7751 : 4 : break;
7752 : : }
7753 : : else
4189 7754 : 82 : XactLockTableWait(memxid, rel, ctid, oper);
7755 : : }
7756 : :
4609 7757 : 58 : pfree(members);
7758 : : }
7759 : :
7760 [ + + ]: 58 : if (remaining)
7761 : 10 : *remaining = remain;
7762 : :
7763 : 58 : return result;
7764 : : }
7765 : :
7766 : : /*
7767 : : * MultiXactIdWait
7768 : : * Sleep on a MultiXactId.
7769 : : *
7770 : : * By the time we finish sleeping, someone else may have changed the Xmax
7771 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7772 : : *
7773 : : * We return (in *remaining, if not NULL) the number of members that are still
7774 : : * running, including any (non-aborted) subtransactions of our own transaction.
7775 : : */
7776 : : static void
4189 7777 : 54 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
7778 : : Relation rel, ItemPointer ctid, XLTW_Oper oper,
7779 : : int *remaining)
7780 : : {
7781 : 54 : (void) Do_MultiXactIdWait(multi, status, infomask, false,
7782 : : rel, ctid, oper, remaining, false);
4609 7783 : 54 : }
7784 : :
7785 : : /*
7786 : : * ConditionalMultiXactIdWait
7787 : : * As above, but only lock if we can get the lock without blocking.
7788 : : *
7789 : : * By the time we finish sleeping, someone else may have changed the Xmax
7790 : : * of the containing tuple, so the caller needs to iterate on us somehow.
7791 : : *
7792 : : * If the multixact is now all gone, return true. Returns false if some
7793 : : * transactions might still be running.
7794 : : *
7795 : : * We return (in *remaining, if not NULL) the number of members that are still
7796 : : * running, including any (non-aborted) subtransactions of our own transaction.
7797 : : */
7798 : : static bool
7799 : 4 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
7800 : : uint16 infomask, Relation rel, int *remaining,
7801 : : bool logLockFailure)
7802 : : {
4189 7803 : 4 : return Do_MultiXactIdWait(multi, status, infomask, true,
7804 : : rel, NULL, XLTW_None, remaining, logLockFailure);
7805 : : }
7806 : :
7807 : : /*
7808 : : * heap_tuple_needs_eventual_freeze
7809 : : *
7810 : : * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7811 : : * will eventually require freezing (if tuple isn't removed by pruning first).
7812 : : */
7813 : : bool
3476 rhaas@postgresql.org 7814 : 2210240 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
7815 : : {
7816 : : TransactionId xid;
7817 : :
7818 : : /*
7819 : : * If xmin is a normal transaction ID, this tuple is definitely not
7820 : : * frozen.
7821 : : */
7822 : 2210240 : xid = HeapTupleHeaderGetXmin(tuple);
7823 [ + + ]: 2210240 : if (TransactionIdIsNormal(xid))
7824 : 14480 : return true;
7825 : :
7826 : : /*
7827 : : * If xmax is a valid xact or multixact, this tuple is also not frozen.
7828 : : */
7829 [ + + ]: 2195760 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7830 : : {
7831 : : MultiXactId multi;
7832 : :
7833 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
7834 [ + - ]: 2 : if (MultiXactIdIsValid(multi))
7835 : 2 : return true;
7836 : : }
7837 : : else
7838 : : {
7839 : 2195758 : xid = HeapTupleHeaderGetRawXmax(tuple);
7840 [ + + ]: 2195758 : if (TransactionIdIsNormal(xid))
7841 : 11 : return true;
7842 : : }
7843 : :
7844 [ - + ]: 2195747 : if (tuple->t_infomask & HEAP_MOVED)
7845 : : {
3476 rhaas@postgresql.org 7846 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
7847 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
7848 : 0 : return true;
7849 : : }
7850 : :
3476 rhaas@postgresql.org 7851 :CBC 2195747 : return false;
7852 : : }
7853 : :
7854 : : /*
7855 : : * heap_tuple_should_freeze
7856 : : *
7857 : : * Return value indicates if heap_prepare_freeze_tuple sibling function would
7858 : : * (or should) force freezing of the heap page that contains caller's tuple.
7859 : : * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
7860 : : * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
7861 : : *
7862 : : * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
7863 : : * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
7864 : : * Our working assumption is that caller won't decide to freeze this tuple.
7865 : : * It's up to caller to only ratchet back its own top-level trackers after the
7866 : : * point that it fully commits to not freezing the tuple/page in question.
7867 : : */
7868 : : bool
983 pg@bowt.ie 7869 : 2018228 : heap_tuple_should_freeze(HeapTupleHeader tuple,
7870 : : const struct VacuumCutoffs *cutoffs,
7871 : : TransactionId *NoFreezePageRelfrozenXid,
7872 : : MultiXactId *NoFreezePageRelminMxid)
7873 : : {
7874 : : TransactionId xid;
7875 : : MultiXactId multi;
989 7876 : 2018228 : bool freeze = false;
7877 : :
7878 : : /* First deal with xmin */
5052 rhaas@postgresql.org 7879 : 2018228 : xid = HeapTupleHeaderGetXmin(tuple);
1252 pg@bowt.ie 7880 [ + + ]: 2018228 : if (TransactionIdIsNormal(xid))
7881 : : {
989 7882 [ - + ]: 2018026 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
983 7883 [ + + ]: 2018026 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7884 : 21306 : *NoFreezePageRelfrozenXid = xid;
989 7885 [ + + ]: 2018026 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7886 : 18902 : freeze = true;
7887 : : }
7888 : :
7889 : : /* Now deal with xmax */
1252 7890 : 2018228 : xid = InvalidTransactionId;
7891 : 2018228 : multi = InvalidMultiXactId;
7892 [ + + ]: 2018228 : if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
4300 alvherre@alvh.no-ip. 7893 : 2 : multi = HeapTupleHeaderGetRawXmax(tuple);
7894 : : else
1252 pg@bowt.ie 7895 : 2018226 : xid = HeapTupleHeaderGetRawXmax(tuple);
7896 : :
7897 [ + + ]: 2018228 : if (TransactionIdIsNormal(xid))
7898 : : {
989 7899 [ - + ]: 248652 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
7900 : : /* xmax is a non-permanent XID */
983 7901 [ + + ]: 248652 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7902 : 3 : *NoFreezePageRelfrozenXid = xid;
989 7903 [ + + ]: 248652 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7904 : 32 : freeze = true;
7905 : : }
1252 7906 [ + + ]: 1769576 : else if (!MultiXactIdIsValid(multi))
7907 : : {
7908 : : /* xmax is a permanent XID or invalid MultiXactId/XID */
7909 : : }
7910 [ - + ]: 2 : else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7911 : : {
7912 : : /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
983 pg@bowt.ie 7913 [ # # ]:UBC 0 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7914 : 0 : *NoFreezePageRelminMxid = multi;
7915 : : /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
989 7916 : 0 : freeze = true;
7917 : : }
7918 : : else
7919 : : {
7920 : : /* xmax is a MultiXactId that may have an updater XID */
7921 : : MultiXactMember *members;
7922 : : int nmembers;
7923 : :
989 pg@bowt.ie 7924 [ - + ]:CBC 2 : Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
983 7925 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7926 : 2 : *NoFreezePageRelminMxid = multi;
989 7927 [ + - ]: 2 : if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
7928 : 2 : freeze = true;
7929 : :
7930 : : /* need to check whether any member of the mxact is old */
1252 7931 : 2 : nmembers = GetMultiXactIdMembers(multi, &members, false,
7932 : 2 : HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
7933 : :
7934 [ + + ]: 5 : for (int i = 0; i < nmembers; i++)
7935 : : {
7936 : 3 : xid = members[i].xid;
989 7937 [ - + ]: 3 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
983 7938 [ - + ]: 3 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
983 pg@bowt.ie 7939 :UBC 0 : *NoFreezePageRelfrozenXid = xid;
989 pg@bowt.ie 7940 [ - + ]:CBC 3 : if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
989 pg@bowt.ie 7941 :UBC 0 : freeze = true;
7942 : : }
1252 pg@bowt.ie 7943 [ + + ]:CBC 2 : if (nmembers > 0)
7944 : 1 : pfree(members);
7945 : : }
7946 : :
5052 rhaas@postgresql.org 7947 [ - + ]: 2018228 : if (tuple->t_infomask & HEAP_MOVED)
7948 : : {
5052 rhaas@postgresql.org 7949 :UBC 0 : xid = HeapTupleHeaderGetXvac(tuple);
1252 pg@bowt.ie 7950 [ # # ]: 0 : if (TransactionIdIsNormal(xid))
7951 : : {
989 7952 [ # # ]: 0 : Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
983 7953 [ # # ]: 0 : if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7954 : 0 : *NoFreezePageRelfrozenXid = xid;
7955 : : /* heap_prepare_freeze_tuple forces xvac freezing */
989 7956 : 0 : freeze = true;
7957 : : }
7958 : : }
7959 : :
989 pg@bowt.ie 7960 :CBC 2018228 : return freeze;
7961 : : }
7962 : :
7963 : : /*
7964 : : * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
7965 : : * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
7966 : : * that caller is in the process of physically removing, e.g. via HOT pruning
7967 : : * or index deletion.
7968 : : *
7969 : : * Caller must initialize its value to InvalidTransactionId, which is
7970 : : * generally interpreted as "definitely no need for a recovery conflict".
7971 : : * Final value must reflect all heap tuples that caller will physically remove
7972 : : * (or remove TID references to) via its ongoing pruning/deletion operation.
7973 : : * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
7974 : : * caller's WAL record) by REDO routine when it replays caller's operation.
7975 : : */
7976 : : void
1024 7977 : 1525853 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
7978 : : TransactionId *snapshotConflictHorizon)
7979 : : {
5740 simon@2ndQuadrant.co 7980 : 1525853 : TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
4609 alvherre@alvh.no-ip. 7981 : 1525853 : TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
5740 simon@2ndQuadrant.co 7982 : 1525853 : TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
7983 : :
5689 tgl@sss.pgh.pa.us 7984 [ - + ]: 1525853 : if (tuple->t_infomask & HEAP_MOVED)
7985 : : {
1024 pg@bowt.ie 7986 [ # # ]:UBC 0 : if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
7987 : 0 : *snapshotConflictHorizon = xvac;
7988 : : }
7989 : :
7990 : : /*
7991 : : * Ignore tuples inserted by an aborted transaction or if the tuple was
7992 : : * updated/deleted by the inserting transaction.
7993 : : *
7994 : : * Look for a committed hint bit, or if no xmin bit is set, check clog.
7995 : : */
4276 rhaas@postgresql.org 7996 [ + + ]:CBC 1525853 : if (HeapTupleHeaderXminCommitted(tuple) ||
7997 [ + + + - ]: 86660 : (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
7998 : : {
5385 simon@2ndQuadrant.co 7999 [ + + + + ]: 2742236 : if (xmax != xmin &&
1024 pg@bowt.ie 8000 : 1293698 : TransactionIdFollows(xmax, *snapshotConflictHorizon))
8001 : 96589 : *snapshotConflictHorizon = xmax;
8002 : : }
5740 simon@2ndQuadrant.co 8003 : 1525853 : }
8004 : :
8005 : : #ifdef USE_PREFETCH
8006 : : /*
8007 : : * Helper function for heap_index_delete_tuples. Issues prefetch requests for
8008 : : * prefetch_count buffers. The prefetch_state keeps track of all the buffers
8009 : : * we can prefetch, and which have already been prefetched; each call to this
8010 : : * function picks up where the previous call left off.
8011 : : *
8012 : : * Note: we expect the deltids array to be sorted in an order that groups TIDs
8013 : : * by heap block, with all TIDs for each block appearing together in exactly
8014 : : * one group.
8015 : : */
8016 : : static void
1697 pg@bowt.ie 8017 : 18589 : index_delete_prefetch_buffer(Relation rel,
8018 : : IndexDeletePrefetchState *prefetch_state,
8019 : : int prefetch_count)
8020 : : {
2356 andres@anarazel.de 8021 : 18589 : BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
8022 : 18589 : int count = 0;
8023 : : int i;
1697 pg@bowt.ie 8024 : 18589 : int ndeltids = prefetch_state->ndeltids;
8025 : 18589 : TM_IndexDelete *deltids = prefetch_state->deltids;
8026 : :
2356 andres@anarazel.de 8027 : 18589 : for (i = prefetch_state->next_item;
1697 pg@bowt.ie 8028 [ + + + + ]: 651452 : i < ndeltids && count < prefetch_count;
2356 andres@anarazel.de 8029 : 632863 : i++)
8030 : : {
1697 pg@bowt.ie 8031 : 632863 : ItemPointer htid = &deltids[i].tid;
8032 : :
2356 andres@anarazel.de 8033 [ + + + + ]: 1260248 : if (cur_hblkno == InvalidBlockNumber ||
8034 : 627385 : ItemPointerGetBlockNumber(htid) != cur_hblkno)
8035 : : {
8036 : 16787 : cur_hblkno = ItemPointerGetBlockNumber(htid);
8037 : 16787 : PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
8038 : 16787 : count++;
8039 : : }
8040 : : }
8041 : :
8042 : : /*
8043 : : * Save the prefetch position so that next time we can continue from that
8044 : : * position.
8045 : : */
8046 : 18589 : prefetch_state->next_item = i;
8047 : 18589 : prefetch_state->cur_hblkno = cur_hblkno;
8048 : 18589 : }
8049 : : #endif
8050 : :
8051 : : /*
8052 : : * Helper function for heap_index_delete_tuples. Checks for index corruption
8053 : : * involving an invalid TID in index AM caller's index page.
8054 : : *
8055 : : * This is an ideal place for these checks. The index AM must hold a buffer
8056 : : * lock on the index page containing the TIDs we examine here, so we don't
8057 : : * have to worry about concurrent VACUUMs at all. We can be sure that the
8058 : : * index is corrupt when htid points directly to an LP_UNUSED item or
8059 : : * heap-only tuple, which is not the case during standard index scans.
8060 : : */
8061 : : static inline void
1402 pg@bowt.ie 8062 : 534366 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
8063 : : Page page, OffsetNumber maxoff,
8064 : : ItemPointer htid, TM_IndexStatus *istatus)
8065 : : {
8066 : 534366 : OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8067 : : ItemId iid;
8068 : :
8069 [ + - + - : 534366 : Assert(OffsetNumberIsValid(istatus->idxoffnum));
- + ]
8070 : :
8071 [ - + ]: 534366 : if (unlikely(indexpagehoffnum > maxoff))
1402 pg@bowt.ie 8072 [ # # ]:UBC 0 : ereport(ERROR,
8073 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8074 : : 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\"",
8075 : : ItemPointerGetBlockNumber(htid),
8076 : : indexpagehoffnum,
8077 : : istatus->idxoffnum, delstate->iblknum,
8078 : : RelationGetRelationName(delstate->irel))));
8079 : :
1402 pg@bowt.ie 8080 :CBC 534366 : iid = PageGetItemId(page, indexpagehoffnum);
8081 [ - + ]: 534366 : if (unlikely(!ItemIdIsUsed(iid)))
1402 pg@bowt.ie 8082 [ # # ]:UBC 0 : ereport(ERROR,
8083 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8084 : : errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8085 : : ItemPointerGetBlockNumber(htid),
8086 : : indexpagehoffnum,
8087 : : istatus->idxoffnum, delstate->iblknum,
8088 : : RelationGetRelationName(delstate->irel))));
8089 : :
1402 pg@bowt.ie 8090 [ + + ]:CBC 534366 : if (ItemIdHasStorage(iid))
8091 : : {
8092 : : HeapTupleHeader htup;
8093 : :
8094 [ - + ]: 315821 : Assert(ItemIdIsNormal(iid));
8095 : 315821 : htup = (HeapTupleHeader) PageGetItem(page, iid);
8096 : :
8097 [ - + ]: 315821 : if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
1402 pg@bowt.ie 8098 [ # # ]:UBC 0 : ereport(ERROR,
8099 : : (errcode(ERRCODE_INDEX_CORRUPTED),
8100 : : errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8101 : : ItemPointerGetBlockNumber(htid),
8102 : : indexpagehoffnum,
8103 : : istatus->idxoffnum, delstate->iblknum,
8104 : : RelationGetRelationName(delstate->irel))));
8105 : : }
1402 pg@bowt.ie 8106 :CBC 534366 : }
8107 : :
8108 : : /*
8109 : : * heapam implementation of tableam's index_delete_tuples interface.
8110 : : *
8111 : : * This helper function is called by index AMs during index tuple deletion.
8112 : : * See tableam header comments for an explanation of the interface implemented
8113 : : * here and a general theory of operation. Note that each call here is either
8114 : : * a simple index deletion call, or a bottom-up index deletion call.
8115 : : *
8116 : : * It's possible for this to generate a fair amount of I/O, since we may be
8117 : : * deleting hundreds of tuples from a single index block. To amortize that
8118 : : * cost to some degree, this uses prefetching and combines repeat accesses to
8119 : : * the same heap block.
8120 : : */
8121 : : TransactionId
1697 8122 : 5478 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
8123 : : {
8124 : : /* Initial assumption is that earlier pruning took care of conflict */
1024 8125 : 5478 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
1711 8126 : 5478 : BlockNumber blkno = InvalidBlockNumber;
2356 andres@anarazel.de 8127 : 5478 : Buffer buf = InvalidBuffer;
1711 pg@bowt.ie 8128 : 5478 : Page page = NULL;
8129 : 5478 : OffsetNumber maxoff = InvalidOffsetNumber;
8130 : : TransactionId priorXmax;
8131 : : #ifdef USE_PREFETCH
8132 : : IndexDeletePrefetchState prefetch_state;
8133 : : int prefetch_distance;
8134 : : #endif
8135 : : SnapshotData SnapshotNonVacuumable;
1697 8136 : 5478 : int finalndeltids = 0,
8137 : 5478 : nblocksaccessed = 0;
8138 : :
8139 : : /* State that's only used in bottom-up index deletion case */
8140 : 5478 : int nblocksfavorable = 0;
8141 : 5478 : int curtargetfreespace = delstate->bottomupfreespace,
8142 : 5478 : lastfreespace = 0,
8143 : 5478 : actualfreespace = 0;
8144 : 5478 : bool bottomup_final_block = false;
8145 : :
8146 : 5478 : InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8147 : :
8148 : : /* Sort caller's deltids array by TID for further processing */
8149 : 5478 : index_delete_sort(delstate);
8150 : :
8151 : : /*
8152 : : * Bottom-up case: resort deltids array in an order attuned to where the
8153 : : * greatest number of promising TIDs are to be found, and determine how
8154 : : * many blocks from the start of sorted array should be considered
8155 : : * favorable. This will also shrink the deltids array in order to
8156 : : * eliminate completely unfavorable blocks up front.
8157 : : */
8158 [ + + ]: 5478 : if (delstate->bottomup)
8159 : 1930 : nblocksfavorable = bottomup_sort_and_shrink(delstate);
8160 : :
8161 : : #ifdef USE_PREFETCH
8162 : : /* Initialize prefetch state. */
2356 andres@anarazel.de 8163 : 5478 : prefetch_state.cur_hblkno = InvalidBlockNumber;
8164 : 5478 : prefetch_state.next_item = 0;
1697 pg@bowt.ie 8165 : 5478 : prefetch_state.ndeltids = delstate->ndeltids;
8166 : 5478 : prefetch_state.deltids = delstate->deltids;
8167 : :
8168 : : /*
8169 : : * Determine the prefetch distance that we will attempt to maintain.
8170 : : *
8171 : : * Since the caller holds a buffer lock somewhere in rel, we'd better make
8172 : : * sure that isn't a catalog relation before we call code that does
8173 : : * syscache lookups, to avoid risk of deadlock.
8174 : : */
2349 tmunro@postgresql.or 8175 [ + + ]: 5478 : if (IsCatalogRelation(rel))
2000 8176 : 3865 : prefetch_distance = maintenance_io_concurrency;
8177 : : else
8178 : : prefetch_distance =
8179 : 1613 : get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
8180 : :
8181 : : /* Cap initial prefetch distance for bottom-up deletion caller */
1697 pg@bowt.ie 8182 [ + + ]: 5478 : if (delstate->bottomup)
8183 : : {
8184 [ - + ]: 1930 : Assert(nblocksfavorable >= 1);
8185 [ - + ]: 1930 : Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8186 : 1930 : prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8187 : : }
8188 : :
8189 : : /* Start prefetching. */
8190 : 5478 : index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8191 : : #endif
8192 : :
8193 : : /* Iterate over deltids, determine which to delete, check their horizon */
8194 [ - + ]: 5478 : Assert(delstate->ndeltids > 0);
8195 [ + + ]: 539844 : for (int i = 0; i < delstate->ndeltids; i++)
8196 : : {
8197 : 536296 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8198 : 536296 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8199 : 536296 : ItemPointer htid = &ideltid->tid;
8200 : : OffsetNumber offnum;
8201 : :
8202 : : /*
8203 : : * Read buffer, and perform required extra steps each time a new block
8204 : : * is encountered. Avoid refetching if it's the same block as the one
8205 : : * from the last htid.
8206 : : */
1711 8207 [ + + + + ]: 1067114 : if (blkno == InvalidBlockNumber ||
8208 : 530818 : ItemPointerGetBlockNumber(htid) != blkno)
8209 : : {
8210 : : /*
8211 : : * Consider giving up early for bottom-up index deletion caller
8212 : : * first. (Only prefetch next-next block afterwards, when it
8213 : : * becomes clear that we're at least going to access the next
8214 : : * block in line.)
8215 : : *
8216 : : * Sometimes the first block frees so much space for bottom-up
8217 : : * caller that the deletion process can end without accessing any
8218 : : * more blocks. It is usually necessary to access 2 or 3 blocks
8219 : : * per bottom-up deletion operation, though.
8220 : : */
1697 8221 [ + + ]: 15041 : if (delstate->bottomup)
8222 : : {
8223 : : /*
8224 : : * We often allow caller to delete a few additional items
8225 : : * whose entries we reached after the point that space target
8226 : : * from caller was satisfied. The cost of accessing the page
8227 : : * was already paid at that point, so it made sense to finish
8228 : : * it off. When that happened, we finalize everything here
8229 : : * (by finishing off the whole bottom-up deletion operation
8230 : : * without needlessly paying the cost of accessing any more
8231 : : * blocks).
8232 : : */
8233 [ + + ]: 4122 : if (bottomup_final_block)
8234 : 163 : break;
8235 : :
8236 : : /*
8237 : : * Give up when we didn't enable our caller to free any
8238 : : * additional space as a result of processing the page that we
8239 : : * just finished up with. This rule is the main way in which
8240 : : * we keep the cost of bottom-up deletion under control.
8241 : : */
8242 [ + + + + ]: 3959 : if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8243 : 1767 : break;
8244 : 2192 : lastfreespace = actualfreespace; /* for next time */
8245 : :
8246 : : /*
8247 : : * Deletion operation (which is bottom-up) will definitely
8248 : : * access the next block in line. Prepare for that now.
8249 : : *
8250 : : * Decay target free space so that we don't hang on for too
8251 : : * long with a marginal case. (Space target is only truly
8252 : : * helpful when it allows us to recognize that we don't need
8253 : : * to access more than 1 or 2 blocks to satisfy caller due to
8254 : : * agreeable workload characteristics.)
8255 : : *
8256 : : * We are a bit more patient when we encounter contiguous
8257 : : * blocks, though: these are treated as favorable blocks. The
8258 : : * decay process is only applied when the next block in line
8259 : : * is not a favorable/contiguous block. This is not an
8260 : : * exception to the general rule; we still insist on finding
8261 : : * at least one deletable item per block accessed. See
8262 : : * bottomup_nblocksfavorable() for full details of the theory
8263 : : * behind favorable blocks and heap block locality in general.
8264 : : *
8265 : : * Note: The first block in line is always treated as a
8266 : : * favorable block, so the earliest possible point that the
8267 : : * decay can be applied is just before we access the second
8268 : : * block in line. The Assert() verifies this for us.
8269 : : */
8270 [ + + - + ]: 2192 : Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8271 [ + + ]: 2192 : if (nblocksfavorable > 0)
8272 : 2059 : nblocksfavorable--;
8273 : : else
8274 : 133 : curtargetfreespace /= 2;
8275 : : }
8276 : :
8277 : : /* release old buffer */
8278 [ + + ]: 13111 : if (BufferIsValid(buf))
8279 : 7633 : UnlockReleaseBuffer(buf);
8280 : :
8281 : 13111 : blkno = ItemPointerGetBlockNumber(htid);
1711 8282 : 13111 : buf = ReadBuffer(rel, blkno);
1697 8283 : 13111 : nblocksaccessed++;
8284 [ + + - + ]: 13111 : Assert(!delstate->bottomup ||
8285 : : nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8286 : :
8287 : : #ifdef USE_PREFETCH
8288 : :
8289 : : /*
8290 : : * To maintain the prefetch distance, prefetch one more page for
8291 : : * each page we read.
8292 : : */
8293 : 13111 : index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8294 : : #endif
8295 : :
1711 8296 : 13111 : LockBuffer(buf, BUFFER_LOCK_SHARE);
8297 : :
8298 : 13111 : page = BufferGetPage(buf);
8299 : 13111 : maxoff = PageGetMaxOffsetNumber(page);
8300 : : }
8301 : :
8302 : : /*
8303 : : * In passing, detect index corruption involving an index page with a
8304 : : * TID that points to a location in the heap that couldn't possibly be
8305 : : * correct. We only do this with actual TIDs from caller's index page
8306 : : * (not items reached by traversing through a HOT chain).
8307 : : */
1402 8308 : 534366 : index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8309 : :
1697 8310 [ + + ]: 534366 : if (istatus->knowndeletable)
8311 [ + - - + ]: 133507 : Assert(!delstate->bottomup && !istatus->promising);
8312 : : else
8313 : : {
8314 : 400859 : ItemPointerData tmp = *htid;
8315 : : HeapTupleData heapTuple;
8316 : :
8317 : : /* Are any tuples from this HOT chain non-vacuumable? */
8318 [ + + ]: 400859 : if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8319 : : &heapTuple, NULL, true))
8320 : 239550 : continue; /* can't delete entry */
8321 : :
8322 : : /* Caller will delete, since whole HOT chain is vacuumable */
8323 : 161309 : istatus->knowndeletable = true;
8324 : :
8325 : : /* Maintain index free space info for bottom-up deletion case */
8326 [ + + ]: 161309 : if (delstate->bottomup)
8327 : : {
8328 [ - + ]: 8698 : Assert(istatus->freespace > 0);
8329 : 8698 : actualfreespace += istatus->freespace;
8330 [ + + ]: 8698 : if (actualfreespace >= curtargetfreespace)
8331 : 2539 : bottomup_final_block = true;
8332 : : }
8333 : : }
8334 : :
8335 : : /*
8336 : : * Maintain snapshotConflictHorizon value for deletion operation as a
8337 : : * whole by advancing current value using heap tuple headers. This is
8338 : : * loosely based on the logic for pruning a HOT chain.
8339 : : */
1711 8340 : 294816 : offnum = ItemPointerGetOffsetNumber(htid);
8341 : 294816 : priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8342 : : for (;;)
2356 andres@anarazel.de 8343 : 20810 : {
8344 : : ItemId lp;
8345 : : HeapTupleHeader htup;
8346 : :
8347 : : /* Sanity check (pure paranoia) */
1445 pg@bowt.ie 8348 [ - + ]: 315626 : if (offnum < FirstOffsetNumber)
1445 pg@bowt.ie 8349 :UBC 0 : break;
8350 : :
8351 : : /*
8352 : : * An offset past the end of page's line pointer array is possible
8353 : : * when the array was truncated
8354 : : */
1445 pg@bowt.ie 8355 [ - + ]:CBC 315626 : if (offnum > maxoff)
1711 pg@bowt.ie 8356 :UBC 0 : break;
8357 : :
1711 pg@bowt.ie 8358 :CBC 315626 : lp = PageGetItemId(page, offnum);
8359 [ + + ]: 315626 : if (ItemIdIsRedirected(lp))
8360 : : {
8361 : 9191 : offnum = ItemIdGetRedirect(lp);
8362 : 9191 : continue;
8363 : : }
8364 : :
8365 : : /*
8366 : : * We'll often encounter LP_DEAD line pointers (especially with an
8367 : : * entry marked knowndeletable by our caller up front). No heap
8368 : : * tuple headers get examined for an htid that leads us to an
8369 : : * LP_DEAD item. This is okay because the earlier pruning
8370 : : * operation that made the line pointer LP_DEAD in the first place
8371 : : * must have considered the original tuple header as part of
8372 : : * generating its own snapshotConflictHorizon value.
8373 : : *
8374 : : * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8375 : : * the same strategy that index vacuuming uses in all cases. Index
8376 : : * VACUUM WAL records don't even have a snapshotConflictHorizon
8377 : : * field of their own for this reason.
8378 : : */
8379 [ + + ]: 306435 : if (!ItemIdIsNormal(lp))
8380 : 195640 : break;
8381 : :
8382 : 110795 : htup = (HeapTupleHeader) PageGetItem(page, lp);
8383 : :
8384 : : /*
8385 : : * Check the tuple XMIN against prior XMAX, if any
8386 : : */
8387 [ + + - + ]: 122414 : if (TransactionIdIsValid(priorXmax) &&
8388 : 11619 : !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
1711 pg@bowt.ie 8389 :UBC 0 : break;
8390 : :
1024 pg@bowt.ie 8391 :CBC 110795 : HeapTupleHeaderAdvanceConflictHorizon(htup,
8392 : : &snapshotConflictHorizon);
8393 : :
8394 : : /*
8395 : : * If the tuple is not HOT-updated, then we are at the end of this
8396 : : * HOT-chain. No need to visit later tuples from the same update
8397 : : * chain (they get their own index entries) -- just move on to
8398 : : * next htid from index AM caller.
8399 : : */
1711 8400 [ + + ]: 110795 : if (!HeapTupleHeaderIsHotUpdated(htup))
8401 : 99176 : break;
8402 : :
8403 : : /* Advance to next HOT chain member */
8404 [ - + ]: 11619 : Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8405 : 11619 : offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8406 : 11619 : priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8407 : : }
8408 : :
8409 : : /* Enable further/final shrinking of deltids for caller */
1697 8410 : 294816 : finalndeltids = i + 1;
8411 : : }
8412 : :
8413 : 5478 : UnlockReleaseBuffer(buf);
8414 : :
8415 : : /*
8416 : : * Shrink deltids array to exclude non-deletable entries at the end. This
8417 : : * is not just a minor optimization. Final deltids array size might be
8418 : : * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8419 : : * ndeltids being zero in all cases with zero total deletable entries.
8420 : : */
8421 [ + + - + ]: 5478 : Assert(finalndeltids > 0 || delstate->bottomup);
8422 : 5478 : delstate->ndeltids = finalndeltids;
8423 : :
1024 8424 : 5478 : return snapshotConflictHorizon;
8425 : : }
8426 : :
8427 : : /*
8428 : : * Specialized inlineable comparison function for index_delete_sort()
8429 : : */
8430 : : static inline int
1697 8431 : 12370187 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
8432 : : {
8433 : 12370187 : ItemPointer tid1 = &deltid1->tid;
8434 : 12370187 : ItemPointer tid2 = &deltid2->tid;
8435 : :
8436 : : {
8437 : 12370187 : BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
8438 : 12370187 : BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
8439 : :
8440 [ + + ]: 12370187 : if (blk1 != blk2)
8441 [ + + ]: 5036311 : return (blk1 < blk2) ? -1 : 1;
8442 : : }
8443 : : {
8444 : 7333876 : OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
8445 : 7333876 : OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
8446 : :
8447 [ + - ]: 7333876 : if (pos1 != pos2)
8448 [ + + ]: 7333876 : return (pos1 < pos2) ? -1 : 1;
8449 : : }
8450 : :
1408 pg@bowt.ie 8451 :UBC 0 : Assert(false);
8452 : :
8453 : : return 0;
8454 : : }
8455 : :
8456 : : /*
8457 : : * Sort deltids array from delstate by TID. This prepares it for further
8458 : : * processing by heap_index_delete_tuples().
8459 : : *
8460 : : * This operation becomes a noticeable consumer of CPU cycles with some
8461 : : * workloads, so we go to the trouble of specialization/micro optimization.
8462 : : * We use shellsort for this because it's easy to specialize, compiles to
8463 : : * relatively few instructions, and is adaptive to presorted inputs/subsets
8464 : : * (which are typical here).
8465 : : */
8466 : : static void
1697 pg@bowt.ie 8467 :CBC 5478 : index_delete_sort(TM_IndexDeleteOp *delstate)
8468 : : {
8469 : 5478 : TM_IndexDelete *deltids = delstate->deltids;
8470 : 5478 : int ndeltids = delstate->ndeltids;
8471 : :
8472 : : /*
8473 : : * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8474 : : *
8475 : : * This implementation is fast with array sizes up to ~4500. This covers
8476 : : * all supported BLCKSZ values.
8477 : : */
8478 : 5478 : const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8479 : :
8480 : : /* Think carefully before changing anything here -- keep swaps cheap */
8481 : : StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8482 : : "element size exceeds 8 bytes");
8483 : :
8484 [ + + ]: 54780 : for (int g = 0; g < lengthof(gaps); g++)
8485 : : {
304 dgustafsson@postgres 8486 [ + + ]: 7412993 : for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8487 : : {
1697 pg@bowt.ie 8488 : 7363691 : TM_IndexDelete d = deltids[i];
8489 : 7363691 : int j = i;
8490 : :
8491 [ + + + + ]: 12720966 : while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8492 : : {
8493 : 5357275 : deltids[j] = deltids[j - hi];
8494 : 5357275 : j -= hi;
8495 : : }
8496 : 7363691 : deltids[j] = d;
8497 : : }
8498 : : }
8499 : 5478 : }
8500 : :
8501 : : /*
8502 : : * Returns how many blocks should be considered favorable/contiguous for a
8503 : : * bottom-up index deletion pass. This is a number of heap blocks that starts
8504 : : * from and includes the first block in line.
8505 : : *
8506 : : * There is always at least one favorable block during bottom-up index
8507 : : * deletion. In the worst case (i.e. with totally random heap blocks) the
8508 : : * first block in line (the only favorable block) can be thought of as a
8509 : : * degenerate array of contiguous blocks that consists of a single block.
8510 : : * heap_index_delete_tuples() will expect this.
8511 : : *
8512 : : * Caller passes blockgroups, a description of the final order that deltids
8513 : : * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8514 : : * processing. Note that deltids need not actually be sorted just yet (caller
8515 : : * only passes deltids to us so that we can interpret blockgroups).
8516 : : *
8517 : : * You might guess that the existence of contiguous blocks cannot matter much,
8518 : : * since in general the main factor that determines which blocks we visit is
8519 : : * the number of promising TIDs, which is a fixed hint from the index AM.
8520 : : * We're not really targeting the general case, though -- the actual goal is
8521 : : * to adapt our behavior to a wide variety of naturally occurring conditions.
8522 : : * The effects of most of the heuristics we apply are only noticeable in the
8523 : : * aggregate, over time and across many _related_ bottom-up index deletion
8524 : : * passes.
8525 : : *
8526 : : * Deeming certain blocks favorable allows heapam to recognize and adapt to
8527 : : * workloads where heap blocks visited during bottom-up index deletion can be
8528 : : * accessed contiguously, in the sense that each newly visited block is the
8529 : : * neighbor of the block that bottom-up deletion just finished processing (or
8530 : : * close enough to it). It will likely be cheaper to access more favorable
8531 : : * blocks sooner rather than later (e.g. in this pass, not across a series of
8532 : : * related bottom-up passes). Either way it is probably only a matter of time
8533 : : * (or a matter of further correlated version churn) before all blocks that
8534 : : * appear together as a single large batch of favorable blocks get accessed by
8535 : : * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8536 : : * appear almost constantly or not even once (it all depends on per-index
8537 : : * workload characteristics).
8538 : : *
8539 : : * Note that the blockgroups sort order applies a power-of-two bucketing
8540 : : * scheme that creates opportunities for contiguous groups of blocks to get
8541 : : * batched together, at least with workloads that are naturally amenable to
8542 : : * being driven by heap block locality. This doesn't just enhance the spatial
8543 : : * locality of bottom-up heap block processing in the obvious way. It also
8544 : : * enables temporal locality of access, since sorting by heap block number
8545 : : * naturally tends to make the bottom-up processing order deterministic.
8546 : : *
8547 : : * Consider the following example to get a sense of how temporal locality
8548 : : * might matter: There is a heap relation with several indexes, each of which
8549 : : * is low to medium cardinality. It is subject to constant non-HOT updates.
8550 : : * The updates are skewed (in one part of the primary key, perhaps). None of
8551 : : * the indexes are logically modified by the UPDATE statements (if they were
8552 : : * then bottom-up index deletion would not be triggered in the first place).
8553 : : * Naturally, each new round of index tuples (for each heap tuple that gets a
8554 : : * heap_update() call) will have the same heap TID in each and every index.
8555 : : * Since these indexes are low cardinality and never get logically modified,
8556 : : * heapam processing during bottom-up deletion passes will access heap blocks
8557 : : * in approximately sequential order. Temporal locality of access occurs due
8558 : : * to bottom-up deletion passes behaving very similarly across each of the
8559 : : * indexes at any given moment. This keeps the number of buffer misses needed
8560 : : * to visit heap blocks to a minimum.
8561 : : */
8562 : : static int
8563 : 1930 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
8564 : : TM_IndexDelete *deltids)
8565 : : {
8566 : 1930 : int64 lastblock = -1;
8567 : 1930 : int nblocksfavorable = 0;
8568 : :
8569 [ - + ]: 1930 : Assert(nblockgroups >= 1);
8570 [ - + ]: 1930 : Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8571 : :
8572 : : /*
8573 : : * We tolerate heap blocks that will be accessed only slightly out of
8574 : : * physical order. Small blips occur when a pair of almost-contiguous
8575 : : * blocks happen to fall into different buckets (perhaps due only to a
8576 : : * small difference in npromisingtids that the bucketing scheme didn't
8577 : : * quite manage to ignore). We effectively ignore these blips by applying
8578 : : * a small tolerance. The precise tolerance we use is a little arbitrary,
8579 : : * but it works well enough in practice.
8580 : : */
8581 [ + + ]: 5846 : for (int b = 0; b < nblockgroups; b++)
8582 : : {
8583 : 5643 : IndexDeleteCounts *group = blockgroups + b;
8584 : 5643 : TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8585 : 5643 : BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8586 : :
8587 [ + + ]: 5643 : if (lastblock != -1 &&
8588 [ + + ]: 3713 : ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8589 [ + + ]: 3129 : (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8590 : : break;
8591 : :
8592 : 3916 : nblocksfavorable++;
8593 : 3916 : lastblock = block;
8594 : : }
8595 : :
8596 : : /* Always indicate that there is at least 1 favorable block */
8597 [ - + ]: 1930 : Assert(nblocksfavorable >= 1);
8598 : :
8599 : 1930 : return nblocksfavorable;
8600 : : }
8601 : :
8602 : : /*
8603 : : * qsort comparison function for bottomup_sort_and_shrink()
8604 : : */
8605 : : static int
8606 : 197990 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8607 : : {
8608 : 197990 : const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8609 : 197990 : const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8610 : :
8611 : : /*
8612 : : * Most significant field is npromisingtids (which we invert the order of
8613 : : * so as to sort in desc order).
8614 : : *
8615 : : * Caller should have already normalized npromisingtids fields into
8616 : : * power-of-two values (buckets).
8617 : : */
8618 [ + + ]: 197990 : if (group1->npromisingtids > group2->npromisingtids)
8619 : 8790 : return -1;
8620 [ + + ]: 189200 : if (group1->npromisingtids < group2->npromisingtids)
8621 : 11046 : return 1;
8622 : :
8623 : : /*
8624 : : * Tiebreak: desc ntids sort order.
8625 : : *
8626 : : * We cannot expect power-of-two values for ntids fields. We should
8627 : : * behave as if they were already rounded up for us instead.
8628 : : */
8629 [ + + ]: 178154 : if (group1->ntids != group2->ntids)
8630 : : {
8631 : 123813 : uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8632 : 123813 : uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8633 : :
8634 [ + + ]: 123813 : if (ntids1 > ntids2)
8635 : 21724 : return -1;
8636 [ + + ]: 102089 : if (ntids1 < ntids2)
8637 : 25085 : return 1;
8638 : : }
8639 : :
8640 : : /*
8641 : : * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8642 : : * block in deltids array) order.
8643 : : *
8644 : : * This is equivalent to sorting in ascending heap block number order
8645 : : * (among otherwise equal subsets of the array). This approach allows us
8646 : : * to avoid accessing the out-of-line TID. (We rely on the assumption
8647 : : * that the deltids array was sorted in ascending heap TID order when
8648 : : * these offsets to the first TID from each heap block group were formed.)
8649 : : */
8650 [ + + ]: 131345 : if (group1->ifirsttid > group2->ifirsttid)
8651 : 65055 : return 1;
8652 [ + - ]: 66290 : if (group1->ifirsttid < group2->ifirsttid)
8653 : 66290 : return -1;
8654 : :
1697 pg@bowt.ie 8655 :UBC 0 : pg_unreachable();
8656 : :
8657 : : return 0;
8658 : : }
8659 : :
8660 : : /*
8661 : : * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8662 : : *
8663 : : * Sorts deltids array in the order needed for useful processing by bottom-up
8664 : : * deletion. The array should already be sorted in TID order when we're
8665 : : * called. The sort process groups heap TIDs from deltids into heap block
8666 : : * groupings. Earlier/more-promising groups/blocks are usually those that are
8667 : : * known to have the most "promising" TIDs.
8668 : : *
8669 : : * Sets new size of deltids array (ndeltids) in state. deltids will only have
8670 : : * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8671 : : * return. This often means that deltids will be shrunk to a small fraction
8672 : : * of its original size (we eliminate many heap blocks from consideration for
8673 : : * caller up front).
8674 : : *
8675 : : * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8676 : : * for a definition and full details.
8677 : : */
8678 : : static int
1697 pg@bowt.ie 8679 :CBC 1930 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
8680 : : {
8681 : : IndexDeleteCounts *blockgroups;
8682 : : TM_IndexDelete *reordereddeltids;
8683 : 1930 : BlockNumber curblock = InvalidBlockNumber;
8684 : 1930 : int nblockgroups = 0;
8685 : 1930 : int ncopied = 0;
8686 : 1930 : int nblocksfavorable = 0;
8687 : :
8688 [ - + ]: 1930 : Assert(delstate->bottomup);
8689 [ - + ]: 1930 : Assert(delstate->ndeltids > 0);
8690 : :
8691 : : /* Calculate per-heap-block count of TIDs */
8692 : 1930 : blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8693 [ + + ]: 910513 : for (int i = 0; i < delstate->ndeltids; i++)
8694 : : {
8695 : 908583 : TM_IndexDelete *ideltid = &delstate->deltids[i];
8696 : 908583 : TM_IndexStatus *istatus = delstate->status + ideltid->id;
8697 : 908583 : ItemPointer htid = &ideltid->tid;
8698 : 908583 : bool promising = istatus->promising;
8699 : :
8700 [ + + ]: 908583 : if (curblock != ItemPointerGetBlockNumber(htid))
8701 : : {
8702 : : /* New block group */
8703 : 38250 : nblockgroups++;
8704 : :
8705 [ + + - + ]: 38250 : Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8706 : : !BlockNumberIsValid(curblock));
8707 : :
8708 : 38250 : curblock = ItemPointerGetBlockNumber(htid);
8709 : 38250 : blockgroups[nblockgroups - 1].ifirsttid = i;
8710 : 38250 : blockgroups[nblockgroups - 1].ntids = 1;
8711 : 38250 : blockgroups[nblockgroups - 1].npromisingtids = 0;
8712 : : }
8713 : : else
8714 : : {
8715 : 870333 : blockgroups[nblockgroups - 1].ntids++;
8716 : : }
8717 : :
8718 [ + + ]: 908583 : if (promising)
8719 : 120868 : blockgroups[nblockgroups - 1].npromisingtids++;
8720 : : }
8721 : :
8722 : : /*
8723 : : * We're about ready to sort block groups to determine the optimal order
8724 : : * for visiting heap blocks. But before we do, round the number of
8725 : : * promising tuples for each block group up to the next power-of-two,
8726 : : * unless it is very low (less than 4), in which case we round up to 4.
8727 : : * npromisingtids is far too noisy to trust when choosing between a pair
8728 : : * of block groups that both have very low values.
8729 : : *
8730 : : * This scheme divides heap blocks/block groups into buckets. Each bucket
8731 : : * contains blocks that have _approximately_ the same number of promising
8732 : : * TIDs as each other. The goal is to ignore relatively small differences
8733 : : * in the total number of promising entries, so that the whole process can
8734 : : * give a little weight to heapam factors (like heap block locality)
8735 : : * instead. This isn't a trade-off, really -- we have nothing to lose. It
8736 : : * would be foolish to interpret small differences in npromisingtids
8737 : : * values as anything more than noise.
8738 : : *
8739 : : * We tiebreak on nhtids when sorting block group subsets that have the
8740 : : * same npromisingtids, but this has the same issues as npromisingtids,
8741 : : * and so nhtids is subject to the same power-of-two bucketing scheme. The
8742 : : * only reason that we don't fix nhtids in the same way here too is that
8743 : : * we'll need accurate nhtids values after the sort. We handle nhtids
8744 : : * bucketization dynamically instead (in the sort comparator).
8745 : : *
8746 : : * See bottomup_nblocksfavorable() for a full explanation of when and how
8747 : : * heap locality/favorable blocks can significantly influence when and how
8748 : : * heap blocks are accessed.
8749 : : */
8750 [ + + ]: 40180 : for (int b = 0; b < nblockgroups; b++)
8751 : : {
8752 : 38250 : IndexDeleteCounts *group = blockgroups + b;
8753 : :
8754 : : /* Better off falling back on nhtids with low npromisingtids */
8755 [ + + ]: 38250 : if (group->npromisingtids <= 4)
8756 : 32762 : group->npromisingtids = 4;
8757 : : else
8758 : 5488 : group->npromisingtids =
8759 : 5488 : pg_nextpower2_32((uint32) group->npromisingtids);
8760 : : }
8761 : :
8762 : : /* Sort groups and rearrange caller's deltids array */
8763 : 1930 : qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8764 : : bottomup_sort_and_shrink_cmp);
8765 : 1930 : reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8766 : :
8767 : 1930 : nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8768 : : /* Determine number of favorable blocks at the start of final deltids */
8769 : 1930 : nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8770 : : delstate->deltids);
8771 : :
8772 [ + + ]: 12899 : for (int b = 0; b < nblockgroups; b++)
8773 : : {
8774 : 10969 : IndexDeleteCounts *group = blockgroups + b;
8775 : 10969 : TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8776 : :
8777 : 10969 : memcpy(reordereddeltids + ncopied, firstdtid,
8778 : 10969 : sizeof(TM_IndexDelete) * group->ntids);
8779 : 10969 : ncopied += group->ntids;
8780 : : }
8781 : :
8782 : : /* Copy final grouped and sorted TIDs back into start of caller's array */
8783 : 1930 : memcpy(delstate->deltids, reordereddeltids,
8784 : : sizeof(TM_IndexDelete) * ncopied);
8785 : 1930 : delstate->ndeltids = ncopied;
8786 : :
8787 : 1930 : pfree(reordereddeltids);
8788 : 1930 : pfree(blockgroups);
8789 : :
8790 : 1930 : return nblocksfavorable;
8791 : : }
8792 : :
8793 : : /*
8794 : : * Perform XLogInsert for a heap-visible operation. 'block' is the block
8795 : : * being marked all-visible, and vm_buffer is the buffer containing the
8796 : : * corresponding visibility map block. Both should have already been modified
8797 : : * and dirtied.
8798 : : *
8799 : : * snapshotConflictHorizon comes from the largest xmin on the page being
8800 : : * marked all-visible. REDO routine uses it to generate recovery conflicts.
8801 : : *
8802 : : * If checksums or wal_log_hints are enabled, we may also generate a full-page
8803 : : * image of heap_buffer. Otherwise, we optimize away the FPI (by specifying
8804 : : * REGBUF_NO_IMAGE for the heap buffer), in which case the caller should *not*
8805 : : * update the heap page's LSN.
8806 : : */
8807 : : XLogRecPtr
889 andres@anarazel.de 8808 : 49891 : log_heap_visible(Relation rel, Buffer heap_buffer, Buffer vm_buffer,
8809 : : TransactionId snapshotConflictHorizon, uint8 vmflags)
8810 : : {
8811 : : xl_heap_visible xlrec;
8812 : : XLogRecPtr recptr;
8813 : : uint8 flags;
8814 : :
4551 simon@2ndQuadrant.co 8815 [ - + ]: 49891 : Assert(BufferIsValid(heap_buffer));
8816 [ - + ]: 49891 : Assert(BufferIsValid(vm_buffer));
8817 : :
1024 pg@bowt.ie 8818 : 49891 : xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
3476 rhaas@postgresql.org 8819 : 49891 : xlrec.flags = vmflags;
888 andres@anarazel.de 8820 [ + + + - : 49891 : if (RelationIsAccessibleInLogicalDecoding(rel))
- + - - -
- + + - +
- - - - -
- ]
8821 : 121 : xlrec.flags |= VISIBILITYMAP_XLOG_CATALOG_REL;
3943 heikki.linnakangas@i 8822 : 49891 : XLogBeginInsert();
207 peter@eisentraut.org 8823 : 49891 : XLogRegisterData(&xlrec, SizeOfHeapVisible);
8824 : :
3943 heikki.linnakangas@i 8825 : 49891 : XLogRegisterBuffer(0, vm_buffer, 0);
8826 : :
8827 : 49891 : flags = REGBUF_STANDARD;
8828 [ + + + - ]: 49891 : if (!XLogHintBitIsNeeded())
8829 : 3466 : flags |= REGBUF_NO_IMAGE;
8830 : 49891 : XLogRegisterBuffer(1, heap_buffer, flags);
8831 : :
8832 : 49891 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
8833 : :
5191 rhaas@postgresql.org 8834 : 49891 : return recptr;
8835 : : }
8836 : :
8837 : : /*
8838 : : * Perform XLogInsert for a heap-update operation. Caller must already
8839 : : * have modified the buffer(s) and marked them dirty.
8840 : : */
8841 : : static XLogRecPtr
4609 alvherre@alvh.no-ip. 8842 : 291460 : log_heap_update(Relation reln, Buffer oldbuf,
8843 : : Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
8844 : : HeapTuple old_key_tuple,
8845 : : bool all_visible_cleared, bool new_all_visible_cleared)
8846 : : {
8847 : : xl_heap_update xlrec;
8848 : : xl_heap_header xlhdr;
8849 : : xl_heap_header xlhdr_idx;
8850 : : uint8 info;
8851 : : uint16 prefix_suffix[2];
4196 heikki.linnakangas@i 8852 : 291460 : uint16 prefixlen = 0,
8853 : 291460 : suffixlen = 0;
8854 : : XLogRecPtr recptr;
3426 kgrittn@postgresql.o 8855 : 291460 : Page page = BufferGetPage(newbuf);
4288 rhaas@postgresql.org 8856 [ + + + - : 291460 : bool need_tuple_data = RelationIsLogicallyLogged(reln);
- + - - -
- + - +
+ ]
8857 : : bool init;
8858 : : int bufflags;
8859 : :
8860 : : /* Caller should not call me on a non-WAL-logged relation */
5381 8861 [ + - + + : 291460 : Assert(RelationNeedsWAL(reln));
+ - - + ]
8862 : :
3943 heikki.linnakangas@i 8863 : 291460 : XLogBeginInsert();
8864 : :
5689 tgl@sss.pgh.pa.us 8865 [ + + ]: 291460 : if (HeapTupleIsHeapOnly(newtup))
6561 8866 : 140939 : info = XLOG_HEAP_HOT_UPDATE;
8867 : : else
8868 : 150521 : info = XLOG_HEAP_UPDATE;
8869 : :
8870 : : /*
8871 : : * If the old and new tuple are on the same page, we only need to log the
8872 : : * parts of the new tuple that were changed. That saves on the amount of
8873 : : * WAL we need to write. Currently, we just count any unchanged bytes in
8874 : : * the beginning and end of the tuple. That's quick to check, and
8875 : : * perfectly covers the common case that only one field is updated.
8876 : : *
8877 : : * We could do this even if the old and new tuple are on different pages,
8878 : : * but only if we don't make a full-page image of the old page, which is
8879 : : * difficult to know in advance. Also, if the old tuple is corrupt for
8880 : : * some reason, it would allow the corruption to propagate the new page,
8881 : : * so it seems best to avoid. Under the general assumption that most
8882 : : * updates tend to create the new tuple version on the same page, there
8883 : : * isn't much to be gained by doing this across pages anyway.
8884 : : *
8885 : : * Skip this if we're taking a full-page image of the new page, as we
8886 : : * don't include the new tuple in the WAL record in that case. Also
8887 : : * disable if wal_level='logical', as logical decoding needs to be able to
8888 : : * read the new tuple in whole from the WAL record alone.
8889 : : */
4196 heikki.linnakangas@i 8890 [ + + + + ]: 291460 : if (oldbuf == newbuf && !need_tuple_data &&
8891 [ + + ]: 140869 : !XLogCheckBufferNeedsBackup(newbuf))
8892 : : {
8893 : 140406 : char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8894 : 140406 : char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8895 : 140406 : int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8896 : 140406 : int newlen = newtup->t_len - newtup->t_data->t_hoff;
8897 : :
8898 : : /* Check for common prefix between old and new tuple */
8899 [ + + ]: 11631984 : for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8900 : : {
8901 [ + + ]: 11606810 : if (newp[prefixlen] != oldp[prefixlen])
8902 : 115232 : break;
8903 : : }
8904 : :
8905 : : /*
8906 : : * Storing the length of the prefix takes 2 bytes, so we need to save
8907 : : * at least 3 bytes or there's no point.
8908 : : */
8909 [ + + ]: 140406 : if (prefixlen < 3)
8910 : 22111 : prefixlen = 0;
8911 : :
8912 : : /* Same for suffix */
8913 [ + + ]: 4536056 : for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
8914 : : {
8915 [ + + ]: 4510634 : if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
8916 : 114984 : break;
8917 : : }
8918 [ + + ]: 140406 : if (suffixlen < 3)
8919 : 34715 : suffixlen = 0;
8920 : : }
8921 : :
8922 : : /* Prepare main WAL data chain */
4288 rhaas@postgresql.org 8923 : 291460 : xlrec.flags = 0;
8924 [ + + ]: 291460 : if (all_visible_cleared)
3774 andres@anarazel.de 8925 : 1556 : xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
4288 rhaas@postgresql.org 8926 [ + + ]: 291460 : if (new_all_visible_cleared)
3774 andres@anarazel.de 8927 : 1003 : xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
4196 heikki.linnakangas@i 8928 [ + + ]: 291460 : if (prefixlen > 0)
3774 andres@anarazel.de 8929 : 118295 : xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
4196 heikki.linnakangas@i 8930 [ + + ]: 291460 : if (suffixlen > 0)
3774 andres@anarazel.de 8931 : 105691 : xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
3943 heikki.linnakangas@i 8932 [ + + ]: 291460 : if (need_tuple_data)
8933 : : {
3774 andres@anarazel.de 8934 : 47017 : xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
3943 heikki.linnakangas@i 8935 [ + + ]: 47017 : if (old_key_tuple)
8936 : : {
8937 [ + + ]: 145 : if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3774 andres@anarazel.de 8938 : 64 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
8939 : : else
8940 : 81 : xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
8941 : : }
8942 : : }
8943 : :
8944 : : /* If new tuple is the single and first tuple on page... */
4196 heikki.linnakangas@i 8945 [ + + + + ]: 294852 : if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
8946 : 3392 : PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
8947 : : {
8948 : 3128 : info |= XLOG_HEAP_INIT_PAGE;
3943 8949 : 3128 : init = true;
8950 : : }
8951 : : else
8952 : 288332 : init = false;
8953 : :
8954 : : /* Prepare WAL data for the old page */
8955 : 291460 : xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
8956 : 291460 : xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
8957 : 582920 : xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
8958 : 291460 : oldtup->t_data->t_infomask2);
8959 : :
8960 : : /* Prepare WAL data for the new page */
8961 : 291460 : xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
8962 : 291460 : xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
8963 : :
8964 : 291460 : bufflags = REGBUF_STANDARD;
8965 [ + + ]: 291460 : if (init)
8966 : 3128 : bufflags |= REGBUF_WILL_INIT;
8967 [ + + ]: 291460 : if (need_tuple_data)
8968 : 47017 : bufflags |= REGBUF_KEEP_DATA;
8969 : :
8970 : 291460 : XLogRegisterBuffer(0, newbuf, bufflags);
8971 [ + + ]: 291460 : if (oldbuf != newbuf)
8972 : 138654 : XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
8973 : :
207 peter@eisentraut.org 8974 : 291460 : XLogRegisterData(&xlrec, SizeOfHeapUpdate);
8975 : :
8976 : : /*
8977 : : * Prepare WAL data for the new tuple.
8978 : : */
4196 heikki.linnakangas@i 8979 [ + + + + ]: 291460 : if (prefixlen > 0 || suffixlen > 0)
8980 : : {
8981 [ + + + + ]: 139943 : if (prefixlen > 0 && suffixlen > 0)
8982 : : {
8983 : 84043 : prefix_suffix[0] = prefixlen;
8984 : 84043 : prefix_suffix[1] = suffixlen;
207 peter@eisentraut.org 8985 : 84043 : XLogRegisterBufData(0, &prefix_suffix, sizeof(uint16) * 2);
8986 : : }
4196 heikki.linnakangas@i 8987 [ + + ]: 55900 : else if (prefixlen > 0)
8988 : : {
207 peter@eisentraut.org 8989 : 34252 : XLogRegisterBufData(0, &prefixlen, sizeof(uint16));
8990 : : }
8991 : : else
8992 : : {
8993 : 21648 : XLogRegisterBufData(0, &suffixlen, sizeof(uint16));
8994 : : }
8995 : : }
8996 : :
3943 heikki.linnakangas@i 8997 : 291460 : xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
8998 : 291460 : xlhdr.t_infomask = newtup->t_data->t_infomask;
8999 : 291460 : xlhdr.t_hoff = newtup->t_data->t_hoff;
3850 tgl@sss.pgh.pa.us 9000 [ - + ]: 291460 : Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
9001 : :
9002 : : /*
9003 : : * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9004 : : *
9005 : : * The 'data' doesn't include the common prefix or suffix.
9006 : : */
207 peter@eisentraut.org 9007 : 291460 : XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
4196 heikki.linnakangas@i 9008 [ + + ]: 291460 : if (prefixlen == 0)
9009 : : {
3943 9010 : 173165 : XLogRegisterBufData(0,
207 peter@eisentraut.org 9011 : 173165 : (char *) newtup->t_data + SizeofHeapTupleHeader,
2999 tgl@sss.pgh.pa.us 9012 : 173165 : newtup->t_len - SizeofHeapTupleHeader - suffixlen);
9013 : : }
9014 : : else
9015 : : {
9016 : : /*
9017 : : * Have to write the null bitmap and data after the common prefix as
9018 : : * two separate rdata entries.
9019 : : */
9020 : : /* bitmap [+ padding] [+ oid] */
3850 9021 [ + - ]: 118295 : if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9022 : : {
3943 heikki.linnakangas@i 9023 : 118295 : XLogRegisterBufData(0,
207 peter@eisentraut.org 9024 : 118295 : (char *) newtup->t_data + SizeofHeapTupleHeader,
2999 tgl@sss.pgh.pa.us 9025 : 118295 : newtup->t_data->t_hoff - SizeofHeapTupleHeader);
9026 : : }
9027 : :
9028 : : /* data after common prefix */
3943 heikki.linnakangas@i 9029 : 118295 : XLogRegisterBufData(0,
207 peter@eisentraut.org 9030 : 118295 : (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
2999 tgl@sss.pgh.pa.us 9031 : 118295 : newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9032 : : }
9033 : :
9034 : : /* We need to log a tuple identity */
3943 heikki.linnakangas@i 9035 [ + + + + ]: 291460 : if (need_tuple_data && old_key_tuple)
9036 : : {
9037 : : /* don't really need this, but its more comfy to decode */
9038 : 145 : xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9039 : 145 : xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9040 : 145 : xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9041 : :
207 peter@eisentraut.org 9042 : 145 : XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
9043 : :
9044 : : /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
3850 tgl@sss.pgh.pa.us 9045 : 145 : XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
9046 : 145 : old_key_tuple->t_len - SizeofHeapTupleHeader);
9047 : : }
9048 : :
9049 : : /* filtering by origin on a row level is much more efficient */
3180 andres@anarazel.de 9050 : 291460 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
9051 : :
3943 heikki.linnakangas@i 9052 : 291460 : recptr = XLogInsert(RM_HEAP_ID, info);
9053 : :
7178 neilc@samurai.com 9054 : 291460 : return recptr;
9055 : : }
9056 : :
9057 : : /*
9058 : : * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
9059 : : *
9060 : : * This is only used in wal_level >= WAL_LEVEL_LOGICAL, and only for catalog
9061 : : * tuples.
9062 : : */
9063 : : static XLogRecPtr
4288 rhaas@postgresql.org 9064 : 23809 : log_heap_new_cid(Relation relation, HeapTuple tup)
9065 : : {
9066 : : xl_heap_new_cid xlrec;
9067 : :
9068 : : XLogRecPtr recptr;
9069 : 23809 : HeapTupleHeader hdr = tup->t_data;
9070 : :
9071 [ - + ]: 23809 : Assert(ItemPointerIsValid(&tup->t_self));
9072 [ - + ]: 23809 : Assert(tup->t_tableOid != InvalidOid);
9073 : :
9074 : 23809 : xlrec.top_xid = GetTopTransactionId();
1158 9075 : 23809 : xlrec.target_locator = relation->rd_locator;
3943 heikki.linnakangas@i 9076 : 23809 : xlrec.target_tid = tup->t_self;
9077 : :
9078 : : /*
9079 : : * If the tuple got inserted & deleted in the same TX we definitely have a
9080 : : * combo CID, set cmin and cmax.
9081 : : */
4288 rhaas@postgresql.org 9082 [ + + ]: 23809 : if (hdr->t_infomask & HEAP_COMBOCID)
9083 : : {
9084 [ - + ]: 1969 : Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
4276 9085 [ - + ]: 1969 : Assert(!HeapTupleHeaderXminInvalid(hdr));
4288 9086 : 1969 : xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9087 : 1969 : xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9088 : 1969 : xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9089 : : }
9090 : : /* No combo CID, so only cmin or cmax can be set by this TX */
9091 : : else
9092 : : {
9093 : : /*
9094 : : * Tuple inserted.
9095 : : *
9096 : : * We need to check for LOCK ONLY because multixacts might be
9097 : : * transferred to the new tuple in case of FOR KEY SHARE updates in
9098 : : * which case there will be an xmax, although the tuple just got
9099 : : * inserted.
9100 : : */
9101 [ + + + + ]: 28532 : if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9102 : 6692 : HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
9103 : : {
9104 : 15149 : xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
9105 : 15149 : xlrec.cmax = InvalidCommandId;
9106 : : }
9107 : : /* Tuple from a different tx updated or deleted. */
9108 : : else
9109 : : {
9110 : 6691 : xlrec.cmin = InvalidCommandId;
9111 : 6691 : xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
9112 : : }
9113 : 21840 : xlrec.combocid = InvalidCommandId;
9114 : : }
9115 : :
9116 : : /*
9117 : : * Note that we don't need to register the buffer here, because this
9118 : : * operation does not modify the page. The insert/update/delete that
9119 : : * called us certainly did, but that's WAL-logged separately.
9120 : : */
3943 heikki.linnakangas@i 9121 : 23809 : XLogBeginInsert();
207 peter@eisentraut.org 9122 : 23809 : XLogRegisterData(&xlrec, SizeOfHeapNewCid);
9123 : :
9124 : : /* will be looked at irrespective of origin */
9125 : :
3943 heikki.linnakangas@i 9126 : 23809 : recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9127 : :
4288 rhaas@postgresql.org 9128 : 23809 : return recptr;
9129 : : }
9130 : :
9131 : : /*
9132 : : * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9133 : : * the old tuple in an UPDATE or DELETE.
9134 : : *
9135 : : * Returns NULL if there's no need to log an identity or if there's no suitable
9136 : : * key defined.
9137 : : *
9138 : : * Pass key_required true if any replica identity columns changed value, or if
9139 : : * any of them have any external data. Delete must always pass true.
9140 : : *
9141 : : * *copy is set to true if the returned tuple is a modified copy rather than
9142 : : * the same tuple that was passed in.
9143 : : */
9144 : : static HeapTuple
1300 akapila@postgresql.o 9145 : 1721227 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
9146 : : bool *copy)
9147 : : {
4288 rhaas@postgresql.org 9148 : 1721227 : TupleDesc desc = RelationGetDescr(relation);
9149 : 1721227 : char replident = relation->rd_rel->relreplident;
9150 : : Bitmapset *idattrs;
9151 : : HeapTuple key_tuple;
9152 : : bool nulls[MaxHeapAttributeNumber];
9153 : : Datum values[MaxHeapAttributeNumber];
9154 : :
9155 : 1721227 : *copy = false;
9156 : :
9157 [ + + + + : 1721227 : if (!RelationIsLogicallyLogged(relation))
- + - - -
- + - +
+ ]
9158 : 1620940 : return NULL;
9159 : :
9160 [ + + ]: 100287 : if (replident == REPLICA_IDENTITY_NOTHING)
9161 : 231 : return NULL;
9162 : :
9163 [ + + ]: 100056 : if (replident == REPLICA_IDENTITY_FULL)
9164 : : {
9165 : : /*
9166 : : * When logging the entire old tuple, it very well could contain
9167 : : * toasted columns. If so, force them to be inlined.
9168 : : */
9169 [ + + ]: 194 : if (HeapTupleHasExternal(tp))
9170 : : {
9171 : 4 : *copy = true;
2196 tgl@sss.pgh.pa.us 9172 : 4 : tp = toast_flatten_tuple(tp, desc);
9173 : : }
4288 rhaas@postgresql.org 9174 : 194 : return tp;
9175 : : }
9176 : :
9177 : : /* if the key isn't required and we're only logging the key, we're done */
1300 akapila@postgresql.o 9178 [ + + ]: 99862 : if (!key_required)
4288 rhaas@postgresql.org 9179 : 46872 : return NULL;
9180 : :
9181 : : /* find out the replica identity columns */
2196 tgl@sss.pgh.pa.us 9182 : 52990 : idattrs = RelationGetIndexAttrBitmap(relation,
9183 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
9184 : :
9185 : : /*
9186 : : * If there's no defined replica identity columns, treat as !key_required.
9187 : : * (This case should not be reachable from heap_update, since that should
9188 : : * calculate key_required accurately. But heap_delete just passes
9189 : : * constant true for key_required, so we can hit this case in deletes.)
9190 : : */
9191 [ + + ]: 52990 : if (bms_is_empty(idattrs))
9192 : 6021 : return NULL;
9193 : :
9194 : : /*
9195 : : * Construct a new tuple containing only the replica identity columns,
9196 : : * with nulls elsewhere. While we're at it, assert that the replica
9197 : : * identity columns aren't null.
9198 : : */
9199 : 46969 : heap_deform_tuple(tp, desc, values, nulls);
9200 : :
9201 [ + + ]: 150901 : for (int i = 0; i < desc->natts; i++)
9202 : : {
9203 [ + + ]: 103932 : if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
9204 : : idattrs))
9205 [ - + ]: 46981 : Assert(!nulls[i]);
9206 : : else
9207 : 56951 : nulls[i] = true;
9208 : : }
9209 : :
4288 rhaas@postgresql.org 9210 : 46969 : key_tuple = heap_form_tuple(desc, values, nulls);
9211 : 46969 : *copy = true;
9212 : :
2196 tgl@sss.pgh.pa.us 9213 : 46969 : bms_free(idattrs);
9214 : :
9215 : : /*
9216 : : * If the tuple, which by here only contains indexed columns, still has
9217 : : * toasted columns, force them to be inlined. This is somewhat unlikely
9218 : : * since there's limits on the size of indexed columns, so we don't
9219 : : * duplicate toast_flatten_tuple()s functionality in the above loop over
9220 : : * the indexed columns, even if it would be more efficient.
9221 : : */
4288 rhaas@postgresql.org 9222 [ + + ]: 46969 : if (HeapTupleHasExternal(key_tuple))
9223 : : {
4141 bruce@momjian.us 9224 : 4 : HeapTuple oldtup = key_tuple;
9225 : :
2196 tgl@sss.pgh.pa.us 9226 : 4 : key_tuple = toast_flatten_tuple(oldtup, desc);
4288 rhaas@postgresql.org 9227 : 4 : heap_freetuple(oldtup);
9228 : : }
9229 : :
9230 : 46969 : return key_tuple;
9231 : : }
9232 : :
9233 : : /*
9234 : : * HeapCheckForSerializableConflictOut
9235 : : * We are reading a tuple. If it's not visible, there may be a
9236 : : * rw-conflict out with the inserter. Otherwise, if it is visible to us
9237 : : * but has been deleted, there may be a rw-conflict out with the deleter.
9238 : : *
9239 : : * We will determine the top level xid of the writing transaction with which
9240 : : * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9241 : : * for overlap with our own transaction.
9242 : : *
9243 : : * This function should be called just about anywhere in heapam.c where a
9244 : : * tuple has been read. The caller must hold at least a shared lock on the
9245 : : * buffer, because this function might set hint bits on the tuple. There is
9246 : : * currently no known reason to call this function from an index AM.
9247 : : */
9248 : : void
2048 tmunro@postgresql.or 9249 : 30114987 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
9250 : : HeapTuple tuple, Buffer buffer,
9251 : : Snapshot snapshot)
9252 : : {
9253 : : TransactionId xid;
9254 : : HTSV_Result htsvResult;
9255 : :
9256 [ + + ]: 30114987 : if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9257 : 30089652 : return;
9258 : :
9259 : : /*
9260 : : * Check to see whether the tuple has been written to by a concurrent
9261 : : * transaction, either to create it not visible to us, or to delete it
9262 : : * while it is visible to us. The "visible" bool indicates whether the
9263 : : * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9264 : : * is going on with it.
9265 : : *
9266 : : * In the event of a concurrently inserted tuple that also happens to have
9267 : : * been concurrently updated (by a separate transaction), the xmin of the
9268 : : * tuple will be used -- not the updater's xid.
9269 : : */
9270 : 25335 : htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9271 [ + + + + : 25335 : switch (htsvResult)
- ]
9272 : : {
9273 : 24533 : case HEAPTUPLE_LIVE:
9274 [ + + ]: 24533 : if (visible)
9275 : 24520 : return;
9276 : 13 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9277 : 13 : break;
9278 : 352 : case HEAPTUPLE_RECENTLY_DEAD:
9279 : : case HEAPTUPLE_DELETE_IN_PROGRESS:
1913 pg@bowt.ie 9280 [ + + ]: 352 : if (visible)
9281 : 281 : xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9282 : : else
9283 : 71 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9284 : :
9285 [ + + ]: 352 : if (TransactionIdPrecedes(xid, TransactionXmin))
9286 : : {
9287 : : /* This is like the HEAPTUPLE_DEAD case */
9288 [ - + ]: 62 : Assert(!visible);
9289 : 62 : return;
9290 : : }
2048 tmunro@postgresql.or 9291 : 290 : break;
9292 : 326 : case HEAPTUPLE_INSERT_IN_PROGRESS:
9293 : 326 : xid = HeapTupleHeaderGetXmin(tuple->t_data);
9294 : 326 : break;
9295 : 124 : case HEAPTUPLE_DEAD:
1913 pg@bowt.ie 9296 [ - + ]: 124 : Assert(!visible);
2048 tmunro@postgresql.or 9297 : 124 : return;
2048 tmunro@postgresql.or 9298 :UBC 0 : default:
9299 : :
9300 : : /*
9301 : : * The only way to get to this default clause is if a new value is
9302 : : * added to the enum type without adding it to this switch
9303 : : * statement. That's a bug, so elog.
9304 : : */
9305 [ # # ]: 0 : elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9306 : :
9307 : : /*
9308 : : * In spite of having all enum values covered and calling elog on
9309 : : * this default, some compilers think this is a code path which
9310 : : * allows xid to be used below without initialization. Silence
9311 : : * that warning.
9312 : : */
9313 : : xid = InvalidTransactionId;
9314 : : }
9315 : :
2048 tmunro@postgresql.or 9316 [ - + ]:CBC 629 : Assert(TransactionIdIsValid(xid));
9317 [ - + ]: 629 : Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
9318 : :
9319 : : /*
9320 : : * Find top level xid. Bail out if xid is too early to be a conflict, or
9321 : : * if it's our own xid.
9322 : : */
9323 [ + + ]: 629 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
9324 : 62 : return;
9325 : 567 : xid = SubTransGetTopmostTransaction(xid);
9326 [ - + ]: 567 : if (TransactionIdPrecedes(xid, TransactionXmin))
2048 tmunro@postgresql.or 9327 :UBC 0 : return;
9328 : :
2048 tmunro@postgresql.or 9329 :CBC 567 : CheckForSerializableConflictOut(relation, xid, snapshot);
9330 : : }
|