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 773 of file pg_visibility.c.

774 {
775  if (!RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
776  ereport(ERROR,
777  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
778  errmsg("relation \"%s\" is of wrong relation kind",
780  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
781 }
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define RelationGetRelationName(relation)
Definition: rel.h:535
Form_pg_class rd_rel
Definition: rel.h:110

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 552 of file pg_visibility.c.

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

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

312 {
313  FuncCallContext *funcctx;
314  corrupt_items *items;
315 
316  if (SRF_IS_FIRSTCALL())
317  {
318  Oid relid = PG_GETARG_OID(0);
319  MemoryContext oldcontext;
320 
321  funcctx = SRF_FIRSTCALL_INIT();
322  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
323  /* collect_corrupt_items will verify the relkind */
324  funcctx->user_fctx = collect_corrupt_items(relid, false, true);
325  MemoryContextSwitchTo(oldcontext);
326  }
327 
328  funcctx = SRF_PERCALL_SETUP();
329  items = (corrupt_items *) funcctx->user_fctx;
330 
331  if (items->next < items->count)
332  SRF_RETURN_NEXT(funcctx, PointerGetDatum(&items->tids[items->next++]));
333 
334  SRF_RETURN_DONE(funcctx);
335 }
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:303
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:307
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:309
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:305
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:327
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
static corrupt_items * collect_corrupt_items(Oid relid, bool all_visible, bool all_frozen)
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
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 343 of file pg_visibility.c.

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

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 378 of file pg_visibility.c.

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

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

References AccessShareLock, BoolGetDatum(), BUFFER_LOCK_SHARE, BufferGetPage(), check_relation_relkind(), ereport, errcode(), errmsg(), ERROR, heap_form_tuple(), HeapTupleGetDatum(), InvalidBuffer, LockBuffer(), MaxBlockNumber, 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] = {0};
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 
92  mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
93  if (vmbuffer != InvalidBuffer)
94  ReleaseBuffer(vmbuffer);
95  values[0] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0);
96  values[1] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0);
97 
99 
101 }

References AccessShareLock, BoolGetDatum(), check_relation_relkind(), ereport, errcode(), errmsg(), ERROR, heap_form_tuple(), HeapTupleGetDatum(), InvalidBuffer, MaxBlockNumber, 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 165 of file pg_visibility.c.

166 {
167  FuncCallContext *funcctx;
168  vbits *info;
169 
170  if (SRF_IS_FIRSTCALL())
171  {
172  Oid relid = PG_GETARG_OID(0);
173  MemoryContext oldcontext;
174 
175  funcctx = SRF_FIRSTCALL_INIT();
176  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
177  funcctx->tuple_desc = pg_visibility_tupdesc(true, false);
178  /* collect_visibility_data will verify the relkind */
179  funcctx->user_fctx = collect_visibility_data(relid, false);
180  MemoryContextSwitchTo(oldcontext);
181  }
182 
183  funcctx = SRF_PERCALL_SETUP();
184  info = (vbits *) funcctx->user_fctx;
185 
186  if (info->next < info->count)
187  {
188  Datum values[3];
189  bool nulls[3] = {0};
190  HeapTuple tuple;
191 
192  values[0] = Int64GetDatum(info->next);
193  values[1] = BoolGetDatum((info->bits[info->next] & (1 << 0)) != 0);
194  values[2] = BoolGetDatum((info->bits[info->next] & (1 << 1)) != 0);
195  info->next++;
196 
197  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
198  SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
199  }
200 
201  SRF_RETURN_DONE(funcctx);
202 }
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(), 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 254 of file pg_visibility.c.

255 {
256  Oid relid = PG_GETARG_OID(0);
257  Relation rel;
258  BlockNumber nblocks;
259  BlockNumber blkno;
260  Buffer vmbuffer = InvalidBuffer;
261  int64 all_visible = 0;
262  int64 all_frozen = 0;
263  TupleDesc tupdesc;
264  Datum values[2];
265  bool nulls[2] = {0};
266 
267  rel = relation_open(relid, AccessShareLock);
268 
269  /* Only some relkinds have a visibility map */
271 
272  nblocks = RelationGetNumberOfBlocks(rel);
273 
274  for (blkno = 0; blkno < nblocks; ++blkno)
275  {
276  int32 mapbits;
277 
278  /* Make sure we are interruptible. */
280 
281  /* Get map info. */
282  mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
283  if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0)
284  ++all_visible;
285  if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
286  ++all_frozen;
287  }
288 
289  /* Clean up. */
290  if (vmbuffer != InvalidBuffer)
291  ReleaseBuffer(vmbuffer);
293 
294  tupdesc = CreateTemplateTupleDesc(2);
295  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "all_visible", INT8OID, -1, 0);
296  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "all_frozen", INT8OID, -1, 0);
297  tupdesc = BlessTupleDesc(tupdesc);
298 
299  values[0] = Int64GetDatum(all_visible);
300  values[1] = Int64GetDatum(all_frozen);
301 
303 }
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, 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 209 of file pg_visibility.c.

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

References vbits::bits, BoolGetDatum(), collect_visibility_data(), vbits::count, heap_form_tuple(), HeapTupleGetDatum(), if(), Int64GetDatum(), MemoryContextSwitchTo(), 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 445 of file pg_visibility.c.

446 {
447  TupleDesc tupdesc;
448  AttrNumber maxattr = 2;
449  AttrNumber a = 0;
450 
451  if (include_blkno)
452  ++maxattr;
453  if (include_pd)
454  ++maxattr;
455  tupdesc = CreateTemplateTupleDesc(maxattr);
456  if (include_blkno)
457  TupleDescInitEntry(tupdesc, ++a, "blkno", INT8OID, -1, 0);
458  TupleDescInitEntry(tupdesc, ++a, "all_visible", BOOLOID, -1, 0);
459  TupleDescInitEntry(tupdesc, ++a, "all_frozen", BOOLOID, -1, 0);
460  if (include_pd)
461  TupleDescInitEntry(tupdesc, ++a, "pd_all_visible", BOOLOID, -1, 0);
462  Assert(a == maxattr);
463 
464  return BlessTupleDesc(tupdesc);
465 }
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 727 of file pg_visibility.c.

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

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 745 of file pg_visibility.c.

746 {
748  TransactionId xmin;
749 
750  state = HeapTupleSatisfiesVacuum(tup, OldestXmin, buffer);
751  if (state != HEAPTUPLE_LIVE)
752  return false; /* all-visible implies live */
753 
754  /*
755  * Neither lazy_scan_heap nor heap_page_is_all_visible will mark a page
756  * all-visible unless every tuple is hinted committed. However, those hint
757  * bits could be lost after a crash, so we can't be certain that they'll
758  * be set here. So just check the xmin.
759  */
760 
761  xmin = HeapTupleHeaderGetXmin(tup->t_data);
762  if (!TransactionIdPrecedes(xmin, OldestXmin))
763  return false; /* xmin not old enough for all to see */
764 
765  return true;
766 }
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.