]> granicus.if.org Git - postgresql/blob - src/backend/commands/vacuum.c
Thank god for searchable mail archives.
[postgresql] / src / backend / commands / vacuum.c
1 /*-------------------------------------------------------------------------
2  *
3  * vacuum.c--
4  *        the postgres vacuum cleaner
5  *
6  * Copyright (c) 1994, Regents of the University of California
7  *
8  *
9  * IDENTIFICATION
10  *        $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.58 1998/01/15 19:42:40 pgsql Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include <sys/types.h>
15 #include <sys/file.h>
16 #include <string.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20
21 #include <postgres.h>
22
23 #include <fmgr.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>
52 #else
53 #include <sys/time.h>
54 #include <sys/resource.h>
55 #endif
56
57 /* #include <port-protos.h> */ /* Why? */
58
59 extern int BlowawayRelationBuffers(Relation rdesc, BlockNumber block);
60
61 bool            VacuumRunning = false;
62
63 static Portal vc_portal;
64
65 static int      MESSAGE_LEVEL;          /* message level */
66
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.fn_addr != NULL )
71 #define VacAttrStatsLtGtValid(stats) ( stats->f_cmplt.fn_addr != NULL && \
72                                                                    stats->f_cmpgt.fn_addr != NULL && \
73                                                                    RegProcedureIsValid(stats->outfunc) )
74
75
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);
104
105 void
106 vacuum(char *vacrel, bool verbose, bool analyze, List *va_spec)
107 {
108         char       *pname;
109         MemoryContext old;
110         PortalVariableMemory pmem;
111         NameData        VacRel;
112         List       *le;
113         List       *va_cols = NIL;
114
115         /*
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.
120          */
121         pname = (char *) palloc(strlen(VACPNAME) + 1);
122         strcpy(pname, VACPNAME);
123         vc_portal = CreatePortal(pname);
124         pfree(pname);
125
126         if (verbose)
127                 MESSAGE_LEVEL = NOTICE;
128         else
129                 MESSAGE_LEVEL = DEBUG;
130
131         /* vacrel gets de-allocated on transaction commit */
132         if (vacrel)
133                 strcpy(VacRel.data, vacrel);
134
135         pmem = PortalGetVariableMemory(vc_portal);
136         old = MemoryContextSwitchTo((MemoryContext) pmem);
137
138         Assert(va_spec == NIL || analyze);
139         foreach(le, va_spec)
140         {
141                 char       *col = (char *) lfirst(le);
142                 char       *dest;
143
144                 dest = (char *) palloc(strlen(col) + 1);
145                 strcpy(dest, col);
146                 va_cols = lappend(va_cols, dest);
147         }
148         MemoryContextSwitchTo(old);
149
150         /* initialize vacuum cleaner */
151         vc_init();
152
153         /* vacuum the database */
154         if (vacrel)
155                 vc_vacuum(&VacRel, analyze, va_cols);
156         else
157                 vc_vacuum(NULL, analyze, NIL);
158
159         PortalDestroy(&vc_portal);
160
161         /* clean up */
162         vc_shutdown();
163 }
164
165 /*
166  *      vc_init(), vc_shutdown() -- start up and shut down the vacuum cleaner.
167  *
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.
172  *
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
180  *              PostgresMain().
181  */
182 static void
183 vc_init()
184 {
185         int                     fd;
186
187         if ((fd = open("pg_vlock", O_CREAT | O_EXCL, 0600)) < 0)
188                 elog(ERROR, "can't create lock file -- another vacuum cleaner running?");
189
190         close(fd);
191
192         /*
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.
197          */
198
199         VacuumRunning = true;
200
201         /* matches the StartTransaction in PostgresMain() */
202         CommitTransactionCommand();
203 }
204
205 static void
206 vc_shutdown()
207 {
208         /* on entry, not in a transaction */
209         if (unlink("pg_vlock") < 0)
210                 elog(ERROR, "vacuum: can't destroy lock file!");
211
212         /* okay, we're done */
213         VacuumRunning = false;
214
215         /* matches the CommitTransaction in PostgresMain() */
216         StartTransactionCommand();
217
218 }
219
220 void
221 vc_abort()
222 {
223         /* on abort, remove the vacuum cleaner lock file */
224         unlink("pg_vlock");
225
226         VacuumRunning = false;
227 }
228
229 /*
230  *      vc_vacuum() -- vacuum the database.
231  *
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
235  *              locks at one time.
236  */
237 static void
238 vc_vacuum(NameData *VacRelP, bool analyze, List *va_cols)
239 {
240         VRelList        vrl,
241                                 cur;
242
243         /* get list of relations */
244         vrl = vc_getrels(VacRelP);
245
246         if (analyze && VacRelP == NULL && vrl != NULL)
247                 vc_delhilowstats(InvalidOid, 0, NULL);
248
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);
252
253         vc_free(vrl);
254 }
255
256 static VRelList
257 vc_getrels(NameData *VacRelP)
258 {
259         Relation        pgclass;
260         TupleDesc       pgcdesc;
261         HeapScanDesc pgcscan;
262         HeapTuple       pgctup;
263         Buffer          buf;
264         PortalVariableMemory portalmem;
265         MemoryContext old;
266         VRelList        vrl,
267                                 cur;
268         Datum           d;
269         char       *rname;
270         char            rkind;
271         bool            n;
272         ScanKeyData pgckey;
273         bool            found = false;
274
275         StartTransactionCommand();
276
277         if (VacRelP->data)
278         {
279                 ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relname,
280                                                            NameEqualRegProcedure,
281                                                            PointerGetDatum(VacRelP->data));
282         }
283         else
284         {
285                 ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relkind,
286                                                   CharacterEqualRegProcedure, CharGetDatum('r'));
287         }
288
289         portalmem = PortalGetVariableMemory(vc_portal);
290         vrl = cur = (VRelList) NULL;
291
292         pgclass = heap_openr(RelationRelationName);
293         pgcdesc = RelationGetTupleDescriptor(pgclass);
294
295         pgcscan = heap_beginscan(pgclass, false, false, 1, &pgckey);
296
297         while (HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &buf)))
298         {
299
300                 found = true;
301
302                 d = heap_getattr(pgctup, buf, Anum_pg_class_relname, pgcdesc, &n);
303                 rname = (char *) d;
304
305                 /*
306                  * don't vacuum large objects for now - something breaks when we
307                  * do
308                  */
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')
313                 {
314                         elog(NOTICE, "Rel %s: can't vacuum LargeObjects now",
315                                  rname);
316                         ReleaseBuffer(buf);
317                         continue;
318                 }
319
320                 d = heap_getattr(pgctup, buf, Anum_pg_class_relkind, pgcdesc, &n);
321
322                 rkind = DatumGetChar(d);
323
324                 /* skip system relations */
325                 if (rkind != 'r')
326                 {
327                         ReleaseBuffer(buf);
328                         elog(NOTICE, "Vacuum: can not process index and certain system tables");
329                         continue;
330                 }
331
332                 /* get a relation list entry for this guy */
333                 old = MemoryContextSwitchTo((MemoryContext) portalmem);
334                 if (vrl == (VRelList) NULL)
335                 {
336                         vrl = cur = (VRelList) palloc(sizeof(VRelListData));
337                 }
338                 else
339                 {
340                         cur->vrl_next = (VRelList) palloc(sizeof(VRelListData));
341                         cur = cur->vrl_next;
342                 }
343                 MemoryContextSwitchTo(old);
344
345                 cur->vrl_relid = pgctup->t_oid;
346                 cur->vrl_next = (VRelList) NULL;
347
348                 /* wei hates it if you forget to do this */
349                 ReleaseBuffer(buf);
350         }
351         if (found == false)
352                 elog(NOTICE, "Vacuum: table not found");
353
354
355         heap_endscan(pgcscan);
356         heap_close(pgclass);
357
358         CommitTransactionCommand();
359
360         return (vrl);
361 }
362
363 /*
364  *      vc_vacone() -- vacuum one heap relation
365  *
366  *              This routine vacuums a single heap, cleans out its indices, and
367  *              updates its statistics npages and ntups statistics.
368  *
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.
374  */
375 static void
376 vc_vacone(Oid relid, bool analyze, List *va_cols)
377 {
378         Relation        pgclass;
379         TupleDesc       pgcdesc;
380         HeapTuple       pgctup,
381                                 pgttup;
382         Buffer          pgcbuf;
383         HeapScanDesc pgcscan;
384         Relation        onerel;
385         ScanKeyData pgckey;
386         VPageListData Vvpl;                     /* List of pages to vacuum and/or clean
387                                                                  * indices */
388         VPageListData Fvpl;                     /* List of pages with space enough for
389                                                                  * re-using */
390         VPageDescr *vpp;
391         Relation   *Irel;
392         int32           nindices,
393                                 i;
394         VRelStats  *vacrelstats;
395
396         StartTransactionCommand();
397
398         ScanKeyEntryInitialize(&pgckey, 0x0, ObjectIdAttributeNumber,
399                                                    ObjectIdEqualRegProcedure,
400                                                    ObjectIdGetDatum(relid));
401
402         pgclass = heap_openr(RelationRelationName);
403         pgcdesc = RelationGetTupleDescriptor(pgclass);
404         pgcscan = heap_beginscan(pgclass, false, false, 1, &pgckey);
405
406         /*
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.
409          */
410
411         if (!HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &pgcbuf)))
412         {
413                 heap_endscan(pgcscan);
414                 heap_close(pgclass);
415                 CommitTransactionCommand();
416                 return;
417         }
418
419         /* now open the class and vacuum it */
420         onerel = heap_open(relid);
421
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))
427         {
428                 int                     attr_cnt,
429                                    *attnums = NULL;
430                 AttributeTupleForm *attr;
431
432                 attr_cnt = onerel->rd_att->natts;
433                 attr = onerel->rd_att->attrs;
434
435                 if (va_cols != NIL)
436                 {
437                         int                     tcnt = 0;
438                         List       *le;
439
440                         if (length(va_cols) > attr_cnt)
441                                 elog(ERROR, "vacuum: too many attributes specified for relation %s",
442                                          (RelationGetRelationName(onerel))->data);
443                         attnums = (int *) palloc(attr_cnt * sizeof(int));
444                         foreach(le, va_cols)
445                         {
446                                 char       *col = (char *) lfirst(le);
447
448                                 for (i = 0; i < attr_cnt; i++)
449                                 {
450                                         if (namestrcmp(&(attr[i]->attname), col) == 0)
451                                                 break;
452                                 }
453                                 if (i < attr_cnt)               /* found */
454                                         attnums[tcnt++] = i;
455                                 else
456                                 {
457                                         elog(ERROR, "vacuum: there is no attribute %s in %s",
458                                                  col, (RelationGetRelationName(onerel))->data);
459                                 }
460                         }
461                         attr_cnt = tcnt;
462                 }
463
464                 vacrelstats->vacattrstats =
465                         (VacAttrStats *) palloc(attr_cnt * sizeof(VacAttrStats));
466
467                 for (i = 0; i < attr_cnt; i++)
468                 {
469                         Operator        func_operator;
470                         OperatorTupleForm pgopform;
471                         VacAttrStats *stats;
472
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;
483
484                         func_operator = oper("=", stats->attr->atttypid, stats->attr->atttypid, true);
485                         if (func_operator != NULL)
486                         {
487                                 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
488                                 fmgr_info(pgopform->oprcode, &(stats->f_cmpeq));
489                         }
490                         else
491                                 stats->f_cmpeq.fn_addr = NULL;
492
493                         func_operator = oper("<", stats->attr->atttypid, stats->attr->atttypid, true);
494                         if (func_operator != NULL)
495                         {
496                                 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
497                                 fmgr_info(pgopform->oprcode, &(stats->f_cmplt));
498                         }
499                         else
500                                 stats->f_cmplt.fn_addr = NULL;
501
502                         func_operator = oper(">", stats->attr->atttypid, stats->attr->atttypid, true);
503                         if (func_operator != NULL)
504                         {
505                                 pgopform = (OperatorTupleForm) GETSTRUCT(func_operator);
506                                 fmgr_info(pgopform->oprcode, &(stats->f_cmpgt));
507                         }
508                         else
509                                 stats->f_cmpgt.fn_addr = NULL;
510
511                         pgttup = SearchSysCacheTuple(TYPOID,
512                                                                  ObjectIdGetDatum(stats->attr->atttypid),
513                                                                                  0, 0, 0);
514                         if (HeapTupleIsValid(pgttup))
515                                 stats->outfunc = ((TypeTupleForm) GETSTRUCT(pgttup))->typoutput;
516                         else
517                                 stats->outfunc = InvalidOid;
518                 }
519                 vacrelstats->va_natts = attr_cnt;
520                 vc_delhilowstats(relid, ((attnums) ? attr_cnt : 0), attnums);
521                 if (attnums)
522                         pfree(attnums);
523         }
524         else
525         {
526                 vacrelstats->va_natts = 0;
527                 vacrelstats->vacattrstats = (VacAttrStats *) NULL;
528         }
529
530         /* we require the relation to be locked until the indices are cleaned */
531         RelationSetLockForWrite(onerel);
532
533         /* scan it */
534         Vvpl.vpl_npages = Fvpl.vpl_npages = 0;
535         vc_scanheap(vacrelstats, onerel, &Vvpl, &Fvpl);
536
537         /* Now open indices */
538         Irel = (Relation *) NULL;
539         vc_getindices(vacrelstats->relid, &nindices, &Irel);
540
541         if (nindices > 0)
542                 vacrelstats->hasindex = true;
543         else
544                 vacrelstats->hasindex = false;
545
546         /* Clean/scan index relation(s) */
547         if (Irel != (Relation *) NULL)
548         {
549                 if (Vvpl.vpl_npages > 0)
550                 {
551                         for (i = 0; i < nindices; i++)
552                                 vc_vaconeind(&Vvpl, Irel[i], vacrelstats->ntups);
553                 }
554                 else
555 /* just scan indices to update statistic */
556                 {
557                         for (i = 0; i < nindices; i++)
558                                 vc_scanoneind(Irel[i], vacrelstats->ntups);
559                 }
560         }
561
562         if (Fvpl.vpl_npages > 0)        /* Try to shrink heap */
563                 vc_rpfheap(vacrelstats, onerel, &Vvpl, &Fvpl, nindices, Irel);
564         else
565         {
566                 if (Irel != (Relation *) NULL)
567                         vc_clsindices(nindices, Irel);
568                 if (Vvpl.vpl_npages > 0)/* Clean pages from Vvpl list */
569                         vc_vacheap(vacrelstats, onerel, &Vvpl);
570         }
571
572         /* ok - free Vvpl list of reapped pages */
573         if (Vvpl.vpl_npages > 0)
574         {
575                 vpp = Vvpl.vpl_pgdesc;
576                 for (i = 0; i < Vvpl.vpl_npages; i++, vpp++)
577                         pfree(*vpp);
578                 pfree(Vvpl.vpl_pgdesc);
579                 if (Fvpl.vpl_npages > 0)
580                         pfree(Fvpl.vpl_pgdesc);
581         }
582
583         /* all done with this class */
584         heap_close(onerel);
585         heap_endscan(pgcscan);
586         heap_close(pgclass);
587
588         /* update statistics in pg_class */
589         vc_updstats(vacrelstats->relid, vacrelstats->npages, vacrelstats->ntups,
590                                 vacrelstats->hasindex, vacrelstats);
591
592         /* next command frees attribute stats */
593
594         CommitTransactionCommand();
595 }
596
597 /*
598  *      vc_scanheap() -- scan an open heap relation
599  *
600  *              This routine sets commit times, constructs Vvpl list of
601  *              empty/uninitialized pages and pages with dead tuples and
602  *              ~LP_USED line pointers, constructs Fvpl list of pages
603  *              appropriate for purposes of shrinking and maintains statistics
604  *              on the number of live tuples in a heap.
605  */
606 static void
607 vc_scanheap(VRelStats *vacrelstats, Relation onerel,
608                         VPageList Vvpl, VPageList Fvpl)
609 {
610         int                     nblocks,
611                                 blkno;
612         ItemId          itemid;
613         ItemPointer itemptr;
614         HeapTuple       htup;
615         Buffer          buf;
616         Page            page,
617                                 tempPage = NULL;
618         OffsetNumber offnum,
619                                 maxoff;
620         bool            pgchanged,
621                                 tupgone,
622                                 dobufrel,
623                                 notup;
624         char       *relname;
625         VPageDescr      vpc,
626                                 vp;
627         uint32          nvac,
628                                 ntups,
629                                 nunused,
630                                 ncrash,
631                                 nempg,
632                                 nnepg,
633                                 nchpg,
634                                 nemend;
635         Size            frsize,
636                                 frsusf;
637         Size            min_tlen = MAXTUPLEN;
638         Size            max_tlen = 0;
639         int32           i /* , attr_cnt */ ;
640         struct rusage ru0,
641                                 ru1;
642         bool            do_shrinking = true;
643
644         getrusage(RUSAGE_SELF, &ru0);
645
646         nvac = ntups = nunused = ncrash = nempg = nnepg = nchpg = nemend = 0;
647         frsize = frsusf = 0;
648
649         relname = (RelationGetRelationName(onerel))->data;
650
651         nblocks = RelationGetNumberOfBlocks(onerel);
652
653         vpc = (VPageDescr) palloc(sizeof(VPageDescrData) + MaxOffsetNumber * sizeof(OffsetNumber));
654         vpc->vpd_nusd = 0;
655
656         for (blkno = 0; blkno < nblocks; blkno++)
657         {
658                 buf = ReadBuffer(onerel, blkno);
659                 page = BufferGetPage(buf);
660                 vpc->vpd_blkno = blkno;
661                 vpc->vpd_noff = 0;
662
663                 if (PageIsNew(page))
664                 {
665                         elog(NOTICE, "Rel %s: Uninitialized page %u - fixing",
666                                  relname, blkno);
667                         PageInit(page, BufferGetPageSize(buf), 0);
668                         vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
669                         frsize += (vpc->vpd_free - sizeof(ItemIdData));
670                         nnepg++;
671                         nemend++;
672                         vc_reappage(Vvpl, vpc);
673                         WriteBuffer(buf);
674                         continue;
675                 }
676
677                 if (PageIsEmpty(page))
678                 {
679                         vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
680                         frsize += (vpc->vpd_free - sizeof(ItemIdData));
681                         nempg++;
682                         nemend++;
683                         vc_reappage(Vvpl, vpc);
684                         ReleaseBuffer(buf);
685                         continue;
686                 }
687
688                 pgchanged = false;
689                 notup = true;
690                 maxoff = PageGetMaxOffsetNumber(page);
691                 for (offnum = FirstOffsetNumber;
692                          offnum <= maxoff;
693                          offnum = OffsetNumberNext(offnum))
694                 {
695                         itemid = PageGetItemId(page, offnum);
696
697                         /*
698                          * Collect un-used items too - it's possible to have indices
699                          * pointing here after crash.
700                          */
701                         if (!ItemIdIsUsed(itemid))
702                         {
703                                 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
704                                 nunused++;
705                                 continue;
706                         }
707
708                         htup = (HeapTuple) PageGetItem(page, itemid);
709                         tupgone = false;
710
711                         if (!(htup->t_infomask & HEAP_XMIN_COMMITTED))
712                         {
713                                 if (htup->t_infomask & HEAP_XMIN_INVALID)
714                                         tupgone = true;
715                                 else
716                                 {
717                                         if (TransactionIdDidAbort(htup->t_xmin))
718                                                 tupgone = true;
719                                         else if (TransactionIdDidCommit(htup->t_xmin))
720                                         {
721                                                 htup->t_infomask |= HEAP_XMIN_COMMITTED;
722                                                 pgchanged = true;
723                                         }
724                                         else if (!TransactionIdIsInProgress(htup->t_xmin))
725                                         {
726                                                 /*
727                                                  * Not Aborted, Not Committed, Not in Progress - 
728                                                  * so it's from crashed process. - vadim 11/26/96
729                                                  */
730                                                 ncrash++;
731                                                 tupgone = true;
732                                         }
733                                         else
734                                         {
735                                                 elog(NOTICE, "Rel %s: TID %u/%u: InsertTransactionInProgress %u - can't shrink relation",
736                                                          relname, blkno, offnum, htup->t_xmin);
737                                                 do_shrinking = false;
738                                         }
739                                 }
740                         }
741
742                         /* 
743                          * here we are concerned about tuples with xmin committed 
744                          * and xmax unknown or committed
745                          */
746                         if (htup->t_infomask & HEAP_XMIN_COMMITTED && 
747                                 !(htup->t_infomask & HEAP_XMAX_INVALID))
748                         {
749                                 if (htup->t_infomask & HEAP_XMAX_COMMITTED)
750                                         tupgone = true;
751                                 else if (TransactionIdDidAbort(htup->t_xmax))
752                                 {
753                                         htup->t_infomask |= HEAP_XMAX_INVALID;
754                                         pgchanged = true;
755                                 }
756                                 else if (TransactionIdDidCommit(htup->t_xmax))
757                                         tupgone = true;
758                                 else if (!TransactionIdIsInProgress(htup->t_xmax))
759                                 {
760                                         /*
761                                          * Not Aborted, Not Committed, Not in Progress - so it
762                                          * from crashed process. - vadim 06/02/97
763                                          */
764                                         htup->t_infomask |= HEAP_XMAX_INVALID;;
765                                         pgchanged = true;
766                                 }
767                                 else
768                                 {
769                                         elog(NOTICE, "Rel %s: TID %u/%u: DeleteTransactionInProgress %u - can't shrink relation",
770                                                  relname, blkno, offnum, htup->t_xmax);
771                                         do_shrinking = false;
772                                 }
773                         }
774
775                         /*
776                          * It's possibly! But from where it comes ? And should we fix
777                          * it ?  - vadim 11/28/96
778                          */
779                         itemptr = &(htup->t_ctid);
780                         if (!ItemPointerIsValid(itemptr) ||
781                                 BlockIdGetBlockNumber(&(itemptr->ip_blkid)) != blkno)
782                         {
783                                 elog(NOTICE, "Rel %s: TID %u/%u: TID IN TUPLEHEADER %u/%u IS NOT THE SAME. TUPGONE %d.",
784                                          relname, blkno, offnum,
785                                          BlockIdGetBlockNumber(&(itemptr->ip_blkid)),
786                                          itemptr->ip_posid, tupgone);
787                         }
788
789                         /*
790                          * Other checks...
791                          */
792                         if (htup->t_len != itemid->lp_len)
793                         {
794                                 elog(NOTICE, "Rel %s: TID %u/%u: TUPLE_LEN IN PAGEHEADER %u IS NOT THE SAME AS IN TUPLEHEADER %u. TUPGONE %d.",
795                                          relname, blkno, offnum,
796                                          itemid->lp_len, htup->t_len, tupgone);
797                         }
798                         if (!OidIsValid(htup->t_oid))
799                         {
800                                 elog(NOTICE, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
801                                          relname, blkno, offnum, tupgone);
802                         }
803
804                         if (tupgone)
805                         {
806                                 ItemId          lpp;
807
808                                 if (tempPage == (Page) NULL)
809                                 {
810                                         Size            pageSize;
811
812                                         pageSize = PageGetPageSize(page);
813                                         tempPage = (Page) palloc(pageSize);
814                                         memmove(tempPage, page, pageSize);
815                                 }
816
817                                 lpp = &(((PageHeader) tempPage)->pd_linp[offnum - 1]);
818
819                                 /* mark it unused */
820                                 lpp->lp_flags &= ~LP_USED;
821
822                                 vpc->vpd_voff[vpc->vpd_noff++] = offnum;
823                                 nvac++;
824
825                         }
826                         else
827                         {
828                                 ntups++;
829                                 notup = false;
830                                 if (htup->t_len < min_tlen)
831                                         min_tlen = htup->t_len;
832                                 if (htup->t_len > max_tlen)
833                                         max_tlen = htup->t_len;
834                                 vc_attrstats(onerel, vacrelstats, htup);
835                         }
836                 }
837
838                 if (pgchanged)
839                 {
840                         WriteBuffer(buf);
841                         dobufrel = false;
842                         nchpg++;
843                 }
844                 else
845                         dobufrel = true;
846                 if (tempPage != (Page) NULL)
847                 {                                               /* Some tuples are gone */
848                         PageRepairFragmentation(tempPage);
849                         vpc->vpd_free = ((PageHeader) tempPage)->pd_upper - ((PageHeader) tempPage)->pd_lower;
850                         frsize += vpc->vpd_free;
851                         vc_reappage(Vvpl, vpc);
852                         pfree(tempPage);
853                         tempPage = (Page) NULL;
854                 }
855                 else if (vpc->vpd_noff > 0)
856                 {                                               /* there are only ~LP_USED line pointers */
857                         vpc->vpd_free = ((PageHeader) page)->pd_upper - ((PageHeader) page)->pd_lower;
858                         frsize += vpc->vpd_free;
859                         vc_reappage(Vvpl, vpc);
860                 }
861                 if (dobufrel)
862                         ReleaseBuffer(buf);
863                 if (notup)
864                         nemend++;
865                 else
866                         nemend = 0;
867         }
868
869         pfree(vpc);
870
871         /* save stats in the rel list for use later */
872         vacrelstats->ntups = ntups;
873         vacrelstats->npages = nblocks;
874 /*        vacrelstats->natts = attr_cnt;*/
875         if (ntups == 0)
876                 min_tlen = max_tlen = 0;
877         vacrelstats->min_tlen = min_tlen;
878         vacrelstats->max_tlen = max_tlen;
879
880         Vvpl->vpl_nemend = nemend;
881         Fvpl->vpl_nemend = nemend;
882
883         /*
884          * Try to make Fvpl keeping in mind that we can't use free space of
885          * "empty" end-pages and last page if it reapped.
886          */
887         if (do_shrinking && Vvpl->vpl_npages - nemend > 0)
888         {
889                 int                     nusf;           /* blocks usefull for re-using */
890
891                 nusf = Vvpl->vpl_npages - nemend;
892                 if ((Vvpl->vpl_pgdesc[nusf - 1])->vpd_blkno == nblocks - nemend - 1)
893                         nusf--;
894
895                 for (i = 0; i < nusf; i++)
896                 {
897                         vp = Vvpl->vpl_pgdesc[i];
898                         if (vc_enough_space(vp, min_tlen))
899                         {
900                                 vc_vpinsert(Fvpl, vp);
901                                 frsusf += vp->vpd_free;
902                         }
903                 }
904         }
905
906         getrusage(RUSAGE_SELF, &ru1);
907
908         elog(MESSAGE_LEVEL, "Rel %s: Pages %u: Changed %u, Reapped %u, Empty %u, New %u; \
909 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.",
910                  relname,
911                  nblocks, nchpg, Vvpl->vpl_npages, nempg, nnepg,
912                  ntups, nvac, ncrash, nunused, min_tlen, max_tlen,
913                  frsize, frsusf, nemend, Fvpl->vpl_npages,
914                  ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
915                  ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
916
917 }                                                               /* vc_scanheap */
918
919
920 /*
921  *      vc_rpfheap() -- try to repaire relation' fragmentation
922  *
923  *              This routine marks dead tuples as unused and tries re-use dead space
924  *              by moving tuples (and inserting indices if needed). It constructs
925  *              Nvpl list of free-ed pages (moved tuples) and clean indices
926  *              for them after committing (in hack-manner - without losing locks
927  *              and freeing memory!) current transaction. It truncates relation
928  *              if some end-blocks are gone away.
929  */
930 static void
931 vc_rpfheap(VRelStats *vacrelstats, Relation onerel,
932                    VPageList Vvpl, VPageList Fvpl, int nindices, Relation *Irel)
933 {
934         TransactionId myXID;
935         CommandId       myCID;
936         Buffer          buf,
937                                 ToBuf;
938         int                     nblocks,
939                                 blkno;
940         Page            page,
941                                 ToPage = NULL;
942         OffsetNumber offnum = 0,
943                                 maxoff = 0,
944                                 newoff,
945                                 moff;
946         ItemId          itemid,
947                                 newitemid;
948         HeapTuple       htup,
949                                 newtup;
950         TupleDesc       tupdesc = NULL;
951         Datum      *idatum = NULL;
952         char       *inulls = NULL;
953         InsertIndexResult iresult;
954         VPageListData Nvpl;
955         VPageDescr      ToVpd = NULL,
956                                 Fvplast,
957                                 Vvplast,
958                                 vpc,
959                            *vpp;
960         int                     ToVpI = 0;
961         IndDesc    *Idesc,
962                            *idcur;
963         int                     Fblklast,
964                                 Vblklast,
965                                 i;
966         Size            tlen;
967         int                     nmoved,
968                                 Fnpages,
969                                 Vnpages;
970         int                     nchkmvd,
971                                 ntups;
972         bool            isempty,
973                                 dowrite;
974         struct rusage ru0,
975                                 ru1;
976
977         getrusage(RUSAGE_SELF, &ru0);
978
979         myXID = GetCurrentTransactionId();
980         myCID = GetCurrentCommandId();
981
982         if (Irel != (Relation *) NULL)          /* preparation for index' inserts */
983         {
984                 vc_mkindesc(onerel, nindices, Irel, &Idesc);
985                 tupdesc = RelationGetTupleDescriptor(onerel);
986                 idatum = (Datum *) palloc(INDEX_MAX_KEYS * sizeof(*idatum));
987                 inulls = (char *) palloc(INDEX_MAX_KEYS * sizeof(*inulls));
988         }
989
990         Nvpl.vpl_npages = 0;
991         Fnpages = Fvpl->vpl_npages;
992         Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
993         Fblklast = Fvplast->vpd_blkno;
994         Assert(Vvpl->vpl_npages > Vvpl->vpl_nemend);
995         Vnpages = Vvpl->vpl_npages - Vvpl->vpl_nemend;
996         Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
997         Vblklast = Vvplast->vpd_blkno;
998         Assert(Vblklast >= Fblklast);
999         ToBuf = InvalidBuffer;
1000         nmoved = 0;
1001
1002         vpc = (VPageDescr) palloc(sizeof(VPageDescrData) + MaxOffsetNumber * sizeof(OffsetNumber));
1003         vpc->vpd_nusd = vpc->vpd_noff = 0;
1004
1005         nblocks = vacrelstats->npages;
1006         for (blkno = nblocks - Vvpl->vpl_nemend - 1;; blkno--)
1007         {
1008                 /* if it's reapped page and it was used by me - quit */
1009                 if (blkno == Fblklast && Fvplast->vpd_nusd > 0)
1010                         break;
1011
1012                 buf = ReadBuffer(onerel, blkno);
1013                 page = BufferGetPage(buf);
1014
1015                 vpc->vpd_noff = 0;
1016
1017                 isempty = PageIsEmpty(page);
1018
1019                 dowrite = false;
1020                 if (blkno == Vblklast)  /* it's reapped page */
1021                 {
1022                         if (Vvplast->vpd_noff > 0)      /* there are dead tuples */
1023                         {                                       /* on this page - clean */
1024                                 Assert(!isempty);
1025                                 vc_vacpage(page, Vvplast);
1026                                 dowrite = true;
1027                         }
1028                         else
1029                         {
1030                                 Assert(isempty);
1031                         }
1032                         --Vnpages;
1033                         Assert(Vnpages > 0);
1034                         /* get prev reapped page from Vvpl */
1035                         Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
1036                         Vblklast = Vvplast->vpd_blkno;
1037                         if (blkno == Fblklast)          /* this page in Fvpl too */
1038                         {
1039                                 --Fnpages;
1040                                 Assert(Fnpages > 0);
1041                                 Assert(Fvplast->vpd_nusd == 0);
1042                                 /* get prev reapped page from Fvpl */
1043                                 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1044                                 Fblklast = Fvplast->vpd_blkno;
1045                         }
1046                         Assert(Fblklast <= Vblklast);
1047                         if (isempty)
1048                         {
1049                                 ReleaseBuffer(buf);
1050                                 continue;
1051                         }
1052                 }
1053                 else
1054                 {
1055                         Assert(!isempty);
1056                 }
1057
1058                 vpc->vpd_blkno = blkno;
1059                 maxoff = PageGetMaxOffsetNumber(page);
1060                 for (offnum = FirstOffsetNumber;
1061                          offnum <= maxoff;
1062                          offnum = OffsetNumberNext(offnum))
1063                 {
1064                         itemid = PageGetItemId(page, offnum);
1065
1066                         if (!ItemIdIsUsed(itemid))
1067                                 continue;
1068
1069                         htup = (HeapTuple) PageGetItem(page, itemid);
1070                         tlen = htup->t_len;
1071
1072                         /* try to find new page for this tuple */
1073                         if (ToBuf == InvalidBuffer ||
1074                                 !vc_enough_space(ToVpd, tlen))
1075                         {
1076                                 if (ToBuf != InvalidBuffer)
1077                                 {
1078                                         WriteBuffer(ToBuf);
1079                                         ToBuf = InvalidBuffer;
1080
1081                                         /*
1082                                          * If no one tuple can't be added to this page -
1083                                          * remove page from Fvpl. - vadim 11/27/96
1084                                          */
1085                                         if (!vc_enough_space(ToVpd, vacrelstats->min_tlen))
1086                                         {
1087                                                 if (ToVpd != Fvplast)
1088                                                 {
1089                                                         Assert(Fnpages > ToVpI + 1);
1090                                                         memmove(Fvpl->vpl_pgdesc + ToVpI,
1091                                                                         Fvpl->vpl_pgdesc + ToVpI + 1,
1092                                                         sizeof(VPageDescr *) * (Fnpages - ToVpI - 1));
1093                                                 }
1094                                                 Assert(Fnpages >= 1);
1095                                                 Fnpages--;
1096                                                 if (Fnpages == 0)
1097                                                         break;
1098                                                 /* get prev reapped page from Fvpl */
1099                                                 Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
1100                                                 Fblklast = Fvplast->vpd_blkno;
1101                                         }
1102                                 }
1103                                 for (i = 0; i < Fnpages; i++)
1104                                 {
1105                                         if (vc_enough_space(Fvpl->vpl_pgdesc[i], tlen))
1106                                                 break;
1107                                 }
1108                                 if (i == Fnpages)
1109                                         break;          /* can't move item anywhere */
1110                                 ToVpI = i;
1111                                 ToVpd = Fvpl->vpl_pgdesc[ToVpI];
1112                                 ToBuf = ReadBuffer(onerel, ToVpd->vpd_blkno);
1113                                 ToPage = BufferGetPage(ToBuf);
1114                                 /* if this page was not used before - clean it */
1115                                 if (!PageIsEmpty(ToPage) && ToVpd->vpd_nusd == 0)
1116                                         vc_vacpage(ToPage, ToVpd);
1117                         }
1118
1119                         /* copy tuple */
1120                         newtup = (HeapTuple) palloc(tlen);
1121                         memmove((char *) newtup, (char *) htup, tlen);
1122
1123                         /* store transaction information */
1124                         TransactionIdStore(myXID, &(newtup->t_xmin));
1125                         newtup->t_cmin = myCID;
1126                         StoreInvalidTransactionId(&(newtup->t_xmax));
1127                         /* set xmin to unknown and xmax to invalid */
1128                         newtup->t_infomask &= ~(HEAP_XACT_MASK);
1129                         newtup->t_infomask |= HEAP_XMAX_INVALID;
1130
1131                         /* add tuple to the page */
1132                         newoff = PageAddItem(ToPage, (Item) newtup, tlen,
1133                                                                  InvalidOffsetNumber, LP_USED);
1134                         if (newoff == InvalidOffsetNumber)
1135                         {
1136                                 elog(ERROR, "\
1137 failed to add item with len = %u to page %u (free space %u, nusd %u, noff %u)",
1138                                          tlen, ToVpd->vpd_blkno, ToVpd->vpd_free,
1139                                          ToVpd->vpd_nusd, ToVpd->vpd_noff);
1140                         }
1141                         newitemid = PageGetItemId(ToPage, newoff);
1142                         pfree(newtup);
1143                         newtup = (HeapTuple) PageGetItem(ToPage, newitemid);
1144                         ItemPointerSet(&(newtup->t_ctid), ToVpd->vpd_blkno, newoff);
1145
1146                         /* now logically delete end-tuple */
1147                         TransactionIdStore(myXID, &(htup->t_xmax));
1148                         htup->t_cmax = myCID;
1149                         /* set xmax to unknown */
1150                         htup->t_infomask &= ~(HEAP_XMAX_INVALID | HEAP_XMAX_COMMITTED);
1151
1152                         ToVpd->vpd_nusd++;
1153                         nmoved++;
1154                         ToVpd->vpd_free = ((PageHeader) ToPage)->pd_upper - ((PageHeader) ToPage)->pd_lower;
1155                         vpc->vpd_voff[vpc->vpd_noff++] = offnum;
1156
1157                         /* insert index' tuples if needed */
1158                         if (Irel != (Relation *) NULL)
1159                         {
1160                                 for (i = 0, idcur = Idesc; i < nindices; i++, idcur++)
1161                                 {
1162                                         FormIndexDatum(
1163                                                                    idcur->natts,
1164                                                            (AttrNumber *) &(idcur->tform->indkey[0]),
1165                                                                    newtup,
1166                                                                    tupdesc,
1167                                                                    InvalidBuffer,
1168                                                                    idatum,
1169                                                                    inulls,
1170                                                                    idcur->finfoP);
1171                                         iresult = index_insert(
1172                                                                                    Irel[i],
1173                                                                                    idatum,
1174                                                                                    inulls,
1175                                                                                    &(newtup->t_ctid),
1176                                                                                    onerel);
1177                                         if (iresult)
1178                                                 pfree(iresult);
1179                                 }
1180                         }
1181
1182                 }                                               /* walk along page */
1183
1184                 if (vpc->vpd_noff > 0)  /* some tuples were moved */
1185                 {
1186                         vc_reappage(&Nvpl, vpc);
1187                         WriteBuffer(buf);
1188                 }
1189                 else if (dowrite)
1190                         WriteBuffer(buf);
1191                 else
1192                         ReleaseBuffer(buf);
1193
1194                 if (offnum <= maxoff)
1195                         break;                          /* some item(s) left */
1196
1197         }                                                       /* walk along relation */
1198
1199         blkno++;                                        /* new number of blocks */
1200
1201         if (ToBuf != InvalidBuffer)
1202         {
1203                 Assert(nmoved > 0);
1204                 WriteBuffer(ToBuf);
1205         }
1206
1207         if (nmoved > 0)
1208         {
1209
1210                 /*
1211                  * We have to commit our tuple' movings before we'll truncate
1212                  * relation, but we shouldn't lose our locks. And so - quick hack:
1213                  * flush buffers and record status of current transaction as
1214                  * committed, and continue. - vadim 11/13/96
1215                  */
1216                 FlushBufferPool(!TransactionFlushEnabled());
1217                 TransactionIdCommit(myXID);
1218                 FlushBufferPool(!TransactionFlushEnabled());
1219         }
1220
1221         /*
1222          * Clean uncleaned reapped pages from Vvpl list and set xmin committed
1223          * for inserted tuples
1224          */
1225         nchkmvd = 0;
1226         for (i = 0, vpp = Vvpl->vpl_pgdesc; i < Vnpages; i++, vpp++)
1227         {
1228                 Assert((*vpp)->vpd_blkno < blkno);
1229                 buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1230                 page = BufferGetPage(buf);
1231                 if ((*vpp)->vpd_nusd == 0)              /* this page was not used */
1232                 {
1233
1234                         /*
1235                          * noff == 0 in empty pages only - such pages should be
1236                          * re-used
1237                          */
1238                         Assert((*vpp)->vpd_noff > 0);
1239                         vc_vacpage(page, *vpp);
1240                 }
1241                 else
1242 /* this page was used */
1243                 {
1244                         ntups = 0;
1245                         moff = PageGetMaxOffsetNumber(page);
1246                         for (newoff = FirstOffsetNumber;
1247                                  newoff <= moff;
1248                                  newoff = OffsetNumberNext(newoff))
1249                         {
1250                                 itemid = PageGetItemId(page, newoff);
1251                                 if (!ItemIdIsUsed(itemid))
1252                                         continue;
1253                                 htup = (HeapTuple) PageGetItem(page, itemid);
1254                                 if (TransactionIdEquals((TransactionId) htup->t_xmin, myXID))
1255                                 {
1256                                         htup->t_infomask |= HEAP_XMIN_COMMITTED;
1257                                         ntups++;
1258                                 }
1259                         }
1260                         Assert((*vpp)->vpd_nusd == ntups);
1261                         nchkmvd += ntups;
1262                 }
1263                 WriteBuffer(buf);
1264         }
1265         Assert(nmoved == nchkmvd);
1266
1267         getrusage(RUSAGE_SELF, &ru1);
1268
1269         elog(MESSAGE_LEVEL, "Rel %s: Pages: %u --> %u; Tuple(s) moved: %u. \
1270 Elapsed %u/%u sec.",
1271                  (RelationGetRelationName(onerel))->data,
1272                  nblocks, blkno, nmoved,
1273                  ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1274                  ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1275
1276         if (Nvpl.vpl_npages > 0)
1277         {
1278                 /* vacuum indices again if needed */
1279                 if (Irel != (Relation *) NULL)
1280                 {
1281                         VPageDescr *vpleft,
1282                                            *vpright,
1283                                                 vpsave;
1284
1285                         /* re-sort Nvpl.vpl_pgdesc */
1286                         for (vpleft = Nvpl.vpl_pgdesc,
1287                                  vpright = Nvpl.vpl_pgdesc + Nvpl.vpl_npages - 1;
1288                                  vpleft < vpright; vpleft++, vpright--)
1289                         {
1290                                 vpsave = *vpleft;
1291                                 *vpleft = *vpright;
1292                                 *vpright = vpsave;
1293                         }
1294                         for (i = 0; i < nindices; i++)
1295                                 vc_vaconeind(&Nvpl, Irel[i], vacrelstats->ntups);
1296                 }
1297
1298                 /*
1299                  * clean moved tuples from last page in Nvpl list if some tuples
1300                  * left there
1301                  */
1302                 if (vpc->vpd_noff > 0 && offnum <= maxoff)
1303                 {
1304                         Assert(vpc->vpd_blkno == blkno - 1);
1305                         buf = ReadBuffer(onerel, vpc->vpd_blkno);
1306                         page = BufferGetPage(buf);
1307                         ntups = 0;
1308                         maxoff = offnum;
1309                         for (offnum = FirstOffsetNumber;
1310                                  offnum < maxoff;
1311                                  offnum = OffsetNumberNext(offnum))
1312                         {
1313                                 itemid = PageGetItemId(page, offnum);
1314                                 if (!ItemIdIsUsed(itemid))
1315                                         continue;
1316                                 htup = (HeapTuple) PageGetItem(page, itemid);
1317                                 Assert(TransactionIdEquals((TransactionId) htup->t_xmax, myXID));
1318                                 itemid->lp_flags &= ~LP_USED;
1319                                 ntups++;
1320                         }
1321                         Assert(vpc->vpd_noff == ntups);
1322                         PageRepairFragmentation(page);
1323                         WriteBuffer(buf);
1324                 }
1325
1326                 /* now - free new list of reapped pages */
1327                 vpp = Nvpl.vpl_pgdesc;
1328                 for (i = 0; i < Nvpl.vpl_npages; i++, vpp++)
1329                         pfree(*vpp);
1330                 pfree(Nvpl.vpl_pgdesc);
1331         }
1332
1333         /* truncate relation */
1334         if (blkno < nblocks)
1335         {
1336                 i = BlowawayRelationBuffers(onerel, blkno);
1337                 if (i < 0)
1338                         elog (FATAL, "VACUUM (vc_rpfheap): BlowawayRelationBuffers returned %d", i);
1339                 blkno = smgrtruncate(DEFAULT_SMGR, onerel, blkno);
1340                 Assert(blkno >= 0);
1341                 vacrelstats->npages = blkno;    /* set new number of blocks */
1342         }
1343
1344         if (Irel != (Relation *) NULL)          /* pfree index' allocations */
1345         {
1346                 pfree(Idesc);
1347                 pfree(idatum);
1348                 pfree(inulls);
1349                 vc_clsindices(nindices, Irel);
1350         }
1351
1352         pfree(vpc);
1353
1354 }                                                               /* vc_rpfheap */
1355
1356 /*
1357  *      vc_vacheap() -- free dead tuples
1358  *
1359  *              This routine marks dead tuples as unused and truncates relation
1360  *              if there are "empty" end-blocks.
1361  */
1362 static void
1363 vc_vacheap(VRelStats *vacrelstats, Relation onerel, VPageList Vvpl)
1364 {
1365         Buffer          buf;
1366         Page            page;
1367         VPageDescr *vpp;
1368         int                     nblocks;
1369         int                     i;
1370
1371         nblocks = Vvpl->vpl_npages;
1372         nblocks -= Vvpl->vpl_nemend;    /* nothing to do with them */
1373
1374         for (i = 0, vpp = Vvpl->vpl_pgdesc; i < nblocks; i++, vpp++)
1375         {
1376                 if ((*vpp)->vpd_noff > 0)
1377                 {
1378                         buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
1379                         page = BufferGetPage(buf);
1380                         vc_vacpage(page, *vpp);
1381                         WriteBuffer(buf);
1382                 }
1383         }
1384
1385         /* truncate relation if there are some empty end-pages */
1386         if (Vvpl->vpl_nemend > 0)
1387         {
1388                 Assert(vacrelstats->npages >= Vvpl->vpl_nemend);
1389                 nblocks = vacrelstats->npages - Vvpl->vpl_nemend;
1390                 elog(MESSAGE_LEVEL, "Rel %s: Pages: %u --> %u.",
1391                          (RelationGetRelationName(onerel))->data,
1392                          vacrelstats->npages, nblocks);
1393
1394                 /*
1395                  * we have to flush "empty" end-pages (if changed, but who knows
1396                  * it) before truncation
1397                  */
1398                 FlushBufferPool(!TransactionFlushEnabled());
1399                 
1400                 i = BlowawayRelationBuffers(onerel, nblocks);
1401                 if (i < 0)
1402                         elog (FATAL, "VACUUM (vc_vacheap): BlowawayRelationBuffers returned %d", i);
1403
1404                 nblocks = smgrtruncate(DEFAULT_SMGR, onerel, nblocks);
1405                 Assert(nblocks >= 0);
1406                 vacrelstats->npages = nblocks;  /* set new number of blocks */
1407         }
1408
1409 }                                                               /* vc_vacheap */
1410
1411 /*
1412  *      vc_vacpage() -- free dead tuples on a page
1413  *                                       and repaire its fragmentation.
1414  */
1415 static void
1416 vc_vacpage(Page page, VPageDescr vpd)
1417 {
1418         ItemId          itemid;
1419         int                     i;
1420
1421         Assert(vpd->vpd_nusd == 0);
1422         for (i = 0; i < vpd->vpd_noff; i++)
1423         {
1424                 itemid = &(((PageHeader) page)->pd_linp[vpd->vpd_voff[i] - 1]);
1425                 itemid->lp_flags &= ~LP_USED;
1426         }
1427         PageRepairFragmentation(page);
1428
1429 }                                                               /* vc_vacpage */
1430
1431 /*
1432  *      _vc_scanoneind() -- scan one index relation to update statistic.
1433  *
1434  */
1435 static void
1436 vc_scanoneind(Relation indrel, int nhtups)
1437 {
1438         RetrieveIndexResult res;
1439         IndexScanDesc iscan;
1440         int                     nitups;
1441         int                     nipages;
1442         struct rusage ru0,
1443                                 ru1;
1444
1445         getrusage(RUSAGE_SELF, &ru0);
1446
1447         /* walk through the entire index */
1448         iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
1449         nitups = 0;
1450
1451         while ((res = index_getnext(iscan, ForwardScanDirection))
1452                    != (RetrieveIndexResult) NULL)
1453         {
1454                 nitups++;
1455                 pfree(res);
1456         }
1457
1458         index_endscan(iscan);
1459
1460         /* now update statistics in pg_class */
1461         nipages = RelationGetNumberOfBlocks(indrel);
1462         vc_updstats(indrel->rd_id, nipages, nitups, false, NULL);
1463
1464         getrusage(RUSAGE_SELF, &ru1);
1465
1466         elog(MESSAGE_LEVEL, "Ind %s: Pages %u; Tuples %u. Elapsed %u/%u sec.",
1467                  indrel->rd_rel->relname.data, nipages, nitups,
1468                  ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1469                  ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1470
1471         if (nitups != nhtups)
1472                 elog(NOTICE, "Ind %s: NUMBER OF INDEX' TUPLES (%u) IS NOT THE SAME AS HEAP' (%u)",
1473                          indrel->rd_rel->relname.data, nitups, nhtups);
1474
1475 }                                                               /* vc_scanoneind */
1476
1477 /*
1478  *      vc_vaconeind() -- vacuum one index relation.
1479  *
1480  *              Vpl is the VPageList of the heap we're currently vacuuming.
1481  *              It's locked. Indrel is an index relation on the vacuumed heap.
1482  *              We don't set locks on the index relation here, since the indexed
1483  *              access methods support locking at different granularities.
1484  *              We let them handle it.
1485  *
1486  *              Finally, we arrange to update the index relation's statistics in
1487  *              pg_class.
1488  */
1489 static void
1490 vc_vaconeind(VPageList vpl, Relation indrel, int nhtups)
1491 {
1492         RetrieveIndexResult res;
1493         IndexScanDesc iscan;
1494         ItemPointer heapptr;
1495         int                     nvac;
1496         int                     nitups;
1497         int                     nipages;
1498         VPageDescr      vp;
1499         struct rusage ru0,
1500                                 ru1;
1501
1502         getrusage(RUSAGE_SELF, &ru0);
1503
1504         /* walk through the entire index */
1505         iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
1506         nvac = 0;
1507         nitups = 0;
1508
1509         while ((res = index_getnext(iscan, ForwardScanDirection))
1510                    != (RetrieveIndexResult) NULL)
1511         {
1512                 heapptr = &res->heap_iptr;
1513
1514                 if ((vp = vc_tidreapped(heapptr, vpl)) != (VPageDescr) NULL)
1515                 {
1516 #if 0
1517                         elog(DEBUG, "<%x,%x> -> <%x,%x>",
1518                                  ItemPointerGetBlockNumber(&(res->index_iptr)),
1519                                  ItemPointerGetOffsetNumber(&(res->index_iptr)),
1520                                  ItemPointerGetBlockNumber(&(res->heap_iptr)),
1521                                  ItemPointerGetOffsetNumber(&(res->heap_iptr)));
1522 #endif
1523                         if (vp->vpd_noff == 0)
1524                         {                                       /* this is EmptyPage !!! */
1525                                 elog(NOTICE, "Ind %s: pointer to EmptyPage (blk %u off %u) - fixing",
1526                                          indrel->rd_rel->relname.data,
1527                                          vp->vpd_blkno, ItemPointerGetOffsetNumber(heapptr));
1528                         }
1529                         ++nvac;
1530                         index_delete(indrel, &res->index_iptr);
1531                 }
1532                 else
1533                 {
1534                         nitups++;
1535                 }
1536
1537                 /* be tidy */
1538                 pfree(res);
1539         }
1540
1541         index_endscan(iscan);
1542
1543         /* now update statistics in pg_class */
1544         nipages = RelationGetNumberOfBlocks(indrel);
1545         vc_updstats(indrel->rd_id, nipages, nitups, false, NULL);
1546
1547         getrusage(RUSAGE_SELF, &ru1);
1548
1549         elog(MESSAGE_LEVEL, "Ind %s: Pages %u; Tuples %u: Deleted %u. Elapsed %u/%u sec.",
1550                  indrel->rd_rel->relname.data, nipages, nitups, nvac,
1551                  ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec,
1552                  ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);
1553
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);
1557
1558 }                                                               /* vc_vaconeind */
1559
1560 /*
1561  *      vc_tidreapped() -- is a particular tid reapped?
1562  *
1563  *              vpl->VPageDescr_array is sorted in right order.
1564  */
1565 static VPageDescr
1566 vc_tidreapped(ItemPointer itemptr, VPageList vpl)
1567 {
1568         OffsetNumber ioffno;
1569         OffsetNumber *voff;
1570         VPageDescr      vp,
1571                            *vpp;
1572         VPageDescrData vpd;
1573
1574         vpd.vpd_blkno = ItemPointerGetBlockNumber(itemptr);
1575         ioffno = ItemPointerGetOffsetNumber(itemptr);
1576
1577         vp = &vpd;
1578         vpp = (VPageDescr *) vc_find_eq((char *) (vpl->vpl_pgdesc),
1579                                            vpl->vpl_npages, sizeof(VPageDescr), (char *) &vp,
1580                                                                         vc_cmp_blk);
1581
1582         if (vpp == (VPageDescr *) NULL)
1583                 return ((VPageDescr) NULL);
1584         vp = *vpp;
1585
1586         /* ok - we are on true page */
1587
1588         if (vp->vpd_noff == 0)
1589         {                                                       /* this is EmptyPage !!! */
1590                 return (vp);
1591         }
1592
1593         voff = (OffsetNumber *) vc_find_eq((char *) (vp->vpd_voff),
1594                                         vp->vpd_noff, sizeof(OffsetNumber), (char *) &ioffno,
1595                                                                            vc_cmp_offno);
1596
1597         if (voff == (OffsetNumber *) NULL)
1598                 return ((VPageDescr) NULL);
1599
1600         return (vp);
1601
1602 }                                                               /* vc_tidreapped */
1603
1604 /*
1605  *      vc_attrstats() -- compute column statistics used by the optimzer
1606  *
1607  *      We compute the column min, max, null and non-null counts.
1608  *      Plus we attempt to find the count of the value that occurs most
1609  *      frequently in each column
1610  *      These figures are used to compute the selectivity of the column
1611  *
1612  *      We use a three-bucked cache to get the most frequent item
1613  *      The 'guess' buckets count hits.  A cache miss causes guess1
1614  *      to get the most hit 'guess' item in the most recent cycle, and
1615  *      the new item goes into guess2.  Whenever the total count of hits
1616  *      of a 'guess' entry is larger than 'best', 'guess' becomes 'best'.
1617  *
1618  *      This method works perfectly for columns with unique values, and columns
1619  *      with only two unique values, plus nulls.
1620  *
1621  *      It becomes less perfect as the number of unique values increases and
1622  *      their distribution in the table becomes more random.
1623  *
1624  */
1625 static void
1626 vc_attrstats(Relation onerel, VRelStats *vacrelstats, HeapTuple htup)
1627 {
1628         int                     i,
1629                                 attr_cnt = vacrelstats->va_natts;
1630         VacAttrStats *vacattrstats = vacrelstats->vacattrstats;
1631         TupleDesc       tupDesc = onerel->rd_att;
1632         Datum           value;
1633         bool            isnull;
1634
1635         for (i = 0; i < attr_cnt; i++)
1636         {
1637                 VacAttrStats *stats = &vacattrstats[i];
1638                 bool            value_hit = true;
1639
1640                 value = heap_getattr(htup, InvalidBuffer,
1641                                                          stats->attr->attnum, tupDesc, &isnull);
1642
1643                 if (!VacAttrStatsEqValid(stats))
1644                         continue;
1645
1646                 if (isnull)
1647                         stats->null_cnt++;
1648                 else
1649                 {
1650                         stats->nonnull_cnt++;
1651                         if (stats->initialized == false)
1652                         {
1653                                 vc_bucketcpy(stats->attr, value, &stats->best, &stats->best_len);
1654                                 /* best_cnt gets incremented later */
1655                                 vc_bucketcpy(stats->attr, value, &stats->guess1, &stats->guess1_len);
1656                                 stats->guess1_cnt = stats->guess1_hits = 1;
1657                                 vc_bucketcpy(stats->attr, value, &stats->guess2, &stats->guess2_len);
1658                                 stats->guess2_hits = 1;
1659                                 if (VacAttrStatsLtGtValid(stats))
1660                                 {
1661                                         vc_bucketcpy(stats->attr, value, &stats->max, &stats->max_len);
1662                                         vc_bucketcpy(stats->attr, value, &stats->min, &stats->min_len);
1663                                 }
1664                                 stats->initialized = true;
1665                         }
1666                         if (VacAttrStatsLtGtValid(stats))
1667                         {
1668                                 if ((*fmgr_faddr(&stats->f_cmplt)) (value, stats->min))
1669                                 {
1670                                         vc_bucketcpy(stats->attr, value, &stats->min, &stats->min_len);
1671                                         stats->min_cnt = 0;
1672                                 }
1673                                 if ((*fmgr_faddr(&stats->f_cmpgt)) (value, stats->max))
1674                                 {
1675                                         vc_bucketcpy(stats->attr, value, &stats->max, &stats->max_len);
1676                                         stats->max_cnt = 0;
1677                                 }
1678                                 if ((*fmgr_faddr(&stats->f_cmpeq)) (value, stats->min))
1679                                         stats->min_cnt++;
1680                                 else if ((*fmgr_faddr(&stats->f_cmpeq)) (value, stats->max))
1681                                         stats->max_cnt++;
1682                         }
1683                         if ((*fmgr_faddr(&stats->f_cmpeq)) (value, stats->best))
1684                                 stats->best_cnt++;
1685                         else if ((*fmgr_faddr(&stats->f_cmpeq)) (value, stats->guess1))
1686                         {
1687                                 stats->guess1_cnt++;
1688                                 stats->guess1_hits++;
1689                         }
1690                         else if ((*fmgr_faddr(&stats->f_cmpeq)) (value, stats->guess2))
1691                                 stats->guess2_hits++;
1692                         else
1693                                 value_hit = false;
1694
1695                         if (stats->guess2_hits > stats->guess1_hits)
1696                         {
1697                                 swapDatum(stats->guess1, stats->guess2);
1698                                 swapInt(stats->guess1_len, stats->guess2_len);
1699                                 stats->guess1_cnt = stats->guess2_hits;
1700                                 swapLong(stats->guess1_hits, stats->guess2_hits);
1701                         }
1702                         if (stats->guess1_cnt > stats->best_cnt)
1703                         {
1704                                 swapDatum(stats->best, stats->guess1);
1705                                 swapInt(stats->best_len, stats->guess1_len);
1706                                 swapLong(stats->best_cnt, stats->guess1_cnt);
1707                                 stats->guess1_hits = 1;
1708                                 stats->guess2_hits = 1;
1709                         }
1710                         if (!value_hit)
1711                         {
1712                                 vc_bucketcpy(stats->attr, value, &stats->guess2, &stats->guess2_len);
1713                                 stats->guess1_hits = 1;
1714                                 stats->guess2_hits = 1;
1715                         }
1716                 }
1717         }
1718         return;
1719 }
1720
1721 /*
1722  *      vc_bucketcpy() -- update pg_class statistics for one relation
1723  *
1724  */
1725 static void
1726 vc_bucketcpy(AttributeTupleForm attr, Datum value, Datum *bucket, int16 *bucket_len)
1727 {
1728         if (attr->attbyval && attr->attlen != -1)
1729                 *bucket = value;
1730         else
1731         {
1732                 int                     len = (attr->attlen != -1 ? attr->attlen : VARSIZE(value));
1733
1734                 if (len > *bucket_len)
1735                 {
1736                         if (*bucket_len != 0)
1737                                 pfree(DatumGetPointer(*bucket));
1738                         *bucket = PointerGetDatum(palloc(len));
1739                         *bucket_len = len;
1740                 }
1741                 memmove(DatumGetPointer(*bucket), DatumGetPointer(value), len);
1742         }
1743 }
1744
1745 /*
1746  *      vc_updstats() -- update pg_class statistics for one relation
1747  *
1748  *              This routine works for both index and heap relation entries in
1749  *              pg_class.  We violate no-overwrite semantics here by storing new
1750  *              values for ntups, npages, and hasindex directly in the pg_class
1751  *              tuple that's already on the page.  The reason for this is that if
1752  *              we updated these tuples in the usual way, then every tuple in pg_class
1753  *              would be replaced every day.  This would make planning and executing
1754  *              historical queries very expensive.
1755  */
1756 static void
1757 vc_updstats(Oid relid, int npages, int ntups, bool hasindex, VRelStats *vacrelstats)
1758 {
1759         Relation        rd,
1760                                 ad,
1761                                 sd;
1762         HeapScanDesc rsdesc,
1763                                 asdesc;
1764         TupleDesc       sdesc;
1765         HeapTuple       rtup,
1766                                 atup,
1767                                 stup;
1768         Buffer          rbuf,
1769                                 abuf;
1770         Form_pg_class pgcform;
1771         ScanKeyData rskey,
1772                                 askey;
1773         AttributeTupleForm attp;
1774
1775         /*
1776          * update number of tuples and number of pages in pg_class
1777          */
1778         ScanKeyEntryInitialize(&rskey, 0x0, ObjectIdAttributeNumber,
1779                                                    ObjectIdEqualRegProcedure,
1780                                                    ObjectIdGetDatum(relid));
1781
1782         rd = heap_openr(RelationRelationName);
1783         rsdesc = heap_beginscan(rd, false, false, 1, &rskey);
1784
1785         if (!HeapTupleIsValid(rtup = heap_getnext(rsdesc, 0, &rbuf)))
1786                 elog(ERROR, "pg_class entry for relid %d vanished during vacuuming",
1787                          relid);
1788
1789         /* overwrite the existing statistics in the tuple */
1790         vc_setpagelock(rd, BufferGetBlockNumber(rbuf));
1791         pgcform = (Form_pg_class) GETSTRUCT(rtup);
1792         pgcform->reltuples = ntups;
1793         pgcform->relpages = npages;
1794         pgcform->relhasindex = hasindex;
1795
1796         if (vacrelstats != NULL && vacrelstats->va_natts > 0)
1797         {
1798                 VacAttrStats *vacattrstats = vacrelstats->vacattrstats;
1799                 int                     natts = vacrelstats->va_natts;
1800
1801                 ad = heap_openr(AttributeRelationName);
1802                 sd = heap_openr(StatisticRelationName);
1803                 ScanKeyEntryInitialize(&askey, 0, Anum_pg_attribute_attrelid,
1804                                                            F_INT4EQ, relid);
1805
1806                 asdesc = heap_beginscan(ad, false, false, 1, &askey);
1807
1808                 while (HeapTupleIsValid(atup = heap_getnext(asdesc, 0, &abuf)))
1809                 {
1810                         int                     i;
1811                         float32data selratio;           /* average ratio of rows selected
1812                                                                                  * for a random constant */
1813                         VacAttrStats *stats;
1814                         Datum           values[Natts_pg_statistic];
1815                         char            nulls[Natts_pg_statistic];
1816
1817                         attp = (AttributeTupleForm) GETSTRUCT(atup);
1818                         if (attp->attnum <= 0)          /* skip system attributes for now, */
1819                                 /* they are unique anyway */
1820                                 continue;
1821
1822                         for (i = 0; i < natts; i++)
1823                         {
1824                                 if (attp->attnum == vacattrstats[i].attr->attnum)
1825                                         break;
1826                         }
1827                         if (i >= natts)
1828                                 continue;
1829                         stats = &(vacattrstats[i]);
1830
1831                         /* overwrite the existing statistics in the tuple */
1832                         if (VacAttrStatsEqValid(stats))
1833                         {
1834
1835                                 vc_setpagelock(ad, BufferGetBlockNumber(abuf));
1836
1837                                 if (stats->nonnull_cnt + stats->null_cnt == 0 ||
1838                                         (stats->null_cnt <= 1 && stats->best_cnt == 1))
1839                                         selratio = 0;
1840                                 else if (VacAttrStatsLtGtValid(stats) && stats->min_cnt + stats->max_cnt == stats->nonnull_cnt)
1841                                 {
1842                                         double          min_cnt_d = stats->min_cnt,
1843                                                                 max_cnt_d = stats->max_cnt,
1844                                                                 null_cnt_d = stats->null_cnt,
1845                                                                 nonnullcnt_d = stats->nonnull_cnt;              /* prevent overflow */
1846
1847                                         selratio = (min_cnt_d * min_cnt_d + max_cnt_d * max_cnt_d + null_cnt_d * null_cnt_d) /
1848                                                 (nonnullcnt_d + null_cnt_d) / (nonnullcnt_d + null_cnt_d);
1849                                 }
1850                                 else
1851                                 {
1852                                         double          most = (double) (stats->best_cnt > stats->null_cnt ? stats->best_cnt : stats->null_cnt);
1853                                         double          total = ((double) stats->nonnull_cnt) + ((double) stats->null_cnt);
1854
1855                                         /*
1856                                          * we assume count of other values are 20% of best
1857                                          * count in table
1858                                          */
1859                                         selratio = (most * most + 0.20 * most * (total - most)) / total / total;
1860                                 }
1861                                 if (selratio > 1.0)
1862                                         selratio = 1.0;
1863                                 attp->attdisbursion = selratio;
1864                                 WriteNoReleaseBuffer(abuf);
1865
1866                                 /* DO PG_STATISTIC INSERTS */
1867
1868                                 /*
1869                                  * doing system relations, especially pg_statistic is a
1870                                  * problem
1871                                  */
1872                                 if (VacAttrStatsLtGtValid(stats) && stats->initialized  /* &&
1873                                                                                                                                                  * !IsSystemRelationName(
1874                                                                                                                                                  *
1875                                          pgcform->relname.data) */ )
1876                                 {
1877                                         FmgrInfo        out_function;
1878                                         char       *out_string;
1879
1880                                         for (i = 0; i < Natts_pg_statistic; ++i)
1881                                                 nulls[i] = ' ';
1882
1883                                         /* ----------------
1884                                          *      initialize values[]
1885                                          * ----------------
1886                                          */
1887                                         i = 0;
1888                                         values[i++] = (Datum) relid;            /* 1 */
1889                                         values[i++] = (Datum) attp->attnum; /* 2 */
1890                                         values[i++] = (Datum) InvalidOid;       /* 3 */
1891                                         fmgr_info(stats->outfunc, &out_function);
1892                                         out_string = (*fmgr_faddr(&out_function)) (stats->min, stats->attr->atttypid);
1893                                         values[i++] = (Datum) fmgr(TextInRegProcedure, out_string);
1894                                         pfree(out_string);
1895                                         out_string = (char *) (*fmgr_faddr(&out_function)) (stats->max, stats->attr->atttypid);
1896                                         values[i++] = (Datum) fmgr(TextInRegProcedure, out_string);
1897                                         pfree(out_string);
1898
1899                                         sdesc = sd->rd_att;
1900
1901                                         stup = heap_formtuple(sdesc, values, nulls);
1902
1903                                         /* ----------------
1904                                          *      insert the tuple in the relation and get the tuple's oid.
1905                                          * ----------------
1906                                          */
1907                                         heap_insert(sd, stup);
1908                                         pfree(DatumGetPointer(values[3]));
1909                                         pfree(DatumGetPointer(values[4]));
1910                                         pfree(stup);
1911                                 }
1912                         }
1913                 }
1914                 heap_endscan(asdesc);
1915                 heap_close(ad);
1916                 heap_close(sd);
1917         }
1918
1919         /* XXX -- after write, should invalidate relcache in other backends */
1920         WriteNoReleaseBuffer(rbuf); /* heap_endscan release scan' buffers ? */
1921
1922         /*
1923          * invalidating system relations confuses the function cache of
1924          * pg_operator and pg_opclass
1925          */
1926         if (!IsSystemRelationName(pgcform->relname.data))
1927                 RelationInvalidateHeapTuple(rd, rtup);
1928
1929         /* that's all, folks */
1930         heap_endscan(rsdesc);
1931         heap_close(rd);
1932 }
1933
1934 /*
1935  *      vc_delhilowstats() -- delete pg_statistics rows
1936  *
1937  */
1938 static void
1939 vc_delhilowstats(Oid relid, int attcnt, int *attnums)
1940 {
1941         Relation        pgstatistic;
1942         HeapScanDesc pgsscan;
1943         HeapTuple       pgstup;
1944         ScanKeyData pgskey;
1945
1946         pgstatistic = heap_openr(StatisticRelationName);
1947
1948         if (relid != InvalidOid)
1949         {
1950                 ScanKeyEntryInitialize(&pgskey, 0x0, Anum_pg_statistic_starelid,
1951                                                            ObjectIdEqualRegProcedure,
1952                                                            ObjectIdGetDatum(relid));
1953                 pgsscan = heap_beginscan(pgstatistic, false, false, 1, &pgskey);
1954         }
1955         else
1956                 pgsscan = heap_beginscan(pgstatistic, false, false, 0, NULL);
1957
1958         while (HeapTupleIsValid(pgstup = heap_getnext(pgsscan, 0, NULL)))
1959         {
1960                 if (attcnt > 0)
1961                 {
1962                         Form_pg_statistic pgs = (Form_pg_statistic) GETSTRUCT(pgstup);
1963                         int                     i;
1964
1965                         for (i = 0; i < attcnt; i++)
1966                         {
1967                                 if (pgs->staattnum == attnums[i] + 1)
1968                                         break;
1969                         }
1970                         if (i >= attcnt)
1971                                 continue;               /* don't delete it */
1972                 }
1973                 heap_delete(pgstatistic, &pgstup->t_ctid);
1974         }
1975
1976         heap_endscan(pgsscan);
1977         heap_close(pgstatistic);
1978 }
1979
1980 static void
1981 vc_setpagelock(Relation rel, BlockNumber blkno)
1982 {
1983         ItemPointerData itm;
1984
1985         ItemPointerSet(&itm, blkno, 1);
1986
1987         RelationSetLockForWritePage(rel, &itm);
1988 }
1989
1990 /*
1991  *      vc_reappage() -- save a page on the array of reapped pages.
1992  *
1993  *              As a side effect of the way that the vacuuming loop for a given
1994  *              relation works, higher pages come after lower pages in the array
1995  *              (and highest tid on a page is last).
1996  */
1997 static void
1998 vc_reappage(VPageList vpl, VPageDescr vpc)
1999 {
2000         VPageDescr      newvpd;
2001
2002         /* allocate a VPageDescrData entry */
2003         newvpd = (VPageDescr) palloc(sizeof(VPageDescrData) + vpc->vpd_noff * sizeof(OffsetNumber));
2004
2005         /* fill it in */
2006         if (vpc->vpd_noff > 0)
2007                 memmove(newvpd->vpd_voff, vpc->vpd_voff, vpc->vpd_noff * sizeof(OffsetNumber));
2008         newvpd->vpd_blkno = vpc->vpd_blkno;
2009         newvpd->vpd_free = vpc->vpd_free;
2010         newvpd->vpd_nusd = vpc->vpd_nusd;
2011         newvpd->vpd_noff = vpc->vpd_noff;
2012
2013         /* insert this page into vpl list */
2014         vc_vpinsert(vpl, newvpd);
2015
2016 }                                                               /* vc_reappage */
2017
2018 static void
2019 vc_vpinsert(VPageList vpl, VPageDescr vpnew)
2020 {
2021
2022         /* allocate a VPageDescr entry if needed */
2023         if (vpl->vpl_npages == 0)
2024                 vpl->vpl_pgdesc = (VPageDescr *) palloc(100 * sizeof(VPageDescr));
2025         else if (vpl->vpl_npages % 100 == 0)
2026                 vpl->vpl_pgdesc = (VPageDescr *) repalloc(vpl->vpl_pgdesc, (vpl->vpl_npages + 100) * sizeof(VPageDescr));
2027         vpl->vpl_pgdesc[vpl->vpl_npages] = vpnew;
2028         (vpl->vpl_npages)++;
2029
2030 }
2031
2032 static void
2033 vc_free(VRelList vrl)
2034 {
2035         VRelList        p_vrl;
2036         MemoryContext old;
2037         PortalVariableMemory pmem;
2038
2039         pmem = PortalGetVariableMemory(vc_portal);
2040         old = MemoryContextSwitchTo((MemoryContext) pmem);
2041
2042         while (vrl != (VRelList) NULL)
2043         {
2044
2045                 /* free rel list entry */
2046                 p_vrl = vrl;
2047                 vrl = vrl->vrl_next;
2048                 pfree(p_vrl);
2049         }
2050
2051         MemoryContextSwitchTo(old);
2052 }
2053
2054 static char *
2055 vc_find_eq(char *bot, int nelem, int size, char *elm, int (*compar) (char *, char *))
2056 {
2057         int                     res;
2058         int                     last = nelem - 1;
2059         int                     celm = nelem / 2;
2060         bool            last_move,
2061                                 first_move;
2062
2063         last_move = first_move = true;
2064         for (;;)
2065         {
2066                 if (first_move == true)
2067                 {
2068                         res = compar(bot, elm);
2069                         if (res > 0)
2070                                 return (NULL);
2071                         if (res == 0)
2072                                 return (bot);
2073                         first_move = false;
2074                 }
2075                 if (last_move == true)
2076                 {
2077                         res = compar(elm, bot + last * size);
2078                         if (res > 0)
2079                                 return (NULL);
2080                         if (res == 0)
2081                                 return (bot + last * size);
2082                         last_move = false;
2083                 }
2084                 res = compar(elm, bot + celm * size);
2085                 if (res == 0)
2086                         return (bot + celm * size);
2087                 if (res < 0)
2088                 {
2089                         if (celm == 0)
2090                                 return (NULL);
2091                         last = celm - 1;
2092                         celm = celm / 2;
2093                         last_move = true;
2094                         continue;
2095                 }
2096
2097                 if (celm == last)
2098                         return (NULL);
2099
2100                 last = last - celm - 1;
2101                 bot = bot + (celm + 1) * size;
2102                 celm = (last + 1) / 2;
2103                 first_move = true;
2104         }
2105
2106 }                                                               /* vc_find_eq */
2107
2108 static int
2109 vc_cmp_blk(char *left, char *right)
2110 {
2111         BlockNumber lblk,
2112                                 rblk;
2113
2114         lblk = (*((VPageDescr *) left))->vpd_blkno;
2115         rblk = (*((VPageDescr *) right))->vpd_blkno;
2116
2117         if (lblk < rblk)
2118                 return (-1);
2119         if (lblk == rblk)
2120                 return (0);
2121         return (1);
2122
2123 }                                                               /* vc_cmp_blk */
2124
2125 static int
2126 vc_cmp_offno(char *left, char *right)
2127 {
2128
2129         if (*(OffsetNumber *) left < *(OffsetNumber *) right)
2130                 return (-1);
2131         if (*(OffsetNumber *) left == *(OffsetNumber *) right)
2132                 return (0);
2133         return (1);
2134
2135 }                                                               /* vc_cmp_offno */
2136
2137
2138 static void
2139 vc_getindices(Oid relid, int *nindices, Relation **Irel)
2140 {
2141         Relation        pgindex;
2142         Relation        irel;
2143         TupleDesc       pgidesc;
2144         HeapTuple       pgitup;
2145         HeapScanDesc pgiscan;
2146         Datum           d;
2147         int                     i,
2148                                 k;
2149         bool            n;
2150         ScanKeyData pgikey;
2151         Oid                *ioid;
2152
2153         *nindices = i = 0;
2154
2155         ioid = (Oid *) palloc(10 * sizeof(Oid));
2156
2157         /* prepare a heap scan on the pg_index relation */
2158         pgindex = heap_openr(IndexRelationName);
2159         pgidesc = RelationGetTupleDescriptor(pgindex);
2160
2161         ScanKeyEntryInitialize(&pgikey, 0x0, Anum_pg_index_indrelid,
2162                                                    ObjectIdEqualRegProcedure,
2163                                                    ObjectIdGetDatum(relid));
2164
2165         pgiscan = heap_beginscan(pgindex, false, false, 1, &pgikey);
2166
2167         while (HeapTupleIsValid(pgitup = heap_getnext(pgiscan, 0, NULL)))
2168         {
2169                 d = heap_getattr(pgitup, InvalidBuffer, Anum_pg_index_indexrelid,
2170                                                  pgidesc, &n);
2171                 i++;
2172                 if (i % 10 == 0)
2173                         ioid = (Oid *) repalloc(ioid, (i + 10) * sizeof(Oid));
2174                 ioid[i - 1] = DatumGetObjectId(d);
2175         }
2176
2177         heap_endscan(pgiscan);
2178         heap_close(pgindex);
2179
2180         if (i == 0)
2181         {                                                       /* No one index found */
2182                 pfree(ioid);
2183                 return;
2184         }
2185
2186         if (Irel != (Relation **) NULL)
2187                 *Irel = (Relation *) palloc(i * sizeof(Relation));
2188
2189         for (k = 0; i > 0;)
2190         {
2191                 irel = index_open(ioid[--i]);
2192                 if (irel != (Relation) NULL)
2193                 {
2194                         if (Irel != (Relation **) NULL)
2195                                 (*Irel)[k] = irel;
2196                         else
2197                                 index_close(irel);
2198                         k++;
2199                 }
2200                 else
2201                         elog(NOTICE, "CAN't OPEN INDEX %u - SKIP IT", ioid[i]);
2202         }
2203         *nindices = k;
2204         pfree(ioid);
2205
2206         if (Irel != (Relation **) NULL && *nindices == 0)
2207         {
2208                 pfree(*Irel);
2209                 *Irel = (Relation *) NULL;
2210         }
2211
2212 }                                                               /* vc_getindices */
2213
2214
2215 static void
2216 vc_clsindices(int nindices, Relation *Irel)
2217 {
2218
2219         if (Irel == (Relation *) NULL)
2220                 return;
2221
2222         while (nindices--)
2223         {
2224                 index_close(Irel[nindices]);
2225         }
2226         pfree(Irel);
2227
2228 }                                                               /* vc_clsindices */
2229
2230
2231 static void
2232 vc_mkindesc(Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc)
2233 {
2234         IndDesc    *idcur;
2235         HeapTuple       pgIndexTup;
2236         AttrNumber *attnumP;
2237         int                     natts;
2238         int                     i;
2239
2240         *Idesc = (IndDesc *) palloc(nindices * sizeof(IndDesc));
2241
2242         for (i = 0, idcur = *Idesc; i < nindices; i++, idcur++)
2243         {
2244                 pgIndexTup =
2245                         SearchSysCacheTuple(INDEXRELID,
2246                                                                 ObjectIdGetDatum(Irel[i]->rd_id),
2247                                                                 0, 0, 0);
2248                 Assert(pgIndexTup);
2249                 idcur->tform = (IndexTupleForm) GETSTRUCT(pgIndexTup);
2250                 for (attnumP = &(idcur->tform->indkey[0]), natts = 0;
2251                          *attnumP != InvalidAttrNumber && natts != INDEX_MAX_KEYS;
2252                          attnumP++, natts++);
2253                 if (idcur->tform->indproc != InvalidOid)
2254                 {
2255                         idcur->finfoP = &(idcur->finfo);
2256                         FIgetnArgs(idcur->finfoP) = natts;
2257                         natts = 1;
2258                         FIgetProcOid(idcur->finfoP) = idcur->tform->indproc;
2259                         *(FIgetname(idcur->finfoP)) = '\0';
2260                 }
2261                 else
2262                         idcur->finfoP = (FuncIndexInfo *) NULL;
2263
2264                 idcur->natts = natts;
2265         }
2266
2267 }                                                               /* vc_mkindesc */
2268
2269
2270 static bool
2271 vc_enough_space(VPageDescr vpd, Size len)
2272 {
2273
2274         len = DOUBLEALIGN(len);
2275
2276         if (len > vpd->vpd_free)
2277                 return (false);
2278
2279         if (vpd->vpd_nusd < vpd->vpd_noff)      /* there are free itemid(s) */
2280                 return (true);                  /* and len <= free_space */
2281
2282         /* ok. noff_usd >= noff_free and so we'll have to allocate new itemid */
2283         if (len <= vpd->vpd_free - sizeof(ItemIdData))
2284                 return (true);
2285
2286         return (false);
2287
2288 }                                                               /* vc_enough_space */