1 /*-------------------------------------------------------------------------
4 * The postgres vacuum cleaner.
6 * This file includes the "full" version of VACUUM, as well as control code
7 * used by all three of full VACUUM, lazy VACUUM, and ANALYZE. See
8 * vacuumlazy.c and analyze.c for the rest of the code for the latter two.
11 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
12 * Portions Copyright (c) 1994, Regents of the University of California
16 * $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.229 2002/06/15 21:52:31 tgl Exp $
18 *-------------------------------------------------------------------------
24 #include "access/clog.h"
25 #include "access/genam.h"
26 #include "access/heapam.h"
27 #include "access/xlog.h"
28 #include "catalog/catalog.h"
29 #include "catalog/catname.h"
30 #include "catalog/namespace.h"
31 #include "catalog/pg_database.h"
32 #include "catalog/pg_index.h"
33 #include "commands/vacuum.h"
34 #include "executor/executor.h"
35 #include "miscadmin.h"
36 #include "storage/freespace.h"
37 #include "storage/sinval.h"
38 #include "storage/smgr.h"
39 #include "tcop/pquery.h"
40 #include "utils/acl.h"
41 #include "utils/builtins.h"
42 #include "utils/fmgroids.h"
43 #include "utils/inval.h"
44 #include "utils/lsyscache.h"
45 #include "utils/relcache.h"
46 #include "utils/syscache.h"
50 typedef struct VacPageData
52 BlockNumber blkno; /* BlockNumber of this Page */
53 Size free; /* FreeSpace on this Page */
54 uint16 offsets_used; /* Number of OffNums used by vacuum */
55 uint16 offsets_free; /* Number of OffNums free or to be free */
56 OffsetNumber offsets[1]; /* Array of free OffNums */
59 typedef VacPageData *VacPage;
61 typedef struct VacPageListData
63 BlockNumber empty_end_pages; /* Number of "empty" end-pages */
64 int num_pages; /* Number of pages in pagedesc */
65 int num_allocated_pages; /* Number of allocated pages in
67 VacPage *pagedesc; /* Descriptions of pages */
70 typedef VacPageListData *VacPageList;
72 typedef struct VTupleLinkData
74 ItemPointerData new_tid;
75 ItemPointerData this_tid;
78 typedef VTupleLinkData *VTupleLink;
80 typedef struct VTupleMoveData
82 ItemPointerData tid; /* tuple ID */
83 VacPage vacpage; /* where to move */
84 bool cleanVpd; /* clean vacpage before using */
87 typedef VTupleMoveData *VTupleMove;
89 typedef struct VRelStats
91 BlockNumber rel_pages;
101 static MemoryContext vac_context = NULL;
103 static int elevel = -1;
105 static TransactionId OldestXmin;
106 static TransactionId FreezeLimit;
108 static TransactionId initialOldestXmin;
109 static TransactionId initialFreezeLimit;
112 /* non-export function prototypes */
113 static List *getrels(const RangeVar *vacrel, const char *stmttype);
114 static void vac_update_dbstats(Oid dbid,
115 TransactionId vacuumXID,
116 TransactionId frozenXID);
117 static void vac_truncate_clog(TransactionId vacuumXID,
118 TransactionId frozenXID);
119 static void vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind);
120 static void full_vacuum_rel(Relation onerel, VacuumStmt *vacstmt);
121 static void scan_heap(VRelStats *vacrelstats, Relation onerel,
122 VacPageList vacuum_pages, VacPageList fraged_pages);
123 static void repair_frag(VRelStats *vacrelstats, Relation onerel,
124 VacPageList vacuum_pages, VacPageList fraged_pages,
125 int nindexes, Relation *Irel);
126 static void vacuum_heap(VRelStats *vacrelstats, Relation onerel,
127 VacPageList vacpagelist);
128 static void vacuum_page(Relation onerel, Buffer buffer, VacPage vacpage);
129 static void vacuum_index(VacPageList vacpagelist, Relation indrel,
130 double num_tuples, int keep_tuples);
131 static void scan_index(Relation indrel, double num_tuples);
132 static bool tid_reaped(ItemPointer itemptr, void *state);
133 static bool dummy_tid_reaped(ItemPointer itemptr, void *state);
134 static void vac_update_fsm(Relation onerel, VacPageList fraged_pages,
135 BlockNumber rel_pages);
136 static VacPage copy_vac_page(VacPage vacpage);
137 static void vpage_insert(VacPageList vacpagelist, VacPage vpnew);
138 static void *vac_bsearch(const void *key, const void *base,
139 size_t nelem, size_t size,
140 int (*compar) (const void *, const void *));
141 static int vac_cmp_blk(const void *left, const void *right);
142 static int vac_cmp_offno(const void *left, const void *right);
143 static int vac_cmp_vtlinks(const void *left, const void *right);
144 static bool enough_space(VacPage vacpage, Size len);
147 /****************************************************************************
149 * Code common to all flavors of VACUUM and ANALYZE *
151 ****************************************************************************
156 * Primary entry point for VACUUM and ANALYZE commands.
159 vacuum(VacuumStmt *vacstmt)
161 const char *stmttype = vacstmt->vacuum ? "VACUUM" : "ANALYZE";
162 MemoryContext anl_context = NULL;
166 if (vacstmt->verbose)
172 * We cannot run VACUUM inside a user transaction block; if we were
173 * inside a transaction, then our commit- and
174 * start-transaction-command calls would not have the intended effect!
175 * Furthermore, the forced commit that occurs before truncating the
176 * relation's file would have the effect of committing the rest of the
177 * user's transaction too, which would certainly not be the desired
180 if (vacstmt->vacuum && IsTransactionBlock())
181 elog(ERROR, "%s cannot run inside a BEGIN/END block", stmttype);
183 /* Running VACUUM from a function would free the function context */
184 if (vacstmt->vacuum && !MemoryContextContains(QueryContext, vacstmt))
185 elog(ERROR, "%s cannot be executed from a function", stmttype);
188 * Send info about dead objects to the statistics collector
191 pgstat_vacuum_tabstat();
194 * Create special memory context for cross-transaction storage.
196 * Since it is a child of QueryContext, it will go away eventually even
197 * if we suffer an error; there's no need for special abort cleanup
200 vac_context = AllocSetContextCreate(QueryContext,
202 ALLOCSET_DEFAULT_MINSIZE,
203 ALLOCSET_DEFAULT_INITSIZE,
204 ALLOCSET_DEFAULT_MAXSIZE);
207 * If we are running only ANALYZE, we don't need per-table transactions,
208 * but we still need a memory context with table lifetime.
210 if (vacstmt->analyze && !vacstmt->vacuum)
211 anl_context = AllocSetContextCreate(QueryContext,
213 ALLOCSET_DEFAULT_MINSIZE,
214 ALLOCSET_DEFAULT_INITSIZE,
215 ALLOCSET_DEFAULT_MAXSIZE);
217 /* Build list of relations to process (note this lives in vac_context) */
218 vrl = getrels(vacstmt->relation, stmttype);
221 * Formerly, there was code here to prevent more than one VACUUM from
222 * executing concurrently in the same database. However, there's no
223 * good reason to prevent that, and manually removing lockfiles after
224 * a vacuum crash was a pain for dbadmins. So, forget about lockfiles,
225 * and just rely on the locks we grab on each target table
226 * to ensure that there aren't two VACUUMs running on the same table
231 * The strangeness with committing and starting transactions here is due
232 * to wanting to run each table's VACUUM as a separate transaction, so
233 * that we don't hold locks unnecessarily long. Also, if we are doing
234 * VACUUM ANALYZE, the ANALYZE part runs as a separate transaction from
235 * the VACUUM to further reduce locking.
237 * vacuum_rel expects to be entered with no transaction active; it will
238 * start and commit its own transaction. But we are called by an SQL
239 * command, and so we are executing inside a transaction already. We
240 * commit the transaction started in PostgresMain() here, and start
241 * another one before exiting to match the commit waiting for us back in
244 * In the case of an ANALYZE statement (no vacuum, just analyze) it's
245 * okay to run the whole thing in the outer transaction, and so we skip
246 * transaction start/stop operations.
250 if (vacstmt->relation == NULL)
253 * It's a database-wide VACUUM.
255 * Compute the initially applicable OldestXmin and FreezeLimit
256 * XIDs, so that we can record these values at the end of the
257 * VACUUM. Note that individual tables may well be processed with
258 * newer values, but we can guarantee that no (non-shared)
259 * relations are processed with older ones.
261 * It is okay to record non-shared values in pg_database, even though
262 * we may vacuum shared relations with older cutoffs, because only
263 * the minimum of the values present in pg_database matters. We
264 * can be sure that shared relations have at some time been
265 * vacuumed with cutoffs no worse than the global minimum; for, if
266 * there is a backend in some other DB with xmin = OLDXMIN that's
267 * determining the cutoff with which we vacuum shared relations,
268 * it is not possible for that database to have a cutoff newer
269 * than OLDXMIN recorded in pg_database.
271 vacuum_set_xid_limits(vacstmt, false,
272 &initialOldestXmin, &initialFreezeLimit);
275 /* matches the StartTransaction in PostgresMain() */
276 CommitTransactionCommand();
280 * Loop to process each selected relation.
284 Oid relid = (Oid) lfirsti(cur);
287 vacuum_rel(relid, vacstmt, RELKIND_RELATION);
288 if (vacstmt->analyze)
290 MemoryContext old_context = NULL;
293 * If we vacuumed, use new transaction for analyze. Otherwise,
294 * we can use the outer transaction, but we still need to call
295 * analyze_rel in a memory context that will be cleaned up on
296 * return (else we leak memory while processing multiple tables).
299 StartTransactionCommand();
301 old_context = MemoryContextSwitchTo(anl_context);
303 analyze_rel(relid, vacstmt);
306 CommitTransactionCommand();
309 MemoryContextSwitchTo(old_context);
310 MemoryContextResetAndDeleteChildren(anl_context);
316 * Finish up processing.
320 /* here, we are not in a transaction */
322 /* matches the CommitTransaction in PostgresMain() */
323 StartTransactionCommand();
326 * If we did a database-wide VACUUM, update the database's pg_database
327 * row with info about the transaction IDs used, and try to truncate
330 if (vacstmt->relation == NULL)
332 vac_update_dbstats(MyDatabaseId,
333 initialOldestXmin, initialFreezeLimit);
334 vac_truncate_clog(initialOldestXmin, initialFreezeLimit);
339 * Clean up working storage --- note we must do this after
340 * StartTransactionCommand, else we might be trying to delete the
343 MemoryContextDelete(vac_context);
347 MemoryContextDelete(anl_context);
351 * Build a list of Oids for each relation to be processed
353 * The list is built in vac_context so that it will survive across our
354 * per-relation transactions.
357 getrels(const RangeVar *vacrel, const char *stmttype)
360 MemoryContext oldcontext;
364 /* Process specific relation */
367 relid = RangeVarGetRelid(vacrel, false);
369 /* Make a relation list entry for this guy */
370 oldcontext = MemoryContextSwitchTo(vac_context);
371 vrl = lappendi(vrl, relid);
372 MemoryContextSwitchTo(oldcontext);
376 /* Process all plain relations listed in pg_class */
382 ScanKeyEntryInitialize(&key, 0x0,
383 Anum_pg_class_relkind,
385 CharGetDatum(RELKIND_RELATION));
387 pgclass = heap_openr(RelationRelationName, AccessShareLock);
389 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
391 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
393 /* Make a relation list entry for this guy */
394 oldcontext = MemoryContextSwitchTo(vac_context);
395 vrl = lappendi(vrl, tuple->t_data->t_oid);
396 MemoryContextSwitchTo(oldcontext);
400 heap_close(pgclass, AccessShareLock);
407 * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
410 vacuum_set_xid_limits(VacuumStmt *vacstmt, bool sharedRel,
411 TransactionId *oldestXmin,
412 TransactionId *freezeLimit)
416 *oldestXmin = GetOldestXmin(sharedRel);
418 Assert(TransactionIdIsNormal(*oldestXmin));
422 /* FREEZE option: use oldest Xmin as freeze cutoff too */
428 * Normal case: freeze cutoff is well in the past, to wit, about
429 * halfway to the wrap horizon
431 limit = GetCurrentTransactionId() - (MaxTransactionId >> 2);
435 * Be careful not to generate a "permanent" XID
437 if (!TransactionIdIsNormal(limit))
438 limit = FirstNormalTransactionId;
441 * Ensure sane relationship of limits
443 if (TransactionIdFollows(limit, *oldestXmin))
445 elog(WARNING, "oldest Xmin is far in the past --- close open transactions soon to avoid wraparound problems");
449 *freezeLimit = limit;
454 * vac_update_relstats() -- update statistics for one relation
456 * Update the whole-relation statistics that are kept in its pg_class
457 * row. There are additional stats that will be updated if we are
458 * doing ANALYZE, but we always update these stats. This routine works
459 * for both index and heap relation entries in pg_class.
461 * We violate no-overwrite semantics here by storing new values for the
462 * statistics columns directly into the pg_class tuple that's already on
463 * the page. The reason for this is that if we updated these tuples in
464 * the usual way, vacuuming pg_class itself wouldn't work very well ---
465 * by the time we got done with a vacuum cycle, most of the tuples in
466 * pg_class would've been obsoleted. Of course, this only works for
467 * fixed-size never-null columns, but these are.
469 * This routine is shared by full VACUUM, lazy VACUUM, and stand-alone
473 vac_update_relstats(Oid relid, BlockNumber num_pages, double num_tuples,
479 Form_pg_class pgcform;
483 * update number of tuples and number of pages in pg_class
485 rd = heap_openr(RelationRelationName, RowExclusiveLock);
487 ctup = SearchSysCache(RELOID,
488 ObjectIdGetDatum(relid),
490 if (!HeapTupleIsValid(ctup))
491 elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
494 /* get the buffer cache tuple */
495 rtup.t_self = ctup->t_self;
496 ReleaseSysCache(ctup);
497 if (!heap_fetch(rd, SnapshotNow, &rtup, &buffer, false, NULL))
498 elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
501 /* overwrite the existing statistics in the tuple */
502 pgcform = (Form_pg_class) GETSTRUCT(&rtup);
503 pgcform->relpages = (int32) num_pages;
504 pgcform->reltuples = num_tuples;
505 pgcform->relhasindex = hasindex;
508 * If we have discovered that there are no indexes, then there's no
509 * primary key either. This could be done more thoroughly...
512 pgcform->relhaspkey = false;
515 * Invalidate the tuple in the catcaches; this also arranges to flush
516 * the relation's relcache entry. (If we fail to commit for some reason,
517 * no flush will occur, but no great harm is done since there are no
518 * noncritical state updates here.)
520 CacheInvalidateHeapTuple(rd, &rtup);
522 /* Write the buffer */
525 heap_close(rd, RowExclusiveLock);
530 * vac_update_dbstats() -- update statistics for one database
532 * Update the whole-database statistics that are kept in its pg_database
535 * We violate no-overwrite semantics here by storing new values for the
536 * statistics columns directly into the tuple that's already on the page.
537 * As with vac_update_relstats, this avoids leaving dead tuples behind
538 * after a VACUUM; which is good since GetRawDatabaseInfo
539 * can get confused by finding dead tuples in pg_database.
541 * This routine is shared by full and lazy VACUUM. Note that it is only
542 * applied after a database-wide VACUUM operation.
545 vac_update_dbstats(Oid dbid,
546 TransactionId vacuumXID,
547 TransactionId frozenXID)
550 ScanKeyData entry[1];
553 Form_pg_database dbform;
555 relation = heap_openr(DatabaseRelationName, RowExclusiveLock);
557 /* Must use a heap scan, since there's no syscache for pg_database */
558 ScanKeyEntryInitialize(&entry[0], 0x0,
559 ObjectIdAttributeNumber, F_OIDEQ,
560 ObjectIdGetDatum(dbid));
562 scan = heap_beginscan(relation, SnapshotNow, 1, entry);
564 tuple = heap_getnext(scan, ForwardScanDirection);
566 if (!HeapTupleIsValid(tuple))
567 elog(ERROR, "database %u does not exist", dbid);
569 dbform = (Form_pg_database) GETSTRUCT(tuple);
571 /* overwrite the existing statistics in the tuple */
572 dbform->datvacuumxid = vacuumXID;
573 dbform->datfrozenxid = frozenXID;
575 /* invalidate the tuple in the cache and write the buffer */
576 CacheInvalidateHeapTuple(relation, tuple);
577 WriteNoReleaseBuffer(scan->rs_cbuf);
581 heap_close(relation, RowExclusiveLock);
586 * vac_truncate_clog() -- attempt to truncate the commit log
588 * Scan pg_database to determine the system-wide oldest datvacuumxid,
589 * and use it to truncate the transaction commit log (pg_clog).
590 * Also generate a warning if the system-wide oldest datfrozenxid
591 * seems to be in danger of wrapping around.
593 * The passed XIDs are simply the ones I just wrote into my pg_database
594 * entry. They're used to initialize the "min" calculations.
596 * This routine is shared by full and lazy VACUUM. Note that it is only
597 * applied after a database-wide VACUUM operation.
600 vac_truncate_clog(TransactionId vacuumXID, TransactionId frozenXID)
607 bool vacuumAlreadyWrapped = false;
608 bool frozenAlreadyWrapped = false;
610 myXID = GetCurrentTransactionId();
612 relation = heap_openr(DatabaseRelationName, AccessShareLock);
614 scan = heap_beginscan(relation, SnapshotNow, 0, NULL);
616 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
618 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
620 /* Ignore non-connectable databases (eg, template0) */
621 /* It's assumed that these have been frozen correctly */
622 if (!dbform->datallowconn)
625 if (TransactionIdIsNormal(dbform->datvacuumxid))
627 if (TransactionIdPrecedes(myXID, dbform->datvacuumxid))
628 vacuumAlreadyWrapped = true;
629 else if (TransactionIdPrecedes(dbform->datvacuumxid, vacuumXID))
630 vacuumXID = dbform->datvacuumxid;
632 if (TransactionIdIsNormal(dbform->datfrozenxid))
634 if (TransactionIdPrecedes(myXID, dbform->datfrozenxid))
635 frozenAlreadyWrapped = true;
636 else if (TransactionIdPrecedes(dbform->datfrozenxid, frozenXID))
637 frozenXID = dbform->datfrozenxid;
643 heap_close(relation, AccessShareLock);
646 * Do not truncate CLOG if we seem to have suffered wraparound already;
647 * the computed minimum XID might be bogus.
649 if (vacuumAlreadyWrapped)
651 elog(WARNING, "Some databases have not been vacuumed in over 2 billion transactions."
652 "\n\tYou may have already suffered transaction-wraparound data loss.");
656 /* Truncate CLOG to the oldest vacuumxid */
657 TruncateCLOG(vacuumXID);
659 /* Give warning about impending wraparound problems */
660 if (frozenAlreadyWrapped)
662 elog(WARNING, "Some databases have not been vacuumed in over 1 billion transactions."
663 "\n\tBetter vacuum them soon, or you may have a wraparound failure.");
667 age = (int32) (myXID - frozenXID);
668 if (age > (int32) ((MaxTransactionId >> 3) * 3))
669 elog(WARNING, "Some databases have not been vacuumed in %d transactions."
670 "\n\tBetter vacuum them within %d transactions,"
671 "\n\tor you may have a wraparound failure.",
672 age, (int32) (MaxTransactionId >> 1) - age);
677 /****************************************************************************
679 * Code common to both flavors of VACUUM *
681 ****************************************************************************
686 * vacuum_rel() -- vacuum one heap relation
688 * Doing one heap at a time incurs extra overhead, since we need to
689 * check that the heap exists again just before we vacuum it. The
690 * reason that we do this is so that vacuuming can be spread across
691 * many small transactions. Otherwise, two-phase locking would require
692 * us to lock the entire database during one pass of the vacuum cleaner.
694 * At entry and exit, we are not inside a transaction.
697 vacuum_rel(Oid relid, VacuumStmt *vacstmt, char expected_relkind)
704 /* Begin a transaction for vacuuming this relation */
705 StartTransactionCommand();
708 * Check for user-requested abort. Note we want this to be inside a
709 * transaction, so xact.c doesn't issue useless WARNING.
711 CHECK_FOR_INTERRUPTS();
714 * Race condition -- if the pg_class tuple has gone away since the
715 * last time we saw it, we don't need to vacuum it.
717 if (!SearchSysCacheExists(RELOID,
718 ObjectIdGetDatum(relid),
721 CommitTransactionCommand();
726 * Determine the type of lock we want --- hard exclusive lock for a
727 * FULL vacuum, but just ShareUpdateExclusiveLock for concurrent
728 * vacuum. Either way, we can be sure that no other backend is
729 * vacuuming the same table.
731 lmode = vacstmt->full ? AccessExclusiveLock : ShareUpdateExclusiveLock;
734 * Open the class, get an appropriate lock on it, and check
737 * We allow the user to vacuum a table if he is superuser, the table
738 * owner, or the database owner (but in the latter case, only if it's
739 * not a shared relation). pg_class_ownercheck includes the superuser case.
741 * Note we choose to treat permissions failure as a WARNING and keep
742 * trying to vacuum the rest of the DB --- is this appropriate?
744 onerel = relation_open(relid, lmode);
746 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
747 (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared)))
749 elog(WARNING, "Skipping \"%s\" --- only table or database owner can VACUUM it",
750 RelationGetRelationName(onerel));
751 relation_close(onerel, lmode);
752 CommitTransactionCommand();
757 * Check that it's a plain table; we used to do this in getrels() but
758 * seems safer to check after we've locked the relation.
760 if (onerel->rd_rel->relkind != expected_relkind)
762 elog(WARNING, "Skipping \"%s\" --- can not process indexes, views or special system tables",
763 RelationGetRelationName(onerel));
764 relation_close(onerel, lmode);
765 CommitTransactionCommand();
770 * Get a session-level lock too. This will protect our access to the
771 * relation across multiple transactions, so that we can vacuum the
772 * relation's TOAST table (if any) secure in the knowledge that no one
773 * is deleting the parent relation.
775 * NOTE: this cannot block, even if someone else is waiting for access,
776 * because the lock manager knows that both lock requests are from the
779 onerelid = onerel->rd_lockInfo.lockRelId;
780 LockRelationForSession(&onerelid, lmode);
783 * Remember the relation's TOAST relation for later
785 toast_relid = onerel->rd_rel->reltoastrelid;
788 * Do the actual work --- either FULL or "lazy" vacuum
791 full_vacuum_rel(onerel, vacstmt);
793 lazy_vacuum_rel(onerel, vacstmt);
795 /* all done with this class, but hold lock until commit */
796 relation_close(onerel, NoLock);
799 * Complete the transaction and free all temporary memory used.
801 CommitTransactionCommand();
804 * If the relation has a secondary toast rel, vacuum that too while we
805 * still hold the session lock on the master table. Note however that
806 * "analyze" will not get done on the toast table. This is good,
807 * because the toaster always uses hardcoded index access and
808 * statistics are totally unimportant for toast relations.
810 if (toast_relid != InvalidOid)
811 vacuum_rel(toast_relid, vacstmt, RELKIND_TOASTVALUE);
814 * Now release the session-level lock on the master table.
816 UnlockRelationForSession(&onerelid, lmode);
820 /****************************************************************************
822 * Code for VACUUM FULL (only) *
824 ****************************************************************************
829 * full_vacuum_rel() -- perform FULL VACUUM for one heap relation
831 * This routine vacuums a single heap, cleans out its indexes, and
832 * updates its num_pages and num_tuples statistics.
834 * At entry, we have already established a transaction and opened
835 * and locked the relation.
838 full_vacuum_rel(Relation onerel, VacuumStmt *vacstmt)
840 VacPageListData vacuum_pages; /* List of pages to vacuum and/or
842 VacPageListData fraged_pages; /* List of pages with space enough
847 VRelStats *vacrelstats;
848 bool reindex = false;
850 if (IsIgnoringSystemIndexes() &&
851 IsSystemRelation(onerel))
854 vacuum_set_xid_limits(vacstmt, onerel->rd_rel->relisshared,
855 &OldestXmin, &FreezeLimit);
858 * Set up statistics-gathering machinery.
860 vacrelstats = (VRelStats *) palloc(sizeof(VRelStats));
861 vacrelstats->rel_pages = 0;
862 vacrelstats->rel_tuples = 0;
863 vacrelstats->hasindex = false;
866 vacuum_pages.num_pages = fraged_pages.num_pages = 0;
867 scan_heap(vacrelstats, onerel, &vacuum_pages, &fraged_pages);
869 /* Now open all indexes of the relation */
870 vac_open_indexes(onerel, &nindexes, &Irel);
873 else if (!RelationGetForm(onerel)->relhasindex)
876 vacrelstats->hasindex = true;
881 * reindex in VACUUM is dangerous under WAL. ifdef out until it
886 vac_close_indexes(nindexes, Irel);
887 Irel = (Relation *) NULL;
888 activate_indexes_of_a_table(RelationGetRelid(onerel), false);
890 #endif /* NOT_USED */
892 /* Clean/scan index relation(s) */
893 if (Irel != (Relation *) NULL)
895 if (vacuum_pages.num_pages > 0)
897 for (i = 0; i < nindexes; i++)
898 vacuum_index(&vacuum_pages, Irel[i],
899 vacrelstats->rel_tuples, 0);
903 /* just scan indexes to update statistic */
904 for (i = 0; i < nindexes; i++)
905 scan_index(Irel[i], vacrelstats->rel_tuples);
909 if (fraged_pages.num_pages > 0)
911 /* Try to shrink heap */
912 repair_frag(vacrelstats, onerel, &vacuum_pages, &fraged_pages,
914 vac_close_indexes(nindexes, Irel);
918 vac_close_indexes(nindexes, Irel);
919 if (vacuum_pages.num_pages > 0)
921 /* Clean pages from vacuum_pages list */
922 vacuum_heap(vacrelstats, onerel, &vacuum_pages);
927 * Flush dirty pages out to disk. We must do this even if we
928 * didn't do anything else, because we want to ensure that all
929 * tuples have correct on-row commit status on disk (see
930 * bufmgr.c's comments for FlushRelationBuffers()).
932 i = FlushRelationBuffers(onerel, vacrelstats->rel_pages);
934 elog(ERROR, "VACUUM (full_vacuum_rel): FlushRelationBuffers returned %d",
941 activate_indexes_of_a_table(RelationGetRelid(onerel), true);
942 #endif /* NOT_USED */
944 /* update shared free space map with final free space info */
945 vac_update_fsm(onerel, &fraged_pages, vacrelstats->rel_pages);
947 /* update statistics in pg_class */
948 vac_update_relstats(RelationGetRelid(onerel), vacrelstats->rel_pages,
949 vacrelstats->rel_tuples, vacrelstats->hasindex);
954 * scan_heap() -- scan an open heap relation
956 * This routine sets commit status bits, constructs vacuum_pages (list
957 * of pages we need to compact free space on and/or clean indexes of
958 * deleted tuples), constructs fraged_pages (list of pages with free
959 * space that tuples could be moved into), and calculates statistics
960 * on the number of live tuples in the heap.
963 scan_heap(VRelStats *vacrelstats, Relation onerel,
964 VacPageList vacuum_pages, VacPageList fraged_pages)
979 BlockNumber empty_pages,
989 Size min_tlen = MaxTupleSize;
992 bool do_shrinking = true;
993 VTupleLink vtlinks = (VTupleLink) palloc(100 * sizeof(VTupleLinkData));
995 int free_vtlinks = 100;
998 vac_init_rusage(&ru0);
1000 relname = RelationGetRelationName(onerel);
1001 elog(elevel, "--Relation %s.%s--",
1002 get_namespace_name(RelationGetNamespace(onerel)),
1005 empty_pages = new_pages = changed_pages = empty_end_pages = 0;
1006 num_tuples = tups_vacuumed = nkeep = nunused = 0;
1009 nblocks = RelationGetNumberOfBlocks(onerel);
1012 * We initially create each VacPage item in a maximal-sized workspace,
1013 * then copy the workspace into a just-large-enough copy.
1015 vacpage = (VacPage) palloc(sizeof(VacPageData) + MaxOffsetNumber * sizeof(OffsetNumber));
1017 for (blkno = 0; blkno < nblocks; blkno++)
1024 CHECK_FOR_INTERRUPTS();
1026 buf = ReadBuffer(onerel, blkno);
1027 page = BufferGetPage(buf);
1029 vacpage->blkno = blkno;
1030 vacpage->offsets_used = 0;
1031 vacpage->offsets_free = 0;
1033 if (PageIsNew(page))
1035 elog(WARNING, "Rel %s: Uninitialized page %u - fixing",
1037 PageInit(page, BufferGetPageSize(buf), 0);
1038 vacpage->free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
1039 free_size += (vacpage->free - sizeof(ItemIdData));
1042 vacpagecopy = copy_vac_page(vacpage);
1043 vpage_insert(vacuum_pages, vacpagecopy);
1044 vpage_insert(fraged_pages, vacpagecopy);
1049 if (PageIsEmpty(page))
1051 vacpage->free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
1052 free_size += (vacpage->free - sizeof(ItemIdData));
1055 vacpagecopy = copy_vac_page(vacpage);
1056 vpage_insert(vacuum_pages, vacpagecopy);
1057 vpage_insert(fraged_pages, vacpagecopy);
1064 maxoff = PageGetMaxOffsetNumber(page);
1065 for (offnum = FirstOffsetNumber;
1067 offnum = OffsetNumberNext(offnum))
1071 itemid = PageGetItemId(page, offnum);
1074 * Collect un-used items too - it's possible to have indexes
1075 * pointing here after crash.
1077 if (!ItemIdIsUsed(itemid))
1079 vacpage->offsets[vacpage->offsets_free++] = offnum;
1084 tuple.t_datamcxt = NULL;
1085 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
1086 tuple.t_len = ItemIdGetLength(itemid);
1087 ItemPointerSet(&(tuple.t_self), blkno, offnum);
1090 sv_infomask = tuple.t_data->t_infomask;
1092 switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin))
1094 case HEAPTUPLE_DEAD:
1095 tupgone = true; /* we can delete the tuple */
1097 case HEAPTUPLE_LIVE:
1100 * Tuple is good. Consider whether to replace its
1101 * xmin value with FrozenTransactionId.
1103 if (TransactionIdIsNormal(HeapTupleHeaderGetXmin(tuple.t_data)) &&
1104 TransactionIdPrecedes(HeapTupleHeaderGetXmin(tuple.t_data),
1107 HeapTupleHeaderSetXmin(tuple.t_data, FrozenTransactionId);
1108 /* infomask should be okay already */
1109 Assert(tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED);
1113 case HEAPTUPLE_RECENTLY_DEAD:
1116 * If tuple is recently deleted then we must not
1117 * remove it from relation.
1122 * If we do shrinking and this tuple is updated one
1123 * then remember it to construct updated tuple
1127 !(ItemPointerEquals(&(tuple.t_self),
1128 &(tuple.t_data->t_ctid))))
1130 if (free_vtlinks == 0)
1132 free_vtlinks = 1000;
1133 vtlinks = (VTupleLink) repalloc(vtlinks,
1134 (free_vtlinks + num_vtlinks) *
1135 sizeof(VTupleLinkData));
1137 vtlinks[num_vtlinks].new_tid = tuple.t_data->t_ctid;
1138 vtlinks[num_vtlinks].this_tid = tuple.t_self;
1143 case HEAPTUPLE_INSERT_IN_PROGRESS:
1146 * This should not happen, since we hold exclusive
1147 * lock on the relation; shouldn't we raise an error?
1149 elog(WARNING, "Rel %s: TID %u/%u: InsertTransactionInProgress %u - can't shrink relation",
1150 relname, blkno, offnum, HeapTupleHeaderGetXmin(tuple.t_data));
1151 do_shrinking = false;
1153 case HEAPTUPLE_DELETE_IN_PROGRESS:
1156 * This should not happen, since we hold exclusive
1157 * lock on the relation; shouldn't we raise an error?
1159 elog(WARNING, "Rel %s: TID %u/%u: DeleteTransactionInProgress %u - can't shrink relation",
1160 relname, blkno, offnum, HeapTupleHeaderGetXmax(tuple.t_data));
1161 do_shrinking = false;
1164 elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result");
1168 /* check for hint-bit update by HeapTupleSatisfiesVacuum */
1169 if (sv_infomask != tuple.t_data->t_infomask)
1175 if (!OidIsValid(tuple.t_data->t_oid) &&
1176 onerel->rd_rel->relhasoids)
1177 elog(WARNING, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
1178 relname, blkno, offnum, (int) tupgone);
1185 * Here we are building a temporary copy of the page with
1186 * dead tuples removed. Below we will apply
1187 * PageRepairFragmentation to the copy, so that we can
1188 * determine how much space will be available after
1189 * removal of dead tuples. But note we are NOT changing
1190 * the real page yet...
1192 if (tempPage == (Page) NULL)
1196 pageSize = PageGetPageSize(page);
1197 tempPage = (Page) palloc(pageSize);
1198 memcpy(tempPage, page, pageSize);
1201 /* mark it unused on the temp page */
1202 lpp = PageGetItemId(tempPage, offnum);
1203 lpp->lp_flags &= ~LP_USED;
1205 vacpage->offsets[vacpage->offsets_free++] = offnum;
1212 if (tuple.t_len < min_tlen)
1213 min_tlen = tuple.t_len;
1214 if (tuple.t_len > max_tlen)
1215 max_tlen = tuple.t_len;
1217 } /* scan along page */
1219 if (tempPage != (Page) NULL)
1221 /* Some tuples are removable; figure free space after removal */
1222 PageRepairFragmentation(tempPage, NULL);
1223 vacpage->free = ((PageHeader) tempPage)->pd_upper - ((PageHeader) tempPage)->pd_lower;
1229 /* Just use current available space */
1230 vacpage->free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
1231 /* Need to reap the page if it has ~LP_USED line pointers */
1232 do_reap = (vacpage->offsets_free > 0);
1235 free_size += vacpage->free;
1238 * Add the page to fraged_pages if it has a useful amount of free
1239 * space. "Useful" means enough for a minimal-sized tuple. But we
1240 * don't know that accurately near the start of the relation, so
1241 * add pages unconditionally if they have >= BLCKSZ/10 free space.
1243 do_frag = (vacpage->free >= min_tlen || vacpage->free >= BLCKSZ / 10);
1245 if (do_reap || do_frag)
1247 vacpagecopy = copy_vac_page(vacpage);
1249 vpage_insert(vacuum_pages, vacpagecopy);
1251 vpage_insert(fraged_pages, vacpagecopy);
1257 empty_end_pages = 0;
1270 /* save stats in the rel list for use later */
1271 vacrelstats->rel_tuples = num_tuples;
1272 vacrelstats->rel_pages = nblocks;
1273 if (num_tuples == 0)
1274 min_tlen = max_tlen = 0;
1275 vacrelstats->min_tlen = min_tlen;
1276 vacrelstats->max_tlen = max_tlen;
1278 vacuum_pages->empty_end_pages = empty_end_pages;
1279 fraged_pages->empty_end_pages = empty_end_pages;
1282 * Clear the fraged_pages list if we found we couldn't shrink. Else,
1283 * remove any "empty" end-pages from the list, and compute usable free
1284 * space = free space in remaining pages.
1288 Assert((BlockNumber) fraged_pages->num_pages >= empty_end_pages);
1289 fraged_pages->num_pages -= empty_end_pages;
1290 usable_free_size = 0;
1291 for (i = 0; i < fraged_pages->num_pages; i++)
1292 usable_free_size += fraged_pages->pagedesc[i]->free;
1296 fraged_pages->num_pages = 0;
1297 usable_free_size = 0;
1300 if (usable_free_size > 0 && num_vtlinks > 0)
1302 qsort((char *) vtlinks, num_vtlinks, sizeof(VTupleLinkData),
1304 vacrelstats->vtlinks = vtlinks;
1305 vacrelstats->num_vtlinks = num_vtlinks;
1309 vacrelstats->vtlinks = NULL;
1310 vacrelstats->num_vtlinks = 0;
1314 elog(elevel, "Pages %u: Changed %u, reaped %u, Empty %u, New %u; \
1315 Tup %.0f: Vac %.0f, Keep/VTL %.0f/%u, UnUsed %.0f, MinLen %lu, MaxLen %lu; \
1316 Re-using: Free/Avail. Space %.0f/%.0f; EndEmpty/Avail. Pages %u/%u.\n\t%s",
1317 nblocks, changed_pages, vacuum_pages->num_pages, empty_pages,
1318 new_pages, num_tuples, tups_vacuumed,
1319 nkeep, vacrelstats->num_vtlinks,
1320 nunused, (unsigned long) min_tlen, (unsigned long) max_tlen,
1321 free_size, usable_free_size,
1322 empty_end_pages, fraged_pages->num_pages,
1323 vac_show_rusage(&ru0));
1329 * repair_frag() -- try to repair relation's fragmentation
1331 * This routine marks dead tuples as unused and tries re-use dead space
1332 * by moving tuples (and inserting indexes if needed). It constructs
1333 * Nvacpagelist list of free-ed pages (moved tuples) and clean indexes
1334 * for them after committing (in hack-manner - without losing locks
1335 * and freeing memory!) current transaction. It truncates relation
1336 * if some end-blocks are gone away.
1339 repair_frag(VRelStats *vacrelstats, Relation onerel,
1340 VacPageList vacuum_pages, VacPageList fraged_pages,
1341 int nindexes, Relation *Irel)
1343 TransactionId myXID;
1347 BlockNumber nblocks,
1349 BlockNumber last_move_dest_block = 0,
1353 OffsetNumber offnum,
1359 HeapTupleData tuple,
1362 ResultRelInfo *resultRelInfo;
1364 TupleTable tupleTable;
1365 TupleTableSlot *slot;
1366 VacPageListData Nvacpagelist;
1367 VacPage cur_page = NULL,
1385 vac_init_rusage(&ru0);
1387 myXID = GetCurrentTransactionId();
1388 myCID = GetCurrentCommandId();
1390 tupdesc = RelationGetDescr(onerel);
1393 * We need a ResultRelInfo and an EState so we can use the regular
1394 * executor's index-entry-making machinery.
1396 resultRelInfo = makeNode(ResultRelInfo);
1397 resultRelInfo->ri_RangeTableIndex = 1; /* dummy */
1398 resultRelInfo->ri_RelationDesc = onerel;
1399 resultRelInfo->ri_TrigDesc = NULL; /* we don't fire triggers */
1401 ExecOpenIndices(resultRelInfo);
1403 estate = CreateExecutorState();
1404 estate->es_result_relations = resultRelInfo;
1405 estate->es_num_result_relations = 1;
1406 estate->es_result_relation_info = resultRelInfo;
1408 /* Set up a dummy tuple table too */
1409 tupleTable = ExecCreateTupleTable(1);
1410 slot = ExecAllocTableSlot(tupleTable);
1411 ExecSetSlotDescriptor(slot, tupdesc, false);
1413 Nvacpagelist.num_pages = 0;
1414 num_fraged_pages = fraged_pages->num_pages;
1415 Assert((BlockNumber) vacuum_pages->num_pages >= vacuum_pages->empty_end_pages);
1416 vacuumed_pages = vacuum_pages->num_pages - vacuum_pages->empty_end_pages;
1417 if (vacuumed_pages > 0)
1419 /* get last reaped page from vacuum_pages */
1420 last_vacuum_page = vacuum_pages->pagedesc[vacuumed_pages - 1];
1421 last_vacuum_block = last_vacuum_page->blkno;
1425 last_vacuum_page = NULL;
1426 last_vacuum_block = InvalidBlockNumber;
1428 cur_buffer = InvalidBuffer;
1431 vacpage = (VacPage) palloc(sizeof(VacPageData) + MaxOffsetNumber * sizeof(OffsetNumber));
1432 vacpage->offsets_used = vacpage->offsets_free = 0;
1435 * Scan pages backwards from the last nonempty page, trying to move
1436 * tuples down to lower pages. Quit when we reach a page that we have
1437 * moved any tuples onto, or the first page if we haven't moved
1438 * anything, or when we find a page we cannot completely empty (this
1439 * last condition is handled by "break" statements within the loop).
1441 * NB: this code depends on the vacuum_pages and fraged_pages lists being
1442 * in order by blkno.
1444 nblocks = vacrelstats->rel_pages;
1445 for (blkno = nblocks - vacuum_pages->empty_end_pages - 1;
1446 blkno > last_move_dest_block;
1449 CHECK_FOR_INTERRUPTS();
1452 * Forget fraged_pages pages at or after this one; they're no
1453 * longer useful as move targets, since we only want to move down.
1454 * Note that since we stop the outer loop at last_move_dest_block,
1455 * pages removed here cannot have had anything moved onto them
1458 * Also note that we don't change the stored fraged_pages list, only
1459 * our local variable num_fraged_pages; so the forgotten pages are
1460 * still available to be loaded into the free space map later.
1462 while (num_fraged_pages > 0 &&
1463 fraged_pages->pagedesc[num_fraged_pages - 1]->blkno >= blkno)
1465 Assert(fraged_pages->pagedesc[num_fraged_pages - 1]->offsets_used == 0);
1470 * Process this page of relation.
1472 buf = ReadBuffer(onerel, blkno);
1473 page = BufferGetPage(buf);
1475 vacpage->offsets_free = 0;
1477 isempty = PageIsEmpty(page);
1481 /* Is the page in the vacuum_pages list? */
1482 if (blkno == last_vacuum_block)
1484 if (last_vacuum_page->offsets_free > 0)
1486 /* there are dead tuples on this page - clean them */
1488 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
1489 vacuum_page(onerel, buf, last_vacuum_page);
1490 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
1496 if (vacuumed_pages > 0)
1498 /* get prev reaped page from vacuum_pages */
1499 last_vacuum_page = vacuum_pages->pagedesc[vacuumed_pages - 1];
1500 last_vacuum_block = last_vacuum_page->blkno;
1504 last_vacuum_page = NULL;
1505 last_vacuum_block = InvalidBlockNumber;
1516 chain_tuple_moved = false; /* no one chain-tuple was moved
1517 * off this page, yet */
1518 vacpage->blkno = blkno;
1519 maxoff = PageGetMaxOffsetNumber(page);
1520 for (offnum = FirstOffsetNumber;
1522 offnum = OffsetNumberNext(offnum))
1524 itemid = PageGetItemId(page, offnum);
1526 if (!ItemIdIsUsed(itemid))
1529 tuple.t_datamcxt = NULL;
1530 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
1531 tuple_len = tuple.t_len = ItemIdGetLength(itemid);
1532 ItemPointerSet(&(tuple.t_self), blkno, offnum);
1534 if (!(tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED))
1536 if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
1537 elog(ERROR, "Invalid XVAC in tuple header");
1538 if (tuple.t_data->t_infomask & HEAP_MOVED_IN)
1539 elog(ERROR, "HEAP_MOVED_IN was not expected");
1542 * If this (chain) tuple is moved by me already then I
1543 * have to check is it in vacpage or not - i.e. is it
1544 * moved while cleaning this page or some previous one.
1546 if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
1548 if (keep_tuples == 0)
1550 if (chain_tuple_moved) /* some chains was moved
1552 { /* cleaning this page */
1553 Assert(vacpage->offsets_free > 0);
1554 for (i = 0; i < vacpage->offsets_free; i++)
1556 if (vacpage->offsets[i] == offnum)
1559 if (i >= vacpage->offsets_free) /* not found */
1561 vacpage->offsets[vacpage->offsets_free++] = offnum;
1567 vacpage->offsets[vacpage->offsets_free++] = offnum;
1572 elog(ERROR, "HEAP_MOVED_OFF was expected");
1576 * If this tuple is in the chain of tuples created in updates
1577 * by "recent" transactions then we have to move all chain of
1578 * tuples to another places.
1580 if ((tuple.t_data->t_infomask & HEAP_UPDATED &&
1581 !TransactionIdPrecedes(HeapTupleHeaderGetXmin(tuple.t_data),
1583 (!(tuple.t_data->t_infomask & HEAP_XMAX_INVALID) &&
1584 !(ItemPointerEquals(&(tuple.t_self),
1585 &(tuple.t_data->t_ctid)))))
1590 ItemPointerData Ctid;
1591 HeapTupleData tp = tuple;
1592 Size tlen = tuple_len;
1593 VTupleMove vtmove = (VTupleMove)
1594 palloc(100 * sizeof(VTupleMoveData));
1596 int free_vtmove = 100;
1597 VacPage to_vacpage = NULL;
1599 bool freeCbuf = false;
1602 if (vacrelstats->vtlinks == NULL)
1603 elog(ERROR, "No one parent tuple was found");
1604 if (cur_buffer != InvalidBuffer)
1606 WriteBuffer(cur_buffer);
1607 cur_buffer = InvalidBuffer;
1611 * If this tuple is in the begin/middle of the chain then
1612 * we have to move to the end of chain.
1614 while (!(tp.t_data->t_infomask & HEAP_XMAX_INVALID) &&
1615 !(ItemPointerEquals(&(tp.t_self),
1616 &(tp.t_data->t_ctid))))
1618 Ctid = tp.t_data->t_ctid;
1620 ReleaseBuffer(Cbuf);
1622 Cbuf = ReadBuffer(onerel,
1623 ItemPointerGetBlockNumber(&Ctid));
1624 Cpage = BufferGetPage(Cbuf);
1625 Citemid = PageGetItemId(Cpage,
1626 ItemPointerGetOffsetNumber(&Ctid));
1627 if (!ItemIdIsUsed(Citemid))
1630 * This means that in the middle of chain there
1631 * was tuple updated by older (than OldestXmin)
1632 * xaction and this tuple is already deleted by
1633 * me. Actually, upper part of chain should be
1634 * removed and seems that this should be handled
1635 * in scan_heap(), but it's not implemented at the
1636 * moment and so we just stop shrinking here.
1638 ReleaseBuffer(Cbuf);
1641 elog(WARNING, "Child itemid in update-chain marked as unused - can't continue repair_frag");
1644 tp.t_datamcxt = NULL;
1645 tp.t_data = (HeapTupleHeader) PageGetItem(Cpage, Citemid);
1647 tlen = tp.t_len = ItemIdGetLength(Citemid);
1651 /* first, can chain be moved ? */
1654 if (to_vacpage == NULL ||
1655 !enough_space(to_vacpage, tlen))
1657 for (i = 0; i < num_fraged_pages; i++)
1659 if (enough_space(fraged_pages->pagedesc[i], tlen))
1663 if (i == num_fraged_pages)
1665 /* can't move item anywhere */
1666 for (i = 0; i < num_vtmove; i++)
1668 Assert(vtmove[i].vacpage->offsets_used > 0);
1669 (vtmove[i].vacpage->offsets_used)--;
1675 to_vacpage = fraged_pages->pagedesc[to_item];
1677 to_vacpage->free -= MAXALIGN(tlen);
1678 if (to_vacpage->offsets_used >= to_vacpage->offsets_free)
1679 to_vacpage->free -= MAXALIGN(sizeof(ItemIdData));
1680 (to_vacpage->offsets_used)++;
1681 if (free_vtmove == 0)
1684 vtmove = (VTupleMove) repalloc(vtmove,
1685 (free_vtmove + num_vtmove) *
1686 sizeof(VTupleMoveData));
1688 vtmove[num_vtmove].tid = tp.t_self;
1689 vtmove[num_vtmove].vacpage = to_vacpage;
1690 if (to_vacpage->offsets_used == 1)
1691 vtmove[num_vtmove].cleanVpd = true;
1693 vtmove[num_vtmove].cleanVpd = false;
1698 if (!(tp.t_data->t_infomask & HEAP_UPDATED) ||
1699 TransactionIdPrecedes(HeapTupleHeaderGetXmin(tp.t_data),
1703 /* Well, try to find tuple with old row version */
1710 VTupleLinkData vtld,
1713 vtld.new_tid = tp.t_self;
1715 vac_bsearch((void *) &vtld,
1716 (void *) (vacrelstats->vtlinks),
1717 vacrelstats->num_vtlinks,
1718 sizeof(VTupleLinkData),
1721 elog(ERROR, "Parent tuple was not found");
1722 tp.t_self = vtlp->this_tid;
1723 Pbuf = ReadBuffer(onerel,
1724 ItemPointerGetBlockNumber(&(tp.t_self)));
1725 Ppage = BufferGetPage(Pbuf);
1726 Pitemid = PageGetItemId(Ppage,
1727 ItemPointerGetOffsetNumber(&(tp.t_self)));
1728 if (!ItemIdIsUsed(Pitemid))
1729 elog(ERROR, "Parent itemid marked as unused");
1730 Ptp.t_datamcxt = NULL;
1731 Ptp.t_data = (HeapTupleHeader) PageGetItem(Ppage, Pitemid);
1732 Assert(ItemPointerEquals(&(vtld.new_tid),
1733 &(Ptp.t_data->t_ctid)));
1736 * Read above about cases when
1737 * !ItemIdIsUsed(Citemid) (child item is
1738 * removed)... Due to the fact that at the moment
1739 * we don't remove unuseful part of update-chain,
1740 * it's possible to get too old parent row here.
1741 * Like as in the case which caused this problem,
1742 * we stop shrinking here. I could try to find
1743 * real parent row but want not to do it because
1744 * of real solution will be implemented anyway,
1745 * latter, and we are too close to 6.5 release. -
1748 if (!(TransactionIdEquals(HeapTupleHeaderGetXmax(Ptp.t_data),
1749 HeapTupleHeaderGetXmin(tp.t_data))))
1752 ReleaseBuffer(Cbuf);
1754 ReleaseBuffer(Pbuf);
1755 for (i = 0; i < num_vtmove; i++)
1757 Assert(vtmove[i].vacpage->offsets_used > 0);
1758 (vtmove[i].vacpage->offsets_used)--;
1761 elog(WARNING, "Too old parent tuple found - can't continue repair_frag");
1764 #ifdef NOT_USED /* I'm not sure that this will wotk
1768 * If this tuple is updated version of row and it
1769 * was created by the same transaction then no one
1770 * is interested in this tuple - mark it as
1773 if (Ptp.t_data->t_infomask & HEAP_UPDATED &&
1774 TransactionIdEquals(HeapTupleHeaderGetXmin(Ptp.t_data),
1775 HeapTupleHeaderGetXmax(Ptp.t_data)))
1777 Ptp.t_data->t_infomask &=
1778 ~(HEAP_XMIN_COMMITTED | HEAP_XMIN_INVALID | HEAP_MOVED_IN);
1779 Ptp.t_data->t_infomask |= HEAP_MOVED_OFF;
1780 HeapTupleHeaderSetXvac(Ptp.t_data, myXID);
1785 tp.t_datamcxt = Ptp.t_datamcxt;
1786 tp.t_data = Ptp.t_data;
1787 tlen = tp.t_len = ItemIdGetLength(Pitemid);
1789 ReleaseBuffer(Cbuf);
1794 if (num_vtmove == 0)
1798 ReleaseBuffer(Cbuf);
1799 if (num_vtmove == 0) /* chain can't be moved */
1804 ItemPointerSetInvalid(&Ctid);
1805 for (ti = 0; ti < num_vtmove; ti++)
1807 VacPage destvacpage = vtmove[ti].vacpage;
1809 /* Get page to move from */
1810 tuple.t_self = vtmove[ti].tid;
1811 Cbuf = ReadBuffer(onerel,
1812 ItemPointerGetBlockNumber(&(tuple.t_self)));
1814 /* Get page to move to */
1815 cur_buffer = ReadBuffer(onerel, destvacpage->blkno);
1817 LockBuffer(cur_buffer, BUFFER_LOCK_EXCLUSIVE);
1818 if (cur_buffer != Cbuf)
1819 LockBuffer(Cbuf, BUFFER_LOCK_EXCLUSIVE);
1821 ToPage = BufferGetPage(cur_buffer);
1822 Cpage = BufferGetPage(Cbuf);
1824 Citemid = PageGetItemId(Cpage,
1825 ItemPointerGetOffsetNumber(&(tuple.t_self)));
1826 tuple.t_datamcxt = NULL;
1827 tuple.t_data = (HeapTupleHeader) PageGetItem(Cpage, Citemid);
1828 tuple_len = tuple.t_len = ItemIdGetLength(Citemid);
1831 * make a copy of the source tuple, and then mark the
1832 * source tuple MOVED_OFF.
1834 heap_copytuple_with_tuple(&tuple, &newtup);
1837 * register invalidation of source tuple in catcaches.
1839 CacheInvalidateHeapTuple(onerel, &tuple);
1841 /* NO ELOG(ERROR) TILL CHANGES ARE LOGGED */
1842 START_CRIT_SECTION();
1844 tuple.t_data->t_infomask &=
1845 ~(HEAP_XMIN_COMMITTED | HEAP_XMIN_INVALID | HEAP_MOVED_IN);
1846 tuple.t_data->t_infomask |= HEAP_MOVED_OFF;
1847 HeapTupleHeaderSetXvac(tuple.t_data, myXID);
1850 * If this page was not used before - clean it.
1852 * NOTE: a nasty bug used to lurk here. It is possible
1853 * for the source and destination pages to be the same
1854 * (since this tuple-chain member can be on a page
1855 * lower than the one we're currently processing in
1856 * the outer loop). If that's true, then after
1857 * vacuum_page() the source tuple will have been
1858 * moved, and tuple.t_data will be pointing at
1859 * garbage. Therefore we must do everything that uses
1860 * tuple.t_data BEFORE this step!!
1862 * This path is different from the other callers of
1863 * vacuum_page, because we have already incremented
1864 * the vacpage's offsets_used field to account for the
1865 * tuple(s) we expect to move onto the page. Therefore
1866 * vacuum_page's check for offsets_used == 0 is wrong.
1867 * But since that's a good debugging check for all
1868 * other callers, we work around it here rather than
1871 if (!PageIsEmpty(ToPage) && vtmove[ti].cleanVpd)
1873 int sv_offsets_used = destvacpage->offsets_used;
1875 destvacpage->offsets_used = 0;
1876 vacuum_page(onerel, cur_buffer, destvacpage);
1877 destvacpage->offsets_used = sv_offsets_used;
1881 * Update the state of the copied tuple, and store it
1882 * on the destination page.
1884 newtup.t_data->t_infomask &=
1885 ~(HEAP_XMIN_COMMITTED | HEAP_XMIN_INVALID | HEAP_MOVED_OFF);
1886 newtup.t_data->t_infomask |= HEAP_MOVED_IN;
1887 HeapTupleHeaderSetXvac(newtup.t_data, myXID);
1888 newoff = PageAddItem(ToPage, (Item) newtup.t_data, tuple_len,
1889 InvalidOffsetNumber, LP_USED);
1890 if (newoff == InvalidOffsetNumber)
1892 elog(PANIC, "moving chain: failed to add item with len = %lu to page %u",
1893 (unsigned long) tuple_len, destvacpage->blkno);
1895 newitemid = PageGetItemId(ToPage, newoff);
1896 pfree(newtup.t_data);
1897 newtup.t_datamcxt = NULL;
1898 newtup.t_data = (HeapTupleHeader) PageGetItem(ToPage, newitemid);
1899 ItemPointerSet(&(newtup.t_self), destvacpage->blkno, newoff);
1903 log_heap_move(onerel, Cbuf, tuple.t_self,
1904 cur_buffer, &newtup);
1906 if (Cbuf != cur_buffer)
1908 PageSetLSN(Cpage, recptr);
1909 PageSetSUI(Cpage, ThisStartUpID);
1911 PageSetLSN(ToPage, recptr);
1912 PageSetSUI(ToPage, ThisStartUpID);
1916 if (destvacpage->blkno > last_move_dest_block)
1917 last_move_dest_block = destvacpage->blkno;
1920 * Set new tuple's t_ctid pointing to itself for last
1921 * tuple in chain, and to next tuple in chain
1924 if (!ItemPointerIsValid(&Ctid))
1925 newtup.t_data->t_ctid = newtup.t_self;
1927 newtup.t_data->t_ctid = Ctid;
1928 Ctid = newtup.t_self;
1933 * Remember that we moved tuple from the current page
1934 * (corresponding index tuple will be cleaned).
1937 vacpage->offsets[vacpage->offsets_free++] =
1938 ItemPointerGetOffsetNumber(&(tuple.t_self));
1942 LockBuffer(cur_buffer, BUFFER_LOCK_UNLOCK);
1943 if (cur_buffer != Cbuf)
1944 LockBuffer(Cbuf, BUFFER_LOCK_UNLOCK);
1946 /* Create index entries for the moved tuple */
1947 if (resultRelInfo->ri_NumIndices > 0)
1949 ExecStoreTuple(&newtup, slot, InvalidBuffer, false);
1950 ExecInsertIndexTuples(slot, &(newtup.t_self),
1954 WriteBuffer(cur_buffer);
1957 cur_buffer = InvalidBuffer;
1959 chain_tuple_moved = true;
1963 /* try to find new page for this tuple */
1964 if (cur_buffer == InvalidBuffer ||
1965 !enough_space(cur_page, tuple_len))
1967 if (cur_buffer != InvalidBuffer)
1969 WriteBuffer(cur_buffer);
1970 cur_buffer = InvalidBuffer;
1972 for (i = 0; i < num_fraged_pages; i++)
1974 if (enough_space(fraged_pages->pagedesc[i], tuple_len))
1977 if (i == num_fraged_pages)
1978 break; /* can't move item anywhere */
1980 cur_page = fraged_pages->pagedesc[cur_item];
1981 cur_buffer = ReadBuffer(onerel, cur_page->blkno);
1982 LockBuffer(cur_buffer, BUFFER_LOCK_EXCLUSIVE);
1983 ToPage = BufferGetPage(cur_buffer);
1984 /* if this page was not used before - clean it */
1985 if (!PageIsEmpty(ToPage) && cur_page->offsets_used == 0)
1986 vacuum_page(onerel, cur_buffer, cur_page);
1989 LockBuffer(cur_buffer, BUFFER_LOCK_EXCLUSIVE);
1991 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
1994 heap_copytuple_with_tuple(&tuple, &newtup);
1997 * register invalidation of source tuple in catcaches.
1999 * (Note: we do not need to register the copied tuple,
2000 * because we are not changing the tuple contents and
2001 * so there cannot be any need to flush negative
2002 * catcache entries.)
2004 CacheInvalidateHeapTuple(onerel, &tuple);
2006 /* NO ELOG(ERROR) TILL CHANGES ARE LOGGED */
2007 START_CRIT_SECTION();
2010 * Mark new tuple as moved_in by vacuum and store vacuum XID
2013 newtup.t_data->t_infomask &=
2014 ~(HEAP_XMIN_COMMITTED | HEAP_XMIN_INVALID | HEAP_MOVED_OFF);
2015 newtup.t_data->t_infomask |= HEAP_MOVED_IN;
2016 HeapTupleHeaderSetXvac(newtup.t_data, myXID);
2018 /* add tuple to the page */
2019 newoff = PageAddItem(ToPage, (Item) newtup.t_data, tuple_len,
2020 InvalidOffsetNumber, LP_USED);
2021 if (newoff == InvalidOffsetNumber)
2023 elog(PANIC, "failed to add item with len = %lu to page %u (free space %lu, nusd %u, noff %u)",
2024 (unsigned long) tuple_len,
2025 cur_page->blkno, (unsigned long) cur_page->free,
2026 cur_page->offsets_used, cur_page->offsets_free);
2028 newitemid = PageGetItemId(ToPage, newoff);
2029 pfree(newtup.t_data);
2030 newtup.t_datamcxt = NULL;
2031 newtup.t_data = (HeapTupleHeader) PageGetItem(ToPage, newitemid);
2032 ItemPointerSet(&(newtup.t_data->t_ctid), cur_page->blkno, newoff);
2033 newtup.t_self = newtup.t_data->t_ctid;
2036 * Mark old tuple as moved_off by vacuum and store vacuum XID
2039 tuple.t_data->t_infomask &=
2040 ~(HEAP_XMIN_COMMITTED | HEAP_XMIN_INVALID | HEAP_MOVED_IN);
2041 tuple.t_data->t_infomask |= HEAP_MOVED_OFF;
2042 HeapTupleHeaderSetXvac(tuple.t_data, myXID);
2046 log_heap_move(onerel, buf, tuple.t_self,
2047 cur_buffer, &newtup);
2049 PageSetLSN(page, recptr);
2050 PageSetSUI(page, ThisStartUpID);
2051 PageSetLSN(ToPage, recptr);
2052 PageSetSUI(ToPage, ThisStartUpID);
2056 cur_page->offsets_used++;
2058 cur_page->free = ((PageHeader) ToPage)->pd_upper - ((PageHeader) ToPage)->pd_lower;
2059 if (cur_page->blkno > last_move_dest_block)
2060 last_move_dest_block = cur_page->blkno;
2062 vacpage->offsets[vacpage->offsets_free++] = offnum;
2064 LockBuffer(cur_buffer, BUFFER_LOCK_UNLOCK);
2065 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
2067 /* insert index' tuples if needed */
2068 if (resultRelInfo->ri_NumIndices > 0)
2070 ExecStoreTuple(&newtup, slot, InvalidBuffer, false);
2071 ExecInsertIndexTuples(slot, &(newtup.t_self), estate, true);
2073 } /* walk along page */
2075 if (offnum < maxoff && keep_tuples > 0)
2079 for (off = OffsetNumberNext(offnum);
2081 off = OffsetNumberNext(off))
2083 itemid = PageGetItemId(page, off);
2084 if (!ItemIdIsUsed(itemid))
2086 tuple.t_datamcxt = NULL;
2087 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2088 if (tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED)
2090 if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
2091 elog(ERROR, "Invalid XVAC in tuple header (4)");
2092 if (tuple.t_data->t_infomask & HEAP_MOVED_IN)
2093 elog(ERROR, "HEAP_MOVED_IN was not expected (2)");
2094 if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
2096 /* some chains was moved while */
2097 if (chain_tuple_moved)
2098 { /* cleaning this page */
2099 Assert(vacpage->offsets_free > 0);
2100 for (i = 0; i < vacpage->offsets_free; i++)
2102 if (vacpage->offsets[i] == off)
2105 if (i >= vacpage->offsets_free) /* not found */
2107 vacpage->offsets[vacpage->offsets_free++] = off;
2108 Assert(keep_tuples > 0);
2114 vacpage->offsets[vacpage->offsets_free++] = off;
2115 Assert(keep_tuples > 0);
2122 if (vacpage->offsets_free > 0) /* some tuples were moved */
2124 if (chain_tuple_moved) /* else - they are ordered */
2126 qsort((char *) (vacpage->offsets), vacpage->offsets_free,
2127 sizeof(OffsetNumber), vac_cmp_offno);
2129 vpage_insert(&Nvacpagelist, copy_vac_page(vacpage));
2137 if (offnum <= maxoff)
2138 break; /* some item(s) left */
2140 } /* walk along relation */
2142 blkno++; /* new number of blocks */
2144 if (cur_buffer != InvalidBuffer)
2146 Assert(num_moved > 0);
2147 WriteBuffer(cur_buffer);
2153 * We have to commit our tuple movings before we truncate the
2154 * relation. Ideally we should do Commit/StartTransactionCommand
2155 * here, relying on the session-level table lock to protect our
2156 * exclusive access to the relation. However, that would require
2157 * a lot of extra code to close and re-open the relation, indexes,
2158 * etc. For now, a quick hack: record status of current
2159 * transaction as committed, and continue.
2161 RecordTransactionCommit();
2165 * We are not going to move any more tuples across pages, but we still
2166 * need to apply vacuum_page to compact free space in the remaining
2167 * pages in vacuum_pages list. Note that some of these pages may also
2168 * be in the fraged_pages list, and may have had tuples moved onto
2169 * them; if so, we already did vacuum_page and needn't do it again.
2171 for (i = 0, curpage = vacuum_pages->pagedesc;
2175 CHECK_FOR_INTERRUPTS();
2176 Assert((*curpage)->blkno < blkno);
2177 if ((*curpage)->offsets_used == 0)
2179 /* this page was not used as a move target, so must clean it */
2180 buf = ReadBuffer(onerel, (*curpage)->blkno);
2181 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
2182 page = BufferGetPage(buf);
2183 if (!PageIsEmpty(page))
2184 vacuum_page(onerel, buf, *curpage);
2185 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
2191 * Now scan all the pages that we moved tuples onto and update tuple
2192 * status bits. This is not really necessary, but will save time for
2193 * future transactions examining these tuples.
2195 * XXX WARNING that this code fails to clear HEAP_MOVED_OFF tuples from
2196 * pages that were move source pages but not move dest pages. One
2197 * also wonders whether it wouldn't be better to skip this step and
2198 * let the tuple status updates happen someplace that's not holding an
2199 * exclusive lock on the relation.
2202 for (i = 0, curpage = fraged_pages->pagedesc;
2203 i < num_fraged_pages;
2206 CHECK_FOR_INTERRUPTS();
2207 Assert((*curpage)->blkno < blkno);
2208 if ((*curpage)->blkno > last_move_dest_block)
2209 break; /* no need to scan any further */
2210 if ((*curpage)->offsets_used == 0)
2211 continue; /* this page was never used as a move dest */
2212 buf = ReadBuffer(onerel, (*curpage)->blkno);
2213 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
2214 page = BufferGetPage(buf);
2216 max_offset = PageGetMaxOffsetNumber(page);
2217 for (newoff = FirstOffsetNumber;
2218 newoff <= max_offset;
2219 newoff = OffsetNumberNext(newoff))
2221 itemid = PageGetItemId(page, newoff);
2222 if (!ItemIdIsUsed(itemid))
2224 tuple.t_datamcxt = NULL;
2225 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2226 if (!(tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED))
2228 if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
2229 elog(ERROR, "Invalid XVAC in tuple header (2)");
2230 if (tuple.t_data->t_infomask & HEAP_MOVED_IN)
2232 tuple.t_data->t_infomask |= HEAP_XMIN_COMMITTED;
2235 else if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
2236 tuple.t_data->t_infomask |= HEAP_XMIN_INVALID;
2238 elog(ERROR, "HEAP_MOVED_OFF/HEAP_MOVED_IN was expected");
2241 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
2243 Assert((*curpage)->offsets_used == num_tuples);
2244 checked_moved += num_tuples;
2246 Assert(num_moved == checked_moved);
2248 elog(elevel, "Rel %s: Pages: %u --> %u; Tuple(s) moved: %u.\n\t%s",
2249 RelationGetRelationName(onerel),
2250 nblocks, blkno, num_moved,
2251 vac_show_rusage(&ru0));
2254 * Reflect the motion of system tuples to catalog cache here.
2256 CommandCounterIncrement();
2258 if (Nvacpagelist.num_pages > 0)
2260 /* vacuum indexes again if needed */
2261 if (Irel != (Relation *) NULL)
2267 /* re-sort Nvacpagelist.pagedesc */
2268 for (vpleft = Nvacpagelist.pagedesc,
2269 vpright = Nvacpagelist.pagedesc + Nvacpagelist.num_pages - 1;
2270 vpleft < vpright; vpleft++, vpright--)
2276 Assert(keep_tuples >= 0);
2277 for (i = 0; i < nindexes; i++)
2278 vacuum_index(&Nvacpagelist, Irel[i],
2279 vacrelstats->rel_tuples, keep_tuples);
2282 /* clean moved tuples from last page in Nvacpagelist list */
2283 if (vacpage->blkno == (blkno - 1) &&
2284 vacpage->offsets_free > 0)
2286 OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)];
2287 OffsetNumber *unused = unbuf;
2290 buf = ReadBuffer(onerel, vacpage->blkno);
2291 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
2292 page = BufferGetPage(buf);
2294 maxoff = PageGetMaxOffsetNumber(page);
2295 for (offnum = FirstOffsetNumber;
2297 offnum = OffsetNumberNext(offnum))
2299 itemid = PageGetItemId(page, offnum);
2300 if (!ItemIdIsUsed(itemid))
2302 tuple.t_datamcxt = NULL;
2303 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2305 if (!(tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED))
2307 if (HeapTupleHeaderGetXvac(tuple.t_data) != myXID)
2308 elog(ERROR, "Invalid XVAC in tuple header (3)");
2309 if (tuple.t_data->t_infomask & HEAP_MOVED_OFF)
2311 itemid->lp_flags &= ~LP_USED;
2315 elog(ERROR, "HEAP_MOVED_OFF was expected (2)");
2319 Assert(vacpage->offsets_free == num_tuples);
2320 START_CRIT_SECTION();
2321 uncnt = PageRepairFragmentation(page, unused);
2325 recptr = log_heap_clean(onerel, buf, (char *) unused,
2326 (char *) (&(unused[uncnt])) - (char *) unused);
2327 PageSetLSN(page, recptr);
2328 PageSetSUI(page, ThisStartUpID);
2331 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
2335 /* now - free new list of reaped pages */
2336 curpage = Nvacpagelist.pagedesc;
2337 for (i = 0; i < Nvacpagelist.num_pages; i++, curpage++)
2339 pfree(Nvacpagelist.pagedesc);
2343 * Flush dirty pages out to disk. We do this unconditionally, even if
2344 * we don't need to truncate, because we want to ensure that all
2345 * tuples have correct on-row commit status on disk (see bufmgr.c's
2346 * comments for FlushRelationBuffers()).
2348 i = FlushRelationBuffers(onerel, blkno);
2350 elog(ERROR, "VACUUM (repair_frag): FlushRelationBuffers returned %d",
2353 /* truncate relation, if needed */
2354 if (blkno < nblocks)
2356 blkno = smgrtruncate(DEFAULT_SMGR, onerel, blkno);
2357 onerel->rd_nblocks = blkno; /* update relcache immediately */
2358 onerel->rd_targblock = InvalidBlockNumber;
2359 vacrelstats->rel_pages = blkno; /* set new number of blocks */
2364 if (vacrelstats->vtlinks != NULL)
2365 pfree(vacrelstats->vtlinks);
2367 ExecDropTupleTable(tupleTable, true);
2369 ExecCloseIndices(resultRelInfo);
2373 * vacuum_heap() -- free dead tuples
2375 * This routine marks dead tuples as unused and truncates relation
2376 * if there are "empty" end-blocks.
2379 vacuum_heap(VRelStats *vacrelstats, Relation onerel, VacPageList vacuum_pages)
2383 BlockNumber relblocks;
2387 nblocks = vacuum_pages->num_pages;
2388 nblocks -= vacuum_pages->empty_end_pages; /* nothing to do with them */
2390 for (i = 0, vacpage = vacuum_pages->pagedesc; i < nblocks; i++, vacpage++)
2392 CHECK_FOR_INTERRUPTS();
2393 if ((*vacpage)->offsets_free > 0)
2395 buf = ReadBuffer(onerel, (*vacpage)->blkno);
2396 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
2397 vacuum_page(onerel, buf, *vacpage);
2398 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
2404 * Flush dirty pages out to disk. We do this unconditionally, even if
2405 * we don't need to truncate, because we want to ensure that all
2406 * tuples have correct on-row commit status on disk (see bufmgr.c's
2407 * comments for FlushRelationBuffers()).
2409 Assert(vacrelstats->rel_pages >= vacuum_pages->empty_end_pages);
2410 relblocks = vacrelstats->rel_pages - vacuum_pages->empty_end_pages;
2412 i = FlushRelationBuffers(onerel, relblocks);
2414 elog(ERROR, "VACUUM (vacuum_heap): FlushRelationBuffers returned %d",
2417 /* truncate relation if there are some empty end-pages */
2418 if (vacuum_pages->empty_end_pages > 0)
2420 elog(elevel, "Rel %s: Pages: %u --> %u.",
2421 RelationGetRelationName(onerel),
2422 vacrelstats->rel_pages, relblocks);
2423 relblocks = smgrtruncate(DEFAULT_SMGR, onerel, relblocks);
2424 onerel->rd_nblocks = relblocks; /* update relcache immediately */
2425 onerel->rd_targblock = InvalidBlockNumber;
2426 vacrelstats->rel_pages = relblocks; /* set new number of
2432 * vacuum_page() -- free dead tuples on a page
2433 * and repair its fragmentation.
2436 vacuum_page(Relation onerel, Buffer buffer, VacPage vacpage)
2438 OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)];
2439 OffsetNumber *unused = unbuf;
2441 Page page = BufferGetPage(buffer);
2445 /* There shouldn't be any tuples moved onto the page yet! */
2446 Assert(vacpage->offsets_used == 0);
2448 START_CRIT_SECTION();
2449 for (i = 0; i < vacpage->offsets_free; i++)
2451 itemid = PageGetItemId(page, vacpage->offsets[i]);
2452 itemid->lp_flags &= ~LP_USED;
2454 uncnt = PageRepairFragmentation(page, unused);
2458 recptr = log_heap_clean(onerel, buffer, (char *) unused,
2459 (char *) (&(unused[uncnt])) - (char *) unused);
2460 PageSetLSN(page, recptr);
2461 PageSetSUI(page, ThisStartUpID);
2467 * scan_index() -- scan one index relation to update statistic.
2469 * We use this when we have no deletions to do.
2472 scan_index(Relation indrel, double num_tuples)
2474 IndexBulkDeleteResult *stats;
2477 vac_init_rusage(&ru0);
2480 * Even though we're not planning to delete anything, use the
2481 * ambulkdelete call, so that the scan happens within the index AM for
2484 stats = index_bulk_delete(indrel, dummy_tid_reaped, NULL);
2489 /* now update statistics in pg_class */
2490 vac_update_relstats(RelationGetRelid(indrel),
2491 stats->num_pages, stats->num_index_tuples,
2494 elog(elevel, "Index %s: Pages %u; Tuples %.0f.\n\t%s",
2495 RelationGetRelationName(indrel),
2496 stats->num_pages, stats->num_index_tuples,
2497 vac_show_rusage(&ru0));
2500 * Check for tuple count mismatch. If the index is partial, then it's
2501 * OK for it to have fewer tuples than the heap; else we got trouble.
2503 if (stats->num_index_tuples != num_tuples)
2505 if (stats->num_index_tuples > num_tuples ||
2506 !vac_is_partial_index(indrel))
2507 elog(WARNING, "Index %s: NUMBER OF INDEX' TUPLES (%.0f) IS NOT THE SAME AS HEAP' (%.0f).\
2508 \n\tRecreate the index.",
2509 RelationGetRelationName(indrel),
2510 stats->num_index_tuples, num_tuples);
2517 * vacuum_index() -- vacuum one index relation.
2519 * Vpl is the VacPageList of the heap we're currently vacuuming.
2520 * It's locked. Indrel is an index relation on the vacuumed heap.
2522 * We don't bother to set locks on the index relation here, since
2523 * the parent table is exclusive-locked already.
2525 * Finally, we arrange to update the index relation's statistics in
2529 vacuum_index(VacPageList vacpagelist, Relation indrel,
2530 double num_tuples, int keep_tuples)
2532 IndexBulkDeleteResult *stats;
2535 vac_init_rusage(&ru0);
2537 /* Do bulk deletion */
2538 stats = index_bulk_delete(indrel, tid_reaped, (void *) vacpagelist);
2543 /* now update statistics in pg_class */
2544 vac_update_relstats(RelationGetRelid(indrel),
2545 stats->num_pages, stats->num_index_tuples,
2548 elog(elevel, "Index %s: Pages %u; Tuples %.0f: Deleted %.0f.\n\t%s",
2549 RelationGetRelationName(indrel), stats->num_pages,
2550 stats->num_index_tuples - keep_tuples, stats->tuples_removed,
2551 vac_show_rusage(&ru0));
2554 * Check for tuple count mismatch. If the index is partial, then it's
2555 * OK for it to have fewer tuples than the heap; else we got trouble.
2557 if (stats->num_index_tuples != num_tuples + keep_tuples)
2559 if (stats->num_index_tuples > num_tuples + keep_tuples ||
2560 !vac_is_partial_index(indrel))
2561 elog(WARNING, "Index %s: NUMBER OF INDEX' TUPLES (%.0f) IS NOT THE SAME AS HEAP' (%.0f).\
2562 \n\tRecreate the index.",
2563 RelationGetRelationName(indrel),
2564 stats->num_index_tuples, num_tuples);
2571 * tid_reaped() -- is a particular tid reaped?
2573 * This has the right signature to be an IndexBulkDeleteCallback.
2575 * vacpagelist->VacPage_array is sorted in right order.
2578 tid_reaped(ItemPointer itemptr, void *state)
2580 VacPageList vacpagelist = (VacPageList) state;
2581 OffsetNumber ioffno;
2585 VacPageData vacpage;
2587 vacpage.blkno = ItemPointerGetBlockNumber(itemptr);
2588 ioffno = ItemPointerGetOffsetNumber(itemptr);
2591 vpp = (VacPage *) vac_bsearch((void *) &vp,
2592 (void *) (vacpagelist->pagedesc),
2593 vacpagelist->num_pages,
2600 /* ok - we are on a partially or fully reaped page */
2603 if (vp->offsets_free == 0)
2605 /* this is EmptyPage, so claim all tuples on it are reaped!!! */
2609 voff = (OffsetNumber *) vac_bsearch((void *) &ioffno,
2610 (void *) (vp->offsets),
2612 sizeof(OffsetNumber),
2623 * Dummy version for scan_index.
2626 dummy_tid_reaped(ItemPointer itemptr, void *state)
2632 * Update the shared Free Space Map with the info we now have about
2633 * free space in the relation, discarding any old info the map may have.
2636 vac_update_fsm(Relation onerel, VacPageList fraged_pages,
2637 BlockNumber rel_pages)
2639 int nPages = fraged_pages->num_pages;
2644 /* +1 to avoid palloc(0) */
2645 pages = (BlockNumber *) palloc((nPages + 1) * sizeof(BlockNumber));
2646 spaceAvail = (Size *) palloc((nPages + 1) * sizeof(Size));
2648 for (i = 0; i < nPages; i++)
2650 pages[i] = fraged_pages->pagedesc[i]->blkno;
2651 spaceAvail[i] = fraged_pages->pagedesc[i]->free;
2654 * fraged_pages may contain entries for pages that we later
2655 * decided to truncate from the relation; don't enter them into
2658 if (pages[i] >= rel_pages)
2665 MultiRecordFreeSpace(&onerel->rd_node,
2667 nPages, pages, spaceAvail);
2672 /* Copy a VacPage structure */
2674 copy_vac_page(VacPage vacpage)
2678 /* allocate a VacPageData entry */
2679 newvacpage = (VacPage) palloc(sizeof(VacPageData) +
2680 vacpage->offsets_free * sizeof(OffsetNumber));
2683 if (vacpage->offsets_free > 0)
2684 memcpy(newvacpage->offsets, vacpage->offsets,
2685 vacpage->offsets_free * sizeof(OffsetNumber));
2686 newvacpage->blkno = vacpage->blkno;
2687 newvacpage->free = vacpage->free;
2688 newvacpage->offsets_used = vacpage->offsets_used;
2689 newvacpage->offsets_free = vacpage->offsets_free;
2695 * Add a VacPage pointer to a VacPageList.
2697 * As a side effect of the way that scan_heap works,
2698 * higher pages come after lower pages in the array
2699 * (and highest tid on a page is last).
2702 vpage_insert(VacPageList vacpagelist, VacPage vpnew)
2704 #define PG_NPAGEDESC 1024
2706 /* allocate a VacPage entry if needed */
2707 if (vacpagelist->num_pages == 0)
2709 vacpagelist->pagedesc = (VacPage *) palloc(PG_NPAGEDESC * sizeof(VacPage));
2710 vacpagelist->num_allocated_pages = PG_NPAGEDESC;
2712 else if (vacpagelist->num_pages >= vacpagelist->num_allocated_pages)
2714 vacpagelist->num_allocated_pages *= 2;
2715 vacpagelist->pagedesc = (VacPage *) repalloc(vacpagelist->pagedesc, vacpagelist->num_allocated_pages * sizeof(VacPage));
2717 vacpagelist->pagedesc[vacpagelist->num_pages] = vpnew;
2718 (vacpagelist->num_pages)++;
2722 * vac_bsearch: just like standard C library routine bsearch(),
2723 * except that we first test to see whether the target key is outside
2724 * the range of the table entries. This case is handled relatively slowly
2725 * by the normal binary search algorithm (ie, no faster than any other key)
2726 * but it occurs often enough in VACUUM to be worth optimizing.
2729 vac_bsearch(const void *key, const void *base,
2730 size_t nelem, size_t size,
2731 int (*compar) (const void *, const void *))
2738 res = compar(key, base);
2742 return (void *) base;
2745 last = (const void *) ((const char *) base + (nelem - 1) * size);
2746 res = compar(key, last);
2750 return (void *) last;
2753 return NULL; /* already checked 'em all */
2754 return bsearch(key, base, nelem, size, compar);
2758 * Comparator routines for use with qsort() and bsearch().
2761 vac_cmp_blk(const void *left, const void *right)
2766 lblk = (*((VacPage *) left))->blkno;
2767 rblk = (*((VacPage *) right))->blkno;
2777 vac_cmp_offno(const void *left, const void *right)
2779 if (*(OffsetNumber *) left < *(OffsetNumber *) right)
2781 if (*(OffsetNumber *) left == *(OffsetNumber *) right)
2787 vac_cmp_vtlinks(const void *left, const void *right)
2789 if (((VTupleLink) left)->new_tid.ip_blkid.bi_hi <
2790 ((VTupleLink) right)->new_tid.ip_blkid.bi_hi)
2792 if (((VTupleLink) left)->new_tid.ip_blkid.bi_hi >
2793 ((VTupleLink) right)->new_tid.ip_blkid.bi_hi)
2795 /* bi_hi-es are equal */
2796 if (((VTupleLink) left)->new_tid.ip_blkid.bi_lo <
2797 ((VTupleLink) right)->new_tid.ip_blkid.bi_lo)
2799 if (((VTupleLink) left)->new_tid.ip_blkid.bi_lo >
2800 ((VTupleLink) right)->new_tid.ip_blkid.bi_lo)
2802 /* bi_lo-es are equal */
2803 if (((VTupleLink) left)->new_tid.ip_posid <
2804 ((VTupleLink) right)->new_tid.ip_posid)
2806 if (((VTupleLink) left)->new_tid.ip_posid >
2807 ((VTupleLink) right)->new_tid.ip_posid)
2814 vac_open_indexes(Relation relation, int *nindexes, Relation **Irel)
2820 indexoidlist = RelationGetIndexList(relation);
2822 *nindexes = length(indexoidlist);
2825 *Irel = (Relation *) palloc(*nindexes * sizeof(Relation));
2830 foreach(indexoidscan, indexoidlist)
2832 Oid indexoid = lfirsti(indexoidscan);
2834 (*Irel)[i] = index_open(indexoid);
2838 freeList(indexoidlist);
2843 vac_close_indexes(int nindexes, Relation *Irel)
2845 if (Irel == (Relation *) NULL)
2849 index_close(Irel[nindexes]);
2855 * Is an index partial (ie, could it contain fewer tuples than the heap?)
2858 vac_is_partial_index(Relation indrel)
2861 * If the index's AM doesn't support nulls, it's partial for our
2864 if (!indrel->rd_am->amindexnulls)
2867 /* Otherwise, look to see if there's a partial-index predicate */
2868 return (VARSIZE(&indrel->rd_index->indpred) > VARHDRSZ);
2873 enough_space(VacPage vacpage, Size len)
2875 len = MAXALIGN(len);
2877 if (len > vacpage->free)
2880 /* if there are free itemid(s) and len <= free_space... */
2881 if (vacpage->offsets_used < vacpage->offsets_free)
2884 /* noff_used >= noff_free and so we'll have to allocate new itemid */
2885 if (len + sizeof(ItemIdData) <= vacpage->free)
2893 * Initialize usage snapshot.
2896 vac_init_rusage(VacRUsage *ru0)
2900 getrusage(RUSAGE_SELF, &ru0->ru);
2901 gettimeofday(&ru0->tv, &tz);
2905 * Compute elapsed time since ru0 usage snapshot, and format into
2906 * a displayable string. Result is in a static string, which is
2907 * tacky, but no one ever claimed that the Postgres backend is
2911 vac_show_rusage(VacRUsage *ru0)
2913 static char result[100];
2916 vac_init_rusage(&ru1);
2918 if (ru1.tv.tv_usec < ru0->tv.tv_usec)
2921 ru1.tv.tv_usec += 1000000;
2923 if (ru1.ru.ru_stime.tv_usec < ru0->ru.ru_stime.tv_usec)
2925 ru1.ru.ru_stime.tv_sec--;
2926 ru1.ru.ru_stime.tv_usec += 1000000;
2928 if (ru1.ru.ru_utime.tv_usec < ru0->ru.ru_utime.tv_usec)
2930 ru1.ru.ru_utime.tv_sec--;
2931 ru1.ru.ru_utime.tv_usec += 1000000;
2934 snprintf(result, sizeof(result),
2935 "CPU %d.%02ds/%d.%02du sec elapsed %d.%02d sec.",
2936 (int) (ru1.ru.ru_stime.tv_sec - ru0->ru.ru_stime.tv_sec),
2937 (int) (ru1.ru.ru_stime.tv_usec - ru0->ru.ru_stime.tv_usec) / 10000,
2938 (int) (ru1.ru.ru_utime.tv_sec - ru0->ru.ru_utime.tv_sec),
2939 (int) (ru1.ru.ru_utime.tv_usec - ru0->ru.ru_utime.tv_usec) / 10000,
2940 (int) (ru1.tv.tv_sec - ru0->tv.tv_sec),
2941 (int) (ru1.tv.tv_usec - ru0->tv.tv_usec) / 10000);