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.53 1997/11/25 21:59:09 momjian 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 <parser/parse_oper.h>
40 #include <storage/smgr.h>
41 #include <storage/lmgr.h>
42 #include <utils/inval.h>
43 #include <utils/mcxt.h>
44 #include <utils/inval.h>
45 #include <utils/syscache.h>
46 #include <utils/builtins.h>
47 #include <commands/vacuum.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);
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 void vc_mkindesc(Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc);
100 static char *vc_find_eq(char *bot, int nelem, int size, char *elm, int (*compar) (char *, char *));
101 static int vc_cmp_blk(char *left, char *right);
102 static int vc_cmp_offno(char *left, char *right);
103 static bool vc_enough_space(VPageDescr vpd, Size len);
106 vacuum(char *vacrel, bool verbose, bool analyze, List *va_spec)
110 PortalVariableMemory pmem;
116 * Create a portal for safe memory across transctions. We need to
117 * palloc the name space for it because our hash function expects the
118 * name to be on a longword boundary. CreatePortal copies the name to
119 * safe storage for us.
121 pname = (char *) palloc(strlen(VACPNAME) + 1);
122 strcpy(pname, VACPNAME);
123 vc_portal = CreatePortal(pname);
127 MESSAGE_LEVEL = NOTICE;
129 MESSAGE_LEVEL = DEBUG;
131 /* vacrel gets de-allocated on transaction commit */
133 strcpy(VacRel.data, vacrel);
135 pmem = PortalGetVariableMemory(vc_portal);
136 old = MemoryContextSwitchTo((MemoryContext) pmem);
138 Assert(va_spec == NIL || analyze);
141 char *col = (char *) lfirst(le);
144 dest = (char *) palloc(strlen(col) + 1);
146 va_cols = lappend(va_cols, dest);
148 MemoryContextSwitchTo(old);
150 /* initialize vacuum cleaner */
153 /* vacuum the database */
155 vc_vacuum(&VacRel, analyze, va_cols);
157 vc_vacuum(NULL, analyze, NIL);
159 PortalDestroy(&vc_portal);
166 * vc_init(), vc_shutdown() -- start up and shut down the vacuum cleaner.
168 * We run exactly one vacuum cleaner at a time. We use the file system
169 * to guarantee an exclusive lock on vacuuming, since a single vacuum
170 * cleaner instantiation crosses transaction boundaries, and we'd lose
171 * postgres-style locks at the end of every transaction.
173 * The strangeness with committing and starting transactions in the
174 * init and shutdown routines is due to the fact that the vacuum cleaner
175 * is invoked via a sql command, and so is already executing inside
176 * a transaction. We need to leave ourselves in a predictable state
177 * on entry and exit to the vacuum cleaner. We commit the transaction
178 * started in PostgresMain() inside vc_init(), and start one in
179 * vc_shutdown() to match the commit waiting for us back in
187 if ((fd = open("pg_vlock", O_CREAT | O_EXCL, 0600)) < 0)
188 elog(WARN, "can't create lock file -- another vacuum cleaner running?");
193 * By here, exclusive open on the lock file succeeded. If we abort
194 * for any reason during vacuuming, we need to remove the lock file.
195 * This global variable is checked in the transaction manager on xact
196 * abort, and the routine vc_abort() is called if necessary.
199 VacuumRunning = true;
201 /* matches the StartTransaction in PostgresMain() */
202 CommitTransactionCommand();
208 /* on entry, not in a transaction */
209 if (unlink("pg_vlock") < 0)
210 elog(WARN, "vacuum: can't destroy lock file!");
212 /* okay, we're done */
213 VacuumRunning = false;
215 /* matches the CommitTransaction in PostgresMain() */
216 StartTransactionCommand();
223 /* on abort, remove the vacuum cleaner lock file */
226 VacuumRunning = false;
230 * vc_vacuum() -- vacuum the database.
232 * This routine builds a list of relations to vacuum, and then calls
233 * code that vacuums them one at a time. We are careful to vacuum each
234 * relation in a separate transaction in order to avoid holding too many
238 vc_vacuum(NameData *VacRelP, bool analyze, List *va_cols)
243 /* get list of relations */
244 vrl = vc_getrels(VacRelP);
246 if (analyze && VacRelP == NULL && vrl != NULL)
247 vc_delhilowstats(InvalidOid, 0, NULL);
249 /* vacuum each heap relation */
250 for (cur = vrl; cur != (VRelList) NULL; cur = cur->vrl_next)
251 vc_vacone(cur->vrl_relid, analyze, va_cols);
257 vc_getrels(NameData *VacRelP)
261 HeapScanDesc pgcscan;
264 PortalVariableMemory portalmem;
275 StartTransactionCommand();
279 ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relname,
280 NameEqualRegProcedure,
281 PointerGetDatum(VacRelP->data));
285 ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relkind,
286 CharacterEqualRegProcedure, CharGetDatum('r'));
289 portalmem = PortalGetVariableMemory(vc_portal);
290 vrl = cur = (VRelList) NULL;
292 pgclass = heap_openr(RelationRelationName);
293 pgcdesc = RelationGetTupleDescriptor(pgclass);
295 pgcscan = heap_beginscan(pgclass, false, false, 1, &pgckey);
297 while (HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &buf)))
302 d = heap_getattr(pgctup, buf, Anum_pg_class_relname, pgcdesc, &n);
306 * don't vacuum large objects for now - something breaks when we
309 if ((strlen(rname) >= 5) && rname[0] == 'x' &&
310 rname[1] == 'i' && rname[2] == 'n' &&
311 (rname[3] == 'v' || rname[3] == 'x') &&
312 rname[4] >= '0' && rname[4] <= '9')
314 elog(NOTICE, "Rel %s: can't vacuum LargeObjects now",
320 d = heap_getattr(pgctup, buf, Anum_pg_class_relkind, pgcdesc, &n);
322 rkind = DatumGetChar(d);
324 /* skip system relations */
328 elog(NOTICE, "Vacuum: can not process index and certain system tables");
332 /* get a relation list entry for this guy */
333 old = MemoryContextSwitchTo((MemoryContext) portalmem);
334 if (vrl == (VRelList) NULL)
336 vrl = cur = (VRelList) palloc(sizeof(VRelListData));
340 cur->vrl_next = (VRelList) palloc(sizeof(VRelListData));
343 MemoryContextSwitchTo(old);
345 cur->vrl_relid = pgctup->t_oid;
346 cur->vrl_next = (VRelList) NULL;
348 /* wei hates it if you forget to do this */
352 elog(NOTICE, "Vacuum: table not found");
355 heap_endscan(pgcscan);
358 CommitTransactionCommand();
364 * vc_vacone() -- vacuum one heap relation
366 * This routine vacuums a single heap, cleans out its indices, and
367 * updates its statistics npages and ntups statistics.
369 * Doing one heap at a time incurs extra overhead, since we need to
370 * check that the heap exists again just before we vacuum it. The
371 * reason that we do this is so that vacuuming can be spread across
372 * many small transactions. Otherwise, two-phase locking would require
373 * us to lock the entire database during one pass of the vacuum cleaner.
376 vc_vacone(Oid relid, bool analyze, List *va_cols)
383 HeapScanDesc pgcscan;
386 VPageListData Vvpl; /* List of pages to vacuum and/or clean
388 VPageListData Fvpl; /* List of pages with space enough for
394 VRelStats *vacrelstats;
396 StartTransactionCommand();
398 ScanKeyEntryInitialize(&pgckey, 0x0, ObjectIdAttributeNumber,
399 ObjectIdEqualRegProcedure,
400 ObjectIdGetDatum(relid));
402 pgclass = heap_openr(RelationRelationName);
403 pgcdesc = RelationGetTupleDescriptor(pgclass);
404 pgcscan = heap_beginscan(pgclass, false, false, 1, &pgckey);
407 * Race condition -- if the pg_class tuple has gone away since the
408 * last time we saw it, we don't need to vacuum it.
411 if (!HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &pgcbuf)))
413 heap_endscan(pgcscan);
415 CommitTransactionCommand();
419 /* now open the class and vacuum it */
420 onerel = heap_open(relid);
422 vacrelstats = (VRelStats *) palloc(sizeof(VRelStats));
423 vacrelstats->relid = relid;
424 vacrelstats->npages = vacrelstats->ntups = 0;
425 vacrelstats->hasindex = false;
426 if (analyze && !IsSystemRelationName((RelationGetRelationName(onerel))->data))
430 AttributeTupleForm *attr;
432 attr_cnt = onerel->rd_att->natts;
433 attr = onerel->rd_att->attrs;
440 if (length(va_cols) > attr_cnt)
441 elog(WARN, "vacuum: too many attributes specified for relation %s",
442 (RelationGetRelationName(onerel))->data);
443 attnums = (int *) palloc(attr_cnt * sizeof(int));
446 char *col = (char *) lfirst(le);
448 for (i = 0; i < attr_cnt; i++)
450 if (namestrcmp(&(attr[i]->attname), col) == 0)
453 if (i < attr_cnt) /* found */
457 elog(WARN, "vacuum: there is no attribute %s in %s",
458 col, (RelationGetRelationName(onerel))->data);
464 vacrelstats->vacattrstats =
465 (VacAttrStats *) palloc(attr_cnt * sizeof(VacAttrStats));
467 for (i = 0; i < attr_cnt; i++)
469 Operator func_operator;
470 OperatorTupleForm pgopform;
473 stats = &vacrelstats->vacattrstats[i];
474 stats->attr = palloc(ATTRIBUTE_TUPLE_SIZE);
475 memmove(stats->attr, attr[((attnums) ? attnums[i] : i)], ATTRIBUTE_TUPLE_SIZE);
476 stats->best = stats->guess1 = stats->guess2 = 0;
477 stats->max = stats->min = 0;
478 stats->best_len = stats->guess1_len = stats->guess2_len = 0;
479 stats->max_len = stats->min_len = 0;
480 stats->initialized = false;
481 stats->best_cnt = stats->guess1_cnt = stats->guess1_hits = stats->guess2_hits = 0;
482 stats->max_cnt = stats->min_cnt = stats->null_cnt = stats->nonnull_cnt = 0;
484 func_operator = oper("=", stats->attr->atttypid, stats->attr->atttypid, true);
485 if (func_operator != NULL)
489 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
490 fmgr_info(pgopform->oprcode, &(stats->f_cmpeq), &nargs);
493 stats->f_cmpeq = NULL;
495 func_operator = oper("<", stats->attr->atttypid, stats->attr->atttypid, true);
496 if (func_operator != NULL)
500 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
501 fmgr_info(pgopform->oprcode, &(stats->f_cmplt), &nargs);
504 stats->f_cmplt = NULL;
506 func_operator = oper(">", stats->attr->atttypid, stats->attr->atttypid, true);
507 if (func_operator != NULL)
511 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
512 fmgr_info(pgopform->oprcode, &(stats->f_cmpgt), &nargs);
515 stats->f_cmpgt = NULL;
517 pgttup = SearchSysCacheTuple(TYPOID,
518 ObjectIdGetDatum(stats->attr->atttypid),
520 if (HeapTupleIsValid(pgttup))
521 stats->outfunc = ((TypeTupleForm) GETSTRUCT(pgttup))->typoutput;
523 stats->outfunc = InvalidOid;
525 vacrelstats->va_natts = attr_cnt;
526 vc_delhilowstats(relid, ((attnums) ? attr_cnt : 0), attnums);
532 vacrelstats->va_natts = 0;
533 vacrelstats->vacattrstats = (VacAttrStats *) NULL;
536 /* we require the relation to be locked until the indices are cleaned */
537 RelationSetLockForWrite(onerel);
540 Vvpl.vpl_npages = Fvpl.vpl_npages = 0;
541 vc_scanheap(vacrelstats, onerel, &Vvpl, &Fvpl);
543 /* Now open indices */
544 Irel = (Relation *) NULL;
545 vc_getindices(vacrelstats->relid, &nindices, &Irel);
548 vacrelstats->hasindex = true;
550 vacrelstats->hasindex = false;
552 /* Clean/scan index relation(s) */
553 if (Irel != (Relation *) NULL)
555 if (Vvpl.vpl_npages > 0)
557 for (i = 0; i < nindices; i++)
558 vc_vaconeind(&Vvpl, Irel[i], vacrelstats->ntups);
561 /* just scan indices to update statistic */
563 for (i = 0; i < nindices; i++)
564 vc_scanoneind(Irel[i], vacrelstats->ntups);
568 if (Fvpl.vpl_npages > 0) /* Try to shrink heap */
569 vc_rpfheap(vacrelstats, onerel, &Vvpl, &Fvpl, nindices, Irel);
572 if (Irel != (Relation *) NULL)
573 vc_clsindices(nindices, Irel);
574 if (Vvpl.vpl_npages > 0)/* Clean pages from Vvpl list */
575 vc_vacheap(vacrelstats, onerel, &Vvpl);
578 /* ok - free Vvpl list of reapped pages */
579 if (Vvpl.vpl_npages > 0)
581 vpp = Vvpl.vpl_pgdesc;
582 for (i = 0; i < Vvpl.vpl_npages; i++, vpp++)
584 pfree(Vvpl.vpl_pgdesc);
585 if (Fvpl.vpl_npages > 0)
586 pfree(Fvpl.vpl_pgdesc);
589 /* all done with this class */
591 heap_endscan(pgcscan);
594 /* update statistics in pg_class */
595 vc_updstats(vacrelstats->relid, vacrelstats->npages, vacrelstats->ntups,
596 vacrelstats->hasindex, vacrelstats);
598 /* next command frees attribute stats */
600 CommitTransactionCommand();
604 * vc_scanheap() -- scan an open heap relation
606 * This routine sets commit times, constructs Vvpl list of
607 * empty/uninitialized pages and pages with dead tuples and
608 * ~LP_USED line pointers, constructs Fvpl list of pages
609 * appropriate for purposes of shrinking and maintains statistics
610 * on the number of live tuples in a heap.
613 vc_scanheap(VRelStats *vacrelstats, Relation onerel,
614 VPageList Vvpl, VPageList Fvpl)
643 Size min_tlen = MAXTUPLEN;
645 int32 i /* , attr_cnt */ ;
648 bool do_shrinking = true;
650 getrusage(RUSAGE_SELF, &ru0);
652 nvac = ntups = nunused = ncrash = nempg = nnepg = nchpg = nemend = 0;
655 relname = (RelationGetRelationName(onerel))->data;
657 nblocks = RelationGetNumberOfBlocks(onerel);
659 vpc = (VPageDescr) palloc(sizeof(VPageDescrData) + MaxOffsetNumber * sizeof(OffsetNumber));
662 for (blkno = 0; blkno < nblocks; blkno++)
664 buf = ReadBuffer(onerel, blkno);
665 page = BufferGetPage(buf);
666 vpc->vpd_blkno = blkno;
671 elog(NOTICE, "Rel %s: Uninitialized page %u - fixing",
673 PageInit(page, BufferGetPageSize(buf), 0);
674 vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
675 frsize += (vpc->vpd_free - sizeof(ItemIdData));
678 vc_reappage(Vvpl, vpc);
683 if (PageIsEmpty(page))
685 vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
686 frsize += (vpc->vpd_free - sizeof(ItemIdData));
689 vc_reappage(Vvpl, vpc);
696 maxoff = PageGetMaxOffsetNumber(page);
697 for (offnum = FirstOffsetNumber;
699 offnum = OffsetNumberNext(offnum))
701 itemid = PageGetItemId(page, offnum);
704 * Collect un-used items too - it's possible to have indices
705 * pointing here after crash.
707 if (!ItemIdIsUsed(itemid))
709 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
714 htup = (HeapTuple) PageGetItem(page, itemid);
717 if (!(htup->t_infomask & HEAP_XMIN_COMMITTED))
719 if (htup->t_infomask & HEAP_XMIN_INVALID)
723 if (TransactionIdDidAbort(htup->t_xmin))
725 else if (TransactionIdDidCommit(htup->t_xmin))
727 htup->t_infomask |= HEAP_XMIN_COMMITTED;
730 else if (!TransactionIdIsInProgress(htup->t_xmin))
733 * Not Aborted, Not Committed, Not in Progress -
734 * so it's from crashed process. - vadim 11/26/96
741 elog(NOTICE, "Rel %s: TID %u/%u: InsertTransactionInProgress %u - can't shrink relation",
742 relname, blkno, offnum, htup->t_xmin);
743 do_shrinking = false;
749 * here we are concerned about tuples with xmin committed
750 * and xmax unknown or committed
752 if (htup->t_infomask & HEAP_XMIN_COMMITTED &&
753 !(htup->t_infomask & HEAP_XMAX_INVALID))
755 if (htup->t_infomask & HEAP_XMAX_COMMITTED)
757 else if (TransactionIdDidAbort(htup->t_xmax))
759 htup->t_infomask |= HEAP_XMAX_INVALID;
762 else if (TransactionIdDidCommit(htup->t_xmax))
764 else if (!TransactionIdIsInProgress(htup->t_xmax))
767 * Not Aborted, Not Committed, Not in Progress - so it
768 * from crashed process. - vadim 06/02/97
770 htup->t_infomask |= HEAP_XMAX_INVALID;;
775 elog(NOTICE, "Rel %s: TID %u/%u: DeleteTransactionInProgress %u - can't shrink relation",
776 relname, blkno, offnum, htup->t_xmax);
777 do_shrinking = false;
782 * It's possibly! But from where it comes ? And should we fix
783 * it ? - vadim 11/28/96
785 itemptr = &(htup->t_ctid);
786 if (!ItemPointerIsValid(itemptr) ||
787 BlockIdGetBlockNumber(&(itemptr->ip_blkid)) != blkno)
789 elog(NOTICE, "Rel %s: TID %u/%u: TID IN TUPLEHEADER %u/%u IS NOT THE SAME. TUPGONE %d.",
790 relname, blkno, offnum,
791 BlockIdGetBlockNumber(&(itemptr->ip_blkid)),
792 itemptr->ip_posid, tupgone);
798 if (htup->t_len != itemid->lp_len)
800 elog(NOTICE, "Rel %s: TID %u/%u: TUPLE_LEN IN PAGEHEADER %u IS NOT THE SAME AS IN TUPLEHEADER %u. TUPGONE %d.",
801 relname, blkno, offnum,
802 itemid->lp_len, htup->t_len, tupgone);
804 if (!OidIsValid(htup->t_oid))
806 elog(NOTICE, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
807 relname, blkno, offnum, tupgone);
814 if (tempPage == (Page) NULL)
818 pageSize = PageGetPageSize(page);
819 tempPage = (Page) palloc(pageSize);
820 memmove(tempPage, page, pageSize);
823 lpp = &(((PageHeader) tempPage)->pd_linp[offnum - 1]);
826 lpp->lp_flags &= ~LP_USED;
828 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
836 if (htup->t_len < min_tlen)
837 min_tlen = htup->t_len;
838 if (htup->t_len > max_tlen)
839 max_tlen = htup->t_len;
840 vc_attrstats(onerel, vacrelstats, htup);
852 if (tempPage != (Page) NULL)
853 { /* Some tuples are gone */
854 PageRepairFragmentation(tempPage);
855 vpc->vpd_free = ((PageHeader) tempPage)->pd_upper - ((PageHeader) tempPage)->pd_lower;
856 frsize += vpc->vpd_free;
857 vc_reappage(Vvpl, vpc);
859 tempPage = (Page) NULL;
861 else if (vpc->vpd_noff > 0)
862 { /* there are only ~LP_USED line pointers */
863 vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
864 frsize += vpc->vpd_free;
865 vc_reappage(Vvpl, vpc);
877 /* save stats in the rel list for use later */
878 vacrelstats->ntups = ntups;
879 vacrelstats->npages = nblocks;
880 /* vacrelstats->natts = attr_cnt;*/
882 min_tlen = max_tlen = 0;
883 vacrelstats->min_tlen = min_tlen;
884 vacrelstats->max_tlen = max_tlen;
886 Vvpl->vpl_nemend = nemend;
887 Fvpl->vpl_nemend = nemend;
890 * Try to make Fvpl keeping in mind that we can't use free space of
891 * "empty" end-pages and last page if it reapped.
893 if (do_shrinking && Vvpl->vpl_npages - nemend > 0)
895 int nusf; /* blocks usefull for re-using */
897 nusf = Vvpl->vpl_npages - nemend;
898 if ((Vvpl->vpl_pgdesc[nusf - 1])->vpd_blkno == nblocks - nemend - 1)
901 for (i = 0; i < nusf; i++)
903 vp = Vvpl->vpl_pgdesc[i];
904 if (vc_enough_space(vp, min_tlen))
906 vc_vpinsert(Fvpl, vp);
907 frsusf += vp->vpd_free;
912 getrusage(RUSAGE_SELF, &ru1);
914 elog(MESSAGE_LEVEL, "Rel %s: Pages %u: Changed %u, Reapped %u, Empty %u, New %u; \
915 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.",
917 nblocks, nchpg, Vvpl->vpl_npages, nempg, nnepg,
918 ntups, nvac, ncrash, nunused, min_tlen, max_tlen,
919 frsize, frsusf, nemend, Fvpl->vpl_npages,
920 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
921 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
927 * vc_rpfheap() -- try to repaire relation' fragmentation
929 * This routine marks dead tuples as unused and tries re-use dead space
930 * by moving tuples (and inserting indices if needed). It constructs
931 * Nvpl list of free-ed pages (moved tuples) and clean indices
932 * for them after committing (in hack-manner - without losing locks
933 * and freeing memory!) current transaction. It truncates relation
934 * if some end-blocks are gone away.
937 vc_rpfheap(VRelStats *vacrelstats, Relation onerel,
938 VPageList Vvpl, VPageList Fvpl, int nindices, Relation *Irel)
948 OffsetNumber offnum = 0,
956 TupleDesc tupdesc = NULL;
957 Datum *idatum = NULL;
959 InsertIndexResult iresult;
961 VPageDescr ToVpd = NULL,
983 getrusage(RUSAGE_SELF, &ru0);
985 myXID = GetCurrentTransactionId();
986 myCID = GetCurrentCommandId();
988 if (Irel != (Relation *) NULL) /* preparation for index' inserts */
990 vc_mkindesc(onerel, nindices, Irel, &Idesc);
991 tupdesc = RelationGetTupleDescriptor(onerel);
992 idatum = (Datum *) palloc(INDEX_MAX_KEYS * sizeof(*idatum));
993 inulls = (char *) palloc(INDEX_MAX_KEYS * sizeof(*inulls));
997 Fnpages = Fvpl->vpl_npages;
998 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
999 Fblklast = Fvplast->vpd_blkno;
1000 Assert(Vvpl->vpl_npages > Vvpl->vpl_nemend);
1001 Vnpages = Vvpl->vpl_npages - Vvpl->vpl_nemend;
1002 Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
1003 Vblklast = Vvplast->vpd_blkno;
1004 Assert(Vblklast >= Fblklast);
1005 ToBuf = InvalidBuffer;
1008 vpc = (VPageDescr) palloc(sizeof(VPageDescrData) + MaxOffsetNumber * sizeof(OffsetNumber));
1009 vpc->vpd_nusd = vpc->vpd_noff = 0;
1011 nblocks = vacrelstats->npages;
1012 for (blkno = nblocks - Vvpl->vpl_nemend - 1;; blkno--)
1014 /* if it's reapped page and it was used by me - quit */
1015 if (blkno == Fblklast && Fvplast->vpd_nusd > 0)
1018 buf = ReadBuffer(onerel, blkno);
1019 page = BufferGetPage(buf);
1023 isempty = PageIsEmpty(page);
1026 if (blkno == Vblklast) /* it's reapped page */
1028 if (Vvplast->vpd_noff > 0) /* there are dead tuples */
1029 { /* on this page - clean */
1031 vc_vacpage(page, Vvplast);
1039 Assert(Vnpages > 0);
1040 /* get prev reapped page from Vvpl */
1041 Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
1042 Vblklast = Vvplast->vpd_blkno;
1043 if (blkno == Fblklast) /* this page in Fvpl too */
1046 Assert(Fnpages > 0);
1047 Assert(Fvplast->vpd_nusd == 0);
1048 /* get prev reapped page from Fvpl */
1049 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1050 Fblklast = Fvplast->vpd_blkno;
1052 Assert(Fblklast <= Vblklast);
1064 vpc->vpd_blkno = blkno;
1065 maxoff = PageGetMaxOffsetNumber(page);
1066 for (offnum = FirstOffsetNumber;
1068 offnum = OffsetNumberNext(offnum))
1070 itemid = PageGetItemId(page, offnum);
1072 if (!ItemIdIsUsed(itemid))
1075 htup = (HeapTuple) PageGetItem(page, itemid);
1078 /* try to find new page for this tuple */
1079 if (ToBuf == InvalidBuffer ||
1080 !vc_enough_space(ToVpd, tlen))
1082 if (ToBuf != InvalidBuffer)
1085 ToBuf = InvalidBuffer;
1088 * If no one tuple can't be added to this page -
1089 * remove page from Fvpl. - vadim 11/27/96
1091 if (!vc_enough_space(ToVpd, vacrelstats->min_tlen))
1093 if (ToVpd != Fvplast)
1095 Assert(Fnpages > ToVpI + 1);
1096 memmove(Fvpl->vpl_pgdesc + ToVpI,
1097 Fvpl->vpl_pgdesc + ToVpI + 1,
1098 sizeof(VPageDescr *) * (Fnpages - ToVpI - 1));
1100 Assert(Fnpages >= 1);
1104 /* get prev reapped page from Fvpl */
1105 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1106 Fblklast = Fvplast->vpd_blkno;
1109 for (i = 0; i < Fnpages; i++)
1111 if (vc_enough_space(Fvpl->vpl_pgdesc[i], tlen))
1115 break; /* can't move item anywhere */
1117 ToVpd = Fvpl->vpl_pgdesc[ToVpI];
1118 ToBuf = ReadBuffer(onerel, ToVpd->vpd_blkno);
1119 ToPage = BufferGetPage(ToBuf);
1120 /* if this page was not used before - clean it */
1121 if (!PageIsEmpty(ToPage) && ToVpd->vpd_nusd == 0)
1122 vc_vacpage(ToPage, ToVpd);
1126 newtup = (HeapTuple) palloc(tlen);
1127 memmove((char *) newtup, (char *) htup, tlen);
1129 /* store transaction information */
1130 TransactionIdStore(myXID, &(newtup->t_xmin));
1131 newtup->t_cmin = myCID;
1132 StoreInvalidTransactionId(&(newtup->t_xmax));
1133 /* set xmin to unknown and xmax to invalid */
1134 newtup->t_infomask &= ~(HEAP_XACT_MASK);
1135 newtup->t_infomask |= HEAP_XMAX_INVALID;
1137 /* add tuple to the page */
1138 newoff = PageAddItem(ToPage, (Item) newtup, tlen,
1139 InvalidOffsetNumber, LP_USED);
1140 if (newoff == InvalidOffsetNumber)
1143 failed to add item with len = %u to page %u (free space %u, nusd %u, noff %u)",
1144 tlen, ToVpd->vpd_blkno, ToVpd->vpd_free,
1145 ToVpd->vpd_nusd, ToVpd->vpd_noff);
1147 newitemid = PageGetItemId(ToPage, newoff);
1149 newtup = (HeapTuple) PageGetItem(ToPage, newitemid);
1150 ItemPointerSet(&(newtup->t_ctid), ToVpd->vpd_blkno, newoff);
1152 /* now logically delete end-tuple */
1153 TransactionIdStore(myXID, &(htup->t_xmax));
1154 htup->t_cmax = myCID;
1155 /* set xmax to unknown */
1156 htup->t_infomask &= ~(HEAP_XMAX_INVALID | HEAP_XMAX_COMMITTED);
1160 ToVpd->vpd_free = ((PageHeader) ToPage)->pd_upper - ((PageHeader) ToPage)->pd_lower;
1161 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
1163 /* insert index' tuples if needed */
1164 if (Irel != (Relation *) NULL)
1166 for (i = 0, idcur = Idesc; i < nindices; i++, idcur++)
1170 (AttrNumber *) &(idcur->tform->indkey[0]),
1177 iresult = index_insert(
1188 } /* walk along page */
1190 if (vpc->vpd_noff > 0) /* some tuples were moved */
1192 vc_reappage(&Nvpl, vpc);
1200 if (offnum <= maxoff)
1201 break; /* some item(s) left */
1203 } /* walk along relation */
1205 blkno++; /* new number of blocks */
1207 if (ToBuf != InvalidBuffer)
1217 * We have to commit our tuple' movings before we'll truncate
1218 * relation, but we shouldn't lose our locks. And so - quick hack:
1219 * flush buffers and record status of current transaction as
1220 * committed, and continue. - vadim 11/13/96
1222 FlushBufferPool(!TransactionFlushEnabled());
1223 TransactionIdCommit(myXID);
1224 FlushBufferPool(!TransactionFlushEnabled());
1228 * Clean uncleaned reapped pages from Vvpl list and set xmin committed
1229 * for inserted tuples
1232 for (i = 0, vpp = Vvpl->vpl_pgdesc; i < Vnpages; i++, vpp++)
1234 Assert((*vpp)->vpd_blkno < blkno);
1235 buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1236 page = BufferGetPage(buf);
1237 if ((*vpp)->vpd_nusd == 0) /* this page was not used */
1241 * noff == 0 in empty pages only - such pages should be
1244 Assert((*vpp)->vpd_noff > 0);
1245 vc_vacpage(page, *vpp);
1248 /* this page was used */
1251 moff = PageGetMaxOffsetNumber(page);
1252 for (newoff = FirstOffsetNumber;
1254 newoff = OffsetNumberNext(newoff))
1256 itemid = PageGetItemId(page, newoff);
1257 if (!ItemIdIsUsed(itemid))
1259 htup = (HeapTuple) PageGetItem(page, itemid);
1260 if (TransactionIdEquals((TransactionId) htup->t_xmin, myXID))
1262 htup->t_infomask |= HEAP_XMIN_COMMITTED;
1266 Assert((*vpp)->vpd_nusd == ntups);
1271 Assert(nmoved == nchkmvd);
1273 getrusage(RUSAGE_SELF, &ru1);
1275 elog(MESSAGE_LEVEL, "Rel %s: Pages: %u --> %u; Tuple(s) moved: %u. \
1276 Elapsed %u/%u sec.",
1277 (RelationGetRelationName(onerel))->data,
1278 nblocks, blkno, nmoved,
1279 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1280 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1282 if (Nvpl.vpl_npages > 0)
1284 /* vacuum indices again if needed */
1285 if (Irel != (Relation *) NULL)
1291 /* re-sort Nvpl.vpl_pgdesc */
1292 for (vpleft = Nvpl.vpl_pgdesc,
1293 vpright = Nvpl.vpl_pgdesc + Nvpl.vpl_npages - 1;
1294 vpleft < vpright; vpleft++, vpright--)
1300 for (i = 0; i < nindices; i++)
1301 vc_vaconeind(&Nvpl, Irel[i], vacrelstats->ntups);
1305 * clean moved tuples from last page in Nvpl list if some tuples
1308 if (vpc->vpd_noff > 0 && offnum <= maxoff)
1310 Assert(vpc->vpd_blkno == blkno - 1);
1311 buf = ReadBuffer(onerel, vpc->vpd_blkno);
1312 page = BufferGetPage(buf);
1315 for (offnum = FirstOffsetNumber;
1317 offnum = OffsetNumberNext(offnum))
1319 itemid = PageGetItemId(page, offnum);
1320 if (!ItemIdIsUsed(itemid))
1322 htup = (HeapTuple) PageGetItem(page, itemid);
1323 Assert(TransactionIdEquals((TransactionId) htup->t_xmax, myXID));
1324 itemid->lp_flags &= ~LP_USED;
1327 Assert(vpc->vpd_noff == ntups);
1328 PageRepairFragmentation(page);
1332 /* now - free new list of reapped pages */
1333 vpp = Nvpl.vpl_pgdesc;
1334 for (i = 0; i < Nvpl.vpl_npages; i++, vpp++)
1336 pfree(Nvpl.vpl_pgdesc);
1339 /* truncate relation */
1340 if (blkno < nblocks)
1342 i = BlowawayRelationBuffers(onerel, blkno);
1344 elog (FATAL, "VACUUM (vc_rpfheap): BlowawayRelationBuffers returned %d", i);
1345 blkno = smgrtruncate(DEFAULT_SMGR, onerel, blkno);
1347 vacrelstats->npages = blkno; /* set new number of blocks */
1350 if (Irel != (Relation *) NULL) /* pfree index' allocations */
1355 vc_clsindices(nindices, Irel);
1363 * vc_vacheap() -- free dead tuples
1365 * This routine marks dead tuples as unused and truncates relation
1366 * if there are "empty" end-blocks.
1369 vc_vacheap(VRelStats *vacrelstats, Relation onerel, VPageList Vvpl)
1377 nblocks = Vvpl->vpl_npages;
1378 nblocks -= Vvpl->vpl_nemend; /* nothing to do with them */
1380 for (i = 0, vpp = Vvpl->vpl_pgdesc; i < nblocks; i++, vpp++)
1382 if ((*vpp)->vpd_noff > 0)
1384 buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1385 page = BufferGetPage(buf);
1386 vc_vacpage(page, *vpp);
1391 /* truncate relation if there are some empty end-pages */
1392 if (Vvpl->vpl_nemend > 0)
1394 Assert(vacrelstats->npages >= Vvpl->vpl_nemend);
1395 nblocks = vacrelstats->npages - Vvpl->vpl_nemend;
1396 elog(MESSAGE_LEVEL, "Rel %s: Pages: %u --> %u.",
1397 (RelationGetRelationName(onerel))->data,
1398 vacrelstats->npages, nblocks);
1401 * we have to flush "empty" end-pages (if changed, but who knows
1402 * it) before truncation
1404 FlushBufferPool(!TransactionFlushEnabled());
1406 i = BlowawayRelationBuffers(onerel, nblocks);
1408 elog (FATAL, "VACUUM (vc_vacheap): BlowawayRelationBuffers returned %d", i);
1410 nblocks = smgrtruncate(DEFAULT_SMGR, onerel, nblocks);
1411 Assert(nblocks >= 0);
1412 vacrelstats->npages = nblocks; /* set new number of blocks */
1418 * vc_vacpage() -- free dead tuples on a page
1419 * and repaire its fragmentation.
1422 vc_vacpage(Page page, VPageDescr vpd)
1427 Assert(vpd->vpd_nusd == 0);
1428 for (i = 0; i < vpd->vpd_noff; i++)
1430 itemid = &(((PageHeader) page)->pd_linp[vpd->vpd_voff[i] - 1]);
1431 itemid->lp_flags &= ~LP_USED;
1433 PageRepairFragmentation(page);
1438 * _vc_scanoneind() -- scan one index relation to update statistic.
1442 vc_scanoneind(Relation indrel, int nhtups)
1444 RetrieveIndexResult res;
1445 IndexScanDesc iscan;
1451 getrusage(RUSAGE_SELF, &ru0);
1453 /* walk through the entire index */
1454 iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
1457 while ((res = index_getnext(iscan, ForwardScanDirection))
1458 != (RetrieveIndexResult) NULL)
1464 index_endscan(iscan);
1466 /* now update statistics in pg_class */
1467 nipages = RelationGetNumberOfBlocks(indrel);
1468 vc_updstats(indrel->rd_id, nipages, nitups, false, NULL);
1470 getrusage(RUSAGE_SELF, &ru1);
1472 elog(MESSAGE_LEVEL, "Ind %s: Pages %u; Tuples %u. Elapsed %u/%u sec.",
1473 indrel->rd_rel->relname.data, nipages, nitups,
1474 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1475 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1477 if (nitups != nhtups)
1478 elog(NOTICE, "Ind %s: NUMBER OF INDEX' TUPLES (%u) IS NOT THE SAME AS HEAP' (%u)",
1479 indrel->rd_rel->relname.data, nitups, nhtups);
1481 } /* vc_scanoneind */
1484 * vc_vaconeind() -- vacuum one index relation.
1486 * Vpl is the VPageList of the heap we're currently vacuuming.
1487 * It's locked. Indrel is an index relation on the vacuumed heap.
1488 * We don't set locks on the index relation here, since the indexed
1489 * access methods support locking at different granularities.
1490 * We let them handle it.
1492 * Finally, we arrange to update the index relation's statistics in
1496 vc_vaconeind(VPageList vpl, Relation indrel, int nhtups)
1498 RetrieveIndexResult res;
1499 IndexScanDesc iscan;
1500 ItemPointer heapptr;
1508 getrusage(RUSAGE_SELF, &ru0);
1510 /* walk through the entire index */
1511 iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
1515 while ((res = index_getnext(iscan, ForwardScanDirection))
1516 != (RetrieveIndexResult) NULL)
1518 heapptr = &res->heap_iptr;
1520 if ((vp = vc_tidreapped(heapptr, vpl)) != (VPageDescr) NULL)
1523 elog(DEBUG, "<%x,%x> -> <%x,%x>",
1524 ItemPointerGetBlockNumber(&(res->index_iptr)),
1525 ItemPointerGetOffsetNumber(&(res->index_iptr)),
1526 ItemPointerGetBlockNumber(&(res->heap_iptr)),
1527 ItemPointerGetOffsetNumber(&(res->heap_iptr)));
1529 if (vp->vpd_noff == 0)
1530 { /* this is EmptyPage !!! */
1531 elog(NOTICE, "Ind %s: pointer to EmptyPage (blk %u off %u) - fixing",
1532 indrel->rd_rel->relname.data,
1533 vp->vpd_blkno, ItemPointerGetOffsetNumber(heapptr));
1536 index_delete(indrel, &res->index_iptr);
1547 index_endscan(iscan);
1549 /* now update statistics in pg_class */
1550 nipages = RelationGetNumberOfBlocks(indrel);
1551 vc_updstats(indrel->rd_id, nipages, nitups, false, NULL);
1553 getrusage(RUSAGE_SELF, &ru1);
1555 elog(MESSAGE_LEVEL, "Ind %s: Pages %u; Tuples %u: Deleted %u. Elapsed %u/%u sec.",
1556 indrel->rd_rel->relname.data, nipages, nitups, nvac,
1557 ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1558 ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1560 if (nitups != nhtups)
1561 elog(NOTICE, "Ind %s: NUMBER OF INDEX' TUPLES (%u) IS NOT THE SAME AS HEAP' (%u)",
1562 indrel->rd_rel->relname.data, nitups, nhtups);
1564 } /* vc_vaconeind */
1567 * vc_tidreapped() -- is a particular tid reapped?
1569 * vpl->VPageDescr_array is sorted in right order.
1572 vc_tidreapped(ItemPointer itemptr, VPageList vpl)
1574 OffsetNumber ioffno;
1580 vpd.vpd_blkno = ItemPointerGetBlockNumber(itemptr);
1581 ioffno = ItemPointerGetOffsetNumber(itemptr);
1584 vpp = (VPageDescr *) vc_find_eq((char *) (vpl->vpl_pgdesc),
1585 vpl->vpl_npages, sizeof(VPageDescr), (char *) &vp,
1588 if (vpp == (VPageDescr *) NULL)
1589 return ((VPageDescr) NULL);
1592 /* ok - we are on true page */
1594 if (vp->vpd_noff == 0)
1595 { /* this is EmptyPage !!! */
1599 voff = (OffsetNumber *) vc_find_eq((char *) (vp->vpd_voff),
1600 vp->vpd_noff, sizeof(OffsetNumber), (char *) &ioffno,
1603 if (voff == (OffsetNumber *) NULL)
1604 return ((VPageDescr) NULL);
1608 } /* vc_tidreapped */
1611 * vc_attrstats() -- compute column statistics used by the optimzer
1613 * We compute the column min, max, null and non-null counts.
1614 * Plus we attempt to find the count of the value that occurs most
1615 * frequently in each column
1616 * These figures are used to compute the selectivity of the column
1618 * We use a three-bucked cache to get the most frequent item
1619 * The 'guess' buckets count hits. A cache miss causes guess1
1620 * to get the most hit 'guess' item in the most recent cycle, and
1621 * the new item goes into guess2. Whenever the total count of hits
1622 * of a 'guess' entry is larger than 'best', 'guess' becomes 'best'.
1624 * This method works perfectly for columns with unique values, and columns
1625 * with only two unique values, plus nulls.
1627 * It becomes less perfect as the number of unique values increases and
1628 * their distribution in the table becomes more random.
1632 vc_attrstats(Relation onerel, VRelStats *vacrelstats, HeapTuple htup)
1635 attr_cnt = vacrelstats->va_natts;
1636 VacAttrStats *vacattrstats = vacrelstats->vacattrstats;
1637 TupleDesc tupDesc = onerel->rd_att;
1641 for (i = 0; i < attr_cnt; i++)
1643 VacAttrStats *stats = &vacattrstats[i];
1644 bool value_hit = true;
1646 value = heap_getattr(htup, InvalidBuffer,
1647 stats->attr->attnum, tupDesc, &isnull);
1649 if (!VacAttrStatsEqValid(stats))
1656 stats->nonnull_cnt++;
1657 if (stats->initialized == false)
1659 vc_bucketcpy(stats->attr, value, &stats->best, &stats->best_len);
1660 /* best_cnt gets incremented later */
1661 vc_bucketcpy(stats->attr, value, &stats->guess1, &stats->guess1_len);
1662 stats->guess1_cnt = stats->guess1_hits = 1;
1663 vc_bucketcpy(stats->attr, value, &stats->guess2, &stats->guess2_len);
1664 stats->guess2_hits = 1;
1665 if (VacAttrStatsLtGtValid(stats))
1667 vc_bucketcpy(stats->attr, value, &stats->max, &stats->max_len);
1668 vc_bucketcpy(stats->attr, value, &stats->min, &stats->min_len);
1670 stats->initialized = true;
1672 if (VacAttrStatsLtGtValid(stats))
1674 if ((*(stats->f_cmplt)) (value, stats->min))
1676 vc_bucketcpy(stats->attr, value, &stats->min, &stats->min_len);
1679 if ((*(stats->f_cmpgt)) (value, stats->max))
1681 vc_bucketcpy(stats->attr, value, &stats->max, &stats->max_len);
1684 if ((*(stats->f_cmpeq)) (value, stats->min))
1686 else if ((*(stats->f_cmpeq)) (value, stats->max))
1689 if ((*(stats->f_cmpeq)) (value, stats->best))
1691 else if ((*(stats->f_cmpeq)) (value, stats->guess1))
1693 stats->guess1_cnt++;
1694 stats->guess1_hits++;
1696 else if ((*(stats->f_cmpeq)) (value, stats->guess2))
1697 stats->guess2_hits++;
1701 if (stats->guess2_hits > stats->guess1_hits)
1703 swapDatum(stats->guess1, stats->guess2);
1704 swapInt(stats->guess1_len, stats->guess2_len);
1705 stats->guess1_cnt = stats->guess2_hits;
1706 swapLong(stats->guess1_hits, stats->guess2_hits);
1708 if (stats->guess1_cnt > stats->best_cnt)
1710 swapDatum(stats->best, stats->guess1);
1711 swapInt(stats->best_len, stats->guess1_len);
1712 swapLong(stats->best_cnt, stats->guess1_cnt);
1713 stats->guess1_hits = 1;
1714 stats->guess2_hits = 1;
1718 vc_bucketcpy(stats->attr, value, &stats->guess2, &stats->guess2_len);
1719 stats->guess1_hits = 1;
1720 stats->guess2_hits = 1;
1728 * vc_bucketcpy() -- update pg_class statistics for one relation
1732 vc_bucketcpy(AttributeTupleForm attr, Datum value, Datum *bucket, int16 *bucket_len)
1734 if (attr->attbyval && attr->attlen != -1)
1738 int len = (attr->attlen != -1 ? attr->attlen : VARSIZE(value));
1740 if (len > *bucket_len)
1742 if (*bucket_len != 0)
1743 pfree(DatumGetPointer(*bucket));
1744 *bucket = PointerGetDatum(palloc(len));
1747 memmove(DatumGetPointer(*bucket), DatumGetPointer(value), len);
1752 * vc_updstats() -- update pg_class statistics for one relation
1754 * This routine works for both index and heap relation entries in
1755 * pg_class. We violate no-overwrite semantics here by storing new
1756 * values for ntups, npages, and hasindex directly in the pg_class
1757 * tuple that's already on the page. The reason for this is that if
1758 * we updated these tuples in the usual way, then every tuple in pg_class
1759 * would be replaced every day. This would make planning and executing
1760 * historical queries very expensive.
1763 vc_updstats(Oid relid, int npages, int ntups, bool hasindex, VRelStats *vacrelstats)
1768 HeapScanDesc rsdesc,
1776 Form_pg_class pgcform;
1779 AttributeTupleForm attp;
1782 * update number of tuples and number of pages in pg_class
1784 ScanKeyEntryInitialize(&rskey, 0x0, ObjectIdAttributeNumber,
1785 ObjectIdEqualRegProcedure,
1786 ObjectIdGetDatum(relid));
1788 rd = heap_openr(RelationRelationName);
1789 rsdesc = heap_beginscan(rd, false, false, 1, &rskey);
1791 if (!HeapTupleIsValid(rtup = heap_getnext(rsdesc, 0, &rbuf)))
1792 elog(WARN, "pg_class entry for relid %d vanished during vacuuming",
1795 /* overwrite the existing statistics in the tuple */
1796 vc_setpagelock(rd, BufferGetBlockNumber(rbuf));
1797 pgcform = (Form_pg_class) GETSTRUCT(rtup);
1798 pgcform->reltuples = ntups;
1799 pgcform->relpages = npages;
1800 pgcform->relhasindex = hasindex;
1802 if (vacrelstats != NULL && vacrelstats->va_natts > 0)
1804 VacAttrStats *vacattrstats = vacrelstats->vacattrstats;
1805 int natts = vacrelstats->va_natts;
1807 ad = heap_openr(AttributeRelationName);
1808 sd = heap_openr(StatisticRelationName);
1809 ScanKeyEntryInitialize(&askey, 0, Anum_pg_attribute_attrelid,
1812 asdesc = heap_beginscan(ad, false, false, 1, &askey);
1814 while (HeapTupleIsValid(atup = heap_getnext(asdesc, 0, &abuf)))
1817 float32data selratio; /* average ratio of rows selected
1818 * for a random constant */
1819 VacAttrStats *stats;
1820 Datum values[Natts_pg_statistic];
1821 char nulls[Natts_pg_statistic];
1823 attp = (AttributeTupleForm) GETSTRUCT(atup);
1824 if (attp->attnum <= 0) /* skip system attributes for now, */
1825 /* they are unique anyway */
1828 for (i = 0; i < natts; i++)
1830 if (attp->attnum == vacattrstats[i].attr->attnum)
1835 stats = &(vacattrstats[i]);
1837 /* overwrite the existing statistics in the tuple */
1838 if (VacAttrStatsEqValid(stats))
1841 vc_setpagelock(ad, BufferGetBlockNumber(abuf));
1843 if (stats->nonnull_cnt + stats->null_cnt == 0 ||
1844 (stats->null_cnt <= 1 && stats->best_cnt == 1))
1846 else if (VacAttrStatsLtGtValid(stats) && stats->min_cnt + stats->max_cnt == stats->nonnull_cnt)
1848 double min_cnt_d = stats->min_cnt,
1849 max_cnt_d = stats->max_cnt,
1850 null_cnt_d = stats->null_cnt,
1851 nonnullcnt_d = stats->nonnull_cnt; /* prevent overflow */
1853 selratio = (min_cnt_d * min_cnt_d + max_cnt_d * max_cnt_d + null_cnt_d * null_cnt_d) /
1854 (nonnullcnt_d + null_cnt_d) / (nonnullcnt_d + null_cnt_d);
1858 double most = (double) (stats->best_cnt > stats->null_cnt ? stats->best_cnt : stats->null_cnt);
1859 double total = ((double) stats->nonnull_cnt) + ((double) stats->null_cnt);
1862 * we assume count of other values are 20% of best
1865 selratio = (most * most + 0.20 * most * (total - most)) / total / total;
1869 attp->attdisbursion = selratio;
1870 WriteNoReleaseBuffer(abuf);
1872 /* DO PG_STATISTIC INSERTS */
1875 * doing system relations, especially pg_statistic is a
1878 if (VacAttrStatsLtGtValid(stats) && stats->initialized /* &&
1879 * !IsSystemRelationName(
1881 pgcform->relname.data) */ )
1883 func_ptr out_function;
1887 for (i = 0; i < Natts_pg_statistic; ++i)
1891 * initialize values[]
1895 values[i++] = (Datum) relid; /* 1 */
1896 values[i++] = (Datum) attp->attnum; /* 2 */
1897 values[i++] = (Datum) InvalidOid; /* 3 */
1898 fmgr_info(stats->outfunc, &out_function, &dummy);
1899 out_string = (*out_function) (stats->min, stats->attr->atttypid);
1900 values[i++] = (Datum) fmgr(TextInRegProcedure, out_string);
1902 out_string = (char *) (*out_function) (stats->max, stats->attr->atttypid);
1903 values[i++] = (Datum) fmgr(TextInRegProcedure, out_string);
1908 stup = heap_formtuple(sdesc, values, nulls);
1911 * insert the tuple in the relation and get the tuple's oid.
1914 heap_insert(sd, stup);
1915 pfree(DatumGetPointer(values[3]));
1916 pfree(DatumGetPointer(values[4]));
1921 heap_endscan(asdesc);
1926 /* XXX -- after write, should invalidate relcache in other backends */
1927 WriteNoReleaseBuffer(rbuf); /* heap_endscan release scan' buffers ? */
1930 * invalidating system relations confuses the function cache of
1931 * pg_operator and pg_opclass
1933 if (!IsSystemRelationName(pgcform->relname.data))
1934 RelationInvalidateHeapTuple(rd, rtup);
1936 /* that's all, folks */
1937 heap_endscan(rsdesc);
1942 * vc_delhilowstats() -- delete pg_statistics rows
1946 vc_delhilowstats(Oid relid, int attcnt, int *attnums)
1948 Relation pgstatistic;
1949 HeapScanDesc pgsscan;
1953 pgstatistic = heap_openr(StatisticRelationName);
1955 if (relid != InvalidOid)
1957 ScanKeyEntryInitialize(&pgskey, 0x0, Anum_pg_statistic_starelid,
1958 ObjectIdEqualRegProcedure,
1959 ObjectIdGetDatum(relid));
1960 pgsscan = heap_beginscan(pgstatistic, false, false, 1, &pgskey);
1963 pgsscan = heap_beginscan(pgstatistic, false, false, 0, NULL);
1965 while (HeapTupleIsValid(pgstup = heap_getnext(pgsscan, 0, NULL)))
1969 Form_pg_statistic pgs = (Form_pg_statistic) GETSTRUCT(pgstup);
1972 for (i = 0; i < attcnt; i++)
1974 if (pgs->staattnum == attnums[i] + 1)
1978 continue; /* don't delete it */
1980 heap_delete(pgstatistic, &pgstup->t_ctid);
1983 heap_endscan(pgsscan);
1984 heap_close(pgstatistic);
1988 vc_setpagelock(Relation rel, BlockNumber blkno)
1990 ItemPointerData itm;
1992 ItemPointerSet(&itm, blkno, 1);
1994 RelationSetLockForWritePage(rel, &itm);
1998 * vc_reappage() -- save a page on the array of reapped pages.
2000 * As a side effect of the way that the vacuuming loop for a given
2001 * relation works, higher pages come after lower pages in the array
2002 * (and highest tid on a page is last).
2005 vc_reappage(VPageList vpl, VPageDescr vpc)
2009 /* allocate a VPageDescrData entry */
2010 newvpd = (VPageDescr) palloc(sizeof(VPageDescrData) + vpc->vpd_noff * sizeof(OffsetNumber));
2013 if (vpc->vpd_noff > 0)
2014 memmove(newvpd->vpd_voff, vpc->vpd_voff, vpc->vpd_noff * sizeof(OffsetNumber));
2015 newvpd->vpd_blkno = vpc->vpd_blkno;
2016 newvpd->vpd_free = vpc->vpd_free;
2017 newvpd->vpd_nusd = vpc->vpd_nusd;
2018 newvpd->vpd_noff = vpc->vpd_noff;
2020 /* insert this page into vpl list */
2021 vc_vpinsert(vpl, newvpd);
2026 vc_vpinsert(VPageList vpl, VPageDescr vpnew)
2029 /* allocate a VPageDescr entry if needed */
2030 if (vpl->vpl_npages == 0)
2031 vpl->vpl_pgdesc = (VPageDescr *) palloc(100 * sizeof(VPageDescr));
2032 else if (vpl->vpl_npages % 100 == 0)
2033 vpl->vpl_pgdesc = (VPageDescr *) repalloc(vpl->vpl_pgdesc, (vpl->vpl_npages + 100) * sizeof(VPageDescr));
2034 vpl->vpl_pgdesc[vpl->vpl_npages] = vpnew;
2035 (vpl->vpl_npages)++;
2040 vc_free(VRelList vrl)
2044 PortalVariableMemory pmem;
2046 pmem = PortalGetVariableMemory(vc_portal);
2047 old = MemoryContextSwitchTo((MemoryContext) pmem);
2049 while (vrl != (VRelList) NULL)
2052 /* free rel list entry */
2054 vrl = vrl->vrl_next;
2058 MemoryContextSwitchTo(old);
2062 vc_find_eq(char *bot, int nelem, int size, char *elm, int (*compar) (char *, char *))
2065 int last = nelem - 1;
2066 int celm = nelem / 2;
2070 last_move = first_move = true;
2073 if (first_move == true)
2075 res = compar(bot, elm);
2082 if (last_move == true)
2084 res = compar(elm, bot + last * size);
2088 return (bot + last * size);
2091 res = compar(elm, bot + celm * size);
2093 return (bot + celm * size);
2107 last = last - celm - 1;
2108 bot = bot + (celm + 1) * size;
2109 celm = (last + 1) / 2;
2116 vc_cmp_blk(char *left, char *right)
2121 lblk = (*((VPageDescr *) left))->vpd_blkno;
2122 rblk = (*((VPageDescr *) right))->vpd_blkno;
2133 vc_cmp_offno(char *left, char *right)
2136 if (*(OffsetNumber *) left < *(OffsetNumber *) right)
2138 if (*(OffsetNumber *) left == *(OffsetNumber *) right)
2142 } /* vc_cmp_offno */
2146 vc_getindices(Oid relid, int *nindices, Relation **Irel)
2152 HeapScanDesc pgiscan;
2162 ioid = (Oid *) palloc(10 * sizeof(Oid));
2164 /* prepare a heap scan on the pg_index relation */
2165 pgindex = heap_openr(IndexRelationName);
2166 pgidesc = RelationGetTupleDescriptor(pgindex);
2168 ScanKeyEntryInitialize(&pgikey, 0x0, Anum_pg_index_indrelid,
2169 ObjectIdEqualRegProcedure,
2170 ObjectIdGetDatum(relid));
2172 pgiscan = heap_beginscan(pgindex, false, false, 1, &pgikey);
2174 while (HeapTupleIsValid(pgitup = heap_getnext(pgiscan, 0, NULL)))
2176 d = heap_getattr(pgitup, InvalidBuffer, Anum_pg_index_indexrelid,
2180 ioid = (Oid *) repalloc(ioid, (i + 10) * sizeof(Oid));
2181 ioid[i - 1] = DatumGetObjectId(d);
2184 heap_endscan(pgiscan);
2185 heap_close(pgindex);
2188 { /* No one index found */
2193 if (Irel != (Relation **) NULL)
2194 *Irel = (Relation *) palloc(i * sizeof(Relation));
2198 irel = index_open(ioid[--i]);
2199 if (irel != (Relation) NULL)
2201 if (Irel != (Relation **) NULL)
2208 elog(NOTICE, "CAN't OPEN INDEX %u - SKIP IT", ioid[i]);
2213 if (Irel != (Relation **) NULL && *nindices == 0)
2216 *Irel = (Relation *) NULL;
2219 } /* vc_getindices */
2223 vc_clsindices(int nindices, Relation *Irel)
2226 if (Irel == (Relation *) NULL)
2231 index_close(Irel[nindices]);
2235 } /* vc_clsindices */
2239 vc_mkindesc(Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc)
2242 HeapTuple pgIndexTup;
2243 AttrNumber *attnumP;
2247 *Idesc = (IndDesc *) palloc(nindices * sizeof(IndDesc));
2249 for (i = 0, idcur = *Idesc; i < nindices; i++, idcur++)
2252 SearchSysCacheTuple(INDEXRELID,
2253 ObjectIdGetDatum(Irel[i]->rd_id),
2256 idcur->tform = (IndexTupleForm) GETSTRUCT(pgIndexTup);
2257 for (attnumP = &(idcur->tform->indkey[0]), natts = 0;
2258 *attnumP != InvalidAttrNumber && natts != INDEX_MAX_KEYS;
2259 attnumP++, natts++);
2260 if (idcur->tform->indproc != InvalidOid)
2262 idcur->finfoP = &(idcur->finfo);
2263 FIgetnArgs(idcur->finfoP) = natts;
2265 FIgetProcOid(idcur->finfoP) = idcur->tform->indproc;
2266 *(FIgetname(idcur->finfoP)) = '\0';
2269 idcur->finfoP = (FuncIndexInfo *) NULL;
2271 idcur->natts = natts;
2278 vc_enough_space(VPageDescr vpd, Size len)
2281 len = DOUBLEALIGN(len);
2283 if (len > vpd->vpd_free)
2286 if (vpd->vpd_nusd < vpd->vpd_noff) /* there are free itemid(s) */
2287 return (true); /* and len <= free_space */
2289 /* ok. noff_usd >= noff_free and so we'll have to allocate new itemid */
2290 if (len <= vpd->vpd_free - sizeof(ItemIdData))
2295 } /* vc_enough_space */