PostgreSQL Source Code  git master
pg_visibility.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/visibilitymap.h"
#include "access/xloginsert.h"
#include "catalog/pg_type.h"
#include "catalog/storage_xlog.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "storage/bufmgr.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
Include dependency graph for pg_visibility.c:

Go to the source code of this file.

Data Structures

struct  vbits
 
struct  corrupt_items
 

Typedefs

typedef struct vbits vbits
 
typedef struct corrupt_items corrupt_items
 

Functions

 PG_FUNCTION_INFO_V1 (pg_visibility_map)
 
 PG_FUNCTION_INFO_V1 (pg_visibility_map_rel)
 
 PG_FUNCTION_INFO_V1 (pg_visibility)
 
 PG_FUNCTION_INFO_V1 (pg_visibility_rel)
 
 PG_FUNCTION_INFO_V1 (pg_visibility_map_summary)
 
 PG_FUNCTION_INFO_V1 (pg_check_frozen)
 
 PG_FUNCTION_INFO_V1 (pg_check_visible)
 
 PG_FUNCTION_INFO_V1 (pg_truncate_visibility_map)
 
static TupleDesc pg_visibility_tupdesc (bool include_blkno, bool include_pd)
 
static vbitscollect_visibility_data (Oid relid, bool include_pd)
 
static corrupt_itemscollect_corrupt_items (Oid relid, bool all_visible, bool all_frozen)
 
static void record_corrupt_item (corrupt_items *items, ItemPointer tid)
 
static bool tuple_all_visible (HeapTuple tup, TransactionId OldestXmin, Buffer buffer)
 
static void check_relation_relkind (Relation rel)
 
Datum pg_visibility_map (PG_FUNCTION_ARGS)
 
Datum pg_visibility (PG_FUNCTION_ARGS)
 
Datum pg_visibility_map_rel (PG_FUNCTION_ARGS)
 
Datum pg_visibility_rel (PG_FUNCTION_ARGS)
 
Datum pg_visibility_map_summary (PG_FUNCTION_ARGS)
 
Datum pg_check_frozen (PG_FUNCTION_ARGS)
 
Datum pg_check_visible (PG_FUNCTION_ARGS)
 
Datum pg_truncate_visibility_map (PG_FUNCTION_ARGS)
 

Variables

 PG_MODULE_MAGIC
 

Typedef Documentation

◆ corrupt_items

typedef struct corrupt_items corrupt_items

◆ vbits

typedef struct vbits vbits

Function Documentation

◆ check_relation_relkind()

static void check_relation_relkind ( Relation  rel)
static

Definition at line 778 of file pg_visibility.c.

779 {
780  if (!RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
781  ereport(ERROR,
782  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
783  errmsg("relation \"%s\" is of wrong relation kind",
785  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
786 }
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define RelationGetRelationName(relation)
Definition: rel.h:523
Form_pg_class rd_rel
Definition: rel.h:109

References ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, RelationData::rd_rel, and RelationGetRelationName.

Referenced by collect_corrupt_items(), collect_visibility_data(), pg_truncate_visibility_map(), pg_visibility(), pg_visibility_map(), and pg_visibility_map_summary().

◆ collect_corrupt_items()

static corrupt_items * collect_corrupt_items ( Oid  relid,
bool  all_visible,
bool  all_frozen 
)
static

Definition at line 557 of file pg_visibility.c.

558 {
559  Relation rel;
560  BlockNumber nblocks;
561  corrupt_items *items;
562  BlockNumber blkno;
563  Buffer vmbuffer = InvalidBuffer;
565  TransactionId OldestXmin = InvalidTransactionId;
566 
567  rel = relation_open(relid, AccessShareLock);
568 
569  /* Only some relkinds have a visibility map */
571 
572  if (all_visible)
573  OldestXmin = GetOldestNonRemovableTransactionId(rel);
574 
575  nblocks = RelationGetNumberOfBlocks(rel);
576 
577  /*
578  * Guess an initial array size. We don't expect many corrupted tuples, so
579  * start with a small array. This function uses the "next" field to track
580  * the next offset where we can store an item (which is the same thing as
581  * the number of items found so far) and the "count" field to track the
582  * number of entries allocated. We'll repurpose these fields before
583  * returning.
584  */
585  items = palloc0(sizeof(corrupt_items));
586  items->next = 0;
587  items->count = 64;
588  items->tids = palloc(items->count * sizeof(ItemPointerData));
589 
590  /* Loop over every block in the relation. */
591  for (blkno = 0; blkno < nblocks; ++blkno)
592  {
593  bool check_frozen = false;
594  bool check_visible = false;
595  Buffer buffer;
596  Page page;
597  OffsetNumber offnum,
598  maxoff;
599 
600  /* Make sure we are interruptible. */
602 
603  /* Use the visibility map to decide whether to check this page. */
604  if (all_frozen && VM_ALL_FROZEN(rel, blkno, &vmbuffer))
605  check_frozen = true;
606  if (all_visible && VM_ALL_VISIBLE(rel, blkno, &vmbuffer))
607  check_visible = true;
608  if (!check_visible && !check_frozen)
609  continue;
610 
611  /* Read and lock the page. */
612  buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
613  bstrategy);
614  LockBuffer(buffer, BUFFER_LOCK_SHARE);
615 
616  page = BufferGetPage(buffer);
617  maxoff = PageGetMaxOffsetNumber(page);
618 
619  /*
620  * The visibility map bits might have changed while we were acquiring
621  * the page lock. Recheck to avoid returning spurious results.
622  */
623  if (check_frozen && !VM_ALL_FROZEN(rel, blkno, &vmbuffer))
624  check_frozen = false;
625  if (check_visible && !VM_ALL_VISIBLE(rel, blkno, &vmbuffer))
626  check_visible = false;
627  if (!check_visible && !check_frozen)
628  {
629  UnlockReleaseBuffer(buffer);
630  continue;
631  }
632 
633  /* Iterate over each tuple on the page. */
634  for (offnum = FirstOffsetNumber;
635  offnum <= maxoff;
636  offnum = OffsetNumberNext(offnum))
637  {
638  HeapTupleData tuple;
639  ItemId itemid;
640 
641  itemid = PageGetItemId(page, offnum);
642 
643  /* Unused or redirect line pointers are of no interest. */
644  if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
645  continue;
646 
647  /* Dead line pointers are neither all-visible nor frozen. */
648  if (ItemIdIsDead(itemid))
649  {
650  ItemPointerSet(&(tuple.t_self), blkno, offnum);
651  record_corrupt_item(items, &tuple.t_self);
652  continue;
653  }
654 
655  /* Initialize a HeapTupleData structure for checks below. */
656  ItemPointerSet(&(tuple.t_self), blkno, offnum);
657  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
658  tuple.t_len = ItemIdGetLength(itemid);
659  tuple.t_tableOid = relid;
660 
661  /*
662  * If we're checking whether the page is all-visible, we expect
663  * the tuple to be all-visible.
664  */
665  if (check_visible &&
666  !tuple_all_visible(&tuple, OldestXmin, buffer))
667  {
668  TransactionId RecomputedOldestXmin;
669 
670  /*
671  * Time has passed since we computed OldestXmin, so it's
672  * possible that this tuple is all-visible in reality even
673  * though it doesn't appear so based on our
674  * previously-computed value. Let's compute a new value so we
675  * can be certain whether there is a problem.
676  *
677  * From a concurrency point of view, it sort of sucks to
678  * retake ProcArrayLock here while we're holding the buffer
679  * exclusively locked, but it should be safe against
680  * deadlocks, because surely
681  * GetOldestNonRemovableTransactionId() should never take a
682  * buffer lock. And this shouldn't happen often, so it's worth
683  * being careful so as to avoid false positives.
684  */
685  RecomputedOldestXmin = GetOldestNonRemovableTransactionId(rel);
686 
687  if (!TransactionIdPrecedes(OldestXmin, RecomputedOldestXmin))
688  record_corrupt_item(items, &tuple.t_self);
689  else
690  {
691  OldestXmin = RecomputedOldestXmin;
692  if (!tuple_all_visible(&tuple, OldestXmin, buffer))
693  record_corrupt_item(items, &tuple.t_self);
694  }
695  }
696 
697  /*
698  * If we're checking whether the page is all-frozen, we expect the
699  * tuple to be in a state where it will never need freezing.
700  */
701  if (check_frozen)
702  {
704  record_corrupt_item(items, &tuple.t_self);
705  }
706  }
707 
708  UnlockReleaseBuffer(buffer);
709  }
710 
711  /* Clean up. */
712  if (vmbuffer != InvalidBuffer)
713  ReleaseBuffer(vmbuffer);
715 
716  /*
717  * Before returning, repurpose the fields to match caller's expectations.
718  * next is now the next item that should be read (rather than written) and
719  * count is now the number of items we wrote (rather than the number we
720  * allocated).
721  */
722  items->count = items->next;
723  items->next = 0;
724 
725  return items;
726 }
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3915
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3938
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4156
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:749
@ BAS_BULKREAD
Definition: bufmgr.h:30
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:216
@ RBM_NORMAL
Definition: bufmgr.h:39
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Pointer Page
Definition: bufpage.h:78
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:356
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:234
#define PageGetItem(page, itemId)
Definition: bufpage.h:339
uint32 TransactionId
Definition: c.h:587
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition: heapam.c:7177
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
#define AccessShareLock
Definition: lockdefs.h:36
void * palloc0(Size size)
Definition: mcxt.c:1099
void * palloc(Size size)
Definition: mcxt.c:1068
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
static void check_relation_relkind(Relation rel)
static void record_corrupt_item(corrupt_items *items, ItemPointer tid)
static bool tuple_all_visible(HeapTuple tup, TransactionId OldestXmin, Buffer buffer)
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:2021
@ MAIN_FORKNUM
Definition: relpath.h:43
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
ItemPointer tids
Definition: pg_visibility.c:40
BlockNumber count
Definition: pg_visibility.c:39
BlockNumber next
Definition: pg_visibility.c:38
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define InvalidTransactionId
Definition: transam.h:31
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:24
#define VM_ALL_FROZEN(r, b, v)
Definition: visibilitymap.h:26

References AccessShareLock, BAS_BULKREAD, BUFFER_LOCK_SHARE, BufferGetPage, CHECK_FOR_INTERRUPTS, check_relation_relkind(), corrupt_items::count, FirstOffsetNumber, GetAccessStrategy(), GetOldestNonRemovableTransactionId(), heap_tuple_needs_eventual_freeze(), InvalidBuffer, InvalidTransactionId, ItemIdGetLength, ItemIdIsDead, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet, LockBuffer(), MAIN_FORKNUM, corrupt_items::next, OffsetNumberNext, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, palloc(), palloc0(), RBM_NORMAL, ReadBufferExtended(), record_corrupt_item(), relation_close(), relation_open(), RelationGetNumberOfBlocks, ReleaseBuffer(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, corrupt_items::tids, TransactionIdPrecedes(), tuple_all_visible(), UnlockReleaseBuffer(), VM_ALL_FROZEN, and VM_ALL_VISIBLE.

Referenced by pg_check_frozen(), and pg_check_visible().

◆ collect_visibility_data()

static vbits * collect_visibility_data ( Oid  relid,
bool  include_pd 
)
static

Definition at line 479 of file pg_visibility.c.

480 {
481  Relation rel;
482  BlockNumber nblocks;
483  vbits *info;
484  BlockNumber blkno;
485  Buffer vmbuffer = InvalidBuffer;
487 
488  rel = relation_open(relid, AccessShareLock);
489 
490  /* Only some relkinds have a visibility map */
492 
493  nblocks = RelationGetNumberOfBlocks(rel);
494  info = palloc0(offsetof(vbits, bits) + nblocks);
495  info->next = 0;
496  info->count = nblocks;
497 
498  for (blkno = 0; blkno < nblocks; ++blkno)
499  {
500  int32 mapbits;
501 
502  /* Make sure we are interruptible. */
504 
505  /* Get map info. */
506  mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
507  if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0)
508  info->bits[blkno] |= (1 << 0);
509  if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
510  info->bits[blkno] |= (1 << 1);
511 
512  /*
513  * Page-level data requires reading every block, so only get it if the
514  * caller needs it. Use a buffer access strategy, too, to prevent
515  * cache-trashing.
516  */
517  if (include_pd)
518  {
519  Buffer buffer;
520  Page page;
521 
522  buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
523  bstrategy);
524  LockBuffer(buffer, BUFFER_LOCK_SHARE);
525 
526  page = BufferGetPage(buffer);
527  if (PageIsAllVisible(page))
528  info->bits[blkno] |= (1 << 2);
529 
530  UnlockReleaseBuffer(buffer);
531  }
532  }
533 
534  /* Clean up. */
535  if (vmbuffer != InvalidBuffer)
536  ReleaseBuffer(vmbuffer);
538 
539  return info;
540 }
#define PageIsAllVisible(page)
Definition: bufpage.h:384
#define offsetof(type, field)
Definition: c.h:727
signed int int32
Definition: c.h:429
BlockNumber next
Definition: pg_visibility.c:31
uint8 bits[FLEXIBLE_ARRAY_MEMBER]
Definition: pg_visibility.c:33
BlockNumber count
Definition: pg_visibility.c:32
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *buf)
#define VISIBILITYMAP_ALL_FROZEN
#define VISIBILITYMAP_ALL_VISIBLE

References AccessShareLock, BAS_BULKREAD, vbits::bits, BUFFER_LOCK_SHARE, BufferGetPage, CHECK_FOR_INTERRUPTS, check_relation_relkind(), vbits::count, GetAccessStrategy(), InvalidBuffer, LockBuffer(), MAIN_FORKNUM, vbits::next, offsetof, PageIsAllVisible, palloc0(), RBM_NORMAL, ReadBufferExtended(), relation_close(), relation_open(), RelationGetNumberOfBlocks, ReleaseBuffer(), UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_get_status().

Referenced by pg_visibility_map_rel(), and pg_visibility_rel().

◆ pg_check_frozen()

Datum pg_check_frozen ( PG_FUNCTION_ARGS  )

Definition at line 316 of file pg_visibility.c.

317 {
318  FuncCallContext *funcctx;
319  corrupt_items *items;
320 
321  if (SRF_IS_FIRSTCALL())
322  {
323  Oid relid = PG_GETARG_OID(0);
324  MemoryContext oldcontext;
325 
326  funcctx = SRF_FIRSTCALL_INIT();
327  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
328  /* collect_corrupt_items will verify the relkind */
329  funcctx->user_fctx = collect_corrupt_items(relid, false, true);
330  MemoryContextSwitchTo(oldcontext);
331  }
332 
333  funcctx = SRF_PERCALL_SETUP();
334  items = (corrupt_items *) funcctx->user_fctx;
335 
336  if (items->next < items->count)
337  SRF_RETURN_NEXT(funcctx, PointerGetDatum(&items->tids[items->next++]));
338 
339  SRF_RETURN_DONE(funcctx);
340 }
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:299
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:303
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:305
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:301
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:323
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static corrupt_items * collect_corrupt_items(Oid relid, bool all_visible, bool all_frozen)
#define PointerGetDatum(X)
Definition: postgres.h:600
unsigned int Oid
Definition: postgres_ext.h:31
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101

References collect_corrupt_items(), corrupt_items::count, if(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, corrupt_items::next, PG_GETARG_OID, PointerGetDatum, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, corrupt_items::tids, and FuncCallContext::user_fctx.

◆ pg_check_visible()

Datum pg_check_visible ( PG_FUNCTION_ARGS  )

Definition at line 348 of file pg_visibility.c.

349 {
350  FuncCallContext *funcctx;
351  corrupt_items *items;
352 
353  if (SRF_IS_FIRSTCALL())
354  {
355  Oid relid = PG_GETARG_OID(0);
356  MemoryContext oldcontext;
357 
358  funcctx = SRF_FIRSTCALL_INIT();
359  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
360  /* collect_corrupt_items will verify the relkind */
361  funcctx->user_fctx = collect_corrupt_items(relid, true, false);
362  MemoryContextSwitchTo(oldcontext);
363  }
364 
365  funcctx = SRF_PERCALL_SETUP();
366  items = (corrupt_items *) funcctx->user_fctx;
367 
368  if (items->next < items->count)
369  SRF_RETURN_NEXT(funcctx, PointerGetDatum(&items->tids[items->next++]));
370 
371  SRF_RETURN_DONE(funcctx);
372 }

References collect_corrupt_items(), corrupt_items::count, if(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, corrupt_items::next, PG_GETARG_OID, PointerGetDatum, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, corrupt_items::tids, and FuncCallContext::user_fctx.

◆ PG_FUNCTION_INFO_V1() [1/8]

PG_FUNCTION_INFO_V1 ( pg_check_frozen  )

◆ PG_FUNCTION_INFO_V1() [2/8]

PG_FUNCTION_INFO_V1 ( pg_check_visible  )

◆ PG_FUNCTION_INFO_V1() [3/8]

PG_FUNCTION_INFO_V1 ( pg_truncate_visibility_map  )

◆ PG_FUNCTION_INFO_V1() [4/8]

PG_FUNCTION_INFO_V1 ( pg_visibility  )

◆ PG_FUNCTION_INFO_V1() [5/8]

PG_FUNCTION_INFO_V1 ( pg_visibility_map  )

◆ PG_FUNCTION_INFO_V1() [6/8]

PG_FUNCTION_INFO_V1 ( pg_visibility_map_rel  )

◆ PG_FUNCTION_INFO_V1() [7/8]

PG_FUNCTION_INFO_V1 ( pg_visibility_map_summary  )

◆ PG_FUNCTION_INFO_V1() [8/8]

PG_FUNCTION_INFO_V1 ( pg_visibility_rel  )

◆ pg_truncate_visibility_map()

Datum pg_truncate_visibility_map ( PG_FUNCTION_ARGS  )

Definition at line 383 of file pg_visibility.c.

384 {
385  Oid relid = PG_GETARG_OID(0);
386  Relation rel;
387  ForkNumber fork;
388  BlockNumber block;
389 
390  rel = relation_open(relid, AccessExclusiveLock);
391 
392  /* Only some relkinds have a visibility map */
394 
395  /* Forcibly reset cached file size */
397 
398  block = visibilitymap_prepare_truncate(rel, 0);
399  if (BlockNumberIsValid(block))
400  {
401  fork = VISIBILITYMAP_FORKNUM;
402  smgrtruncate(RelationGetSmgr(rel), &fork, 1, &block);
403  }
404 
405  if (RelationNeedsWAL(rel))
406  {
407  xl_smgr_truncate xlrec;
408 
409  xlrec.blkno = 0;
410  xlrec.rnode = rel->rd_node;
411  xlrec.flags = SMGR_TRUNCATE_VM;
412 
413  XLogBeginInsert();
414  XLogRegisterData((char *) &xlrec, sizeof(xlrec));
415 
417  }
418 
419  /*
420  * Release the lock right away, not at commit time.
421  *
422  * It would be a problem to release the lock prior to commit if this
423  * truncate operation sends any transactional invalidation messages. Other
424  * backends would potentially be able to lock the relation without
425  * processing them in the window of time between when we release the lock
426  * here and when we sent the messages at our eventual commit. However,
427  * we're currently only sending a non-transactional smgr invalidation,
428  * which will have been posted to shared memory immediately from within
429  * smgr_truncate. Therefore, there should be no race here.
430  *
431  * The reason why it's desirable to release the lock early here is because
432  * of the possibility that someone will need to use this to blow away many
433  * visibility map forks at once. If we can't release the lock until
434  * commit time, the transaction doing this will accumulate
435  * AccessExclusiveLocks on all of those relations at the same time, which
436  * is undesirable. However, if this turns out to be unsafe we may have no
437  * choice...
438  */
440 
441  /* Nothing to return. */
442  PG_RETURN_VOID();
443 }
#define InvalidBlockNumber
Definition: block.h:33
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define AccessExclusiveLock
Definition: lockdefs.h:43
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:556
#define RelationNeedsWAL(relation)
Definition: rel.h:613
ForkNumber
Definition: relpath.h:41
@ VISIBILITYMAP_FORKNUM
Definition: relpath.h:45
void smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks, BlockNumber *nblocks)
Definition: smgr.c:626
#define SMGR_TRUNCATE_VM
Definition: storage_xlog.h:41
#define XLOG_SMGR_TRUNCATE
Definition: storage_xlog.h:31
RelFileNode rd_node
Definition: rel.h:56
BlockNumber smgr_cached_nblocks[MAX_FORKNUM+1]
Definition: smgr.h:54
BlockNumber blkno
Definition: storage_xlog.h:48
RelFileNode rnode
Definition: storage_xlog.h:49
BlockNumber visibilitymap_prepare_truncate(Relation rel, BlockNumber nheapblocks)
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:443
void XLogBeginInsert(void)
Definition: xloginsert.c:150
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:351
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71

References AccessExclusiveLock, xl_smgr_truncate::blkno, BlockNumberIsValid, check_relation_relkind(), xl_smgr_truncate::flags, InvalidBlockNumber, PG_GETARG_OID, PG_RETURN_VOID, RelationData::rd_node, relation_close(), relation_open(), RelationGetSmgr(), RelationNeedsWAL, xl_smgr_truncate::rnode, SMgrRelationData::smgr_cached_nblocks, SMGR_TRUNCATE_VM, smgrtruncate(), VISIBILITYMAP_FORKNUM, visibilitymap_prepare_truncate(), XLOG_SMGR_TRUNCATE, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

◆ pg_visibility()

Datum pg_visibility ( PG_FUNCTION_ARGS  )

Definition at line 109 of file pg_visibility.c.

110 {
111  Oid relid = PG_GETARG_OID(0);
112  int64 blkno = PG_GETARG_INT64(1);
113  int32 mapbits;
114  Relation rel;
115  Buffer vmbuffer = InvalidBuffer;
116  Buffer buffer;
117  Page page;
118  TupleDesc tupdesc;
119  Datum values[3];
120  bool nulls[3];
121 
122  rel = relation_open(relid, AccessShareLock);
123 
124  /* Only some relkinds have a visibility map */
126 
127  if (blkno < 0 || blkno > MaxBlockNumber)
128  ereport(ERROR,
129  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
130  errmsg("invalid block number")));
131 
132  tupdesc = pg_visibility_tupdesc(false, true);
133  MemSet(nulls, 0, sizeof(nulls));
134 
135  mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
136  if (vmbuffer != InvalidBuffer)
137  ReleaseBuffer(vmbuffer);
138  values[0] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0);
139  values[1] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0);
140 
141  /* Here we have to explicitly check rel size ... */
142  if (blkno < RelationGetNumberOfBlocks(rel))
143  {
144  buffer = ReadBuffer(rel, blkno);
145  LockBuffer(buffer, BUFFER_LOCK_SHARE);
146 
147  page = BufferGetPage(buffer);
149 
150  UnlockReleaseBuffer(buffer);
151  }
152  else
153  {
154  /* As with the vismap, silently return 0 for pages past EOF */
155  values[2] = BoolGetDatum(false);
156  }
157 
159 
161 }
#define MaxBlockNumber
Definition: block.h:35
static Datum values[MAXATTR]
Definition: bootstrap.c:156
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:702
#define MemSet(start, val, len)
Definition: c.h:1008
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:220
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
static TupleDesc pg_visibility_tupdesc(bool include_blkno, bool include_pd)
uintptr_t Datum
Definition: postgres.h:411
#define BoolGetDatum(X)
Definition: postgres.h:446

References AccessShareLock, BoolGetDatum, BUFFER_LOCK_SHARE, BufferGetPage, check_relation_relkind(), ereport, errcode(), errmsg(), ERROR, heap_form_tuple(), HeapTupleGetDatum, InvalidBuffer, LockBuffer(), MaxBlockNumber, MemSet, PageIsAllVisible, PG_GETARG_INT64, PG_GETARG_OID, PG_RETURN_DATUM, pg_visibility_tupdesc(), ReadBuffer(), relation_close(), relation_open(), RelationGetNumberOfBlocks, ReleaseBuffer(), UnlockReleaseBuffer(), values, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_get_status().

◆ pg_visibility_map()

Datum pg_visibility_map ( PG_FUNCTION_ARGS  )

Definition at line 69 of file pg_visibility.c.

70 {
71  Oid relid = PG_GETARG_OID(0);
72  int64 blkno = PG_GETARG_INT64(1);
73  int32 mapbits;
74  Relation rel;
75  Buffer vmbuffer = InvalidBuffer;
76  TupleDesc tupdesc;
77  Datum values[2];
78  bool nulls[2];
79 
80  rel = relation_open(relid, AccessShareLock);
81 
82  /* Only some relkinds have a visibility map */
84 
85  if (blkno < 0 || blkno > MaxBlockNumber)
86  ereport(ERROR,
87  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
88  errmsg("invalid block number")));
89 
90  tupdesc = pg_visibility_tupdesc(false, false);
91  MemSet(nulls, 0, sizeof(nulls));
92 
93  mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
94  if (vmbuffer != InvalidBuffer)
95  ReleaseBuffer(vmbuffer);
96  values[0] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0);
97  values[1] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0);
98 
100 
102 }

References AccessShareLock, BoolGetDatum, check_relation_relkind(), ereport, errcode(), errmsg(), ERROR, heap_form_tuple(), HeapTupleGetDatum, InvalidBuffer, MaxBlockNumber, MemSet, PG_GETARG_INT64, PG_GETARG_OID, PG_RETURN_DATUM, pg_visibility_tupdesc(), relation_close(), relation_open(), ReleaseBuffer(), values, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_get_status().

◆ pg_visibility_map_rel()

Datum pg_visibility_map_rel ( PG_FUNCTION_ARGS  )

Definition at line 167 of file pg_visibility.c.

168 {
169  FuncCallContext *funcctx;
170  vbits *info;
171 
172  if (SRF_IS_FIRSTCALL())
173  {
174  Oid relid = PG_GETARG_OID(0);
175  MemoryContext oldcontext;
176 
177  funcctx = SRF_FIRSTCALL_INIT();
178  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
179  funcctx->tuple_desc = pg_visibility_tupdesc(true, false);
180  /* collect_visibility_data will verify the relkind */
181  funcctx->user_fctx = collect_visibility_data(relid, false);
182  MemoryContextSwitchTo(oldcontext);
183  }
184 
185  funcctx = SRF_PERCALL_SETUP();
186  info = (vbits *) funcctx->user_fctx;
187 
188  if (info->next < info->count)
189  {
190  Datum values[3];
191  bool nulls[3];
192  HeapTuple tuple;
193 
194  MemSet(nulls, 0, sizeof(nulls));
195  values[0] = Int64GetDatum(info->next);
196  values[1] = BoolGetDatum((info->bits[info->next] & (1 << 0)) != 0);
197  values[2] = BoolGetDatum((info->bits[info->next] & (1 << 1)) != 0);
198  info->next++;
199 
200  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
201  SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
202  }
203 
204  SRF_RETURN_DONE(funcctx);
205 }
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1683
static vbits * collect_visibility_data(Oid relid, bool include_pd)
TupleDesc tuple_desc
Definition: funcapi.h:112

References vbits::bits, BoolGetDatum, collect_visibility_data(), vbits::count, heap_form_tuple(), HeapTupleGetDatum, if(), Int64GetDatum(), MemoryContextSwitchTo(), MemSet, FuncCallContext::multi_call_memory_ctx, vbits::next, PG_GETARG_OID, pg_visibility_tupdesc(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, FuncCallContext::tuple_desc, FuncCallContext::user_fctx, and values.

◆ pg_visibility_map_summary()

Datum pg_visibility_map_summary ( PG_FUNCTION_ARGS  )

Definition at line 258 of file pg_visibility.c.

259 {
260  Oid relid = PG_GETARG_OID(0);
261  Relation rel;
262  BlockNumber nblocks;
263  BlockNumber blkno;
264  Buffer vmbuffer = InvalidBuffer;
265  int64 all_visible = 0;
266  int64 all_frozen = 0;
267  TupleDesc tupdesc;
268  Datum values[2];
269  bool nulls[2];
270 
271  rel = relation_open(relid, AccessShareLock);
272 
273  /* Only some relkinds have a visibility map */
275 
276  nblocks = RelationGetNumberOfBlocks(rel);
277 
278  for (blkno = 0; blkno < nblocks; ++blkno)
279  {
280  int32 mapbits;
281 
282  /* Make sure we are interruptible. */
284 
285  /* Get map info. */
286  mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
287  if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0)
288  ++all_visible;
289  if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
290  ++all_frozen;
291  }
292 
293  /* Clean up. */
294  if (vmbuffer != InvalidBuffer)
295  ReleaseBuffer(vmbuffer);
297 
298  tupdesc = CreateTemplateTupleDesc(2);
299  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "all_visible", INT8OID, -1, 0);
300  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "all_frozen", INT8OID, -1, 0);
301  tupdesc = BlessTupleDesc(tupdesc);
302 
303  MemSet(nulls, 0, sizeof(nulls));
304  values[0] = Int64GetDatum(all_visible);
305  values[1] = Int64GetDatum(all_frozen);
306 
308 }
int16 AttrNumber
Definition: attnum.h:21
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2071
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:583

References AccessShareLock, BlessTupleDesc(), CHECK_FOR_INTERRUPTS, check_relation_relkind(), CreateTemplateTupleDesc(), heap_form_tuple(), HeapTupleGetDatum, Int64GetDatum(), InvalidBuffer, MemSet, PG_GETARG_OID, PG_RETURN_DATUM, relation_close(), relation_open(), RelationGetNumberOfBlocks, ReleaseBuffer(), TupleDescInitEntry(), values, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_get_status().

◆ pg_visibility_rel()

Datum pg_visibility_rel ( PG_FUNCTION_ARGS  )

Definition at line 212 of file pg_visibility.c.

213 {
214  FuncCallContext *funcctx;
215  vbits *info;
216 
217  if (SRF_IS_FIRSTCALL())
218  {
219  Oid relid = PG_GETARG_OID(0);
220  MemoryContext oldcontext;
221 
222  funcctx = SRF_FIRSTCALL_INIT();
223  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
224  funcctx->tuple_desc = pg_visibility_tupdesc(true, true);
225  /* collect_visibility_data will verify the relkind */
226  funcctx->user_fctx = collect_visibility_data(relid, true);
227  MemoryContextSwitchTo(oldcontext);
228  }
229 
230  funcctx = SRF_PERCALL_SETUP();
231  info = (vbits *) funcctx->user_fctx;
232 
233  if (info->next < info->count)
234  {
235  Datum values[4];
236  bool nulls[4];
237  HeapTuple tuple;
238 
239  MemSet(nulls, 0, sizeof(nulls));
240  values[0] = Int64GetDatum(info->next);
241  values[1] = BoolGetDatum((info->bits[info->next] & (1 << 0)) != 0);
242  values[2] = BoolGetDatum((info->bits[info->next] & (1 << 1)) != 0);
243  values[3] = BoolGetDatum((info->bits[info->next] & (1 << 2)) != 0);
244  info->next++;
245 
246  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
247  SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
248  }
249 
250  SRF_RETURN_DONE(funcctx);
251 }

References vbits::bits, BoolGetDatum, collect_visibility_data(), vbits::count, heap_form_tuple(), HeapTupleGetDatum, if(), Int64GetDatum(), MemoryContextSwitchTo(), MemSet, FuncCallContext::multi_call_memory_ctx, vbits::next, PG_GETARG_OID, pg_visibility_tupdesc(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, FuncCallContext::tuple_desc, FuncCallContext::user_fctx, and values.

◆ pg_visibility_tupdesc()

static TupleDesc pg_visibility_tupdesc ( bool  include_blkno,
bool  include_pd 
)
static

Definition at line 450 of file pg_visibility.c.

451 {
452  TupleDesc tupdesc;
453  AttrNumber maxattr = 2;
454  AttrNumber a = 0;
455 
456  if (include_blkno)
457  ++maxattr;
458  if (include_pd)
459  ++maxattr;
460  tupdesc = CreateTemplateTupleDesc(maxattr);
461  if (include_blkno)
462  TupleDescInitEntry(tupdesc, ++a, "blkno", INT8OID, -1, 0);
463  TupleDescInitEntry(tupdesc, ++a, "all_visible", BOOLOID, -1, 0);
464  TupleDescInitEntry(tupdesc, ++a, "all_frozen", BOOLOID, -1, 0);
465  if (include_pd)
466  TupleDescInitEntry(tupdesc, ++a, "pd_all_visible", BOOLOID, -1, 0);
467  Assert(a == maxattr);
468 
469  return BlessTupleDesc(tupdesc);
470 }
int a
Definition: isn.c:69
Assert(fmt[strlen(fmt) - 1] !='\n')

References a, Assert(), BlessTupleDesc(), CreateTemplateTupleDesc(), and TupleDescInitEntry().

Referenced by pg_visibility(), pg_visibility_map(), pg_visibility_map_rel(), and pg_visibility_rel().

◆ record_corrupt_item()

static void record_corrupt_item ( corrupt_items items,
ItemPointer  tid 
)
static

Definition at line 732 of file pg_visibility.c.

733 {
734  /* enlarge output array if needed. */
735  if (items->next >= items->count)
736  {
737  items->count *= 2;
738  items->tids = repalloc(items->tids,
739  items->count * sizeof(ItemPointerData));
740  }
741  /* and add the new item */
742  items->tids[items->next++] = *tid;
743 }
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188

References corrupt_items::count, corrupt_items::next, repalloc(), and corrupt_items::tids.

Referenced by collect_corrupt_items().

◆ tuple_all_visible()

static bool tuple_all_visible ( HeapTuple  tup,
TransactionId  OldestXmin,
Buffer  buffer 
)
static

Definition at line 750 of file pg_visibility.c.

751 {
753  TransactionId xmin;
754 
755  state = HeapTupleSatisfiesVacuum(tup, OldestXmin, buffer);
756  if (state != HEAPTUPLE_LIVE)
757  return false; /* all-visible implies live */
758 
759  /*
760  * Neither lazy_scan_heap nor heap_page_is_all_visible will mark a page
761  * all-visible unless every tuple is hinted committed. However, those hint
762  * bits could be lost after a crash, so we can't be certain that they'll
763  * be set here. So just check the xmin.
764  */
765 
766  xmin = HeapTupleHeaderGetXmin(tup->t_data);
767  if (!TransactionIdPrecedes(xmin, OldestXmin))
768  return false; /* xmin not old enough for all to see */
769 
770  return true;
771 }
HTSV_Result
Definition: heapam.h:94
@ HEAPTUPLE_LIVE
Definition: heapam.h:96
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:308
Definition: regguts.h:318

References HEAPTUPLE_LIVE, HeapTupleHeaderGetXmin, HeapTupleSatisfiesVacuum(), HeapTupleData::t_data, and TransactionIdPrecedes().

Referenced by collect_corrupt_items().

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 27 of file pg_visibility.c.