summaryrefslogtreecommitdiff
path: root/src/backend/commands/vacuum.c
blob: 66fc0a19b224e79c47fe2a471d27e337bc5aa47a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
/*-------------------------------------------------------------------------
 *
 * vacuum.c--
 *    the postgres vacuum cleaner
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *    $Header: /cvsroot/pgsql/src/backend/commands/vacuum.c,v 1.11 1996/11/29 10:27:59 vadim Exp $
 *
 *-------------------------------------------------------------------------
 */
#include <sys/file.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <postgres.h>

#include <utils/portal.h>
#include <access/genam.h>
#include <access/heapam.h>
#include <access/xact.h>
#include <storage/bufmgr.h>
#include <access/transam.h>
#include <catalog/pg_index.h>
#include <catalog/index.h>
#include <catalog/catname.h>
#include <catalog/pg_class.h>
#include <catalog/pg_proc.h>
#include <storage/smgr.h>
#include <storage/lmgr.h>
#include <utils/mcxt.h>
#include <utils/syscache.h>
#include <commands/vacuum.h>
#include <storage/bufpage.h>
#include "storage/shmem.h"
#ifdef NEED_RUSAGE
# include <rusagestub.h>
#else /* NEED_RUSAGE */
# include <sys/time.h>
# include <sys/resource.h>
#endif /* NEED_RUSAGE */

bool VacuumRunning =	false;

#ifdef VACUUM_QUIET
static int MESSLEV = DEBUG;
#else
static int MESSLEV = NOTICE;
#endif

typedef struct {
    FuncIndexInfo	finfo;
    FuncIndexInfo	*finfoP;
    IndexTupleForm	tform;
    int			natts;
} IndDesc;

/* non-export function prototypes */
static void _vc_init(void);
static void _vc_shutdown(void);
static void _vc_vacuum(NameData *VacRelP);
static VRelList _vc_getrels(Portal p, NameData *VacRelP);
static void _vc_vacone (VRelList curvrl);
static void _vc_scanheap (VRelList curvrl, Relation onerel, VPageList Vvpl, VPageList Fvpl);
static void _vc_rpfheap (VRelList curvrl, Relation onerel, VPageList Vvpl, VPageList Fvpl, int nindices, Relation *Irel);
static void _vc_vacheap (VRelList curvrl, Relation onerel, VPageList vpl);
static void _vc_vacpage (Page page, VPageDescr vpd, Relation archrel);
static void _vc_vaconeind (VPageList vpl, Relation indrel, int nhtups);
static void _vc_updstats(Oid relid, int npages, int ntuples, bool hasindex);
static void _vc_setpagelock(Relation rel, BlockNumber blkno);
static VPageDescr _vc_tidreapped (ItemPointer itemptr, VPageList curvrl);
static void _vc_reappage (VPageList vpl, VPageDescr vpc);
static void _vc_vpinsert (VPageList vpl, VPageDescr vpnew);
static void _vc_free(Portal p, VRelList vrl);
static void _vc_getindices (Oid relid, int *nindices, Relation **Irel);
static void _vc_clsindices (int nindices, Relation *Irel);
static Relation _vc_getarchrel(Relation heaprel);
static void _vc_archive(Relation archrel, HeapTuple htup);
static bool _vc_isarchrel(char *rname);
static void _vc_mkindesc (Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc);
static char * _vc_find_eq (char *bot, int nelem, int size, char *elm, int (*compar)(char *, char *));
static int _vc_cmp_blk (char *left, char *right);
static int _vc_cmp_offno (char *left, char *right);
static bool _vc_enough_space (VPageDescr vpd, Size len);


void
vacuum(char *vacrel)
{
    NameData VacRel;

    /* vacrel gets de-allocated on transaction commit */
    	
    /* initialize vacuum cleaner */
    _vc_init();

    /* vacuum the database */
    if (vacrel)
    {
	strcpy(VacRel.data,vacrel);
	_vc_vacuum(&VacRel);
    }
    else
	_vc_vacuum(NULL);

    /* clean up */
    _vc_shutdown();
}

/*
 *  _vc_init(), _vc_shutdown() -- start up and shut down the vacuum cleaner.
 *
 *	We run exactly one vacuum cleaner at a time.  We use the file system
 *	to guarantee an exclusive lock on vacuuming, since a single vacuum
 *	cleaner instantiation crosses transaction boundaries, and we'd lose
 *	postgres-style locks at the end of every transaction.
 *
 *	The strangeness with committing and starting transactions in the
 *	init and shutdown routines is due to the fact that the vacuum cleaner
 *	is invoked via a sql command, and so is already executing inside
 *	a transaction.  We need to leave ourselves in a predictable state
 *	on entry and exit to the vacuum cleaner.  We commit the transaction
 *	started in PostgresMain() inside _vc_init(), and start one in
 *	_vc_shutdown() to match the commit waiting for us back in
 *	PostgresMain().
 */
static void
_vc_init()
{
    int fd;

    if ((fd = open("pg_vlock", O_CREAT|O_EXCL, 0600)) < 0)
	elog(WARN, "can't create lock file -- another vacuum cleaner running?");

    close(fd);

    /*
     *  By here, exclusive open on the lock file succeeded.  If we abort
     *  for any reason during vacuuming, we need to remove the lock file.
     *  This global variable is checked in the transaction manager on xact
     *  abort, and the routine vc_abort() is called if necessary.
     */

    VacuumRunning = true;

    /* matches the StartTransaction in PostgresMain() */
    CommitTransactionCommand();
}

static void
_vc_shutdown()
{
    /* on entry, not in a transaction */
    if (unlink("pg_vlock") < 0)
	elog(WARN, "vacuum: can't destroy lock file!");

    /* okay, we're done */
    VacuumRunning = false;

    /* matches the CommitTransaction in PostgresMain() */
    StartTransactionCommand();
}

void
vc_abort()
{
    /* on abort, remove the vacuum cleaner lock file */
    (void) unlink("pg_vlock");

    VacuumRunning = false;
}

/*
 *  _vc_vacuum() -- vacuum the database.
 *
 *	This routine builds a list of relations to vacuum, and then calls
 *	code that vacuums them one at a time.  We are careful to vacuum each
 *	relation in a separate transaction in order to avoid holding too many
 *	locks at one time.
 */
static void
_vc_vacuum(NameData *VacRelP)
{
    VRelList vrl, cur;
    char *pname;
    Portal p;

    /*
     *  Create a portal for safe memory across transctions.  We need to
     *  palloc the name space for it because our hash function expects
     *	the name to be on a longword boundary.  CreatePortal copies the
     *  name to safe storage for us.
     */

    pname = (char *) palloc(strlen(VACPNAME) + 1);
    strcpy(pname, VACPNAME);
    p = CreatePortal(pname);
    pfree(pname);

    /* get list of relations */
    vrl = _vc_getrels(p, VacRelP);

    /* vacuum each heap relation */
    for (cur = vrl; cur != (VRelList) NULL; cur = cur->vrl_next)
	_vc_vacone (cur);

    _vc_free(p, vrl);

    PortalDestroy(&p);
}

static VRelList
_vc_getrels(Portal p, NameData *VacRelP)
{
    Relation pgclass;
    TupleDesc pgcdesc;
    HeapScanDesc pgcscan;
    HeapTuple pgctup;
    Buffer buf;
    PortalVariableMemory portalmem;
    MemoryContext old;
    VRelList vrl, cur;
    Datum d;
    char *rname;
    char rkind;
    int16 smgrno;
    bool n;
    ScanKeyData  pgckey;
    bool found = false;

    StartTransactionCommand();

    if (VacRelP->data) {
	ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relname,
			       NameEqualRegProcedure, 
			       PointerGetDatum(VacRelP->data));
    } else {
	ScanKeyEntryInitialize(&pgckey, 0x0, Anum_pg_class_relkind,
			       CharacterEqualRegProcedure, CharGetDatum('r'));
    }

    portalmem = PortalGetVariableMemory(p);
    vrl = cur = (VRelList) NULL;

    pgclass = heap_openr(RelationRelationName);
    pgcdesc = RelationGetTupleDescriptor(pgclass);

    pgcscan = heap_beginscan(pgclass, false, NowTimeQual, 1, &pgckey);

    while (HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &buf))) {

	found = true;
	
	/*
	 *  We have to be careful not to vacuum the archive (since it
	 *  already contains vacuumed tuples), and not to vacuum
	 *  relations on write-once storage managers like the Sony
	 *  jukebox at Berkeley.
	 */

	d = (Datum) heap_getattr(pgctup, buf, Anum_pg_class_relname,
				 pgcdesc, &n);
	rname = (char*)d;

	/* skip archive relations */
	if (_vc_isarchrel(rname)) {
	    ReleaseBuffer(buf);
	    continue;
	}

	/* don't vacuum large objects for now - something breaks when we do */
	if ( (strlen(rname) > 4) && rname[0] == 'X' &&
		rname[1] == 'i' && rname[2] == 'n' &&
		(rname[3] == 'v' || rname[3] == 'x'))
	{
	    elog (NOTICE, "Rel %.*s: can't vacuum LargeObjects now", 
			NAMEDATALEN, rname);
	    ReleaseBuffer(buf);
	    continue;
	}

	d = (Datum) heap_getattr(pgctup, buf, Anum_pg_class_relsmgr,
				 pgcdesc, &n);
	smgrno = DatumGetInt16(d);

	/* skip write-once storage managers */
	if (smgriswo(smgrno)) {
	    ReleaseBuffer(buf);
	    continue;
	}

	d = (Datum) heap_getattr(pgctup, buf, Anum_pg_class_relkind,
				 pgcdesc, &n);

	rkind = DatumGetChar(d);

	/* skip system relations */
	if (rkind != 'r') {
	    ReleaseBuffer(buf);
	    elog(NOTICE, "Vacuum: can not process index and certain system tables" );
	    continue;
	}
				 
	/* get a relation list entry for this guy */
	old = MemoryContextSwitchTo((MemoryContext)portalmem);
	if (vrl == (VRelList) NULL) {
	    vrl = cur = (VRelList) palloc(sizeof(VRelListData));
	} else {
	    cur->vrl_next = (VRelList) palloc(sizeof(VRelListData));
	    cur = cur->vrl_next;
	}
	(void) MemoryContextSwitchTo(old);

	cur->vrl_relid = pgctup->t_oid;
	cur->vrl_attlist = (VAttList) NULL;
	cur->vrl_npages = cur->vrl_ntups = 0;
	cur->vrl_hasindex = false;
	cur->vrl_next = (VRelList) NULL;

	/* wei hates it if you forget to do this */
	ReleaseBuffer(buf);
    }
    if (found == false)
    	elog(NOTICE, "Vacuum: table not found" );

    
    heap_close(pgclass);
    heap_endscan(pgcscan);

    CommitTransactionCommand();

    return (vrl);
}

/*
 *  _vc_vacone() -- vacuum one heap relation
 *
 *	This routine vacuums a single heap, cleans out its indices, and
 *	updates its statistics npages and ntuples statistics.
 *
 *	Doing one heap at a time incurs extra overhead, since we need to
 *	check that the heap exists again just before we vacuum it.  The
 *	reason that we do this is so that vacuuming can be spread across
 *	many small transactions.  Otherwise, two-phase locking would require
 *	us to lock the entire database during one pass of the vacuum cleaner.
 */
static void
_vc_vacone (VRelList curvrl)
{
    Relation pgclass;
    TupleDesc pgcdesc;
    HeapTuple pgctup;
    Buffer pgcbuf;
    HeapScanDesc pgcscan;
    Relation onerel;
    ScanKeyData pgckey;
    VPageListData Vvpl;	/* List of pages to vacuum and/or clean indices */
    VPageListData Fvpl;	/* List of pages with space enough for re-using */
    VPageDescr *vpp;
    Relation *Irel;
    int nindices;
    int i;

    StartTransactionCommand();

    ScanKeyEntryInitialize(&pgckey, 0x0, ObjectIdAttributeNumber,
			   ObjectIdEqualRegProcedure,
			   ObjectIdGetDatum(curvrl->vrl_relid));

    pgclass = heap_openr(RelationRelationName);
    pgcdesc = RelationGetTupleDescriptor(pgclass);
    pgcscan = heap_beginscan(pgclass, false, NowTimeQual, 1, &pgckey);

    /*
     *  Race condition -- if the pg_class tuple has gone away since the
     *  last time we saw it, we don't need to vacuum it.
     */

    if (!HeapTupleIsValid(pgctup = heap_getnext(pgcscan, 0, &pgcbuf))) {
	heap_endscan(pgcscan);
	heap_close(pgclass);
	CommitTransactionCommand();
	return;
    }

    /* now open the class and vacuum it */
    onerel = heap_open(curvrl->vrl_relid);

    /* we require the relation to be locked until the indices are cleaned */
    RelationSetLockForWrite(onerel);

    /* scan it */
    Vvpl.vpl_npages = Fvpl.vpl_npages = 0;
    _vc_scanheap(curvrl, onerel, &Vvpl, &Fvpl);

    /* Now open/count indices */
    Irel = (Relation *) NULL;
    if ( Vvpl.vpl_npages > 0 )
		    /* Open all indices of this relation */
	_vc_getindices(curvrl->vrl_relid, &nindices, &Irel);
    else
		    /* Count indices only */
	_vc_getindices(curvrl->vrl_relid, &nindices, NULL);
    
    if ( nindices > 0 )
	curvrl->vrl_hasindex = true;
    else
	curvrl->vrl_hasindex = false;

    /* Clean index' relation(s) */
    if ( Irel != (Relation*) NULL )
    {
	for (i = 0; i < nindices; i++)
	    _vc_vaconeind (&Vvpl, Irel[i], curvrl->vrl_ntups);
    }

    if ( Fvpl.vpl_npages > 0 )		/* Try to shrink heap */
    	_vc_rpfheap (curvrl, onerel, &Vvpl, &Fvpl, nindices, Irel);
    else if ( Vvpl.vpl_npages > 0 )	/* Clean pages from Vvpl list */
	_vc_vacheap (curvrl, onerel, &Vvpl);

    /* ok - free Vvpl list of reapped pages */
    if ( Vvpl.vpl_npages > 0 )
    {
    	vpp = Vvpl.vpl_pgdesc;
    	for (i = 0; i < Vvpl.vpl_npages; i++, vpp++)
	    pfree(*vpp);
    	pfree (Vvpl.vpl_pgdesc);
    	if ( Fvpl.vpl_npages > 0 )
	    pfree (Fvpl.vpl_pgdesc);
    }

    /* all done with this class */
    heap_close(onerel);
    heap_endscan(pgcscan);
    heap_close(pgclass);

    /* update statistics in pg_class */
    _vc_updstats(curvrl->vrl_relid, curvrl->vrl_npages, curvrl->vrl_ntups,
		 curvrl->vrl_hasindex);

    CommitTransactionCommand();
}

/*
 *  _vc_scanheap() -- scan an open heap relation
 *
 *	This routine sets commit times, constructs Vvpl list of 
 *	empty/uninitialized pages and pages with dead tuples and
 *	~LP_USED line pointers, constructs Fvpl list of pages
 *	appropriate for purposes of shrinking and maintains statistics 
 *	on the number of live tuples in a heap.
 */
static void
_vc_scanheap (VRelList curvrl, Relation onerel, 
			VPageList Vvpl, VPageList Fvpl)
{
    int nblocks, blkno;
    ItemId itemid;
    ItemPointer itemptr;
    HeapTuple htup;
    Buffer buf;
    Page page, tempPage = NULL;
    OffsetNumber offnum, maxoff;
    bool pgchanged, tupgone, dobufrel, notup;
    AbsoluteTime purgetime, expiretime;
    RelativeTime preservetime;
    char *relname;
    VPageDescr vpc, vp;
    uint32 nvac, ntups, nunused, ncrash, nempg, nnepg, nchpg, nemend;
    Size frsize, frsusf;
    Size min_tlen = MAXTUPLEN;
    Size max_tlen = 0;
    int i;
    struct rusage ru0, ru1;

    getrusage(RUSAGE_SELF, &ru0);

    nvac = ntups = nunused = ncrash = nempg = nnepg = nchpg = nemend = 0;
    frsize = frsusf = 0;
    
    relname = (RelationGetRelationName(onerel))->data;

    nblocks = RelationGetNumberOfBlocks(onerel);

    /* calculate the purge time: tuples that expired before this time
       will be archived or deleted */
    purgetime = GetCurrentTransactionStartTime();
    expiretime = (AbsoluteTime)onerel->rd_rel->relexpires;
    preservetime = (RelativeTime)onerel->rd_rel->relpreserved;

    if (RelativeTimeIsValid(preservetime) && (preservetime)) {
	purgetime -= preservetime;
	if (AbsoluteTimeIsBackwardCompatiblyValid(expiretime) &&
	    expiretime > purgetime)
	    purgetime = expiretime;
    }

    else if (AbsoluteTimeIsBackwardCompatiblyValid(expiretime))
	purgetime = expiretime;

    vpc = (VPageDescr) palloc (sizeof(VPageDescrData) + MaxOffsetNumber*sizeof(OffsetNumber));
    vpc->vpd_nusd = 0;
	    
    for (blkno = 0; blkno < nblocks; blkno++) {
	buf = ReadBuffer(onerel, blkno);
	page = BufferGetPage(buf);
	vpc->vpd_blkno = blkno;
	vpc->vpd_noff = 0;

	if (PageIsNew(page)) {
	    elog (NOTICE, "Rel %.*s: Uninitialized page %u - fixing",
		NAMEDATALEN, relname, blkno);
	    PageInit (page, BufferGetPageSize (buf), 0);
	    vpc->vpd_free = ((PageHeader)page)->pd_upper - ((PageHeader)page)->pd_lower;
	    frsize += (vpc->vpd_free - sizeof (ItemIdData));
	    nnepg++;
	    nemend++;
	    _vc_reappage (Vvpl, vpc);
	    WriteBuffer(buf);
	    continue;
	}

	if (PageIsEmpty(page)) {
	    vpc->vpd_free = ((PageHeader)page)->pd_upper - ((PageHeader)page)->pd_lower;
	    frsize += (vpc->vpd_free - sizeof (ItemIdData));
	    nempg++;
	    nemend++;
	    _vc_reappage (Vvpl, vpc);
	    ReleaseBuffer(buf);
	    continue;
	}

	pgchanged = false;
	notup = true;
	maxoff = PageGetMaxOffsetNumber(page);
	for (offnum = FirstOffsetNumber;
	     offnum <= maxoff;
	     offnum = OffsetNumberNext(offnum)) {
	    itemid = PageGetItemId(page, offnum);

	    /*
	     * Collect un-used items too - it's possible to have
	     * indices pointing here after crash.
	     */
	    if (!ItemIdIsUsed(itemid)) {
	    	vpc->vpd_voff[vpc->vpd_noff++] = offnum;
	    	nunused++;
		continue;
	    }

	    htup = (HeapTuple) PageGetItem(page, itemid);
	    tupgone = false;

	    if (!AbsoluteTimeIsBackwardCompatiblyValid(htup->t_tmin) && 
		TransactionIdIsValid((TransactionId)htup->t_xmin)) {

		if (TransactionIdDidAbort(htup->t_xmin)) {
		    tupgone = true;
		} else if (TransactionIdDidCommit(htup->t_xmin)) {
		    htup->t_tmin = TransactionIdGetCommitTime(htup->t_xmin);
		    pgchanged = true;
		} else if ( !TransactionIdIsInProgress (htup->t_xmin) ) {
		    /* 
		     * Not Aborted, Not Committed, Not in Progress -
		     * so it from crashed process. - vadim 11/26/96
		     */
		    ncrash++;
		    tupgone = true;
		}
		else {
		    elog (MESSLEV, "Rel %.*s: InsertTransactionInProgress %u for TID %u/%u",
			NAMEDATALEN, relname, htup->t_xmin, blkno, offnum);
		}
	    }

	    if (TransactionIdIsValid((TransactionId)htup->t_xmax)) {
		if (TransactionIdDidAbort(htup->t_xmax)) {
		    StoreInvalidTransactionId(&(htup->t_xmax));
		    pgchanged = true;
		} else if (TransactionIdDidCommit(htup->t_xmax)) {
		    if (!AbsoluteTimeIsBackwardCompatiblyReal(htup->t_tmax)) {

			htup->t_tmax = TransactionIdGetCommitTime(htup->t_xmax);  
			pgchanged = true;
		    }

		    /*
		     *  Reap the dead tuple if its expiration time is
		     *  before purgetime.
		     */

		    if (htup->t_tmax < purgetime) {
			tupgone = true;
		    }
		}
	    }

	    /*
	     * Is it possible at all ? - vadim 11/26/96
	     */
	    if ( !TransactionIdIsValid((TransactionId)htup->t_xmin) )
	    {
		elog (NOTICE, "TID %u/%u: INSERT_TRANSACTION_ID IS INVALID. \
DELETE_TRANSACTION_ID_VALID %d, TUPGONE %d.", 
			TransactionIdIsValid((TransactionId)htup->t_xmax),
			tupgone);
	    }
	    
	    /*
	     * It's possibly! But from where it comes ?
	     * And should we fix it ?  - vadim 11/28/96
	     */
	    itemptr = &(htup->t_ctid);
	    if ( !ItemPointerIsValid (itemptr) || 
	    		BlockIdGetBlockNumber(&(itemptr->ip_blkid)) != blkno )
	    {
	    	elog (NOTICE, "ITEM POINTER IS INVALID: %u/%u FOR %u/%u. TUPGONE %d.", 
	    		BlockIdGetBlockNumber(&(itemptr->ip_blkid)), 
	    		itemptr->ip_posid, blkno, offnum, tupgone);
	    }

	    /*
	     * Other checks...
	     */
	    if ( htup->t_len != itemid->lp_len )
	    {
	    	elog (NOTICE, "PAGEHEADER' LEN %u IS NOT THE SAME AS HTUP' %u FOR %u/%u.TUPGONE %d.", 
	    		itemid->lp_len, htup->t_len, blkno, offnum, tupgone);
	    }
	    if ( !OidIsValid(htup->t_oid) )
	    {
	    	elog (NOTICE, "OID IS INVALID FOR %u/%u.TUPGONE %d.", 
	    		blkno, offnum, tupgone);
	    }
	    
	    if (tupgone) {
		ItemId lpp;
                                                    
		if ( tempPage == (Page) NULL )
		{
		    Size pageSize;
		    
		    pageSize = PageGetPageSize(page);
		    tempPage = (Page) palloc(pageSize);
		    memmove (tempPage, page, pageSize);
		}
		
		lpp = &(((PageHeader) tempPage)->pd_linp[offnum - 1]);

		/* mark it unused */
		lpp->lp_flags &= ~LP_USED;

	    	vpc->vpd_voff[vpc->vpd_noff++] = offnum;
	    	nvac++;

	    } else {
		ntups++;
		notup = false;
		if ( htup->t_len < min_tlen )
		    min_tlen = htup->t_len;
		if ( htup->t_len > max_tlen )
		    max_tlen = htup->t_len;
	    }
	}

	if (pgchanged) {
	    WriteBuffer(buf);
	    dobufrel = false;
	    nchpg++;
	}
	else
	    dobufrel = true;
	if ( tempPage != (Page) NULL )
	{ /* Some tuples are gone */
	    PageRepairFragmentation(tempPage);
	    vpc->vpd_free = ((PageHeader)tempPage)->pd_upper - ((PageHeader)tempPage)->pd_lower;
	    frsize += vpc->vpd_free;
	    _vc_reappage (Vvpl, vpc);
	    pfree (tempPage);
	    tempPage = (Page) NULL;
	}
	else if ( vpc->vpd_noff > 0 )
	{ /* there are only ~LP_USED line pointers */
	    vpc->vpd_free = ((PageHeader)page)->pd_upper - ((PageHeader)page)->pd_lower;
	    frsize += vpc->vpd_free;
	    _vc_reappage (Vvpl, vpc);
	}
	if ( dobufrel )
	    ReleaseBuffer(buf);
	if ( notup )
	    nemend++;
	else
	    nemend = 0;
    }

    pfree (vpc);

    /* save stats in the rel list for use later */
    curvrl->vrl_ntups = ntups;
    curvrl->vrl_npages = nblocks;
    if ( ntups == 0 )
    	min_tlen = max_tlen = 0;
    curvrl->vrl_min_tlen = min_tlen;
    curvrl->vrl_max_tlen = max_tlen;
    
    Vvpl->vpl_nemend = nemend;
    Fvpl->vpl_nemend = nemend;

    /* 
     * Try to make Fvpl keeping in mind that we can't use free space 
     * of "empty" end-pages and last page if it reapped.
     */
    if ( Vvpl->vpl_npages - nemend > 0 )
    {
	int nusf;		/* blocks usefull for re-using */
	
	nusf = Vvpl->vpl_npages - nemend;
	if ( (Vvpl->vpl_pgdesc[nusf-1])->vpd_blkno == nblocks - nemend - 1 )
	    nusf--;
    
	for (i = 0; i < nusf; i++)
    	{
	    vp = Vvpl->vpl_pgdesc[i];
	    if ( _vc_enough_space (vp, min_tlen) )
	    {
		_vc_vpinsert (Fvpl, vp);
		frsusf += vp->vpd_free;
	    }
	}
    }

    getrusage(RUSAGE_SELF, &ru1);
    
    elog (MESSLEV, "Rel %.*s: Pages %u: Changed %u, Reapped %u, Empty %u, New %u; \
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.",
	NAMEDATALEN, relname, 
	nblocks, nchpg, Vvpl->vpl_npages, nempg, nnepg,
	ntups, nvac, ncrash, nunused, min_tlen, max_tlen, 
	frsize, frsusf, nemend, Fvpl->vpl_npages,
	ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec, 
	ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);

} /* _vc_scanheap */


/*
 *  _vc_rpfheap() -- try to repaire relation' fragmentation
 *
 *	This routine marks dead tuples as unused and tries re-use dead space
 *	by moving tuples (and inserting indices if needed). It constructs 
 *	Nvpl list of free-ed pages (moved tuples) and clean indices
 *	for them after committing (in hack-manner - without losing locks
 *	and freeing memory!) current transaction. It truncates relation
 *	if some end-blocks are gone away.
 */
static void
_vc_rpfheap (VRelList curvrl, Relation onerel, 
		VPageList Vvpl, VPageList Fvpl, int nindices, Relation *Irel)
{
    TransactionId myXID;
    CommandId myCID;
    AbsoluteTime myCTM = 0;
    Buffer buf, ToBuf;
    int nblocks, blkno;
    Page page, ToPage = NULL;
    OffsetNumber offnum = 0, maxoff = 0, newoff, moff;
    ItemId itemid, newitemid;
    HeapTuple htup, newtup;
    TupleDesc tupdesc = NULL;
    Datum *idatum = NULL;
    char *inulls = NULL;
    InsertIndexResult iresult;
    VPageListData Nvpl;
    VPageDescr ToVpd = NULL, Fvplast, Vvplast, vpc, *vpp;
    int ToVpI = 0;
    IndDesc *Idesc, *idcur;
    int Fblklast, Vblklast, i;
    Size tlen;
    int nmoved, Fnpages, Vnpages;
    int nchkmvd, ntups;
    bool isempty, dowrite;
    Relation archrel;
    struct rusage ru0, ru1;

    getrusage(RUSAGE_SELF, &ru0);

    myXID = GetCurrentTransactionId();
    myCID = GetCurrentCommandId();
	
    if ( Irel != (Relation*) NULL )	/* preparation for index' inserts */
    {
	_vc_mkindesc (onerel, nindices, Irel, &Idesc);
	tupdesc = RelationGetTupleDescriptor(onerel);
	idatum = (Datum *) palloc(INDEX_MAX_KEYS * sizeof (*idatum));
	inulls = (char *) palloc(INDEX_MAX_KEYS * sizeof (*inulls));
    }

    /* if the relation has an archive, open it */
    if (onerel->rd_rel->relarch != 'n')
    {
	archrel = _vc_getarchrel(onerel);
	/* Archive tuples from "empty" end-pages */
	for ( vpp = Vvpl->vpl_pgdesc + Vvpl->vpl_npages - 1, 
				i = Vvpl->vpl_nemend; i > 0; i--, vpp-- )
	{
	    if ( (*vpp)->vpd_noff > 0 )
	    {
	    	buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
	    	page = BufferGetPage(buf);
	    	Assert ( !PageIsEmpty(page) );
		_vc_vacpage (page, *vpp, archrel);
		WriteBuffer (buf);
	    }
	}
    }
    else
	archrel = (Relation) NULL;

    Nvpl.vpl_npages = 0;
    Fnpages = Fvpl->vpl_npages;
    Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
    Fblklast = Fvplast->vpd_blkno;
    Assert ( Vvpl->vpl_npages > Vvpl->vpl_nemend );
    Vnpages = Vvpl->vpl_npages - Vvpl->vpl_nemend;
    Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
    Vblklast = Vvplast->vpd_blkno;
    Assert ( Vblklast >= Fblklast );
    ToBuf = InvalidBuffer;
    nmoved = 0;

    vpc = (VPageDescr) palloc (sizeof(VPageDescrData) + MaxOffsetNumber*sizeof(OffsetNumber));
    vpc->vpd_nusd = vpc->vpd_noff = 0;
	
    nblocks = curvrl->vrl_npages;
    for (blkno = nblocks - Vvpl->vpl_nemend - 1; ; blkno--)
    {
	/* if it's reapped page and it was used by me - quit */
	if ( blkno == Fblklast && Fvplast->vpd_nusd > 0 )
	    break;

	buf = ReadBuffer(onerel, blkno);
	page = BufferGetPage(buf);

	vpc->vpd_noff = 0;

	isempty = PageIsEmpty(page);

	dowrite = false;
	if ( blkno == Vblklast )		/* it's reapped page */
	{
	    if ( Vvplast->vpd_noff > 0 )	/* there are dead tuples */
	    {					/* on this page - clean */
		Assert ( ! isempty );
		_vc_vacpage (page, Vvplast, archrel);
		dowrite = true;
	    }
	    else
		Assert ( isempty );
	    Assert ( --Vnpages > 0 );
	    /* get prev reapped page from Vvpl */
	    Vvplast = Vvpl->vpl_pgdesc[Vnpages - 1];
	    Vblklast = Vvplast->vpd_blkno;
	    if ( blkno == Fblklast )	/* this page in Fvpl too */
	    {
		Assert ( --Fnpages > 0 );
		Assert ( Fvplast->vpd_nusd == 0 );
		/* get prev reapped page from Fvpl */
		Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
		Fblklast = Fvplast->vpd_blkno;
	    }
	    Assert ( Fblklast <= Vblklast );
	    if ( isempty )
	    {
		ReleaseBuffer(buf);
		continue;
	    }
	}
	else
	{
	    Assert ( ! isempty );
	}

	vpc->vpd_blkno = blkno;
	maxoff = PageGetMaxOffsetNumber(page);
	for (offnum = FirstOffsetNumber;
		offnum <= maxoff;
		offnum = OffsetNumberNext(offnum))
	{
	    itemid = PageGetItemId(page, offnum);

	    if (!ItemIdIsUsed(itemid))
		continue;

	    htup = (HeapTuple) PageGetItem(page, itemid);
	    tlen = htup->t_len;
		
	    /* try to find new page for this tuple */
	    if ( ToBuf == InvalidBuffer ||
		! _vc_enough_space (ToVpd, tlen) )
	    {
		if ( ToBuf != InvalidBuffer )
		{
		    WriteBuffer(ToBuf);
		    ToBuf = InvalidBuffer;
 		    /*
 		     * If no one tuple can't be added to this page -
 		     * remove page from Fvpl. - vadim 11/27/96
 		     */ 
 		    if ( !_vc_enough_space (ToVpd, curvrl->vrl_min_tlen) )
 		    {
 		    	if ( ToVpd != Fvplast )
 		    	{
 		    	    Assert ( Fnpages > ToVpI + 1 );
 		    	    memmove (Fvpl->vpl_pgdesc + ToVpI, 
 		    	    	Fvpl->vpl_pgdesc + ToVpI + 1, 
 		    	    	sizeof (VPageDescr*) * (Fnpages - ToVpI - 1));
 		    	}
 		    	Assert ( Fnpages >= 1 );
 		    	Fnpages--;
 		    	if ( Fnpages == 0 )
 		    	    break;
			/* get prev reapped page from Fvpl */
			Fvplast = Fvpl->vpl_pgdesc[Fnpages - 1];
			Fblklast = Fvplast->vpd_blkno;
 		    }
 		}
		for (i=0; i < Fnpages; i++)
		{
		    if ( _vc_enough_space (Fvpl->vpl_pgdesc[i], tlen) )
			break;
		}
		if ( i == Fnpages )
		    break;			/* can't move item anywhere */
 		ToVpI = i;
 		ToVpd = Fvpl->vpl_pgdesc[ToVpI];
		ToBuf = ReadBuffer(onerel, ToVpd->vpd_blkno);
		ToPage = BufferGetPage(ToBuf);
		/* if this page was not used before - clean it */
		if ( ! PageIsEmpty(ToPage) && ToVpd->vpd_nusd == 0 )
		    _vc_vacpage (ToPage, ToVpd, archrel);
	    }
		
	    /* copy tuple */
	    newtup = (HeapTuple) palloc (tlen);
	    memmove((char *) newtup, (char *) htup, tlen);

	    /* store transaction information */
	    TransactionIdStore(myXID, &(newtup->t_xmin));
	    newtup->t_cmin = myCID;
	    StoreInvalidTransactionId(&(newtup->t_xmax));
	    newtup->t_tmin = INVALID_ABSTIME;
	    newtup->t_tmax = CURRENT_ABSTIME;
	    ItemPointerSetInvalid(&newtup->t_chain);

	    /* add tuple to the page */
	    newoff = PageAddItem (ToPage, (Item)newtup, tlen, 
				InvalidOffsetNumber, LP_USED);
	    if ( newoff == InvalidOffsetNumber )
	    {
		elog (WARN, "\
failed to add item with len = %u to page %u (free space %u, nusd %u, noff %u)",
		tlen, ToVpd->vpd_blkno, ToVpd->vpd_free, 
		ToVpd->vpd_nusd, ToVpd->vpd_noff);
	    }
	    newitemid = PageGetItemId(ToPage, newoff);
	    pfree (newtup);
	    newtup = (HeapTuple) PageGetItem(ToPage, newitemid);
	    ItemPointerSet(&(newtup->t_ctid), ToVpd->vpd_blkno, newoff);

	    /* now logically delete end-tuple */
	    TransactionIdStore(myXID, &(htup->t_xmax));
	    htup->t_cmax = myCID;
	    memmove ((char*)&(htup->t_chain), (char*)&(newtup->t_ctid), sizeof (newtup->t_ctid));

	    ToVpd->vpd_nusd++;
	    nmoved++;
	    ToVpd->vpd_free = ((PageHeader)ToPage)->pd_upper - ((PageHeader)ToPage)->pd_lower;
	    vpc->vpd_voff[vpc->vpd_noff++] = offnum;
		
	    /* insert index' tuples if needed */
	    if ( Irel != (Relation*) NULL )
	    {
		for (i = 0, idcur = Idesc; i < nindices; i++, idcur++)
		{
		    FormIndexDatum (
		    		idcur->natts,
		    		(AttrNumber *)&(idcur->tform->indkey[0]),
				newtup, 
				tupdesc,
				InvalidBuffer,
				idatum,
				inulls,
				idcur->finfoP);
		    iresult = index_insert (
				Irel[i],
				idatum,
				inulls,
				&(newtup->t_ctid),
				true);
		    if (iresult) pfree(iresult);
		}
	    }
		
	} /* walk along page */

	if ( vpc->vpd_noff > 0 )		/* some tuples were moved */
	{
	    _vc_reappage (&Nvpl, vpc);
	    WriteBuffer(buf);
	}
	else if ( dowrite )
	    WriteBuffer(buf);
	else
	    ReleaseBuffer(buf);
	    
	if ( offnum <= maxoff )
	    break;				/* some item(s) left */
	    
    } /* walk along relation */
	
    blkno++;				/* new number of blocks */

    if ( ToBuf != InvalidBuffer )
    {
	Assert (nmoved > 0);
	WriteBuffer(ToBuf);
    }

    if ( nmoved > 0 )
    {
	/* 
	 * We have to commit our tuple' movings before we'll truncate 
	 * relation, but we shouldn't lose our locks. And so - quick hack: 
	 * flush buffers and record status of current transaction
	 * as committed, and continue. - vadim 11/13/96
	 */
	FlushBufferPool(!TransactionFlushEnabled());
	TransactionIdCommit(myXID);
	FlushBufferPool(!TransactionFlushEnabled());
	myCTM = TransactionIdGetCommitTime(myXID);
    }
	
    /* 
     * Clean uncleaned reapped pages from Vvpl list 
     * and set commit' times  for inserted tuples
     */
    nchkmvd = 0;
    for (i = 0, vpp = Vvpl->vpl_pgdesc; i < Vnpages; i++, vpp++)
    {
	Assert ( (*vpp)->vpd_blkno < blkno );
	buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
	page = BufferGetPage(buf);
	if ( (*vpp)->vpd_nusd == 0 )	/* this page was not used */
	{
	    /* noff == 0 in empty pages only - such pages should be re-used */
	    Assert ( (*vpp)->vpd_noff > 0 );
	    _vc_vacpage (page, *vpp, archrel);
	}
	else				/* this page was used */
	{
	    ntups = 0;
	    moff = PageGetMaxOffsetNumber(page);
	    for (newoff = FirstOffsetNumber;
			newoff <= moff;
			newoff = OffsetNumberNext(newoff))
	    {
	    	itemid = PageGetItemId(page, newoff);
	    	if (!ItemIdIsUsed(itemid))
		    continue;
	    	htup = (HeapTuple) PageGetItem(page, itemid);
	    	if ( TransactionIdEquals((TransactionId)htup->t_xmin, myXID) )
	    	{
	    	    htup->t_tmin = myCTM;
	    	    ntups++;
	    	}
	    }
	    Assert ( (*vpp)->vpd_nusd == ntups );
	    nchkmvd += ntups;
	}
    	WriteBuffer (buf);
    }
    Assert ( nmoved == nchkmvd );

    getrusage(RUSAGE_SELF, &ru1);
    
    elog (MESSLEV, "Rel %.*s: Pages: %u --> %u; Tuple(s) moved: %u. \
Elapsed %u/%u sec.",
		NAMEDATALEN, (RelationGetRelationName(onerel))->data, 
		nblocks, blkno, nmoved,
		ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec, 
		ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);

    if ( Nvpl.vpl_npages > 0 )
    {
	/* vacuum indices again if needed */
	if ( Irel != (Relation*) NULL )
	{
	    VPageDescr *vpleft, *vpright, vpsave;
		
	    /* re-sort Nvpl.vpl_pgdesc */
	    for (vpleft = Nvpl.vpl_pgdesc, 
		vpright = Nvpl.vpl_pgdesc + Nvpl.vpl_npages - 1;
		vpleft < vpright; vpleft++, vpright--)
	    {
		vpsave = *vpleft; *vpleft = *vpright; *vpright = vpsave;
	    }
	    for (i = 0; i < nindices; i++)
		_vc_vaconeind (&Nvpl, Irel[i], curvrl->vrl_ntups);
	}

	/* 
	 * clean moved tuples from last page in Nvpl list
	 * if some tuples left there
	 */
	if ( vpc->vpd_noff > 0 && offnum <= maxoff )
	{
	    Assert (vpc->vpd_blkno == blkno - 1);
	    buf = ReadBuffer(onerel, vpc->vpd_blkno);
	    page = BufferGetPage (buf);
	    ntups = 0;
	    maxoff = offnum;
	    for (offnum = FirstOffsetNumber;
			offnum < maxoff;
			offnum = OffsetNumberNext(offnum))
	    {
	    	itemid = PageGetItemId(page, offnum);
	    	if (!ItemIdIsUsed(itemid))
		    continue;
	    	htup = (HeapTuple) PageGetItem(page, itemid);
	    	Assert ( TransactionIdEquals((TransactionId)htup->t_xmax, myXID) );
		itemid->lp_flags &= ~LP_USED;
		ntups++;
	    }
	    Assert ( vpc->vpd_noff == ntups );
	    PageRepairFragmentation(page);
	    WriteBuffer (buf);
	}

	/* now - free new list of reapped pages */
	vpp = Nvpl.vpl_pgdesc;
	for (i = 0; i < Nvpl.vpl_npages; i++, vpp++)
	    pfree(*vpp);
	pfree (Nvpl.vpl_pgdesc);
    }
	
    /* truncate relation */
    if ( blkno < nblocks )
    {
    	blkno = smgrtruncate (onerel->rd_rel->relsmgr, onerel, blkno);
	Assert ( blkno >= 0 );
	curvrl->vrl_npages = blkno;	/* set new number of blocks */
    }

    if ( archrel != (Relation) NULL )
	heap_close(archrel);

    if ( Irel != (Relation*) NULL )	/* pfree index' allocations */
    {
	pfree (Idesc);
	pfree (idatum);
	pfree (inulls);
	_vc_clsindices (nindices, Irel);
    }

    pfree (vpc);

} /* _vc_rpfheap */

/*
 *  _vc_vacheap() -- free dead tuples
 *
 *	This routine marks dead tuples as unused and truncates relation
 *	if there are "empty" end-blocks.
 */
static void
_vc_vacheap (VRelList curvrl, Relation onerel, VPageList Vvpl)
{
    Buffer buf;
    Page page;
    VPageDescr *vpp;
    Relation archrel;
    int nblocks;
    int i;

    nblocks = Vvpl->vpl_npages;
    /* if the relation has an archive, open it */
    if (onerel->rd_rel->relarch != 'n')
	archrel = _vc_getarchrel(onerel);
    else
    {
	archrel = (Relation) NULL;
	nblocks -= Vvpl->vpl_nemend;	/* nothing to do with them */
    }
	
    for (i = 0, vpp = Vvpl->vpl_pgdesc; i < nblocks; i++, vpp++)
    {
	if ( (*vpp)->vpd_noff > 0 )
	{
	    buf = ReadBuffer(onerel, (*vpp)->vpd_blkno);
	    page = BufferGetPage (buf);
	    _vc_vacpage (page, *vpp, archrel);
	    WriteBuffer (buf);
	}
    }

    /* truncate relation if there are some empty end-pages */
    if ( Vvpl->vpl_nemend > 0 )
    {
	Assert ( curvrl->vrl_npages >= Vvpl->vpl_nemend );
	nblocks = curvrl->vrl_npages - Vvpl->vpl_nemend;
	elog (MESSLEV, "Rel %.*s: Pages: %u --> %u.",
		NAMEDATALEN, (RelationGetRelationName(onerel))->data, 
		curvrl->vrl_npages, nblocks);

	/* 
	 * we have to flush "empty" end-pages (if changed, but who knows it)
	 * before truncation 
	 */
	FlushBufferPool(!TransactionFlushEnabled());

    	nblocks = smgrtruncate (onerel->rd_rel->relsmgr, onerel, nblocks);
	Assert ( nblocks >= 0 );
	curvrl->vrl_npages = nblocks;	/* set new number of blocks */
    }

    if ( archrel != (Relation) NULL )
	heap_close(archrel);

} /* _vc_vacheap */

/*
 *  _vc_vacpage() -- free (and archive if needed) dead tuples on a page
 *		     and repaire its fragmentation.
 */
static void
_vc_vacpage (Page page, VPageDescr vpd, Relation archrel)
{
    ItemId itemid;
    HeapTuple htup;
    int i;
    
    Assert ( vpd->vpd_nusd == 0 );
    for (i=0; i < vpd->vpd_noff; i++)
    {
	itemid = &(((PageHeader) page)->pd_linp[vpd->vpd_voff[i] - 1]);
	if ( archrel != (Relation) NULL && ItemIdIsUsed(itemid) )
	{
	    htup = (HeapTuple) PageGetItem (page, itemid);
	    _vc_archive (archrel, htup);
	}
	itemid->lp_flags &= ~LP_USED;
    }
    PageRepairFragmentation(page);

} /* _vc_vacpage */

/*
 *  _vc_vaconeind() -- vacuum one index relation.
 *
 *	Vpl is the VPageList of the heap we're currently vacuuming.
 *	It's locked. Indrel is an index relation on the vacuumed heap. 
 *	We don't set locks on the index	relation here, since the indexed 
 *	access methods support locking at different granularities. 
 *	We let them handle it.
 *
 *	Finally, we arrange to update the index relation's statistics in
 *	pg_class.
 */
static void
_vc_vaconeind(VPageList vpl, Relation indrel, int nhtups)
{
    RetrieveIndexResult res;
    IndexScanDesc iscan;
    ItemPointer heapptr;
    int nvac;
    int nitups;
    int nipages;
    VPageDescr vp;
    struct rusage ru0, ru1;

    getrusage(RUSAGE_SELF, &ru0);

    /* walk through the entire index */
    iscan = index_beginscan(indrel, false, 0, (ScanKey) NULL);
    nvac = 0;
    nitups = 0;

    while ((res = index_getnext(iscan, ForwardScanDirection))
	   != (RetrieveIndexResult) NULL) {
	heapptr = &res->heap_iptr;

	if ( (vp = _vc_tidreapped (heapptr, vpl)) != (VPageDescr) NULL)
	{
#if 0
	    elog(DEBUG, "<%x,%x> -> <%x,%x>",
		 ItemPointerGetBlockNumber(&(res->index_iptr)),
		 ItemPointerGetOffsetNumber(&(res->index_iptr)),
		 ItemPointerGetBlockNumber(&(res->heap_iptr)),
		 ItemPointerGetOffsetNumber(&(res->heap_iptr)));
#endif
	    if ( vp->vpd_noff == 0 ) 
	    {				/* this is EmptyPage !!! */
	    	elog (NOTICE, "Ind %.*s: pointer to EmptyPage (blk %u off %u) - fixing",
			NAMEDATALEN, indrel->rd_rel->relname.data,
	    		vp->vpd_blkno, ItemPointerGetOffsetNumber(heapptr));
	    }
	    ++nvac;
	    index_delete(indrel, &res->index_iptr);
	} else {
	    nitups++;
	}

	/* be tidy */
	pfree(res);
    }

    index_endscan(iscan);

    /* now update statistics in pg_class */
    nipages = RelationGetNumberOfBlocks(indrel);
    _vc_updstats(indrel->rd_id, nipages, nitups, false);

    getrusage(RUSAGE_SELF, &ru1);

    elog (MESSLEV, "Ind %.*s: Pages %u; Tuples %u: Deleted %u. Elapsed %u/%u sec.",
	NAMEDATALEN, indrel->rd_rel->relname.data, nipages, nitups, nvac,
	ru1.ru_stime.tv_sec - ru0.ru_stime.tv_sec, 
	ru1.ru_utime.tv_sec - ru0.ru_utime.tv_sec);

    if ( nitups != nhtups )
    	elog (NOTICE, "NUMBER OF INDEX' TUPLES (%u) IS NOT THE SAME AS HEAP' (%u)",
    		nitups, nhtups);

} /* _vc_vaconeind */

/*
 *  _vc_tidreapped() -- is a particular tid reapped?
 *
 *	vpl->VPageDescr_array is sorted in right order.
 */
static VPageDescr
_vc_tidreapped(ItemPointer itemptr, VPageList vpl)
{
    OffsetNumber ioffno;
    OffsetNumber *voff;
    VPageDescr vp, *vpp;
    VPageDescrData vpd;

    vpd.vpd_blkno = ItemPointerGetBlockNumber(itemptr);
    ioffno = ItemPointerGetOffsetNumber(itemptr);
	
    vp = &vpd;
    vpp = (VPageDescr*) _vc_find_eq ((char*)(vpl->vpl_pgdesc), 
		vpl->vpl_npages, sizeof (VPageDescr), (char*)&vp, 
		_vc_cmp_blk);

    if ( vpp == (VPageDescr*) NULL )
	return ((VPageDescr)NULL);
    vp = *vpp;

    /* ok - we are on true page */

    if ( vp->vpd_noff == 0 ) {		/* this is EmptyPage !!! */
	return (vp);
    }
    
    voff = (OffsetNumber*) _vc_find_eq ((char*)(vp->vpd_voff), 
		vp->vpd_noff, sizeof (OffsetNumber), (char*)&ioffno, 
		_vc_cmp_offno);

    if ( voff == (OffsetNumber*) NULL )
	return ((VPageDescr)NULL);

    return (vp);

} /* _vc_tidreapped */

/*
 *  _vc_updstats() -- update pg_class statistics for one relation
 *
 *	This routine works for both index and heap relation entries in
 *	pg_class.  We violate no-overwrite semantics here by storing new
 *	values for ntuples, npages, and hasindex directly in the pg_class
 *	tuple that's already on the page.  The reason for this is that if
 *	we updated these tuples in the usual way, then every tuple in pg_class
 *	would be replaced every day.  This would make planning and executing
 *	historical queries very expensive.
 */
static void
_vc_updstats(Oid relid, int npages, int ntuples, bool hasindex)
{
    Relation rd;
    HeapScanDesc sdesc;
    HeapTuple tup;
    Buffer buf;
    Form_pg_class pgcform;
    ScanKeyData skey;

    /*
     * update number of tuples and number of pages in pg_class
     */
    ScanKeyEntryInitialize(&skey, 0x0, ObjectIdAttributeNumber,
			   ObjectIdEqualRegProcedure,
			   ObjectIdGetDatum(relid));

    rd = heap_openr(RelationRelationName);
    sdesc = heap_beginscan(rd, false, NowTimeQual, 1, &skey);

    if (!HeapTupleIsValid(tup = heap_getnext(sdesc, 0, &buf)))
	elog(WARN, "pg_class entry for relid %d vanished during vacuuming",
		   relid);

    /* overwrite the existing statistics in the tuple */
    _vc_setpagelock(rd, BufferGetBlockNumber(buf));
    pgcform = (Form_pg_class) GETSTRUCT(tup);
    pgcform->reltuples = ntuples;
    pgcform->relpages = npages;
    pgcform->relhasindex = hasindex;
 
    /* XXX -- after write, should invalidate relcache in other backends */
    WriteNoReleaseBuffer(buf);	/* heap_endscan release scan' buffers ? */

    /* that's all, folks */
    heap_endscan(sdesc);
    heap_close(rd);

}

static void _vc_setpagelock(Relation rel, BlockNumber blkno)
{
    ItemPointerData itm;

    ItemPointerSet(&itm, blkno, 1);

    RelationSetLockForWritePage(rel, &itm);
}


/*
 *  _vc_reappage() -- save a page on the array of reapped pages.
 *
 *	As a side effect of the way that the vacuuming loop for a given
 *	relation works, higher pages come after lower pages in the array
 *	(and highest tid on a page is last).
 */
static void 
_vc_reappage(VPageList vpl, VPageDescr vpc)
{
    VPageDescr newvpd;

    /* allocate a VPageDescrData entry */
    newvpd = (VPageDescr) palloc(sizeof(VPageDescrData) + vpc->vpd_noff*sizeof(OffsetNumber));

    /* fill it in */
    if ( vpc->vpd_noff > 0 )
    	memmove (newvpd->vpd_voff, vpc->vpd_voff, vpc->vpd_noff*sizeof(OffsetNumber));
    newvpd->vpd_blkno = vpc->vpd_blkno;
    newvpd->vpd_free = vpc->vpd_free;
    newvpd->vpd_nusd = vpc->vpd_nusd;
    newvpd->vpd_noff = vpc->vpd_noff;

    /* insert this page into vpl list */
    _vc_vpinsert (vpl, newvpd);
    
} /* _vc_reappage */

static void
_vc_vpinsert (VPageList vpl, VPageDescr vpnew)
{

    /* allocate a VPageDescr entry if needed */
    if ( vpl->vpl_npages == 0 )
    	vpl->vpl_pgdesc = (VPageDescr*) palloc(100*sizeof(VPageDescr));
    else if ( vpl->vpl_npages % 100 == 0 )
    	vpl->vpl_pgdesc = (VPageDescr*) repalloc(vpl->vpl_pgdesc, (vpl->vpl_npages+100)*sizeof(VPageDescr));
    vpl->vpl_pgdesc[vpl->vpl_npages] = vpnew;
    (vpl->vpl_npages)++;
    
}

static void
_vc_free(Portal p, VRelList vrl)
{
    VRelList p_vrl;
    VAttList p_val, val;
    MemoryContext old;
    PortalVariableMemory pmem;

    pmem = PortalGetVariableMemory(p);
    old = MemoryContextSwitchTo((MemoryContext)pmem);

    while (vrl != (VRelList) NULL) {

	/* free attribute list */
	val = vrl->vrl_attlist;
	while (val != (VAttList) NULL) {
	    p_val = val;
	    val = val->val_next;
	    pfree(p_val);
	}

	/* free rel list entry */
	p_vrl = vrl;
	vrl = vrl->vrl_next;
	pfree(p_vrl);
    }

    (void) MemoryContextSwitchTo(old);
}

/*
 *  _vc_getarchrel() -- open the archive relation for a heap relation
 *
 *	The archive relation is named 'a,XXXXX' for the heap relation
 *	whose relid is XXXXX.
 */

#define ARCHIVE_PREFIX	"a,"

static Relation
_vc_getarchrel(Relation heaprel)
{
    Relation archrel;
    char *archrelname;

    archrelname = palloc(sizeof(ARCHIVE_PREFIX) + NAMEDATALEN); /* bogus */
    sprintf(archrelname, "%s%d", ARCHIVE_PREFIX, heaprel->rd_id);

    archrel = heap_openr(archrelname);

    pfree(archrelname);
    return (archrel);
}

/*
 *  _vc_archive() -- write a tuple to an archive relation
 *
 *	In the future, this will invoke the archived accessd method.  For
 *	now, archive relations are on mag disk.
 */
static void
_vc_archive(Relation archrel, HeapTuple htup)
{
    doinsert(archrel, htup);
}

static bool
_vc_isarchrel(char *rname)
{
    if (strncmp(ARCHIVE_PREFIX, rname,strlen(ARCHIVE_PREFIX)) == 0)
	return (true);

    return (false);
}

static char *
_vc_find_eq (char *bot, int nelem, int size, char *elm, int (*compar)(char *, char *))
{
    int res;
    int last = nelem - 1;
    int celm = nelem / 2;
    bool last_move, first_move;
    
    last_move = first_move = true;
    for ( ; ; )
    {
	if ( first_move == true )
	{
	    res = compar (bot, elm);
	    if ( res > 0 )
		return (NULL);
	    if ( res == 0 )
		return (bot);
	    first_move = false;
	}
	if ( last_move == true )
	{
	    res = compar (elm, bot + last*size);
	    if ( res > 0 )
		return (NULL);
	    if ( res == 0 )
		return (bot + last*size);
	    last_move = false;
	}
    	res = compar (elm, bot + celm*size);
    	if ( res == 0 )
	    return (bot + celm*size);
	if ( res < 0 )
	{
	    if ( celm == 0 )
		return (NULL);
	    last = celm - 1;
	    celm = celm / 2;
	    last_move = true;
	    continue;
	}
	
	if ( celm == last )
	    return (NULL);
	    
	last = last - celm - 1;
	bot = bot + (celm+1)*size;
	celm = (last + 1) / 2;
	first_move = true;
    }

} /* _vc_find_eq */

static int 
_vc_cmp_blk (char *left, char *right)
{
    BlockNumber lblk, rblk;

    lblk = (*((VPageDescr*)left))->vpd_blkno;
    rblk = (*((VPageDescr*)right))->vpd_blkno;

    if ( lblk < rblk )
    	return (-1);
    if ( lblk == rblk )
    	return (0);
    return (1);

} /* _vc_cmp_blk */

static int 
_vc_cmp_offno (char *left, char *right)
{

    if ( *(OffsetNumber*)left < *(OffsetNumber*)right )
    	return (-1);
    if ( *(OffsetNumber*)left == *(OffsetNumber*)right )
    	return (0);
    return (1);

} /* _vc_cmp_offno */


static void
_vc_getindices (Oid relid, int *nindices, Relation **Irel)
{
    Relation pgindex;
    Relation irel;
    TupleDesc pgidesc;
    HeapTuple pgitup;
    HeapScanDesc pgiscan;
    Datum d;
    int i, k;
    bool n;
    ScanKeyData pgikey;
    Oid *ioid;

    *nindices = i = 0;
    
    ioid = (Oid *) palloc(10*sizeof(Oid));

    /* prepare a heap scan on the pg_index relation */
    pgindex = heap_openr(IndexRelationName);
    pgidesc = RelationGetTupleDescriptor(pgindex);

    ScanKeyEntryInitialize(&pgikey, 0x0, Anum_pg_index_indrelid,
			   ObjectIdEqualRegProcedure,
			   ObjectIdGetDatum(relid));

    pgiscan = heap_beginscan(pgindex, false, NowTimeQual, 1, &pgikey);

    while (HeapTupleIsValid(pgitup = heap_getnext(pgiscan, 0, NULL))) {
	d = (Datum) heap_getattr(pgitup, InvalidBuffer, Anum_pg_index_indexrelid,
				 pgidesc, &n);
	i++;
	if ( i % 10 == 0 )
	    ioid = (Oid *) repalloc(ioid, (i+10)*sizeof(Oid));
	ioid[i-1] = DatumGetObjectId(d);
    }

    heap_endscan(pgiscan);
    heap_close(pgindex);

    if ( i == 0 ) {	/* No one index found */
	pfree(ioid);
	return;
    }

    if ( Irel != (Relation **) NULL )
	*Irel = (Relation *) palloc(i * sizeof(Relation));
    
    for (k = 0; i > 0; )
    {
	irel = index_open(ioid[--i]);
	if ( irel != (Relation) NULL )
	{
	    if ( Irel != (Relation **) NULL )
		(*Irel)[k] = irel;
	    else
		index_close (irel);
	    k++;
	}
	else
	    elog (NOTICE, "CAN't OPEN INDEX %u - SKIP IT", ioid[i]);
    }
    *nindices = k;
    pfree(ioid);

    if ( Irel != (Relation **) NULL && *nindices == 0 )
    {
	pfree (*Irel);
	*Irel = (Relation *) NULL;
    }

} /* _vc_getindices */


static void
_vc_clsindices (int nindices, Relation *Irel)
{

    if ( Irel == (Relation*) NULL )
    	return;

    while (nindices--) {
	index_close (Irel[nindices]);
    }
    pfree (Irel);

} /* _vc_clsindices */


static void
_vc_mkindesc (Relation onerel, int nindices, Relation *Irel, IndDesc **Idesc)
{
    IndDesc *idcur;
    HeapTuple pgIndexTup;
    AttrNumber *attnumP;
    int natts;
    int i;

    *Idesc = (IndDesc *) palloc (nindices * sizeof (IndDesc));
    
    for (i = 0, idcur = *Idesc; i < nindices; i++, idcur++) {
	pgIndexTup =
		SearchSysCacheTuple(INDEXRELID,
				ObjectIdGetDatum(Irel[i]->rd_id),
				0,0,0);
	Assert(pgIndexTup);
	idcur->tform = (IndexTupleForm)GETSTRUCT(pgIndexTup);
	for (attnumP = &(idcur->tform->indkey[0]), natts = 0;
		*attnumP != InvalidAttrNumber && natts != INDEX_MAX_KEYS;
		attnumP++, natts++);
	if (idcur->tform->indproc != InvalidOid) {
	    idcur->finfoP = &(idcur->finfo);
	    FIgetnArgs(idcur->finfoP) = natts;
	    natts = 1;
	    FIgetProcOid(idcur->finfoP) = idcur->tform->indproc;
	    *(FIgetname(idcur->finfoP)) = '\0';
	} else
	    idcur->finfoP = (FuncIndexInfo *) NULL;
	
	idcur->natts = natts;
    }
    
} /* _vc_mkindesc */


static bool
_vc_enough_space (VPageDescr vpd, Size len)
{

    len = DOUBLEALIGN(len);

    if ( len > vpd->vpd_free )
    	return (false);
    
    if ( vpd->vpd_nusd < vpd->vpd_noff )	/* there are free itemid(s) */
    	return (true);				/* and len <= free_space */
    
    /* ok. noff_usd >= noff_free and so we'll have to allocate new itemid */
    if ( len <= vpd->vpd_free - sizeof (ItemIdData) )
    	return (true);
    
    return (false);
    
} /* _vc_enough_space */