Coverage Report

Created: 2026-12-01 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/access/heap/visibilitymap.c
Line
Count
Source
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
0
#define MAPSIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData))
132
133
/* Number of heap blocks we can represent in one byte */
134
0
#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
0
#define HEAPBLOCKS_PER_PAGE (MAPSIZE * HEAPBLOCKS_PER_BYTE)
138
139
/* Mapping from heap block number to the right bit in the visibility map */
140
0
#define HEAPBLK_TO_MAPBLOCK(x) ((x) / HEAPBLOCKS_PER_PAGE)
141
#define HEAPBLK_TO_MAPBLOCK_LIMIT(x) \
142
0
  ((x) / HEAPBLOCKS_PER_PAGE + ((x) % HEAPBLOCKS_PER_PAGE != 0))
143
0
#define HEAPBLK_TO_MAPBYTE(x) (((x) % HEAPBLOCKS_PER_PAGE) / HEAPBLOCKS_PER_BYTE)
144
0
#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
0
#define VISIBLE_MASK8 (0x55)  /* The lower bit of each bit pair */
148
0
#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
visibilitymap_clear(RelFileLocator rlocator, BlockNumber heapBlk,
165
          Buffer vmbuf, uint8 flags)
166
0
{
167
0
  int     mapByte = HEAPBLK_TO_MAPBYTE(heapBlk);
168
0
  int     mapOffset = HEAPBLK_TO_OFFSET(heapBlk);
169
0
  BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
170
0
  uint8   mask = flags << mapOffset;
171
0
  Page    page;
172
0
  char     *map;
173
0
  bool    cleared = false;
174
175
  /* Must never clear all_visible bit while leaving all_frozen bit set */
176
0
  Assert(flags & VISIBILITYMAP_VALID_BITS);
177
0
  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
0
  if (!BufferIsValid(vmbuf) || BufferGetBlockNumber(vmbuf) != mapBlock)
186
0
    elog(ERROR, "wrong buffer passed to visibilitymap_clear");
187
188
0
  Assert(BufferIsLockedByMeInMode(vmbuf, BUFFER_LOCK_EXCLUSIVE));
189
190
0
  page = BufferGetPage(vmbuf);
191
0
  map = PageGetContents(page);
192
193
0
  if (map[mapByte] & mask)
194
0
  {
195
0
    map[mapByte] &= ~mask;
196
197
0
    MarkBufferDirty(vmbuf);
198
0
    cleared = true;
199
0
  }
200
201
0
  return cleared;
202
0
}
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
visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
222
0
{
223
0
  BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
224
225
  /* Reuse the old pinned buffer if possible */
226
0
  if (BufferIsValid(*vmbuf))
227
0
  {
228
0
    if (BufferGetBlockNumber(*vmbuf) == mapBlock)
229
0
      return;
230
231
0
    ReleaseBuffer(*vmbuf);
232
0
  }
233
0
  *vmbuf = vm_readbuf(rel, mapBlock, true);
234
0
}
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
visibilitymap_pin_ok(BlockNumber heapBlk, Buffer vmbuf)
246
0
{
247
0
  BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
248
249
0
  return BufferIsValid(vmbuf) && BufferGetBlockNumber(vmbuf) == mapBlock;
250
0
}
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
visibilitymap_set(BlockNumber heapBlk,
275
          Buffer vmBuf, uint8 flags,
276
          RelFileLocator rlocator)
277
0
{
278
0
  BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
279
0
  uint32    mapByte = HEAPBLK_TO_MAPBYTE(heapBlk);
280
0
  uint8   mapOffset = HEAPBLK_TO_OFFSET(heapBlk);
281
0
  Page    page;
282
0
  uint8    *map;
283
0
  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
0
  Assert(InRecovery || CritSectionCount > 0);
294
295
  /* Flags should be valid. Also never clear bits with this function */
296
0
  Assert((flags & VISIBILITYMAP_VALID_BITS) == flags);
297
298
  /* Must never set all_frozen bit without also setting all_visible bit */
299
0
  Assert(flags != VISIBILITYMAP_ALL_FROZEN);
300
301
  /* Check that we have the right VM page pinned */
302
0
  if (!BufferIsValid(vmBuf) || BufferGetBlockNumber(vmBuf) != mapBlock)
303
0
    elog(ERROR, "wrong VM buffer passed to visibilitymap_set");
304
305
0
  Assert(BufferIsLockedByMeInMode(vmBuf, BUFFER_LOCK_EXCLUSIVE));
306
307
0
  page = BufferGetPage(vmBuf);
308
0
  map = (uint8 *) PageGetContents(page);
309
310
0
  status = (map[mapByte] >> mapOffset) & VISIBILITYMAP_VALID_BITS;
311
0
  if (flags != status)
312
0
  {
313
0
    map[mapByte] |= (flags << mapOffset);
314
0
    MarkBufferDirty(vmBuf);
315
0
  }
316
317
0
  return status;
318
0
}
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
visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
366
0
{
367
0
  BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk);
368
0
  uint32    mapByte = HEAPBLK_TO_MAPBYTE(heapBlk);
369
0
  uint8   mapOffset = HEAPBLK_TO_OFFSET(heapBlk);
370
0
  char     *map;
371
0
  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
0
  if (BufferIsValid(*vmbuf))
379
0
  {
380
0
    if (BufferGetBlockNumber(*vmbuf) != mapBlock)
381
0
    {
382
0
      ReleaseBuffer(*vmbuf);
383
0
      *vmbuf = InvalidBuffer;
384
0
    }
385
0
  }
386
387
0
  if (!BufferIsValid(*vmbuf))
388
0
  {
389
0
    *vmbuf = vm_readbuf(rel, mapBlock, false);
390
0
    if (!BufferIsValid(*vmbuf))
391
0
      return (uint8) 0;
392
0
  }
393
394
0
  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
0
  result = ((map[mapByte] >> mapOffset) & VISIBILITYMAP_VALID_BITS);
402
0
  return result;
403
0
}
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
visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
414
0
{
415
0
  BlockNumber mapBlock;
416
0
  BlockNumber nvisible = 0;
417
0
  BlockNumber nfrozen = 0;
418
419
  /* all_visible must be specified */
420
0
  Assert(all_visible);
421
422
0
  for (mapBlock = 0;; mapBlock++)
423
0
  {
424
0
    Buffer    mapBuffer;
425
0
    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
0
    mapBuffer = vm_readbuf(rel, mapBlock, false);
433
0
    if (!BufferIsValid(mapBuffer))
434
0
      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
0
    map = (uint64 *) PageGetContents(BufferGetPage(mapBuffer));
442
443
0
    nvisible += pg_popcount_masked((const char *) map, MAPSIZE, VISIBLE_MASK8);
444
0
    if (all_frozen)
445
0
      nfrozen += pg_popcount_masked((const char *) map, MAPSIZE, FROZEN_MASK8);
446
447
0
    ReleaseBuffer(mapBuffer);
448
0
  }
449
450
0
  *all_visible = nvisible;
451
0
  if (all_frozen)
452
0
    *all_frozen = nfrozen;
453
0
}
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
visibilitymap_prepare_truncate(Relation rel, BlockNumber nheapblocks)
468
0
{
469
0
  BlockNumber newnblocks;
470
471
  /* last remaining block, byte, and bit */
472
0
  BlockNumber truncBlock = HEAPBLK_TO_MAPBLOCK(nheapblocks);
473
0
  uint32    truncByte = HEAPBLK_TO_MAPBYTE(nheapblocks);
474
0
  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
0
  if (!smgrexists(RelationGetSmgr(rel), VISIBILITYMAP_FORKNUM))
485
0
    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
0
  if (truncByte != 0 || truncOffset != 0)
495
0
  {
496
0
    Buffer    mapBuffer;
497
0
    Page    page;
498
0
    char     *map;
499
500
0
    newnblocks = truncBlock + 1;
501
502
0
    mapBuffer = vm_readbuf(rel, truncBlock, false);
503
0
    if (!BufferIsValid(mapBuffer))
504
0
    {
505
      /* nothing to do, the file was already smaller */
506
0
      return InvalidBlockNumber;
507
0
    }
508
509
0
    page = BufferGetPage(mapBuffer);
510
0
    map = PageGetContents(page);
511
512
0
    LockBuffer(mapBuffer, BUFFER_LOCK_EXCLUSIVE);
513
514
    /* NO EREPORT(ERROR) from here till changes are logged */
515
0
    START_CRIT_SECTION();
516
517
    /* Clear out the unwanted bytes. */
518
0
    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
0
    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
0
    MarkBufferDirty(mapBuffer);
541
0
    if (!InRecovery && RelationNeedsWAL(rel) && XLogHintBitIsNeeded())
542
0
      log_newpage_buffer(mapBuffer, false);
543
544
0
    END_CRIT_SECTION();
545
546
0
    UnlockReleaseBuffer(mapBuffer);
547
0
  }
548
0
  else
549
0
    newnblocks = truncBlock;
550
551
0
  if (smgrnblocks(RelationGetSmgr(rel), VISIBILITYMAP_FORKNUM) <= newnblocks)
552
0
  {
553
    /* nothing to do, the file was already smaller than requested size */
554
0
    return InvalidBlockNumber;
555
0
  }
556
557
0
  return newnblocks;
558
0
}
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
visibilitymap_truncation_length(BlockNumber nheapblocks)
571
0
{
572
0
  return HEAPBLK_TO_MAPBLOCK_LIMIT(nheapblocks);
573
0
}
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
vm_readbuf(Relation rel, BlockNumber blkno, bool extend)
583
0
{
584
0
  Buffer    buf;
585
0
  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
0
  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
0
  if (reln->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM] == InvalidBlockNumber)
599
0
  {
600
0
    if (smgrexists(reln, VISIBILITYMAP_FORKNUM))
601
0
      smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
602
0
    else
603
0
      reln->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM] = 0;
604
0
  }
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
0
  if (blkno >= reln->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM])
616
0
  {
617
0
    if (extend)
618
0
      buf = vm_extend(rel, blkno + 1);
619
0
    else
620
0
      return InvalidBuffer;
621
0
  }
622
0
  else
623
0
    buf = ReadBufferExtended(rel, VISIBILITYMAP_FORKNUM, blkno,
624
0
                 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
0
  if (PageIsNew(BufferGetPage(buf)))
642
0
  {
643
0
    LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
644
0
    if (PageIsNew(BufferGetPage(buf)))
645
0
      PageInit(BufferGetPage(buf), BLCKSZ, 0);
646
0
    LockBuffer(buf, BUFFER_LOCK_UNLOCK);
647
0
  }
648
0
  return buf;
649
0
}
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
vm_extend(Relation rel, BlockNumber vm_nblocks)
657
0
{
658
0
  Buffer    buf;
659
660
0
  buf = ExtendBufferedRelTo(BMR_REL(rel), VISIBILITYMAP_FORKNUM, NULL,
661
0
                EB_CREATE_FORK_IF_NEEDED |
662
0
                EB_CLEAR_SIZE_CACHE,
663
0
                vm_nblocks,
664
0
                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
0
  CacheInvalidateSmgr(RelationGetSmgr(rel)->smgr_rlocator);
674
675
0
  return buf;
676
0
}