Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * visibilitymap.c
4 : : * bitmap for tracking visibility of heap tuples
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/access/heap/visibilitymap.c
12 : : *
13 : : * INTERFACE ROUTINES
14 : : * visibilitymap_clear - clear bits for one page in the visibility map
15 : : * visibilitymap_pin - pin a map page for setting a bit
16 : : * visibilitymap_pin_ok - check whether correct map page is already pinned
17 : : * visibilitymap_set - set bit(s) in a previously pinned page
18 : : * visibilitymap_get_status - get status of bits
19 : : * visibilitymap_count - count number of bits set in visibility map
20 : : * visibilitymap_prepare_truncate -
21 : : * prepare for truncation of the visibility map
22 : : *
23 : : * NOTES
24 : : *
25 : : * The visibility map is a bitmap with two bits (all-visible and all-frozen)
26 : : * per heap page. A set all-visible bit means that all tuples on the page are
27 : : * known visible to all transactions, and therefore the page doesn't need to
28 : : * be pruned. A set all-frozen bit means that all tuples on the page are
29 : : * completely frozen, so even an aggressive VACUUM can skip the page. The
30 : : * all-frozen bit must be set only when the page is already all-visible.
31 : : *
32 : : * The map is conservative in the sense that we make sure that whenever a bit
33 : : * is set, we know the condition is true, but if a bit is not set, it might or
34 : : * might not be true.
35 : : *
36 : : * Changes to the visibility map bits are WAL-logged as part of the operation
37 : : * setting or clearing the bit. Callers of visibility map functions must make
38 : : * sure that the VM block changes are recorded in the WAL record and the
39 : : * affected VM block(s) is registered in the same WAL record. Replay of the
40 : : * operation that rendered the bit set or cleared must then also read the VM
41 : : * page and make the appropriate changes.
42 : : *
43 : : * The visibility map bits operate as a hint in one direction: if they are
44 : : * clear, it may still be the case that every tuple on the page is visible to
45 : : * all transactions (we just don't know that for certain). However, if they
46 : : * are set, we may skip scanning heap pages during vacuum and advance
47 : : * relfrozenxid, skip pruning on-access, and skip reading heap pages for an
48 : : * index-only scan. If they are incorrectly set, this can lead to data
49 : : * corruption and wrong results.
50 : : *
51 : : * When the VM all-visible bit is set, PD_ALL_VISIBLE must be set on the heap
52 : : * page so that a later modification knows to clear the VM bit. When a
53 : : * modification makes the page no longer all-visible, it should clear
54 : : * PD_ALL_VISIBLE as well, since heap scans rely on that flag to skip
55 : : * per-tuple visibility checks.
56 : : *
57 : : * When clearing the VM, if a crash occurs after the heap page makes it to
58 : : * disk but before the VM page makes it to disk, replay must clear the VM or
59 : : * the next index-only scan can return wrong results or vacuum may incorrectly
60 : : * advance relfrozenxid.
61 : : *
62 : : * When setting the VM, if a crash occurs after the visibility map page makes
63 : : * it to disk and before the updated heap page makes it to disk, redo must set
64 : : * the bit on the heap page. Otherwise, the next insert, update, or delete on
65 : : * the heap page will fail to realize that the visibility map bit must be
66 : : * cleared, possibly causing index-only scans to return wrong answers.
67 : : *
68 : : * VACUUM will normally skip pages for which the visibility map bit is set;
69 : : * such pages can't contain any dead tuples and therefore don't need vacuuming.
70 : : * On-access pruning can skip checking individual tuples when the VM shows
71 : : * the page is all-visible.
72 : : *
73 : : * LOCKING
74 : : *
75 : : * In heapam.c, whenever a page is modified so that not all tuples on the page
76 : : * are visible to everyone anymore, the corresponding bit in the visibility
77 : : * map is cleared. In order to be crash-safe, we need to do this while still
78 : : * holding a lock on the heap page and in the same critical section that logs
79 : : * the page modification. However, we don't want to hold the heap buffer lock
80 : : * over any I/O that may be required to read in the visibility map page. To
81 : : * avoid this, we examine the heap page before locking it; if the page-level
82 : : * PD_ALL_VISIBLE bit is set, we pin the visibility map page. Then, we lock
83 : : * the heap buffer. But this creates a race condition: there is a possibility
84 : : * that in the time it takes to lock the heap buffer, the PD_ALL_VISIBLE bit
85 : : * gets set. If that happens, we have to unlock the heap buffer, pin the
86 : : * visibility map page, and relock the heap buffer. This should be uncommon:
87 : : * another backend must set PD_ALL_VISIBLE between our unlocked check and
88 : : * acquisition of the heap buffer lock. For on-access pruning, that backend
89 : : * must already hold the cleanup lock when we pin the heap buffer.
90 : : *
91 : : * Setting or clearing VM bits requires locks on both the heap and VM buffers.
92 : : * When setting a bit, we hold the heap buffer lock from the time we check the
93 : : * heap page until we set the bit, so another backend cannot invalidate the
94 : : * result of the check in between.
95 : : *
96 : : * Callers acquire the exclusive VM buffer lock after the heap buffer lock and
97 : : * before entering the critical section. Both locks are held throughout the
98 : : * critical section, including WAL insertion and updating the page LSNs. The
99 : : * VM buffer must remain locked while the WAL record is constructed, since the
100 : : * record may include a full-page image of it.
101 : : *
102 : : * When a bit is set or cleared, the LSN of the visibility map page is updated
103 : : * if the change is WAL-logged. This ensures that the WAL record is flushed
104 : : * before the visibility map page is written to disk and that FPIs are
105 : : * correctly generated. When setting a bit, this ensures that the WAL record
106 : : * of the changes that made it possible to set the bit is flushed first.
107 : : *
108 : : *-------------------------------------------------------------------------
109 : : */
110 : : #include "postgres.h"
111 : :
112 : : #include "access/heapam_xlog.h"
113 : : #include "access/visibilitymap.h"
114 : : #include "access/xloginsert.h"
115 : : #include "access/xlogutils.h"
116 : : #include "miscadmin.h"
117 : : #include "port/pg_bitutils.h"
118 : : #include "storage/bufmgr.h"
119 : : #include "storage/smgr.h"
120 : : #include "utils/inval.h"
121 : : #include "utils/rel.h"
122 : :
123 : :
124 : : /*#define TRACE_VISIBILITYMAP */
125 : :
126 : : /*
127 : : * Size of the bitmap on each visibility map page, in bytes. There's no
128 : : * extra headers, so the whole page minus the standard page header is
129 : : * used for the bitmap.
130 : : */
131 : : #define MAPSIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData))
132 : :
133 : : /* Number of heap blocks we can represent in one byte */
134 : : #define HEAPBLOCKS_PER_BYTE (BITS_PER_BYTE / BITS_PER_HEAPBLOCK)
135 : :
136 : : /* Number of heap blocks we can represent in one visibility map page. */
137 : : #define HEAPBLOCKS_PER_PAGE (MAPSIZE * HEAPBLOCKS_PER_BYTE)
138 : :
139 : : /* Mapping from heap block number to the right bit in the visibility map */
140 : : #define HEAPBLK_TO_MAPBLOCK(x) ((x) / HEAPBLOCKS_PER_PAGE)
141 : : #define HEAPBLK_TO_MAPBLOCK_LIMIT(x) \
142 : : ((x) / HEAPBLOCKS_PER_PAGE + ((x) % HEAPBLOCKS_PER_PAGE != 0))
143 : : #define HEAPBLK_TO_MAPBYTE(x) (((x) % HEAPBLOCKS_PER_PAGE) / HEAPBLOCKS_PER_BYTE)
144 : : #define HEAPBLK_TO_OFFSET(x) (((x) % HEAPBLOCKS_PER_BYTE) * BITS_PER_HEAPBLOCK)
145 : :
146 : : /* Masks for counting subsets of bits in the visibility map. */
147 : : #define VISIBLE_MASK8 (0x55) /* The lower bit of each bit pair */
148 : : #define FROZEN_MASK8 (0xaa) /* The upper bit of each bit pair */
149 : :
150 : : /* prototypes for internal routines */
151 : : static Buffer vm_readbuf(Relation rel, BlockNumber blkno, bool extend);
152 : : static Buffer vm_extend(Relation rel, BlockNumber vm_nblocks);
153 : :
154 : : /*
155 : : * visibilitymap_clear - clear specified bits for one page in visibility map
156 : : *
157 : : * You must pass a buffer containing the correct map page to this function,
158 : : * which already needs to be pinned and locked exclusively.
159 : : *
160 : : * This function doesn't do any I/O. Returns true if any bits have been
161 : : * cleared and false otherwise.
162 : : */
163 : : bool
164 : 28493 : visibilitymap_clear(RelFileLocator rlocator, BlockNumber heapBlk,
165 : : Buffer vmbuf, uint8 flags)
166 : : {
167 : 28493 : int mapByte = HEAPBLK_TO_MAPBYTE(heapBlk);
168 : 28493 : int mapOffset = HEAPBLK_TO_OFFSET(heapBlk);
169 : 28493 : BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
170 : 28493 : uint8 mask = flags << mapOffset;
171 : : Page page;
172 : : char *map;
173 : 28493 : bool cleared = false;
174 : :
175 : : /* Must never clear all_visible bit while leaving all_frozen bit set */
176 : : Assert(flags & VISIBILITYMAP_VALID_BITS);
177 : : Assert(flags != VISIBILITYMAP_ALL_VISIBLE);
178 : :
179 : : #ifdef TRACE_VISIBILITYMAP
180 : : elog(DEBUG1, "vm_clear %s %d",
181 : : relpathbackend(rlocator, MyProcNumber, MAIN_FORKNUM).str,
182 : : heapBlk);
183 : : #endif
184 : :
185 [ + - - + ]: 28493 : if (!BufferIsValid(vmbuf) || BufferGetBlockNumber(vmbuf) != mapBlock)
186 [ # # ]: 0 : elog(ERROR, "wrong buffer passed to visibilitymap_clear");
187 : :
188 : : Assert(BufferIsLockedByMeInMode(vmbuf, BUFFER_LOCK_EXCLUSIVE));
189 : :
190 : 28493 : page = BufferGetPage(vmbuf);
191 : 28493 : map = PageGetContents(page);
192 : :
193 [ + + ]: 28493 : if (map[mapByte] & mask)
194 : : {
195 : 24333 : map[mapByte] &= ~mask;
196 : :
197 : 24333 : MarkBufferDirty(vmbuf);
198 : 24333 : cleared = true;
199 : : }
200 : :
201 : 28493 : return cleared;
202 : : }
203 : :
204 : : /*
205 : : * visibilitymap_pin - pin a map page for setting a bit
206 : : *
207 : : * Setting a bit in the visibility map is a two-phase operation. First, call
208 : : * visibilitymap_pin, to pin the visibility map page containing the bit for
209 : : * the heap page. Because that can require I/O to read the map page, you
210 : : * shouldn't hold a lock on the heap page while doing that. Then, call
211 : : * visibilitymap_set to actually set the bit.
212 : : *
213 : : * On entry, *vmbuf should be InvalidBuffer or a valid buffer returned by
214 : : * an earlier call to visibilitymap_pin or visibilitymap_get_status on the same
215 : : * relation. On return, *vmbuf is a valid buffer with the map page containing
216 : : * the bit for heapBlk.
217 : : *
218 : : * If the page doesn't exist in the map file yet, it is extended.
219 : : */
220 : : void
221 : 1279734 : visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
222 : : {
223 : 1279734 : BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
224 : :
225 : : /* Reuse the old pinned buffer if possible */
226 [ + + ]: 1279734 : if (BufferIsValid(*vmbuf))
227 : : {
228 [ + - ]: 541060 : if (BufferGetBlockNumber(*vmbuf) == mapBlock)
229 : 541060 : return;
230 : :
231 : 0 : ReleaseBuffer(*vmbuf);
232 : : }
233 : 738674 : *vmbuf = vm_readbuf(rel, mapBlock, true);
234 : : }
235 : :
236 : : /*
237 : : * visibilitymap_pin_ok - do we already have the correct page pinned?
238 : : *
239 : : * On entry, vmbuf should be InvalidBuffer or a valid buffer returned by
240 : : * an earlier call to visibilitymap_pin or visibilitymap_get_status on the same
241 : : * relation. The return value indicates whether the buffer covers the
242 : : * given heapBlk.
243 : : */
244 : : bool
245 : 19424 : visibilitymap_pin_ok(BlockNumber heapBlk, Buffer vmbuf)
246 : : {
247 : 19424 : BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
248 : :
249 [ + + + - ]: 19424 : return BufferIsValid(vmbuf) && BufferGetBlockNumber(vmbuf) == mapBlock;
250 : : }
251 : :
252 : : /*
253 : : * Set VM (visibility map) flags in the VM block in vmBuf.
254 : : *
255 : : * This function is intended for callers that log VM changes together
256 : : * with the heap page modifications that rendered the page all-visible.
257 : : *
258 : : * vmBuf must be pinned and exclusively locked, and it must cover the VM bits
259 : : * corresponding to heapBlk.
260 : : *
261 : : * In normal operation (not recovery), this must be called inside a critical
262 : : * section that also applies the necessary heap page changes and, if
263 : : * applicable, emits WAL.
264 : : *
265 : : * The caller is responsible for ensuring consistency between the heap page
266 : : * and the VM page by holding a pin and exclusive lock on the buffer
267 : : * containing heapBlk.
268 : : *
269 : : * rlocator is used only for debugging messages.
270 : : *
271 : : * Returns the state of the page's VM bits before setting flags.
272 : : */
273 : : uint8
274 : 107898 : visibilitymap_set(BlockNumber heapBlk,
275 : : Buffer vmBuf, uint8 flags,
276 : : RelFileLocator rlocator)
277 : : {
278 : 107898 : BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
279 : 107898 : uint32 mapByte = HEAPBLK_TO_MAPBYTE(heapBlk);
280 : 107898 : uint8 mapOffset = HEAPBLK_TO_OFFSET(heapBlk);
281 : : Page page;
282 : : uint8 *map;
283 : : uint8 status;
284 : :
285 : : #ifdef TRACE_VISIBILITYMAP
286 : : elog(DEBUG1, "vm_set flags 0x%02X for %s %d",
287 : : flags,
288 : : relpathbackend(rlocator, MyProcNumber, MAIN_FORKNUM).str,
289 : : heapBlk);
290 : : #endif
291 : :
292 : : /* Call in same critical section where WAL is emitted. */
293 : : Assert(InRecovery || CritSectionCount > 0);
294 : :
295 : : /* Flags should be valid. Also never clear bits with this function */
296 : : Assert((flags & VISIBILITYMAP_VALID_BITS) == flags);
297 : :
298 : : /* Must never set all_frozen bit without also setting all_visible bit */
299 : : Assert(flags != VISIBILITYMAP_ALL_FROZEN);
300 : :
301 : : /* Check that we have the right VM page pinned */
302 [ + - - + ]: 107898 : if (!BufferIsValid(vmBuf) || BufferGetBlockNumber(vmBuf) != mapBlock)
303 [ # # ]: 0 : elog(ERROR, "wrong VM buffer passed to visibilitymap_set");
304 : :
305 : : Assert(BufferIsLockedByMeInMode(vmBuf, BUFFER_LOCK_EXCLUSIVE));
306 : :
307 : 107898 : page = BufferGetPage(vmBuf);
308 : 107898 : map = (uint8 *) PageGetContents(page);
309 : :
310 : 107898 : status = (map[mapByte] >> mapOffset) & VISIBILITYMAP_VALID_BITS;
311 [ + - ]: 107898 : if (flags != status)
312 : : {
313 : 107898 : map[mapByte] |= (flags << mapOffset);
314 : 107898 : MarkBufferDirty(vmBuf);
315 : : }
316 : :
317 : 107898 : return status;
318 : : }
319 : :
320 : : /*
321 : : * visibilitymap_get_status - get status of bits
322 : : *
323 : : * Are all tuples on heapBlk visible to all or are marked frozen, according
324 : : * to the visibility map?
325 : : *
326 : : * On entry, *vmbuf should be InvalidBuffer or a valid buffer returned by an
327 : : * earlier call to visibilitymap_pin or visibilitymap_get_status on the same
328 : : * relation. On return, *vmbuf is a valid buffer with the map page containing
329 : : * the bit for heapBlk, or InvalidBuffer. The caller is responsible for
330 : : * releasing *vmbuf after it's done testing and setting bits.
331 : : *
332 : : * NOTE: This function is typically called without a lock on the heap page,
333 : : * so somebody else could change the bit just after we look at it. In fact,
334 : : * since we don't lock the visibility map page either, it's even possible that
335 : : * someone else could have changed the bit just before we look at it, but yet
336 : : * we might see the old value. It is the caller's responsibility to deal with
337 : : * all concurrency issues! In practice it can't be stale enough to matter for
338 : : * the primary use case: index-only scans that check whether a heap fetch can
339 : : * be skipped.
340 : : *
341 : : * The argument for why it can't be stale enough to matter for the primary use
342 : : * case is as follows:
343 : : *
344 : : * Inserts: we need to detect that a VM bit was cleared by an insert right
345 : : * away, because the new tuple is present in the index but not yet visible.
346 : : * Reading the TID from the index page (under a shared lock on the index
347 : : * buffer) is serialized with the insertion of the TID into the index (under
348 : : * an exclusive lock on the same index buffer). Because the VM bit is cleared
349 : : * before the index is updated, and locking/unlocking of the index page acts
350 : : * as a full memory barrier, we are sure to see the cleared bit whenever we
351 : : * see a recently-inserted TID.
352 : : *
353 : : * Deletes: the clearing of the VM bit by a delete is NOT serialized with the
354 : : * index page access, because deletes do not update the index page (only
355 : : * VACUUM removes the index TID). So we may see a significantly stale value.
356 : : * However, we don't need to detect the delete right away, because the tuple
357 : : * remains visible until the deleting transaction commits or the statement
358 : : * ends (if it's our own transaction). In either case, the lock on the VM
359 : : * buffer will have been released (acting as a write barrier) after clearing
360 : : * the bit. And for us to have a snapshot that includes the deleting
361 : : * transaction (making the tuple invisible), we must have acquired
362 : : * ProcArrayLock after that time, acting as a read barrier.
363 : : */
364 : : uint8
365 : 5767151 : visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
366 : : {
367 : 5767151 : BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
368 : 5767151 : uint32 mapByte = HEAPBLK_TO_MAPBYTE(heapBlk);
369 : 5767151 : uint8 mapOffset = HEAPBLK_TO_OFFSET(heapBlk);
370 : : char *map;
371 : : uint8 result;
372 : :
373 : : #ifdef TRACE_VISIBILITYMAP
374 : : elog(DEBUG1, "vm_get_status %s %d", RelationGetRelationName(rel), heapBlk);
375 : : #endif
376 : :
377 : : /* Reuse the old pinned buffer if possible */
378 [ + + ]: 5767151 : if (BufferIsValid(*vmbuf))
379 : : {
380 [ - + ]: 5562551 : if (BufferGetBlockNumber(*vmbuf) != mapBlock)
381 : : {
382 : 0 : ReleaseBuffer(*vmbuf);
383 : 0 : *vmbuf = InvalidBuffer;
384 : : }
385 : : }
386 : :
387 [ + + ]: 5767151 : if (!BufferIsValid(*vmbuf))
388 : : {
389 : 204600 : *vmbuf = vm_readbuf(rel, mapBlock, false);
390 [ + + ]: 204600 : if (!BufferIsValid(*vmbuf))
391 : 76250 : return (uint8) 0;
392 : : }
393 : :
394 : 5690901 : map = PageGetContents(BufferGetPage(*vmbuf));
395 : :
396 : : /*
397 : : * A single byte read is atomic. There could be memory-ordering effects
398 : : * here, but for performance reasons we make it the caller's job to worry
399 : : * about that.
400 : : */
401 : 5690901 : result = ((map[mapByte] >> mapOffset) & VISIBILITYMAP_VALID_BITS);
402 : 5690901 : return result;
403 : : }
404 : :
405 : : /*
406 : : * visibilitymap_count - count number of bits set in visibility map
407 : : *
408 : : * Note: we ignore the possibility of race conditions when the table is being
409 : : * extended concurrently with the call. New pages added to the table aren't
410 : : * going to be marked all-visible or all-frozen, so they won't affect the result.
411 : : */
412 : : void
413 : 139067 : visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
414 : : {
415 : : BlockNumber mapBlock;
416 : 139067 : BlockNumber nvisible = 0;
417 : 139067 : BlockNumber nfrozen = 0;
418 : :
419 : : /* all_visible must be specified */
420 : : Assert(all_visible);
421 : :
422 : 139067 : for (mapBlock = 0;; mapBlock++)
423 : 52783 : {
424 : : Buffer mapBuffer;
425 : : uint64 *map;
426 : :
427 : : /*
428 : : * Read till we fall off the end of the map. We assume that any extra
429 : : * bytes in the last page are zeroed, so we don't bother excluding
430 : : * them from the count.
431 : : */
432 : 191850 : mapBuffer = vm_readbuf(rel, mapBlock, false);
433 [ + + ]: 191850 : if (!BufferIsValid(mapBuffer))
434 : 139067 : break;
435 : :
436 : : /*
437 : : * We choose not to lock the page, since the result is going to be
438 : : * immediately stale anyway if anyone is concurrently setting or
439 : : * clearing bits, and we only really need an approximate value.
440 : : */
441 : 52783 : map = (uint64 *) PageGetContents(BufferGetPage(mapBuffer));
442 : :
443 : 52783 : nvisible += pg_popcount_masked((const char *) map, MAPSIZE, VISIBLE_MASK8);
444 [ + - ]: 52783 : if (all_frozen)
445 : 52783 : nfrozen += pg_popcount_masked((const char *) map, MAPSIZE, FROZEN_MASK8);
446 : :
447 : 52783 : ReleaseBuffer(mapBuffer);
448 : : }
449 : :
450 : 139067 : *all_visible = nvisible;
451 [ + - ]: 139067 : if (all_frozen)
452 : 139067 : *all_frozen = nfrozen;
453 : 139067 : }
454 : :
455 : : /*
456 : : * visibilitymap_prepare_truncate -
457 : : * prepare for truncation of the visibility map
458 : : *
459 : : * nheapblocks is the new size of the heap.
460 : : *
461 : : * Return the number of blocks of new visibility map.
462 : : * If it's InvalidBlockNumber, there is nothing to truncate;
463 : : * otherwise the caller is responsible for calling smgrtruncate()
464 : : * to truncate the visibility map pages.
465 : : */
466 : : BlockNumber
467 : 303 : visibilitymap_prepare_truncate(Relation rel, BlockNumber nheapblocks)
468 : : {
469 : : BlockNumber newnblocks;
470 : :
471 : : /* last remaining block, byte, and bit */
472 : 303 : BlockNumber truncBlock = HEAPBLK_TO_MAPBLOCK(nheapblocks);
473 : 303 : uint32 truncByte = HEAPBLK_TO_MAPBYTE(nheapblocks);
474 : 303 : uint8 truncOffset = HEAPBLK_TO_OFFSET(nheapblocks);
475 : :
476 : : #ifdef TRACE_VISIBILITYMAP
477 : : elog(DEBUG1, "vm_truncate %s %d", RelationGetRelationName(rel), nheapblocks);
478 : : #endif
479 : :
480 : : /*
481 : : * If no visibility map has been created yet for this relation, there's
482 : : * nothing to truncate.
483 : : */
484 [ + + ]: 303 : if (!smgrexists(RelationGetSmgr(rel), VISIBILITYMAP_FORKNUM))
485 : 23 : return InvalidBlockNumber;
486 : :
487 : : /*
488 : : * Unless the new size is exactly at a visibility map page boundary, the
489 : : * tail bits in the last remaining map page, representing truncated heap
490 : : * blocks, need to be cleared. This is not only tidy, but also necessary
491 : : * because we don't get a chance to clear the bits if the heap is extended
492 : : * again.
493 : : */
494 [ + + + + ]: 280 : if (truncByte != 0 || truncOffset != 0)
495 : 185 : {
496 : : Buffer mapBuffer;
497 : : Page page;
498 : : char *map;
499 : :
500 : 185 : newnblocks = truncBlock + 1;
501 : :
502 : 185 : mapBuffer = vm_readbuf(rel, truncBlock, false);
503 [ - + ]: 185 : if (!BufferIsValid(mapBuffer))
504 : : {
505 : : /* nothing to do, the file was already smaller */
506 : 0 : return InvalidBlockNumber;
507 : : }
508 : :
509 : 185 : page = BufferGetPage(mapBuffer);
510 : 185 : map = PageGetContents(page);
511 : :
512 : 185 : LockBuffer(mapBuffer, BUFFER_LOCK_EXCLUSIVE);
513 : :
514 : : /* NO EREPORT(ERROR) from here till changes are logged */
515 : 185 : START_CRIT_SECTION();
516 : :
517 : : /* Clear out the unwanted bytes. */
518 [ + + + - : 185 : MemSet(&map[truncByte + 1], 0, MAPSIZE - (truncByte + 1));
+ - - + -
- ]
519 : :
520 : : /*----
521 : : * Mask out the unwanted bits of the last remaining byte.
522 : : *
523 : : * ((1 << 0) - 1) = 00000000
524 : : * ((1 << 1) - 1) = 00000001
525 : : * ...
526 : : * ((1 << 6) - 1) = 00111111
527 : : * ((1 << 7) - 1) = 01111111
528 : : *----
529 : : */
530 : 185 : map[truncByte] &= (1 << truncOffset) - 1;
531 : :
532 : : /*
533 : : * Truncation of a relation is WAL-logged at a higher-level, and we
534 : : * will be called at WAL replay. But if checksums are enabled, we need
535 : : * to still write a WAL record to protect against a torn page, if the
536 : : * page is flushed to disk before the truncation WAL record. We cannot
537 : : * use MarkBufferDirtyHint here, because that will not dirty the page
538 : : * during recovery.
539 : : */
540 : 185 : MarkBufferDirty(mapBuffer);
541 [ + + + + : 185 : if (!InRecovery && RelationNeedsWAL(rel) && XLogHintBitIsNeeded())
+ + + - +
- + + +
+ ]
542 : 151 : log_newpage_buffer(mapBuffer, false);
543 : :
544 : 185 : END_CRIT_SECTION();
545 : :
546 : 185 : UnlockReleaseBuffer(mapBuffer);
547 : : }
548 : : else
549 : 95 : newnblocks = truncBlock;
550 : :
551 [ + + ]: 280 : if (smgrnblocks(RelationGetSmgr(rel), VISIBILITYMAP_FORKNUM) <= newnblocks)
552 : : {
553 : : /* nothing to do, the file was already smaller than requested size */
554 : 186 : return InvalidBlockNumber;
555 : : }
556 : :
557 : 94 : return newnblocks;
558 : : }
559 : :
560 : : /*
561 : : * visibilitymap_truncation_length -
562 : : * compute truncation length for visibility map
563 : : *
564 : : * Given a proposed truncation length for the main fork, compute the
565 : : * correct truncation length for the visibility map. Should return the
566 : : * same answer as visibilitymap_prepare_truncate(), but without modifying
567 : : * anything.
568 : : */
569 : : BlockNumber
570 : 61 : visibilitymap_truncation_length(BlockNumber nheapblocks)
571 : : {
572 : 61 : return HEAPBLK_TO_MAPBLOCK_LIMIT(nheapblocks);
573 : : }
574 : :
575 : : /*
576 : : * Read a visibility map page.
577 : : *
578 : : * If the page doesn't exist, InvalidBuffer is returned, or if 'extend' is
579 : : * true, the visibility map file is extended.
580 : : */
581 : : static Buffer
582 : 1135309 : vm_readbuf(Relation rel, BlockNumber blkno, bool extend)
583 : : {
584 : : Buffer buf;
585 : : SMgrRelation reln;
586 : :
587 : : /*
588 : : * Caution: re-using this smgr pointer could fail if the relcache entry
589 : : * gets closed. It's safe as long as we only do smgr-level operations
590 : : * between here and the last use of the pointer.
591 : : */
592 : 1135309 : reln = RelationGetSmgr(rel);
593 : :
594 : : /*
595 : : * If we haven't cached the size of the visibility map fork yet, check it
596 : : * first.
597 : : */
598 [ + + ]: 1135309 : if (reln->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM] == InvalidBlockNumber)
599 : : {
600 [ + + ]: 162524 : if (smgrexists(reln, VISIBILITYMAP_FORKNUM))
601 : 72990 : smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
602 : : else
603 : 89534 : reln->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM] = 0;
604 : : }
605 : :
606 : : /*
607 : : * For reading we use ZERO_ON_ERROR mode, and initialize the page if
608 : : * necessary. It's always safe to clear bits, so it's better to clear
609 : : * corrupt pages than error out.
610 : : *
611 : : * We use the same path below to initialize pages when extending the
612 : : * relation, as a concurrent extension can end up with vm_extend()
613 : : * returning an already-initialized page.
614 : : */
615 [ + + ]: 1135309 : if (blkno >= reln->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM])
616 : : {
617 [ + + ]: 220209 : if (extend)
618 : 4892 : buf = vm_extend(rel, blkno + 1);
619 : : else
620 : 215317 : return InvalidBuffer;
621 : : }
622 : : else
623 : 915100 : buf = ReadBufferExtended(rel, VISIBILITYMAP_FORKNUM, blkno,
624 : : RBM_ZERO_ON_ERROR, NULL);
625 : :
626 : : /*
627 : : * Initializing the page when needed is trickier than it looks, because of
628 : : * the possibility of multiple backends doing this concurrently, and our
629 : : * desire to not uselessly take the buffer lock in the normal path where
630 : : * the page is OK. We must take the lock to initialize the page, so
631 : : * recheck page newness after we have the lock, in case someone else
632 : : * already did it. Also, because we initially check PageIsNew with no
633 : : * lock, it's possible to fall through and return the buffer while someone
634 : : * else is still initializing the page (i.e., we might see pd_upper as set
635 : : * but other page header fields are still zeroes). This is harmless for
636 : : * callers that will take a buffer lock themselves, but some callers
637 : : * inspect the page without any lock at all. The latter is OK only so
638 : : * long as it doesn't depend on the page header having correct contents.
639 : : * Current usage is safe because PageGetContents() does not require that.
640 : : */
641 [ + + ]: 919992 : if (PageIsNew(BufferGetPage(buf)))
642 : : {
643 : 5200 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
644 [ + - ]: 5200 : if (PageIsNew(BufferGetPage(buf)))
645 : 5200 : PageInit(BufferGetPage(buf), BLCKSZ, 0);
646 : 5200 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
647 : : }
648 : 919992 : return buf;
649 : : }
650 : :
651 : : /*
652 : : * Ensure that the visibility map fork is at least vm_nblocks long, extending
653 : : * it if necessary with zeroed pages.
654 : : */
655 : : static Buffer
656 : 4892 : vm_extend(Relation rel, BlockNumber vm_nblocks)
657 : : {
658 : : Buffer buf;
659 : :
660 : 4892 : buf = ExtendBufferedRelTo(BMR_REL(rel), VISIBILITYMAP_FORKNUM, NULL,
661 : : EB_CREATE_FORK_IF_NEEDED |
662 : : EB_CLEAR_SIZE_CACHE,
663 : : vm_nblocks,
664 : : RBM_ZERO_ON_ERROR);
665 : :
666 : : /*
667 : : * Send a shared-inval message to force other backends to close any smgr
668 : : * references they may have for this rel, which we are about to change.
669 : : * This is a useful optimization because it means that backends don't have
670 : : * to keep checking for creation or extension of the file, which happens
671 : : * infrequently.
672 : : */
673 : 4892 : CacheInvalidateSmgr(RelationGetSmgr(rel)->smgr_rlocator);
674 : :
675 : 4892 : return buf;
676 : : }
|