1 /*-------------------------------------------------------------------------
4 * the postgres vacuum cleaner
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.48 1997/09/22 07:12:33 vadim Exp $
12 *-------------------------------------------------------------------------
14 #include <sys/types.h>
24 #include <utils/portal.h>
25 #include <access/genam.h>
26 #include <access/heapam.h>
27 #include <access/xact.h>
28 #include <storage/bufmgr.h>
29 #include <access/transam.h>
30 #include <catalog/pg_index.h>
31 #include <catalog/index.h>
32 #include <catalog/catname.h>
33 #include <catalog/catalog.h>
34 #include <catalog/pg_class.h>
35 #include <catalog/pg_proc.h>
36 #include <catalog/pg_statistic.h>
37 #include <catalog/pg_type.h>
38 #include <catalog/pg_operator.h>
39 #include <storage/smgr.h>
40 #include <storage/lmgr.h>
41 #include <utils/inval.h>
42 #include <utils/mcxt.h>
43 #include <utils/inval.h>
44 #include <utils/syscache.h>
45 #include <utils/builtins.h>
46 #include <commands/vacuum.h>
47 #include <parser/catalog_utils.h>
48 #include <storage/bufpage.h>
49 #include "storage/shmem.h"
50 #ifndef HAVE_GETRUSAGE
51 #include <rusagestub.h>
54 #include <sys/resource.h>
57 #include <port-protos.h>
59 extern int BlowawayRelationBuffers(Relation rdesc, BlockNumber block);
61 bool VacuumRunning = false;
63 static Portal vc_portal;
65 static int MESSAGE_LEVEL; /* message level */
67 #define swapLong(a,b) {long tmp; tmp=a; a=b; b=tmp;}
68 #define swapInt(a,b) {int tmp; tmp=a; a=b; b=tmp;}
69 #define swapDatum(a,b) {Datum tmp; tmp=a; a=b; b=tmp;}
70 #define VacAttrStatsEqValid(stats) ( stats->f_cmpeq != NULL )
71 #define VacAttrStatsLtGtValid(stats) ( stats->f_cmplt != NULL && \
72 stats->f_cmpgt != NULL && \
73 RegProcedureIsValid(stats->outfunc) )
76 /* non-export function prototypes */
77 static void vc_init(void);
78 static void vc_shutdown(void);
79 static void vc_vacuum(NameData *VacRelP, bool analyze, List *va_cols);
80 static VRelList vc_getrels(NameData *VacRelP);
81 static void vc_vacone(Oid relid, bool analyze, List *va_cols);
82 static void vc_scanheap(VRelStats *vacrelstats, Relation onerel, VPageList Vvpl, VPageList Fvpl);
83 static void vc_rpfheap(VRelStats *vacrelstats, Relation onerel, VPageList Vvpl, VPageList Fvpl, int nindices, Relation *Irel);
84 static void vc_vacheap(VRelStats *vacrelstats, Relation onerel, VPageList vpl);
85 static void vc_vacpage(Page page, VPageDescr vpd, Relation archrel);
86 static void vc_vaconeind(VPageList vpl, Relation indrel, int nhtups);
87 static void vc_scanoneind(Relation indrel, int nhtups);
88 static void vc_attrstats(Relation onerel, VRelStats *vacrelstats, HeapTuple htup);
89 static void vc_bucketcpy(AttributeTupleForm attr, Datum value, Datum *bucket, int16 *bucket_len);
90 static void vc_updstats(Oid relid, int npages, int ntups, bool hasindex, VRelStats *vacrelstats);
91 static void vc_delhilowstats(Oid relid, int attcnt, int *attnums);
92 static void vc_setpagelock(Relation rel, BlockNumber blkno);
93 static VPageDescr vc_tidreapped(ItemPointer itemptr, VPageList vpl);
94 static void vc_reappage(VPageList vpl, VPageDescr vpc);
95 static void vc_vpinsert(VPageList vpl, VPageDescr vpnew);
96 static void vc_free(VRelList vrl);
97 static void vc_getindices(Oid relid, int *nindices, Relation **Irel);
98 static void vc_clsindices(int nindices, Relation *Irel);
99 static Relation vc_getarchrel(Relation heaprel);
100 static void vc_archive(Relation archrel, HeapTuple htup);
101 static bool vc_isarchrel(char *rname);
102 static void vc_mkindesc(Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc);
103 static char *vc_find_eq(char *bot, int nelem, int size, char *elm, int (*compar) (char *, char *));
104 static int vc_cmp_blk(char *left, char *right);
105 static int vc_cmp_offno(char *left, char *right);
106 static bool vc_enough_space(VPageDescr vpd, Size len);
109 vacuum(char *vacrel, bool verbose, bool analyze, List *va_spec)
113 PortalVariableMemory pmem;
119 * Create a portal for safe memory across transctions. We need to
120 * palloc the name space for it because our hash function expects the
121 * name to be on a longword boundary. CreatePortal copies the name to
122 * safe storage for us.
124 pname = (char *) palloc(strlen(VACPNAME) + 1);
125 strcpy(pname, VACPNAME);
126 vc_portal = CreatePortal(pname);
130 MESSAGE_LEVEL = NOTICE;
132 MESSAGE_LEVEL = DEBUG;
134 /* vacrel gets de-allocated on transaction commit */
136 strcpy(VacRel.data, vacrel);
138 pmem = PortalGetVariableMemory(vc_portal);
139 old = MemoryContextSwitchTo((MemoryContext) pmem);
141 Assert(va_spec == NIL || analyze);
144 char *col = (char *) lfirst(le);
147 dest = (char *) palloc(strlen(col) + 1);
149 va_cols = lappend(va_cols, dest);
151 MemoryContextSwitchTo(old);
153 /* initialize vacuum cleaner */
156 /* vacuum the database */
158 vc_vacuum(&VacRel, analyze, va_cols);
160 vc_vacuum(NULL, analyze, NIL);
162 PortalDestroy(&vc_portal);
169 * vc_init(), vc_shutdown() -- start up and shut down the vacuum cleaner.
171 * We run exactly one vacuum cleaner at a time. We use the file system
172 * to guarantee an exclusive lock on vacuuming, since a single vacuum
173 * cleaner instantiation crosses transaction boundaries, and we'd lose
174 * postgres-style locks at the end of every transaction.
176 * The strangeness with committing and starting transactions in the
177 * init and shutdown routines is due to the fact that the vacuum cleaner
178 * is invoked via a sql command, and so is already executing inside
179 * a transaction. We need to leave ourselves in a predictable state
180 * on entry and exit to the vacuum cleaner. We commit the transaction
181 * started in PostgresMain() inside vc_init(), and start one in
182 * vc_shutdown() to match the commit waiting for us back in
190 if ((fd = open("pg_vlock", O_CREAT | O_EXCL, 0600)) < 0)
191 elog(WARN, "can't create lock file -- another vacuum cleaner running?");
196 * By here, exclusive open on the lock file succeeded. If we abort
197 * for any reason during vacuuming, we need to remove the lock file.
198 * This global variable is checked in the transaction manager on xact
199 * abort, and the routine vc_abort() is called if necessary.
202 VacuumRunning = true;
204 /* matches the StartTransaction in PostgresMain() */
205 CommitTransactionCommand();
211 /* on entry, not in a transaction */
212 if (unlink("pg_vlock") < 0)
213 elog(WARN, "vacuum: can't destroy lock file!");
215 /* okay, we're done */
216 VacuumRunning = false;
218 /* matches the CommitTransaction in PostgresMain() */
219 StartTransactionCommand();
226 /* on abort, remove the vacuum cleaner lock file */
229 VacuumRunning = false;
233 * vc_vacuum() -- vacuum the database.
235 * This routine builds a list of relations to vacuum, and then calls
236 * code that vacuums them one at a time. We are careful to vacuum each
237 * relation in a separate transaction in order to avoid holding too many
241 vc_vacuum(NameData *VacRelP, bool analyze, List *va_cols)
246 /* get list of relations */
247 vrl = vc_getrels(VacRelP);
249 if (analyze && VacRelP == NULL && vrl != NULL)
250 vc_delhilowstats(InvalidOid, 0, NULL);
252 /* vacuum each heap relation */
253 for (cur = vrl; cur != (VRelList) NULL; cur = cur->vrl_next)
254 vc_vacone(cur->vrl_relid, analyze, va_cols);
260 vc_getrels(NameData *VacRelP)
264 HeapScanDesc pgcscan;
267 PortalVariableMemory portalmem;
279 StartTransactionCommand();
283 ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relname,
284 NameEqualRegProcedure,
285 PointerGetDatum(VacRelP->data));
289 ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relkind,
290 CharacterEqualRegProcedure, CharGetDatum('r'));
293 portalmem = PortalGetVariableMemory(vc_portal);
294 vrl = cur = (VRelList) NULL;
296 pgclass = heap_openr(RelationRelationName);
297 pgcdesc = RelationGetTupleDescriptor(pgclass);
299 pgcscan = heap_beginscan(pgclass, false, NowTimeQual, 1, &pgckey);
301 while (HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &buf)))
307 * We have to be careful not to vacuum the archive (since it
308 * already contains vacuumed tuples), and not to vacuum relations
309 * on write-once storage managers like the Sony jukebox at
313 d = heap_getattr(pgctup, buf, Anum_pg_class_relname, pgcdesc, &n);
316 /* skip archive relations */
317 if (vc_isarchrel(rname))
324 * don't vacuum large objects for now - something breaks when we
327 if ((strlen(rname) >= 5) && rname[0] == 'x' &&
328 rname[1] == 'i' && rname[2] == 'n' &&
329 (rname[3] == 'v' || rname[3] == 'x') &&
330 rname[4] >= '0' && rname[4] <= '9')
332 elog(NOTICE, "Rel %s: can't vacuum LargeObjects now",
338 d = heap_getattr(pgctup, buf, Anum_pg_class_relsmgr, pgcdesc, &n);
339 smgrno = DatumGetInt16(d);
341 /* skip write-once storage managers */
342 if (smgriswo(smgrno))
348 d = heap_getattr(pgctup, buf, Anum_pg_class_relkind, pgcdesc, &n);
350 rkind = DatumGetChar(d);
352 /* skip system relations */
356 elog(NOTICE, "Vacuum: can not process index and certain system tables");
360 /* get a relation list entry for this guy */
361 old = MemoryContextSwitchTo((MemoryContext) portalmem);
362 if (vrl == (VRelList) NULL)
364 vrl = cur = (VRelList) palloc(sizeof(VRelListData));
368 cur->vrl_next = (VRelList) palloc(sizeof(VRelListData));
371 MemoryContextSwitchTo(old);
373 cur->vrl_relid = pgctup->t_oid;
374 cur->vrl_next = (VRelList) NULL;
376 /* wei hates it if you forget to do this */
380 elog(NOTICE, "Vacuum: table not found");
383 heap_endscan(pgcscan);
386 CommitTransactionCommand();
392 * vc_vacone() -- vacuum one heap relation
394 * This routine vacuums a single heap, cleans out its indices, and
395 * updates its statistics npages and ntups statistics.
397 * Doing one heap at a time incurs extra overhead, since we need to
398 * check that the heap exists again just before we vacuum it. The
399 * reason that we do this is so that vacuuming can be spread across
400 * many small transactions. Otherwise, two-phase locking would require
401 * us to lock the entire database during one pass of the vacuum cleaner.
404 vc_vacone(Oid relid, bool analyze, List *va_cols)
411 HeapScanDesc pgcscan;
414 VPageListData Vvpl; /* List of pages to vacuum and/or clean
416 VPageListData Fvpl; /* List of pages with space enough for
422 VRelStats *vacrelstats;
424 StartTransactionCommand();
426 ScanKeyEntryInitialize(&pgckey, 0x0, ObjectIdAttributeNumber,
427 ObjectIdEqualRegProcedure,
428 ObjectIdGetDatum(relid));
430 pgclass = heap_openr(RelationRelationName);
431 pgcdesc = RelationGetTupleDescriptor(pgclass);
432 pgcscan = heap_beginscan(pgclass, false, NowTimeQual, 1, &pgckey);
435 * Race condition -- if the pg_class tuple has gone away since the
436 * last time we saw it, we don't need to vacuum it.
439 if (!HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &pgcbuf)))
441 heap_endscan(pgcscan);
443 CommitTransactionCommand();
447 /* now open the class and vacuum it */
448 onerel = heap_open(relid);
450 vacrelstats = (VRelStats *) palloc(sizeof(VRelStats));
451 vacrelstats->relid = relid;
452 vacrelstats->npages = vacrelstats->ntups = 0;
453 vacrelstats->hasindex = false;
454 if (analyze && !IsSystemRelationName((RelationGetRelationName(onerel))->data))
458 AttributeTupleForm *attr;
460 attr_cnt = onerel->rd_att->natts;
461 attr = onerel->rd_att->attrs;
468 if (length(va_cols) > attr_cnt)
469 elog(WARN, "vacuum: too many attributes specified for relation %s",
470 (RelationGetRelationName(onerel))->data);
471 attnums = (int *) palloc(attr_cnt * sizeof(int));
474 char *col = (char *) lfirst(le);
476 for (i = 0; i < attr_cnt; i++)
478 if (namestrcmp(&(attr[i]->attname), col) == 0)
481 if (i < attr_cnt) /* found */
485 elog(WARN, "vacuum: there is no attribute %s in %s",
486 col, (RelationGetRelationName(onerel))->data);
492 vacrelstats->vacattrstats =
493 (VacAttrStats *) palloc(attr_cnt * sizeof(VacAttrStats));
495 for (i = 0; i < attr_cnt; i++)
497 Operator func_operator;
498 OperatorTupleForm pgopform;
501 stats = &vacrelstats->vacattrstats[i];
502 stats->attr = palloc(ATTRIBUTE_TUPLE_SIZE);
503 memmove(stats->attr, attr[((attnums) ? attnums[i] : i)], ATTRIBUTE_TUPLE_SIZE);
504 stats->best = stats->guess1 = stats->guess2 = 0;
505 stats->max = stats->min = 0;
506 stats->best_len = stats->guess1_len = stats->guess2_len = 0;
507 stats->max_len = stats->min_len = 0;
508 stats->initialized = false;
509 stats->best_cnt = stats->guess1_cnt = stats->guess1_hits = stats->guess2_hits = 0;
510 stats->max_cnt = stats->min_cnt = stats->null_cnt = stats->nonnull_cnt = 0;
512 func_operator = oper("=", stats->attr->atttypid, stats->attr->atttypid, true);
513 if (func_operator != NULL)
517 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
518 fmgr_info(pgopform->oprcode, &(stats->f_cmpeq), &nargs);
521 stats->f_cmpeq = NULL;
523 func_operator = oper("<", stats->attr->atttypid, stats->attr->atttypid, true);
524 if (func_operator != NULL)
528 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
529 fmgr_info(pgopform->oprcode, &(stats->f_cmplt), &nargs);
532 stats->f_cmplt = NULL;
534 func_operator = oper(">", stats->attr->atttypid, stats->attr->atttypid, true);
535 if (func_operator != NULL)
539 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
540 fmgr_info(pgopform->oprcode, &(stats->f_cmpgt), &nargs);
543 stats->f_cmpgt = NULL;
545 pgttup = SearchSysCacheTuple(TYPOID,
546 ObjectIdGetDatum(stats->attr->atttypid),
548 if (HeapTupleIsValid(pgttup))
549 stats->outfunc = ((TypeTupleForm) GETSTRUCT(pgttup))->typoutput;
551 stats->outfunc = InvalidOid;
553 vacrelstats->va_natts = attr_cnt;
554 vc_delhilowstats(relid, ((attnums) ? attr_cnt : 0), attnums);
560 vacrelstats->va_natts = 0;
561 vacrelstats->vacattrstats = (VacAttrStats *) NULL;
564 /* we require the relation to be locked until the indices are cleaned */
565 RelationSetLockForWrite(onerel);
568 Vvpl.vpl_npages = Fvpl.vpl_npages = 0;
569 vc_scanheap(vacrelstats, onerel, &Vvpl, &Fvpl);
571 /* Now open indices */
572 Irel = (Relation *) NULL;
573 vc_getindices(vacrelstats->relid, &nindices, &Irel);
576 vacrelstats->hasindex = true;
578 vacrelstats->hasindex = false;
580 /* Clean/scan index relation(s) */
581 if (Irel != (Relation *) NULL)
583 if (Vvpl.vpl_npages > 0)
585 for (i = 0; i < nindices; i++)
586 vc_vaconeind(&Vvpl, Irel[i], vacrelstats->ntups);
589 /* just scan indices to update statistic */
591 for (i = 0; i < nindices; i++)
592 vc_scanoneind(Irel[i], vacrelstats->ntups);
596 if (Fvpl.vpl_npages > 0) /* Try to shrink heap */
597 vc_rpfheap(vacrelstats, onerel, &Vvpl, &Fvpl, nindices, Irel);
600 if (Irel != (Relation *) NULL)
601 vc_clsindices(nindices, Irel);
602 if (Vvpl.vpl_npages > 0)/* Clean pages from Vvpl list */
603 vc_vacheap(vacrelstats, onerel, &Vvpl);
606 /* ok - free Vvpl list of reapped pages */
607 if (Vvpl.vpl_npages > 0)
609 vpp = Vvpl.vpl_pgdesc;
610 for (i = 0; i < Vvpl.vpl_npages; i++, vpp++)
612 pfree(Vvpl.vpl_pgdesc);
613 if (Fvpl.vpl_npages > 0)
614 pfree(Fvpl.vpl_pgdesc);
617 /* all done with this class */
619 heap_endscan(pgcscan);
622 /* update statistics in pg_class */
623 vc_updstats(vacrelstats->relid, vacrelstats->npages, vacrelstats->ntups,
624 vacrelstats->hasindex, vacrelstats);
626 /* next command frees attribute stats */
628 CommitTransactionCommand();
632 * vc_scanheap() -- scan an open heap relation
634 * This routine sets commit times, constructs Vvpl list of
635 * empty/uninitialized pages and pages with dead tuples and
636 * ~LP_USED line pointers, constructs Fvpl list of pages
637 * appropriate for purposes of shrinking and maintains statistics
638 * on the number of live tuples in a heap.
641 vc_scanheap(VRelStats *vacrelstats, Relation onerel,
642 VPageList Vvpl, VPageList Fvpl)
671 Size min_tlen = MAXTUPLEN;
673 int32 i /* , attr_cnt */ ;
676 bool do_shrinking = true;
678 getrusage(RUSAGE_SELF, &ru0);
680 nvac = ntups = nunused = ncrash = nempg = nnepg = nchpg = nemend = 0;
683 relname = (RelationGetRelationName(onerel))->data;
685 nblocks = RelationGetNumberOfBlocks(onerel);
687 vpc = (VPageDescr) palloc(sizeof(VPageDescrData) + MaxOffsetNumber * sizeof(OffsetNumber));
690 for (blkno = 0; blkno < nblocks; blkno++)
692 buf = ReadBuffer(onerel, blkno);
693 page = BufferGetPage(buf);
694 vpc->vpd_blkno = blkno;
699 elog(NOTICE, "Rel %s: Uninitialized page %u - fixing",
701 PageInit(page, BufferGetPageSize(buf), 0);
702 vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
703 frsize += (vpc->vpd_free - sizeof(ItemIdData));
706 vc_reappage(Vvpl, vpc);
711 if (PageIsEmpty(page))
713 vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
714 frsize += (vpc->vpd_free - sizeof(ItemIdData));
717 vc_reappage(Vvpl, vpc);
724 maxoff = PageGetMaxOffsetNumber(page);
725 for (offnum = FirstOffsetNumber;
727 offnum = OffsetNumberNext(offnum))
729 itemid = PageGetItemId(page, offnum);
732 * Collect un-used items too - it's possible to have indices
733 * pointing here after crash.
735 if (!ItemIdIsUsed(itemid))
737 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
742 htup = (HeapTuple) PageGetItem(page, itemid);
745 if (!AbsoluteTimeIsBackwardCompatiblyValid(htup->t_tmin) &&
746 TransactionIdIsValid((TransactionId) htup->t_xmin))
749 if (TransactionIdDidAbort(htup->t_xmin))
753 else if (TransactionIdDidCommit(htup->t_xmin))
755 htup->t_tmin = TransactionIdGetCommitTime(htup->t_xmin);
758 else if (!TransactionIdIsInProgress(htup->t_xmin))
762 * Not Aborted, Not Committed, Not in Progress - so it
763 * from crashed process. - vadim 11/26/96
770 elog(NOTICE, "Rel %s: TID %u/%u: InsertTransactionInProgress %u - can't shrink relation",
771 relname, blkno, offnum, htup->t_xmin);
772 do_shrinking = false;
776 if (TransactionIdIsValid((TransactionId) htup->t_xmax))
778 if (TransactionIdDidAbort(htup->t_xmax))
780 StoreInvalidTransactionId(&(htup->t_xmax));
783 else if (TransactionIdDidCommit(htup->t_xmax))
785 else if (!TransactionIdIsInProgress(htup->t_xmax))
789 * Not Aborted, Not Committed, Not in Progress - so it
790 * from crashed process. - vadim 06/02/97
792 StoreInvalidTransactionId(&(htup->t_xmax));
797 elog(NOTICE, "Rel %s: TID %u/%u: DeleteTransactionInProgress %u - can't shrink relation",
798 relname, blkno, offnum, htup->t_xmax);
799 do_shrinking = false;
804 * Is it possible at all ? - vadim 11/26/96
806 if (!TransactionIdIsValid((TransactionId) htup->t_xmin))
808 elog(NOTICE, "Rel %s: TID %u/%u: INSERT_TRANSACTION_ID IS INVALID. \
809 DELETE_TRANSACTION_ID_VALID %d, TUPGONE %d.",
810 relname, blkno, offnum,
811 TransactionIdIsValid((TransactionId) htup->t_xmax),
816 * It's possibly! But from where it comes ? And should we fix
817 * it ? - vadim 11/28/96
819 itemptr = &(htup->t_ctid);
820 if (!ItemPointerIsValid(itemptr) ||
821 BlockIdGetBlockNumber(&(itemptr->ip_blkid)) != blkno)
823 elog(NOTICE, "Rel %s: TID %u/%u: TID IN TUPLEHEADER %u/%u IS NOT THE SAME. TUPGONE %d.",
824 relname, blkno, offnum,
825 BlockIdGetBlockNumber(&(itemptr->ip_blkid)),
826 itemptr->ip_posid, tupgone);
832 if (htup->t_len != itemid->lp_len)
834 elog(NOTICE, "Rel %s: TID %u/%u: TUPLE_LEN IN PAGEHEADER %u IS NOT THE SAME AS IN TUPLEHEADER %u. TUPGONE %d.",
835 relname, blkno, offnum,
836 itemid->lp_len, htup->t_len, tupgone);
838 if (!OidIsValid(htup->t_oid))
840 elog(NOTICE, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
841 relname, blkno, offnum, tupgone);
848 if (tempPage == (Page) NULL)
852 pageSize = PageGetPageSize(page);
853 tempPage = (Page) palloc(pageSize);
854 memmove(tempPage, page, pageSize);
857 lpp = &(((PageHeader) tempPage)->pd_linp[offnum - 1]);
860 lpp->lp_flags &= ~LP_USED;
862 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
870 if (htup->t_len < min_tlen)
871 min_tlen = htup->t_len;
872 if (htup->t_len > max_tlen)
873 max_tlen = htup->t_len;
874 vc_attrstats(onerel, vacrelstats, htup);
886 if (tempPage != (Page) NULL)
887 { /* Some tuples are gone */
888 PageRepairFragmentation(tempPage);
889 vpc->vpd_free = ((PageHeader) tempPage)->pd_upper - ((PageHeader) tempPage)->pd_lower;
890 frsize += vpc->vpd_free;
891 vc_reappage(Vvpl, vpc);
893 tempPage = (Page) NULL;
895 else if (vpc->vpd_noff > 0)
896 { /* there are only ~LP_USED line pointers */
897 vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
898 frsize += vpc->vpd_free;
899 vc_reappage(Vvpl, vpc);
911 /* save stats in the rel list for use later */
912 vacrelstats->ntups = ntups;
913 vacrelstats->npages = nblocks;
914 /* vacrelstats->natts = attr_cnt;*/
916 min_tlen = max_tlen = 0;
917 vacrelstats->min_tlen = min_tlen;
918 vacrelstats->max_tlen = max_tlen;
920 Vvpl->vpl_nemend = nemend;
921 Fvpl->vpl_nemend = nemend;
924 * Try to make Fvpl keeping in mind that we can't use free space of
925 * "empty" end-pages and last page if it reapped.
927 if (do_shrinking && Vvpl->vpl_npages - nemend > 0)
929 int nusf; /* blocks usefull for re-using */
931 nusf = Vvpl->vpl_npages - nemend;
932 if ((Vvpl->vpl_pgdesc[nusf - 1])->vpd_blkno == nblocks - nemend - 1)
935 for (i = 0; i < nusf; i++)
937 vp = Vvpl->vpl_pgdesc[i];
938 if (vc_enough_space(vp, min_tlen))
940 vc_vpinsert(Fvpl, vp);
941 frsusf += vp->vpd_free;
946 getrusage(RUSAGE_SELF, &ru1);
948 elog(MESSAGE_LEVEL, "Rel %s: Pages %u: Changed %u, Reapped %u, Empty %u, New %u; \
949 Tup %u: Vac %u, Crash %u, UnUsed %u, MinLen %u, MaxLen %u; Re-using: Free/Avail. Space %u/%u; EndEmpty/Avail. Pages %u/%u. Elapsed %u/%u sec.",
951 nblocks, nchpg, Vvpl->vpl_npages, nempg, nnepg,
952 ntups, nvac, ncrash, nunused, min_tlen, max_tlen,
953 frsize, frsusf, nemend, Fvpl->vpl_npages,
954 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
955 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
961 * vc_rpfheap() -- try to repaire relation' fragmentation
963 * This routine marks dead tuples as unused and tries re-use dead space
964 * by moving tuples (and inserting indices if needed). It constructs
965 * Nvpl list of free-ed pages (moved tuples) and clean indices
966 * for them after committing (in hack-manner - without losing locks
967 * and freeing memory!) current transaction. It truncates relation
968 * if some end-blocks are gone away.
971 vc_rpfheap(VRelStats *vacrelstats, Relation onerel,
972 VPageList Vvpl, VPageList Fvpl, int nindices, Relation *Irel)
976 AbsoluteTime myCTM = 0;
983 OffsetNumber offnum = 0,
991 TupleDesc tupdesc = NULL;
992 Datum *idatum = NULL;
994 InsertIndexResult iresult;
996 VPageDescr ToVpd = NULL,
1019 getrusage(RUSAGE_SELF, &ru0);
1021 myXID = GetCurrentTransactionId();
1022 myCID = GetCurrentCommandId();
1024 if (Irel != (Relation *) NULL) /* preparation for index' inserts */
1026 vc_mkindesc(onerel, nindices, Irel, &Idesc);
1027 tupdesc = RelationGetTupleDescriptor(onerel);
1028 idatum = (Datum *) palloc(INDEX_MAX_KEYS * sizeof(*idatum));
1029 inulls = (char *) palloc(INDEX_MAX_KEYS * sizeof(*inulls));
1032 /* if the relation has an archive, open it */
1033 if (onerel->rd_rel->relarch != 'n')
1035 archrel = vc_getarchrel(onerel);
1036 /* Archive tuples from "empty" end-pages */
1037 for (vpp = Vvpl->vpl_pgdesc + Vvpl->vpl_npages - 1,
1038 i = Vvpl->vpl_nemend; i > 0; i--, vpp--)
1040 if ((*vpp)->vpd_noff > 0)
1042 buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1043 page = BufferGetPage(buf);
1044 Assert(!PageIsEmpty(page));
1045 vc_vacpage(page, *vpp, archrel);
1051 archrel = (Relation) NULL;
1053 Nvpl.vpl_npages = 0;
1054 Fnpages = Fvpl->vpl_npages;
1055 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1056 Fblklast = Fvplast->vpd_blkno;
1057 Assert(Vvpl->vpl_npages > Vvpl->vpl_nemend);
1058 Vnpages = Vvpl->vpl_npages - Vvpl->vpl_nemend;
1059 Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
1060 Vblklast = Vvplast->vpd_blkno;
1061 Assert(Vblklast >= Fblklast);
1062 ToBuf = InvalidBuffer;
1065 vpc = (VPageDescr) palloc(sizeof(VPageDescrData) + MaxOffsetNumber * sizeof(OffsetNumber));
1066 vpc->vpd_nusd = vpc->vpd_noff = 0;
1068 nblocks = vacrelstats->npages;
1069 for (blkno = nblocks - Vvpl->vpl_nemend - 1;; blkno--)
1071 /* if it's reapped page and it was used by me - quit */
1072 if (blkno == Fblklast && Fvplast->vpd_nusd > 0)
1075 buf = ReadBuffer(onerel, blkno);
1076 page = BufferGetPage(buf);
1080 isempty = PageIsEmpty(page);
1083 if (blkno == Vblklast) /* it's reapped page */
1085 if (Vvplast->vpd_noff > 0) /* there are dead tuples */
1086 { /* on this page - clean */
1088 vc_vacpage(page, Vvplast, archrel);
1096 Assert(Vnpages > 0);
1097 /* get prev reapped page from Vvpl */
1098 Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
1099 Vblklast = Vvplast->vpd_blkno;
1100 if (blkno == Fblklast) /* this page in Fvpl too */
1103 Assert(Fnpages > 0);
1104 Assert(Fvplast->vpd_nusd == 0);
1105 /* get prev reapped page from Fvpl */
1106 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1107 Fblklast = Fvplast->vpd_blkno;
1109 Assert(Fblklast <= Vblklast);
1121 vpc->vpd_blkno = blkno;
1122 maxoff = PageGetMaxOffsetNumber(page);
1123 for (offnum = FirstOffsetNumber;
1125 offnum = OffsetNumberNext(offnum))
1127 itemid = PageGetItemId(page, offnum);
1129 if (!ItemIdIsUsed(itemid))
1132 htup = (HeapTuple) PageGetItem(page, itemid);
1135 /* try to find new page for this tuple */
1136 if (ToBuf == InvalidBuffer ||
1137 !vc_enough_space(ToVpd, tlen))
1139 if (ToBuf != InvalidBuffer)
1142 ToBuf = InvalidBuffer;
1145 * If no one tuple can't be added to this page -
1146 * remove page from Fvpl. - vadim 11/27/96
1148 if (!vc_enough_space(ToVpd, vacrelstats->min_tlen))
1150 if (ToVpd != Fvplast)
1152 Assert(Fnpages > ToVpI + 1);
1153 memmove(Fvpl->vpl_pgdesc + ToVpI,
1154 Fvpl->vpl_pgdesc + ToVpI + 1,
1155 sizeof(VPageDescr *) * (Fnpages - ToVpI - 1));
1157 Assert(Fnpages >= 1);
1161 /* get prev reapped page from Fvpl */
1162 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1163 Fblklast = Fvplast->vpd_blkno;
1166 for (i = 0; i < Fnpages; i++)
1168 if (vc_enough_space(Fvpl->vpl_pgdesc[i], tlen))
1172 break; /* can't move item anywhere */
1174 ToVpd = Fvpl->vpl_pgdesc[ToVpI];
1175 ToBuf = ReadBuffer(onerel, ToVpd->vpd_blkno);
1176 ToPage = BufferGetPage(ToBuf);
1177 /* if this page was not used before - clean it */
1178 if (!PageIsEmpty(ToPage) && ToVpd->vpd_nusd == 0)
1179 vc_vacpage(ToPage, ToVpd, archrel);
1183 newtup = (HeapTuple) palloc(tlen);
1184 memmove((char *) newtup, (char *) htup, tlen);
1186 /* store transaction information */
1187 TransactionIdStore(myXID, &(newtup->t_xmin));
1188 newtup->t_cmin = myCID;
1189 StoreInvalidTransactionId(&(newtup->t_xmax));
1190 newtup->t_tmin = INVALID_ABSTIME;
1191 newtup->t_tmax = CURRENT_ABSTIME;
1192 ItemPointerSetInvalid(&newtup->t_chain);
1194 /* add tuple to the page */
1195 newoff = PageAddItem(ToPage, (Item) newtup, tlen,
1196 InvalidOffsetNumber, LP_USED);
1197 if (newoff == InvalidOffsetNumber)
1200 failed to add item with len = %u to page %u (free space %u, nusd %u, noff %u)",
1201 tlen, ToVpd->vpd_blkno, ToVpd->vpd_free,
1202 ToVpd->vpd_nusd, ToVpd->vpd_noff);
1204 newitemid = PageGetItemId(ToPage, newoff);
1206 newtup = (HeapTuple) PageGetItem(ToPage, newitemid);
1207 ItemPointerSet(&(newtup->t_ctid), ToVpd->vpd_blkno, newoff);
1209 /* now logically delete end-tuple */
1210 TransactionIdStore(myXID, &(htup->t_xmax));
1211 htup->t_cmax = myCID;
1212 memmove((char *) &(htup->t_chain), (char *) &(newtup->t_ctid), sizeof(newtup->t_ctid));
1216 ToVpd->vpd_free = ((PageHeader) ToPage)->pd_upper - ((PageHeader) ToPage)->pd_lower;
1217 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
1219 /* insert index' tuples if needed */
1220 if (Irel != (Relation *) NULL)
1222 for (i = 0, idcur = Idesc; i < nindices; i++, idcur++)
1226 (AttrNumber *) &(idcur->tform->indkey[0]),
1233 iresult = index_insert(
1244 } /* walk along page */
1246 if (vpc->vpd_noff > 0) /* some tuples were moved */
1248 vc_reappage(&Nvpl, vpc);
1256 if (offnum <= maxoff)
1257 break; /* some item(s) left */
1259 } /* walk along relation */
1261 blkno++; /* new number of blocks */
1263 if (ToBuf != InvalidBuffer)
1273 * We have to commit our tuple' movings before we'll truncate
1274 * relation, but we shouldn't lose our locks. And so - quick hack:
1275 * flush buffers and record status of current transaction as
1276 * committed, and continue. - vadim 11/13/96
1278 FlushBufferPool(!TransactionFlushEnabled());
1279 TransactionIdCommit(myXID);
1280 FlushBufferPool(!TransactionFlushEnabled());
1281 myCTM = TransactionIdGetCommitTime(myXID);
1285 * Clean uncleaned reapped pages from Vvpl list and set commit' times
1286 * for inserted tuples
1289 for (i = 0, vpp = Vvpl->vpl_pgdesc; i < Vnpages; i++, vpp++)
1291 Assert((*vpp)->vpd_blkno < blkno);
1292 buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1293 page = BufferGetPage(buf);
1294 if ((*vpp)->vpd_nusd == 0) /* this page was not used */
1298 * noff == 0 in empty pages only - such pages should be
1301 Assert((*vpp)->vpd_noff > 0);
1302 vc_vacpage(page, *vpp, archrel);
1305 /* this page was used */
1308 moff = PageGetMaxOffsetNumber(page);
1309 for (newoff = FirstOffsetNumber;
1311 newoff = OffsetNumberNext(newoff))
1313 itemid = PageGetItemId(page, newoff);
1314 if (!ItemIdIsUsed(itemid))
1316 htup = (HeapTuple) PageGetItem(page, itemid);
1317 if (TransactionIdEquals((TransactionId) htup->t_xmin, myXID))
1319 htup->t_tmin = myCTM;
1323 Assert((*vpp)->vpd_nusd == ntups);
1328 Assert(nmoved == nchkmvd);
1330 getrusage(RUSAGE_SELF, &ru1);
1332 elog(MESSAGE_LEVEL, "Rel %s: Pages: %u --> %u; Tuple(s) moved: %u. \
1333 Elapsed %u/%u sec.",
1334 (RelationGetRelationName(onerel))->data,
1335 nblocks, blkno, nmoved,
1336 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1337 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1339 if (Nvpl.vpl_npages > 0)
1341 /* vacuum indices again if needed */
1342 if (Irel != (Relation *) NULL)
1348 /* re-sort Nvpl.vpl_pgdesc */
1349 for (vpleft = Nvpl.vpl_pgdesc,
1350 vpright = Nvpl.vpl_pgdesc + Nvpl.vpl_npages - 1;
1351 vpleft < vpright; vpleft++, vpright--)
1357 for (i = 0; i < nindices; i++)
1358 vc_vaconeind(&Nvpl, Irel[i], vacrelstats->ntups);
1362 * clean moved tuples from last page in Nvpl list if some tuples
1365 if (vpc->vpd_noff > 0 && offnum <= maxoff)
1367 Assert(vpc->vpd_blkno == blkno - 1);
1368 buf = ReadBuffer(onerel, vpc->vpd_blkno);
1369 page = BufferGetPage(buf);
1372 for (offnum = FirstOffsetNumber;
1374 offnum = OffsetNumberNext(offnum))
1376 itemid = PageGetItemId(page, offnum);
1377 if (!ItemIdIsUsed(itemid))
1379 htup = (HeapTuple) PageGetItem(page, itemid);
1380 Assert(TransactionIdEquals((TransactionId) htup->t_xmax, myXID));
1381 itemid->lp_flags &= ~LP_USED;
1384 Assert(vpc->vpd_noff == ntups);
1385 PageRepairFragmentation(page);
1389 /* now - free new list of reapped pages */
1390 vpp = Nvpl.vpl_pgdesc;
1391 for (i = 0; i < Nvpl.vpl_npages; i++, vpp++)
1393 pfree(Nvpl.vpl_pgdesc);
1396 /* truncate relation */
1397 if (blkno < nblocks)
1399 i = BlowawayRelationBuffers(onerel, blkno);
1401 elog (FATAL, "VACUUM (vc_rpfheap): BlowawayRelationBuffers returned %d", i);
1402 blkno = smgrtruncate(onerel->rd_rel->relsmgr, onerel, blkno);
1404 vacrelstats->npages = blkno; /* set new number of blocks */
1407 if (archrel != (Relation) NULL)
1408 heap_close(archrel);
1410 if (Irel != (Relation *) NULL) /* pfree index' allocations */
1415 vc_clsindices(nindices, Irel);
1423 * vc_vacheap() -- free dead tuples
1425 * This routine marks dead tuples as unused and truncates relation
1426 * if there are "empty" end-blocks.
1429 vc_vacheap(VRelStats *vacrelstats, Relation onerel, VPageList Vvpl)
1438 nblocks = Vvpl->vpl_npages;
1439 /* if the relation has an archive, open it */
1440 if (onerel->rd_rel->relarch != 'n')
1441 archrel = vc_getarchrel(onerel);
1444 archrel = (Relation) NULL;
1445 nblocks -= Vvpl->vpl_nemend; /* nothing to do with them */
1448 for (i = 0, vpp = Vvpl->vpl_pgdesc; i < nblocks; i++, vpp++)
1450 if ((*vpp)->vpd_noff > 0)
1452 buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1453 page = BufferGetPage(buf);
1454 vc_vacpage(page, *vpp, archrel);
1459 /* truncate relation if there are some empty end-pages */
1460 if (Vvpl->vpl_nemend > 0)
1462 Assert(vacrelstats->npages >= Vvpl->vpl_nemend);
1463 nblocks = vacrelstats->npages - Vvpl->vpl_nemend;
1464 elog(MESSAGE_LEVEL, "Rel %s: Pages: %u --> %u.",
1465 (RelationGetRelationName(onerel))->data,
1466 vacrelstats->npages, nblocks);
1469 * we have to flush "empty" end-pages (if changed, but who knows
1470 * it) before truncation
1472 FlushBufferPool(!TransactionFlushEnabled());
1474 i = BlowawayRelationBuffers(onerel, nblocks);
1476 elog (FATAL, "VACUUM (vc_vacheap): BlowawayRelationBuffers returned %d", i);
1478 nblocks = smgrtruncate(onerel->rd_rel->relsmgr, onerel, nblocks);
1479 Assert(nblocks >= 0);
1480 vacrelstats->npages = nblocks; /* set new number of blocks */
1483 if (archrel != (Relation) NULL)
1484 heap_close(archrel);
1489 * vc_vacpage() -- free (and archive if needed) dead tuples on a page
1490 * and repaire its fragmentation.
1493 vc_vacpage(Page page, VPageDescr vpd, Relation archrel)
1499 Assert(vpd->vpd_nusd == 0);
1500 for (i = 0; i < vpd->vpd_noff; i++)
1502 itemid = &(((PageHeader) page)->pd_linp[vpd->vpd_voff[i] - 1]);
1503 if (archrel != (Relation) NULL && ItemIdIsUsed(itemid))
1505 htup = (HeapTuple) PageGetItem(page, itemid);
1506 vc_archive(archrel, htup);
1508 itemid->lp_flags &= ~LP_USED;
1510 PageRepairFragmentation(page);
1515 * _vc_scanoneind() -- scan one index relation to update statistic.
1519 vc_scanoneind(Relation indrel, int nhtups)
1521 RetrieveIndexResult res;
1522 IndexScanDesc iscan;
1528 getrusage(RUSAGE_SELF, &ru0);
1530 /* walk through the entire index */
1531 iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
1534 while ((res = index_getnext(iscan, ForwardScanDirection))
1535 != (RetrieveIndexResult) NULL)
1541 index_endscan(iscan);
1543 /* now update statistics in pg_class */
1544 nipages = RelationGetNumberOfBlocks(indrel);
1545 vc_updstats(indrel->rd_id, nipages, nitups, false, NULL);
1547 getrusage(RUSAGE_SELF, &ru1);
1549 elog(MESSAGE_LEVEL, "Ind %s: Pages %u; Tuples %u. Elapsed %u/%u sec.",
1550 indrel->rd_rel->relname.data, nipages, nitups,
1551 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1552 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1554 if (nitups != nhtups)
1555 elog(NOTICE, "Ind %s: NUMBER OF INDEX' TUPLES (%u) IS NOT THE SAME AS HEAP' (%u)",
1556 indrel->rd_rel->relname.data, nitups, nhtups);
1558 } /* vc_scanoneind */
1561 * vc_vaconeind() -- vacuum one index relation.
1563 * Vpl is the VPageList of the heap we're currently vacuuming.
1564 * It's locked. Indrel is an index relation on the vacuumed heap.
1565 * We don't set locks on the index relation here, since the indexed
1566 * access methods support locking at different granularities.
1567 * We let them handle it.
1569 * Finally, we arrange to update the index relation's statistics in
1573 vc_vaconeind(VPageList vpl, Relation indrel, int nhtups)
1575 RetrieveIndexResult res;
1576 IndexScanDesc iscan;
1577 ItemPointer heapptr;
1585 getrusage(RUSAGE_SELF, &ru0);
1587 /* walk through the entire index */
1588 iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
1592 while ((res = index_getnext(iscan, ForwardScanDirection))
1593 != (RetrieveIndexResult) NULL)
1595 heapptr = &res->heap_iptr;
1597 if ((vp = vc_tidreapped(heapptr, vpl)) != (VPageDescr) NULL)
1600 elog(DEBUG, "<%x,%x> -> <%x,%x>",
1601 ItemPointerGetBlockNumber(&(res->index_iptr)),
1602 ItemPointerGetOffsetNumber(&(res->index_iptr)),
1603 ItemPointerGetBlockNumber(&(res->heap_iptr)),
1604 ItemPointerGetOffsetNumber(&(res->heap_iptr)));
1606 if (vp->vpd_noff == 0)
1607 { /* this is EmptyPage !!! */
1608 elog(NOTICE, "Ind %s: pointer to EmptyPage (blk %u off %u) - fixing",
1609 indrel->rd_rel->relname.data,
1610 vp->vpd_blkno, ItemPointerGetOffsetNumber(heapptr));
1613 index_delete(indrel, &res->index_iptr);
1624 index_endscan(iscan);
1626 /* now update statistics in pg_class */
1627 nipages = RelationGetNumberOfBlocks(indrel);
1628 vc_updstats(indrel->rd_id, nipages, nitups, false, NULL);
1630 getrusage(RUSAGE_SELF, &ru1);
1632 elog(MESSAGE_LEVEL, "Ind %s: Pages %u; Tuples %u: Deleted %u. Elapsed %u/%u sec.",
1633 indrel->rd_rel->relname.data, nipages, nitups, nvac,
1634 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1635 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1637 if (nitups != nhtups)
1638 elog(NOTICE, "Ind %s: NUMBER OF INDEX' TUPLES (%u) IS NOT THE SAME AS HEAP' (%u)",
1639 indrel->rd_rel->relname.data, nitups, nhtups);
1641 } /* vc_vaconeind */
1644 * vc_tidreapped() -- is a particular tid reapped?
1646 * vpl->VPageDescr_array is sorted in right order.
1649 vc_tidreapped(ItemPointer itemptr, VPageList vpl)
1651 OffsetNumber ioffno;
1657 vpd.vpd_blkno = ItemPointerGetBlockNumber(itemptr);
1658 ioffno = ItemPointerGetOffsetNumber(itemptr);
1661 vpp = (VPageDescr *) vc_find_eq((char *) (vpl->vpl_pgdesc),
1662 vpl->vpl_npages, sizeof(VPageDescr), (char *) &vp,
1665 if (vpp == (VPageDescr *) NULL)
1666 return ((VPageDescr) NULL);
1669 /* ok - we are on true page */
1671 if (vp->vpd_noff == 0)
1672 { /* this is EmptyPage !!! */
1676 voff = (OffsetNumber *) vc_find_eq((char *) (vp->vpd_voff),
1677 vp->vpd_noff, sizeof(OffsetNumber), (char *) &ioffno,
1680 if (voff == (OffsetNumber *) NULL)
1681 return ((VPageDescr) NULL);
1685 } /* vc_tidreapped */
1688 * vc_attrstats() -- compute column statistics used by the optimzer
1690 * We compute the column min, max, null and non-null counts.
1691 * Plus we attempt to find the count of the value that occurs most
1692 * frequently in each column
1693 * These figures are used to compute the selectivity of the column
1695 * We use a three-bucked cache to get the most frequent item
1696 * The 'guess' buckets count hits. A cache miss causes guess1
1697 * to get the most hit 'guess' item in the most recent cycle, and
1698 * the new item goes into guess2. Whenever the total count of hits
1699 * of a 'guess' entry is larger than 'best', 'guess' becomes 'best'.
1701 * This method works perfectly for columns with unique values, and columns
1702 * with only two unique values, plus nulls.
1704 * It becomes less perfect as the number of unique values increases and
1705 * their distribution in the table becomes more random.
1709 vc_attrstats(Relation onerel, VRelStats *vacrelstats, HeapTuple htup)
1712 attr_cnt = vacrelstats->va_natts;
1713 VacAttrStats *vacattrstats = vacrelstats->vacattrstats;
1714 TupleDesc tupDesc = onerel->rd_att;
1718 for (i = 0; i < attr_cnt; i++)
1720 VacAttrStats *stats = &vacattrstats[i];
1721 bool value_hit = true;
1723 value = heap_getattr(htup, InvalidBuffer,
1724 stats->attr->attnum, tupDesc, &isnull);
1726 if (!VacAttrStatsEqValid(stats))
1733 stats->nonnull_cnt++;
1734 if (stats->initialized == false)
1736 vc_bucketcpy(stats->attr, value, &stats->best, &stats->best_len);
1737 /* best_cnt gets incremented later */
1738 vc_bucketcpy(stats->attr, value, &stats->guess1, &stats->guess1_len);
1739 stats->guess1_cnt = stats->guess1_hits = 1;
1740 vc_bucketcpy(stats->attr, value, &stats->guess2, &stats->guess2_len);
1741 stats->guess2_hits = 1;
1742 if (VacAttrStatsLtGtValid(stats))
1744 vc_bucketcpy(stats->attr, value, &stats->max, &stats->max_len);
1745 vc_bucketcpy(stats->attr, value, &stats->min, &stats->min_len);
1747 stats->initialized = true;
1749 if (VacAttrStatsLtGtValid(stats))
1751 if ((*(stats->f_cmplt)) (value, stats->min))
1753 vc_bucketcpy(stats->attr, value, &stats->min, &stats->min_len);
1756 if ((*(stats->f_cmpgt)) (value, stats->max))
1758 vc_bucketcpy(stats->attr, value, &stats->max, &stats->max_len);
1761 if ((*(stats->f_cmpeq)) (value, stats->min))
1763 else if ((*(stats->f_cmpeq)) (value, stats->max))
1766 if ((*(stats->f_cmpeq)) (value, stats->best))
1768 else if ((*(stats->f_cmpeq)) (value, stats->guess1))
1770 stats->guess1_cnt++;
1771 stats->guess1_hits++;
1773 else if ((*(stats->f_cmpeq)) (value, stats->guess2))
1774 stats->guess2_hits++;
1778 if (stats->guess2_hits > stats->guess1_hits)
1780 swapDatum(stats->guess1, stats->guess2);
1781 swapInt(stats->guess1_len, stats->guess2_len);
1782 stats->guess1_cnt = stats->guess2_hits;
1783 swapLong(stats->guess1_hits, stats->guess2_hits);
1785 if (stats->guess1_cnt > stats->best_cnt)
1787 swapDatum(stats->best, stats->guess1);
1788 swapInt(stats->best_len, stats->guess1_len);
1789 swapLong(stats->best_cnt, stats->guess1_cnt);
1790 stats->guess1_hits = 1;
1791 stats->guess2_hits = 1;
1795 vc_bucketcpy(stats->attr, value, &stats->guess2, &stats->guess2_len);
1796 stats->guess1_hits = 1;
1797 stats->guess2_hits = 1;
1805 * vc_bucketcpy() -- update pg_class statistics for one relation
1809 vc_bucketcpy(AttributeTupleForm attr, Datum value, Datum *bucket, int16 *bucket_len)
1811 if (attr->attbyval && attr->attlen != -1)
1815 int len = (attr->attlen != -1 ? attr->attlen : VARSIZE(value));
1817 if (len > *bucket_len)
1819 if (*bucket_len != 0)
1820 pfree(DatumGetPointer(*bucket));
1821 *bucket = PointerGetDatum(palloc(len));
1824 memmove(DatumGetPointer(*bucket), DatumGetPointer(value), len);
1829 * vc_updstats() -- update pg_class statistics for one relation
1831 * This routine works for both index and heap relation entries in
1832 * pg_class. We violate no-overwrite semantics here by storing new
1833 * values for ntups, npages, and hasindex directly in the pg_class
1834 * tuple that's already on the page. The reason for this is that if
1835 * we updated these tuples in the usual way, then every tuple in pg_class
1836 * would be replaced every day. This would make planning and executing
1837 * historical queries very expensive.
1840 vc_updstats(Oid relid, int npages, int ntups, bool hasindex, VRelStats *vacrelstats)
1845 HeapScanDesc rsdesc,
1853 Form_pg_class pgcform;
1856 AttributeTupleForm attp;
1859 * update number of tuples and number of pages in pg_class
1861 ScanKeyEntryInitialize(&rskey, 0x0, ObjectIdAttributeNumber,
1862 ObjectIdEqualRegProcedure,
1863 ObjectIdGetDatum(relid));
1865 rd = heap_openr(RelationRelationName);
1866 rsdesc = heap_beginscan(rd, false, NowTimeQual, 1, &rskey);
1868 if (!HeapTupleIsValid(rtup = heap_getnext(rsdesc, 0, &rbuf)))
1869 elog(WARN, "pg_class entry for relid %d vanished during vacuuming",
1872 /* overwrite the existing statistics in the tuple */
1873 vc_setpagelock(rd, BufferGetBlockNumber(rbuf));
1874 pgcform = (Form_pg_class) GETSTRUCT(rtup);
1875 pgcform->reltuples = ntups;
1876 pgcform->relpages = npages;
1877 pgcform->relhasindex = hasindex;
1879 if (vacrelstats != NULL && vacrelstats->va_natts > 0)
1881 VacAttrStats *vacattrstats = vacrelstats->vacattrstats;
1882 int natts = vacrelstats->va_natts;
1884 ad = heap_openr(AttributeRelationName);
1885 sd = heap_openr(StatisticRelationName);
1886 ScanKeyEntryInitialize(&askey, 0, Anum_pg_attribute_attrelid,
1889 asdesc = heap_beginscan(ad, false, NowTimeQual, 1, &askey);
1891 while (HeapTupleIsValid(atup = heap_getnext(asdesc, 0, &abuf)))
1894 float32data selratio; /* average ratio of rows selected
1895 * for a random constant */
1896 VacAttrStats *stats;
1897 Datum values[Natts_pg_statistic];
1898 char nulls[Natts_pg_statistic];
1900 attp = (AttributeTupleForm) GETSTRUCT(atup);
1901 if (attp->attnum <= 0) /* skip system attributes for now, */
1902 /* they are unique anyway */
1905 for (i = 0; i < natts; i++)
1907 if (attp->attnum == vacattrstats[i].attr->attnum)
1912 stats = &(vacattrstats[i]);
1914 /* overwrite the existing statistics in the tuple */
1915 if (VacAttrStatsEqValid(stats))
1918 vc_setpagelock(ad, BufferGetBlockNumber(abuf));
1920 if (stats->nonnull_cnt + stats->null_cnt == 0 ||
1921 (stats->null_cnt <= 1 && stats->best_cnt == 1))
1923 else if (VacAttrStatsLtGtValid(stats) && stats->min_cnt + stats->max_cnt == stats->nonnull_cnt)
1925 double min_cnt_d = stats->min_cnt,
1926 max_cnt_d = stats->max_cnt,
1927 null_cnt_d = stats->null_cnt,
1928 nonnullcnt_d = stats->nonnull_cnt; /* prevent overflow */
1930 selratio = (min_cnt_d * min_cnt_d + max_cnt_d * max_cnt_d + null_cnt_d * null_cnt_d) /
1931 (nonnullcnt_d + null_cnt_d) / (nonnullcnt_d + null_cnt_d);
1935 double most = (double) (stats->best_cnt > stats->null_cnt ? stats->best_cnt : stats->null_cnt);
1936 double total = ((double) stats->nonnull_cnt) + ((double) stats->null_cnt);
1939 * we assume count of other values are 20% of best
1942 selratio = (most * most + 0.20 * most * (total - most)) / total / total;
1946 attp->attdisbursion = selratio;
1947 WriteNoReleaseBuffer(abuf);
1949 /* DO PG_STATISTIC INSERTS */
1952 * doing system relations, especially pg_statistic is a
1955 if (VacAttrStatsLtGtValid(stats) && stats->initialized /* &&
1956 * !IsSystemRelationName(
1958 pgcform->relname.data) */ )
1960 func_ptr out_function;
1964 for (i = 0; i < Natts_pg_statistic; ++i)
1968 * initialize values[]
1972 values[i++] = (Datum) relid; /* 1 */
1973 values[i++] = (Datum) attp->attnum; /* 2 */
1974 values[i++] = (Datum) InvalidOid; /* 3 */
1975 fmgr_info(stats->outfunc, &out_function, &dummy);
1976 out_string = (*out_function) (stats->min, stats->attr->atttypid);
1977 values[i++] = (Datum) fmgr(TextInRegProcedure, out_string);
1979 out_string = (char *) (*out_function) (stats->max, stats->attr->atttypid);
1980 values[i++] = (Datum) fmgr(TextInRegProcedure, out_string);
1985 stup = heap_formtuple(sdesc, values, nulls);
1988 * insert the tuple in the relation and get the tuple's oid.
1991 heap_insert(sd, stup);
1992 pfree(DatumGetPointer(values[3]));
1993 pfree(DatumGetPointer(values[4]));
1998 heap_endscan(asdesc);
2003 /* XXX -- after write, should invalidate relcache in other backends */
2004 WriteNoReleaseBuffer(rbuf); /* heap_endscan release scan' buffers ? */
2007 * invalidating system relations confuses the function cache of
2008 * pg_operator and pg_opclass
2010 if (!IsSystemRelationName(pgcform->relname.data))
2011 RelationInvalidateHeapTuple(rd, rtup);
2013 /* that's all, folks */
2014 heap_endscan(rsdesc);
2019 * vc_delhilowstats() -- delete pg_statistics rows
2023 vc_delhilowstats(Oid relid, int attcnt, int *attnums)
2025 Relation pgstatistic;
2026 HeapScanDesc pgsscan;
2030 pgstatistic = heap_openr(StatisticRelationName);
2032 if (relid != InvalidOid)
2034 ScanKeyEntryInitialize(&pgskey, 0x0, Anum_pg_statistic_starelid,
2035 ObjectIdEqualRegProcedure,
2036 ObjectIdGetDatum(relid));
2037 pgsscan = heap_beginscan(pgstatistic, false, NowTimeQual, 1, &pgskey);
2040 pgsscan = heap_beginscan(pgstatistic, false, NowTimeQual, 0, NULL);
2042 while (HeapTupleIsValid(pgstup = heap_getnext(pgsscan, 0, NULL)))
2046 Form_pg_statistic pgs = (Form_pg_statistic) GETSTRUCT(pgstup);
2049 for (i = 0; i < attcnt; i++)
2051 if (pgs->staattnum == attnums[i] + 1)
2055 continue; /* don't delete it */
2057 heap_delete(pgstatistic, &pgstup->t_ctid);
2060 heap_endscan(pgsscan);
2061 heap_close(pgstatistic);
2065 vc_setpagelock(Relation rel, BlockNumber blkno)
2067 ItemPointerData itm;
2069 ItemPointerSet(&itm, blkno, 1);
2071 RelationSetLockForWritePage(rel, &itm);
2075 * vc_reappage() -- save a page on the array of reapped pages.
2077 * As a side effect of the way that the vacuuming loop for a given
2078 * relation works, higher pages come after lower pages in the array
2079 * (and highest tid on a page is last).
2082 vc_reappage(VPageList vpl, VPageDescr vpc)
2086 /* allocate a VPageDescrData entry */
2087 newvpd = (VPageDescr) palloc(sizeof(VPageDescrData) + vpc->vpd_noff * sizeof(OffsetNumber));
2090 if (vpc->vpd_noff > 0)
2091 memmove(newvpd->vpd_voff, vpc->vpd_voff, vpc->vpd_noff * sizeof(OffsetNumber));
2092 newvpd->vpd_blkno = vpc->vpd_blkno;
2093 newvpd->vpd_free = vpc->vpd_free;
2094 newvpd->vpd_nusd = vpc->vpd_nusd;
2095 newvpd->vpd_noff = vpc->vpd_noff;
2097 /* insert this page into vpl list */
2098 vc_vpinsert(vpl, newvpd);
2103 vc_vpinsert(VPageList vpl, VPageDescr vpnew)
2106 /* allocate a VPageDescr entry if needed */
2107 if (vpl->vpl_npages == 0)
2108 vpl->vpl_pgdesc = (VPageDescr *) palloc(100 * sizeof(VPageDescr));
2109 else if (vpl->vpl_npages % 100 == 0)
2110 vpl->vpl_pgdesc = (VPageDescr *) repalloc(vpl->vpl_pgdesc, (vpl->vpl_npages + 100) * sizeof(VPageDescr));
2111 vpl->vpl_pgdesc[vpl->vpl_npages] = vpnew;
2112 (vpl->vpl_npages)++;
2117 vc_free(VRelList vrl)
2121 PortalVariableMemory pmem;
2123 pmem = PortalGetVariableMemory(vc_portal);
2124 old = MemoryContextSwitchTo((MemoryContext) pmem);
2126 while (vrl != (VRelList) NULL)
2129 /* free rel list entry */
2131 vrl = vrl->vrl_next;
2135 MemoryContextSwitchTo(old);
2139 * vc_getarchrel() -- open the archive relation for a heap relation
2141 * The archive relation is named 'a,XXXXX' for the heap relation
2142 * whose relid is XXXXX.
2145 #define ARCHIVE_PREFIX "a,"
2148 vc_getarchrel(Relation heaprel)
2153 archrelname = palloc(sizeof(ARCHIVE_PREFIX) + NAMEDATALEN); /* bogus */
2154 sprintf(archrelname, "%s%d", ARCHIVE_PREFIX, heaprel->rd_id);
2156 archrel = heap_openr(archrelname);
2163 * vc_archive() -- write a tuple to an archive relation
2165 * In the future, this will invoke the archived accessd method. For
2166 * now, archive relations are on mag disk.
2169 vc_archive(Relation archrel, HeapTuple htup)
2171 doinsert(archrel, htup);
2175 vc_isarchrel(char *rname)
2177 if (strncmp(ARCHIVE_PREFIX, rname, strlen(ARCHIVE_PREFIX)) == 0)
2184 vc_find_eq(char *bot, int nelem, int size, char *elm, int (*compar) (char *, char *))
2187 int last = nelem - 1;
2188 int celm = nelem / 2;
2192 last_move = first_move = true;
2195 if (first_move == true)
2197 res = compar(bot, elm);
2204 if (last_move == true)
2206 res = compar(elm, bot + last * size);
2210 return (bot + last * size);
2213 res = compar(elm, bot + celm * size);
2215 return (bot + celm * size);
2229 last = last - celm - 1;
2230 bot = bot + (celm + 1) * size;
2231 celm = (last + 1) / 2;
2238 vc_cmp_blk(char *left, char *right)
2243 lblk = (*((VPageDescr *) left))->vpd_blkno;
2244 rblk = (*((VPageDescr *) right))->vpd_blkno;
2255 vc_cmp_offno(char *left, char *right)
2258 if (*(OffsetNumber *) left < *(OffsetNumber *) right)
2260 if (*(OffsetNumber *) left == *(OffsetNumber *) right)
2264 } /* vc_cmp_offno */
2268 vc_getindices(Oid relid, int *nindices, Relation **Irel)
2274 HeapScanDesc pgiscan;
2284 ioid = (Oid *) palloc(10 * sizeof(Oid));
2286 /* prepare a heap scan on the pg_index relation */
2287 pgindex = heap_openr(IndexRelationName);
2288 pgidesc = RelationGetTupleDescriptor(pgindex);
2290 ScanKeyEntryInitialize(&pgikey, 0x0, Anum_pg_index_indrelid,
2291 ObjectIdEqualRegProcedure,
2292 ObjectIdGetDatum(relid));
2294 pgiscan = heap_beginscan(pgindex, false, NowTimeQual, 1, &pgikey);
2296 while (HeapTupleIsValid(pgitup = heap_getnext(pgiscan, 0, NULL)))
2298 d = heap_getattr(pgitup, InvalidBuffer, Anum_pg_index_indexrelid,
2302 ioid = (Oid *) repalloc(ioid, (i + 10) * sizeof(Oid));
2303 ioid[i - 1] = DatumGetObjectId(d);
2306 heap_endscan(pgiscan);
2307 heap_close(pgindex);
2310 { /* No one index found */
2315 if (Irel != (Relation **) NULL)
2316 *Irel = (Relation *) palloc(i * sizeof(Relation));
2320 irel = index_open(ioid[--i]);
2321 if (irel != (Relation) NULL)
2323 if (Irel != (Relation **) NULL)
2330 elog(NOTICE, "CAN't OPEN INDEX %u - SKIP IT", ioid[i]);
2335 if (Irel != (Relation **) NULL && *nindices == 0)
2338 *Irel = (Relation *) NULL;
2341 } /* vc_getindices */
2345 vc_clsindices(int nindices, Relation *Irel)
2348 if (Irel == (Relation *) NULL)
2353 index_close(Irel[nindices]);
2357 } /* vc_clsindices */
2361 vc_mkindesc(Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc)
2364 HeapTuple pgIndexTup;
2365 AttrNumber *attnumP;
2369 *Idesc = (IndDesc *) palloc(nindices * sizeof(IndDesc));
2371 for (i = 0, idcur = *Idesc; i < nindices; i++, idcur++)
2374 SearchSysCacheTuple(INDEXRELID,
2375 ObjectIdGetDatum(Irel[i]->rd_id),
2378 idcur->tform = (IndexTupleForm) GETSTRUCT(pgIndexTup);
2379 for (attnumP = &(idcur->tform->indkey[0]), natts = 0;
2380 *attnumP != InvalidAttrNumber && natts != INDEX_MAX_KEYS;
2381 attnumP++, natts++);
2382 if (idcur->tform->indproc != InvalidOid)
2384 idcur->finfoP = &(idcur->finfo);
2385 FIgetnArgs(idcur->finfoP) = natts;
2387 FIgetProcOid(idcur->finfoP) = idcur->tform->indproc;
2388 *(FIgetname(idcur->finfoP)) = '\0';
2391 idcur->finfoP = (FuncIndexInfo *) NULL;
2393 idcur->natts = natts;
2400 vc_enough_space(VPageDescr vpd, Size len)
2403 len = DOUBLEALIGN(len);
2405 if (len > vpd->vpd_free)
2408 if (vpd->vpd_nusd < vpd->vpd_noff) /* there are free itemid(s) */
2409 return (true); /* and len <= free_space */
2411 /* ok. noff_usd >= noff_free and so we'll have to allocate new itemid */
2412 if (len <= vpd->vpd_free - sizeof(ItemIdData))
2417 } /* vc_enough_space */