1 /*-------------------------------------------------------------------------
4 * display visibility map information and page-level visibility bits
6 * Copyright (c) 2016-2017, PostgreSQL Global Development Group
8 * contrib/pg_visibility/pg_visibility.c
9 *-------------------------------------------------------------------------
13 #include "access/htup_details.h"
14 #include "access/visibilitymap.h"
15 #include "catalog/pg_type.h"
16 #include "catalog/storage_xlog.h"
18 #include "miscadmin.h"
19 #include "storage/bufmgr.h"
20 #include "storage/procarray.h"
21 #include "storage/smgr.h"
22 #include "utils/rel.h"
30 uint8 bits[FLEXIBLE_ARRAY_MEMBER];
33 typedef struct corrupt_items
40 PG_FUNCTION_INFO_V1(pg_visibility_map);
41 PG_FUNCTION_INFO_V1(pg_visibility_map_rel);
42 PG_FUNCTION_INFO_V1(pg_visibility);
43 PG_FUNCTION_INFO_V1(pg_visibility_rel);
44 PG_FUNCTION_INFO_V1(pg_visibility_map_summary);
45 PG_FUNCTION_INFO_V1(pg_check_frozen);
46 PG_FUNCTION_INFO_V1(pg_check_visible);
47 PG_FUNCTION_INFO_V1(pg_truncate_visibility_map);
49 static TupleDesc pg_visibility_tupdesc(bool include_blkno, bool include_pd);
50 static vbits *collect_visibility_data(Oid relid, bool include_pd);
51 static corrupt_items *collect_corrupt_items(Oid relid, bool all_visible,
53 static void record_corrupt_item(corrupt_items *items, ItemPointer tid);
54 static bool tuple_all_visible(HeapTuple tup, TransactionId OldestXmin,
56 static void check_relation_relkind(Relation rel);
59 * Visibility map information for a single block of a relation.
61 * Note: the VM code will silently return zeroes for pages past the end
62 * of the map, so we allow probes up to MaxBlockNumber regardless of the
63 * actual relation size.
66 pg_visibility_map(PG_FUNCTION_ARGS)
68 Oid relid = PG_GETARG_OID(0);
69 int64 blkno = PG_GETARG_INT64(1);
72 Buffer vmbuffer = InvalidBuffer;
77 rel = relation_open(relid, AccessShareLock);
79 /* Only some relkinds have a visibility map */
80 check_relation_relkind(rel);
82 if (blkno < 0 || blkno > MaxBlockNumber)
84 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
85 errmsg("invalid block number")));
87 tupdesc = pg_visibility_tupdesc(false, false);
88 MemSet(nulls, 0, sizeof(nulls));
90 mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
91 if (vmbuffer != InvalidBuffer)
92 ReleaseBuffer(vmbuffer);
93 values[0] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0);
94 values[1] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0);
96 relation_close(rel, AccessShareLock);
98 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
102 * Visibility map information for a single block of a relation, plus the
103 * page-level information for the same block.
106 pg_visibility(PG_FUNCTION_ARGS)
108 Oid relid = PG_GETARG_OID(0);
109 int64 blkno = PG_GETARG_INT64(1);
112 Buffer vmbuffer = InvalidBuffer;
119 rel = relation_open(relid, AccessShareLock);
121 /* Only some relkinds have a visibility map */
122 check_relation_relkind(rel);
124 if (blkno < 0 || blkno > MaxBlockNumber)
126 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
127 errmsg("invalid block number")));
129 tupdesc = pg_visibility_tupdesc(false, true);
130 MemSet(nulls, 0, sizeof(nulls));
132 mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
133 if (vmbuffer != InvalidBuffer)
134 ReleaseBuffer(vmbuffer);
135 values[0] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0);
136 values[1] = BoolGetDatum((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0);
138 /* Here we have to explicitly check rel size ... */
139 if (blkno < RelationGetNumberOfBlocks(rel))
141 buffer = ReadBuffer(rel, blkno);
142 LockBuffer(buffer, BUFFER_LOCK_SHARE);
144 page = BufferGetPage(buffer);
145 values[2] = BoolGetDatum(PageIsAllVisible(page));
147 UnlockReleaseBuffer(buffer);
151 /* As with the vismap, silently return 0 for pages past EOF */
152 values[2] = BoolGetDatum(false);
155 relation_close(rel, AccessShareLock);
157 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
161 * Visibility map information for every block in a relation.
164 pg_visibility_map_rel(PG_FUNCTION_ARGS)
166 FuncCallContext *funcctx;
169 if (SRF_IS_FIRSTCALL())
171 Oid relid = PG_GETARG_OID(0);
172 MemoryContext oldcontext;
174 funcctx = SRF_FIRSTCALL_INIT();
175 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
176 funcctx->tuple_desc = pg_visibility_tupdesc(true, false);
177 /* collect_visibility_data will verify the relkind */
178 funcctx->user_fctx = collect_visibility_data(relid, false);
179 MemoryContextSwitchTo(oldcontext);
182 funcctx = SRF_PERCALL_SETUP();
183 info = (vbits *) funcctx->user_fctx;
185 if (info->next < info->count)
191 MemSet(nulls, 0, sizeof(nulls));
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);
197 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
198 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
201 SRF_RETURN_DONE(funcctx);
205 * Visibility map information for every block in a relation, plus the page
206 * level information for each block.
209 pg_visibility_rel(PG_FUNCTION_ARGS)
211 FuncCallContext *funcctx;
214 if (SRF_IS_FIRSTCALL())
216 Oid relid = PG_GETARG_OID(0);
217 MemoryContext oldcontext;
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);
227 funcctx = SRF_PERCALL_SETUP();
228 info = (vbits *) funcctx->user_fctx;
230 if (info->next < info->count)
236 MemSet(nulls, 0, sizeof(nulls));
237 values[0] = Int64GetDatum(info->next);
238 values[1] = BoolGetDatum((info->bits[info->next] & (1 << 0)) != 0);
239 values[2] = BoolGetDatum((info->bits[info->next] & (1 << 1)) != 0);
240 values[3] = BoolGetDatum((info->bits[info->next] & (1 << 2)) != 0);
243 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
244 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
247 SRF_RETURN_DONE(funcctx);
251 * Count the number of all-visible and all-frozen pages in the visibility
252 * map for a particular relation.
255 pg_visibility_map_summary(PG_FUNCTION_ARGS)
257 Oid relid = PG_GETARG_OID(0);
261 Buffer vmbuffer = InvalidBuffer;
262 int64 all_visible = 0;
263 int64 all_frozen = 0;
268 rel = relation_open(relid, AccessShareLock);
270 /* Only some relkinds have a visibility map */
271 check_relation_relkind(rel);
273 nblocks = RelationGetNumberOfBlocks(rel);
275 for (blkno = 0; blkno < nblocks; ++blkno)
279 /* Make sure we are interruptible. */
280 CHECK_FOR_INTERRUPTS();
283 mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
284 if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0)
286 if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
291 if (vmbuffer != InvalidBuffer)
292 ReleaseBuffer(vmbuffer);
293 relation_close(rel, AccessShareLock);
295 tupdesc = CreateTemplateTupleDesc(2, false);
296 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "all_visible", INT8OID, -1, 0);
297 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "all_frozen", INT8OID, -1, 0);
298 tupdesc = BlessTupleDesc(tupdesc);
300 MemSet(nulls, 0, sizeof(nulls));
301 values[0] = Int64GetDatum(all_visible);
302 values[1] = Int64GetDatum(all_frozen);
304 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
308 * Return the TIDs of non-frozen tuples present in pages marked all-frozen
309 * in the visibility map. We hope no one will ever find any, but there could
310 * be bugs, database corruption, etc.
313 pg_check_frozen(PG_FUNCTION_ARGS)
315 FuncCallContext *funcctx;
316 corrupt_items *items;
318 if (SRF_IS_FIRSTCALL())
320 Oid relid = PG_GETARG_OID(0);
321 MemoryContext oldcontext;
323 funcctx = SRF_FIRSTCALL_INIT();
324 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
325 /* collect_corrupt_items will verify the relkind */
326 funcctx->user_fctx = collect_corrupt_items(relid, false, true);
327 MemoryContextSwitchTo(oldcontext);
330 funcctx = SRF_PERCALL_SETUP();
331 items = (corrupt_items *) funcctx->user_fctx;
333 if (items->next < items->count)
334 SRF_RETURN_NEXT(funcctx, PointerGetDatum(&items->tids[items->next++]));
336 SRF_RETURN_DONE(funcctx);
340 * Return the TIDs of not-all-visible tuples in pages marked all-visible
341 * in the visibility map. We hope no one will ever find any, but there could
342 * be bugs, database corruption, etc.
345 pg_check_visible(PG_FUNCTION_ARGS)
347 FuncCallContext *funcctx;
348 corrupt_items *items;
350 if (SRF_IS_FIRSTCALL())
352 Oid relid = PG_GETARG_OID(0);
353 MemoryContext oldcontext;
355 funcctx = SRF_FIRSTCALL_INIT();
356 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
357 /* collect_corrupt_items will verify the relkind */
358 funcctx->user_fctx = collect_corrupt_items(relid, true, false);
359 MemoryContextSwitchTo(oldcontext);
362 funcctx = SRF_PERCALL_SETUP();
363 items = (corrupt_items *) funcctx->user_fctx;
365 if (items->next < items->count)
366 SRF_RETURN_NEXT(funcctx, PointerGetDatum(&items->tids[items->next++]));
368 SRF_RETURN_DONE(funcctx);
372 * Remove the visibility map fork for a relation. If there turn out to be
373 * any bugs in the visibility map code that require rebuilding the VM, this
374 * provides users with a way to do it that is cleaner than shutting down the
375 * server and removing files by hand.
377 * This is a cut-down version of RelationTruncate.
380 pg_truncate_visibility_map(PG_FUNCTION_ARGS)
382 Oid relid = PG_GETARG_OID(0);
385 rel = relation_open(relid, AccessExclusiveLock);
387 /* Only some relkinds have a visibility map */
388 check_relation_relkind(rel);
390 RelationOpenSmgr(rel);
391 rel->rd_smgr->smgr_vm_nblocks = InvalidBlockNumber;
393 visibilitymap_truncate(rel, 0);
395 if (RelationNeedsWAL(rel))
397 xl_smgr_truncate xlrec;
400 xlrec.rnode = rel->rd_node;
401 xlrec.flags = SMGR_TRUNCATE_VM;
404 XLogRegisterData((char *) &xlrec, sizeof(xlrec));
406 XLogInsert(RM_SMGR_ID, XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
410 * Release the lock right away, not at commit time.
412 * It would be a problem to release the lock prior to commit if this
413 * truncate operation sends any transactional invalidation messages. Other
414 * backends would potentially be able to lock the relation without
415 * processing them in the window of time between when we release the lock
416 * here and when we sent the messages at our eventual commit. However,
417 * we're currently only sending a non-transactional smgr invalidation,
418 * which will have been posted to shared memory immediately from within
419 * visibilitymap_truncate. Therefore, there should be no race here.
421 * The reason why it's desirable to release the lock early here is because
422 * of the possibility that someone will need to use this to blow away many
423 * visibility map forks at once. If we can't release the lock until
424 * commit time, the transaction doing this will accumulate
425 * AccessExclusiveLocks on all of those relations at the same time, which
426 * is undesirable. However, if this turns out to be unsafe we may have no
429 relation_close(rel, AccessExclusiveLock);
431 /* Nothing to return. */
436 * Helper function to construct whichever TupleDesc we need for a particular
440 pg_visibility_tupdesc(bool include_blkno, bool include_pd)
443 AttrNumber maxattr = 2;
450 tupdesc = CreateTemplateTupleDesc(maxattr, false);
452 TupleDescInitEntry(tupdesc, ++a, "blkno", INT8OID, -1, 0);
453 TupleDescInitEntry(tupdesc, ++a, "all_visible", BOOLOID, -1, 0);
454 TupleDescInitEntry(tupdesc, ++a, "all_frozen", BOOLOID, -1, 0);
456 TupleDescInitEntry(tupdesc, ++a, "pd_all_visible", BOOLOID, -1, 0);
457 Assert(a == maxattr);
459 return BlessTupleDesc(tupdesc);
463 * Collect visibility data about a relation.
465 * Checks relkind of relid and will throw an error if the relation does not
469 collect_visibility_data(Oid relid, bool include_pd)
475 Buffer vmbuffer = InvalidBuffer;
476 BufferAccessStrategy bstrategy = GetAccessStrategy(BAS_BULKREAD);
478 rel = relation_open(relid, AccessShareLock);
480 /* Only some relkinds have a visibility map */
481 check_relation_relkind(rel);
483 nblocks = RelationGetNumberOfBlocks(rel);
484 info = palloc0(offsetof(vbits, bits) +nblocks);
486 info->count = nblocks;
488 for (blkno = 0; blkno < nblocks; ++blkno)
492 /* Make sure we are interruptible. */
493 CHECK_FOR_INTERRUPTS();
496 mapbits = (int32) visibilitymap_get_status(rel, blkno, &vmbuffer);
497 if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0)
498 info->bits[blkno] |= (1 << 0);
499 if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
500 info->bits[blkno] |= (1 << 1);
503 * Page-level data requires reading every block, so only get it if the
504 * caller needs it. Use a buffer access strategy, too, to prevent
512 buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
514 LockBuffer(buffer, BUFFER_LOCK_SHARE);
516 page = BufferGetPage(buffer);
517 if (PageIsAllVisible(page))
518 info->bits[blkno] |= (1 << 2);
520 UnlockReleaseBuffer(buffer);
525 if (vmbuffer != InvalidBuffer)
526 ReleaseBuffer(vmbuffer);
527 relation_close(rel, AccessShareLock);
533 * Returns a list of items whose visibility map information does not match
534 * the status of the tuples on the page.
536 * If all_visible is passed as true, this will include all items which are
537 * on pages marked as all-visible in the visibility map but which do not
538 * seem to in fact be all-visible.
540 * If all_frozen is passed as true, this will include all items which are
541 * on pages marked as all-frozen but which do not seem to in fact be frozen.
543 * Checks relkind of relid and will throw an error if the relation does not
546 static corrupt_items *
547 collect_corrupt_items(Oid relid, bool all_visible, bool all_frozen)
551 corrupt_items *items;
553 Buffer vmbuffer = InvalidBuffer;
554 BufferAccessStrategy bstrategy = GetAccessStrategy(BAS_BULKREAD);
555 TransactionId OldestXmin = InvalidTransactionId;
559 /* Don't pass rel; that will fail in recovery. */
560 OldestXmin = GetOldestXmin(NULL, PROCARRAY_FLAGS_VACUUM);
563 rel = relation_open(relid, AccessShareLock);
565 /* Only some relkinds have a visibility map */
566 check_relation_relkind(rel);
568 nblocks = RelationGetNumberOfBlocks(rel);
571 * Guess an initial array size. We don't expect many corrupted tuples, so
572 * start with a small array. This function uses the "next" field to track
573 * the next offset where we can store an item (which is the same thing as
574 * the number of items found so far) and the "count" field to track the
575 * number of entries allocated. We'll repurpose these fields before
578 items = palloc0(sizeof(corrupt_items));
581 items->tids = palloc(items->count * sizeof(ItemPointerData));
583 /* Loop over every block in the relation. */
584 for (blkno = 0; blkno < nblocks; ++blkno)
586 bool check_frozen = false;
587 bool check_visible = false;
593 /* Make sure we are interruptible. */
594 CHECK_FOR_INTERRUPTS();
596 /* Use the visibility map to decide whether to check this page. */
597 if (all_frozen && VM_ALL_FROZEN(rel, blkno, &vmbuffer))
599 if (all_visible && VM_ALL_VISIBLE(rel, blkno, &vmbuffer))
600 check_visible = true;
601 if (!check_visible && !check_frozen)
604 /* Read and lock the page. */
605 buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
607 LockBuffer(buffer, BUFFER_LOCK_SHARE);
609 page = BufferGetPage(buffer);
610 maxoff = PageGetMaxOffsetNumber(page);
613 * The visibility map bits might have changed while we were acquiring
614 * the page lock. Recheck to avoid returning spurious results.
616 if (check_frozen && !VM_ALL_FROZEN(rel, blkno, &vmbuffer))
617 check_frozen = false;
618 if (check_visible && !VM_ALL_VISIBLE(rel, blkno, &vmbuffer))
619 check_visible = false;
620 if (!check_visible && !check_frozen)
622 UnlockReleaseBuffer(buffer);
626 /* Iterate over each tuple on the page. */
627 for (offnum = FirstOffsetNumber;
629 offnum = OffsetNumberNext(offnum))
634 itemid = PageGetItemId(page, offnum);
636 /* Unused or redirect line pointers are of no interest. */
637 if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
640 /* Dead line pointers are neither all-visible nor frozen. */
641 if (ItemIdIsDead(itemid))
643 ItemPointerSet(&(tuple.t_self), blkno, offnum);
644 record_corrupt_item(items, &tuple.t_self);
648 /* Initialize a HeapTupleData structure for checks below. */
649 ItemPointerSet(&(tuple.t_self), blkno, offnum);
650 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
651 tuple.t_len = ItemIdGetLength(itemid);
652 tuple.t_tableOid = relid;
655 * If we're checking whether the page is all-visible, we expect
656 * the tuple to be all-visible.
659 !tuple_all_visible(&tuple, OldestXmin, buffer))
661 TransactionId RecomputedOldestXmin;
664 * Time has passed since we computed OldestXmin, so it's
665 * possible that this tuple is all-visible in reality even
666 * though it doesn't appear so based on our
667 * previously-computed value. Let's compute a new value so we
668 * can be certain whether there is a problem.
670 * From a concurrency point of view, it sort of sucks to
671 * retake ProcArrayLock here while we're holding the buffer
672 * exclusively locked, but it should be safe against
673 * deadlocks, because surely GetOldestXmin() should never take
674 * a buffer lock. And this shouldn't happen often, so it's
675 * worth being careful so as to avoid false positives.
677 RecomputedOldestXmin = GetOldestXmin(NULL, PROCARRAY_FLAGS_VACUUM);
679 if (!TransactionIdPrecedes(OldestXmin, RecomputedOldestXmin))
680 record_corrupt_item(items, &tuple.t_self);
683 OldestXmin = RecomputedOldestXmin;
684 if (!tuple_all_visible(&tuple, OldestXmin, buffer))
685 record_corrupt_item(items, &tuple.t_self);
690 * If we're checking whether the page is all-frozen, we expect the
691 * tuple to be in a state where it will never need freezing.
695 if (heap_tuple_needs_eventual_freeze(tuple.t_data))
696 record_corrupt_item(items, &tuple.t_self);
700 UnlockReleaseBuffer(buffer);
704 if (vmbuffer != InvalidBuffer)
705 ReleaseBuffer(vmbuffer);
706 relation_close(rel, AccessShareLock);
709 * Before returning, repurpose the fields to match caller's expectations.
710 * next is now the next item that should be read (rather than written) and
711 * count is now the number of items we wrote (rather than the number we
714 items->count = items->next;
721 * Remember one corrupt item.
724 record_corrupt_item(corrupt_items *items, ItemPointer tid)
726 /* enlarge output array if needed. */
727 if (items->next >= items->count)
730 items->tids = repalloc(items->tids,
731 items->count * sizeof(ItemPointerData));
733 /* and add the new item */
734 items->tids[items->next++] = *tid;
738 * Check whether a tuple is all-visible relative to a given OldestXmin value.
739 * The buffer should contain the tuple and should be locked and pinned.
742 tuple_all_visible(HeapTuple tup, TransactionId OldestXmin, Buffer buffer)
747 state = HeapTupleSatisfiesVacuum(tup, OldestXmin, buffer);
748 if (state != HEAPTUPLE_LIVE)
749 return false; /* all-visible implies live */
752 * Neither lazy_scan_heap nor heap_page_is_all_visible will mark a page
753 * all-visible unless every tuple is hinted committed. However, those hint
754 * bits could be lost after a crash, so we can't be certain that they'll
755 * be set here. So just check the xmin.
758 xmin = HeapTupleHeaderGetXmin(tup->t_data);
759 if (!TransactionIdPrecedes(xmin, OldestXmin))
760 return false; /* xmin not old enough for all to see */
766 * check_relation_relkind - convenience routine to check that relation
767 * is of the relkind supported by the callers
770 check_relation_relkind(Relation rel)
772 if (rel->rd_rel->relkind != RELKIND_RELATION &&
773 rel->rd_rel->relkind != RELKIND_MATVIEW &&
774 rel->rd_rel->relkind != RELKIND_TOASTVALUE)
776 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
777 errmsg("\"%s\" is not a table, materialized view, or TOAST table",
778 RelationGetRelationName(rel))));