1 /*-------------------------------------------------------------------------
4 * POSTGRES free space map for quickly finding free space in relations
7 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/storage/freespace/freespace.c,v 1.28 2003/12/20 17:31:21 momjian Exp $
16 * The only really interesting aspect of this code is the heuristics for
17 * deciding how much information we can afford to keep about each relation,
18 * given that we have a limited amount of workspace in shared memory.
19 * These currently work as follows:
21 * The number of distinct relations tracked is limited by a configuration
22 * variable (MaxFSMRelations). When this would be exceeded, we discard the
23 * least recently used relation. A doubly-linked list with move-to-front
24 * behavior keeps track of which relation is least recently used.
26 * For each known relation, we track the average request size given to
27 * GetPageWithFreeSpace() as well as the most recent number of pages given
28 * to RecordRelationFreeSpace(). The average request size is not directly
29 * used in this module, but we expect VACUUM to use it to filter out
30 * uninteresting amounts of space before calling RecordRelationFreeSpace().
31 * The sum of the RRFS page counts is thus the total number of "interesting"
32 * pages that we would like to track; this is called DesiredFSMPages.
34 * The number of pages actually tracked is limited by a configuration variable
35 * (MaxFSMPages). When this is less than DesiredFSMPages, each relation
36 * gets to keep a fraction MaxFSMPages/DesiredFSMPages of its free pages.
37 * We discard pages with less free space to reach this target.
39 * Actually, our space allocation is done in "chunks" of CHUNKPAGES pages,
40 * with each relation guaranteed at least one chunk. This reduces thrashing
41 * of the storage allocations when there are small changes in the RRFS page
42 * counts from one VACUUM to the next. (XXX it might also be worthwhile to
43 * impose some kind of moving-average smoothing on the RRFS page counts?)
45 * So the actual arithmetic is: for each relation compute myRequest as the
46 * number of chunks needed to hold its RRFS page count (not counting the
47 * first, guaranteed chunk); compute sumRequests as the sum of these values
48 * over all relations; then for each relation figure its target allocation
50 * 1 + round(spareChunks * myRequest / sumRequests)
51 * where spareChunks = totalChunks - numRels is the number of chunks we have
52 * a choice what to do with. We round off these numbers because truncating
53 * all of them would waste significant space. But because of roundoff, it's
54 * possible for the last few relations to get less space than they should;
55 * the target allocation must be checked against remaining available space.
57 *-------------------------------------------------------------------------
66 #include "miscadmin.h"
67 #include "storage/fd.h"
68 #include "storage/freespace.h"
69 #include "storage/itemptr.h"
70 #include "storage/lwlock.h"
71 #include "storage/shmem.h"
74 /* Initial value for average-request moving average */
75 #define INITIAL_AVERAGE ((Size) (BLCKSZ / 32))
78 * Number of pages and bytes per allocation chunk. Indexes can squeeze 50%
79 * more pages into the same space because they don't need to remember how much
80 * free space on each page. The nominal number of pages, CHUNKPAGES, is for
81 * regular rels, and INDEXCHUNKPAGES is for indexes. CHUNKPAGES should be
82 * even so that no space is wasted in the index case.
85 #define CHUNKBYTES (CHUNKPAGES * sizeof(FSMPageData))
86 #define INDEXCHUNKPAGES ((int) (CHUNKBYTES / sizeof(IndexFSMPageData)))
90 * Typedefs and macros for items in the page-storage arena. We use the
91 * existing ItemPointer and BlockId data structures, which are designed
92 * to pack well (they should be 6 and 4 bytes apiece regardless of machine
93 * alignment issues). Unfortunately we can't use the ItemPointer access
94 * macros, because they include Asserts insisting that ip_posid != 0.
96 typedef ItemPointerData FSMPageData;
97 typedef BlockIdData IndexFSMPageData;
99 #define FSMPageGetPageNum(ptr) \
100 BlockIdGetBlockNumber(&(ptr)->ip_blkid)
101 #define FSMPageGetSpace(ptr) \
102 ((Size) (ptr)->ip_posid)
103 #define FSMPageSetPageNum(ptr, pg) \
104 BlockIdSet(&(ptr)->ip_blkid, pg)
105 #define FSMPageSetSpace(ptr, sz) \
106 ((ptr)->ip_posid = (OffsetNumber) (sz))
107 #define IndexFSMPageGetPageNum(ptr) \
108 BlockIdGetBlockNumber(ptr)
109 #define IndexFSMPageSetPageNum(ptr, pg) \
113 * During database shutdown, we store the contents of FSM into a disk file,
114 * which is re-read during startup. This way we don't have a startup
115 * transient condition where FSM isn't really functioning.
117 * The file format is:
119 * endian constant 0x01020304 for detecting endianness problems
122 * -- for each rel, in *reverse* usage order:
128 * arena data array of storedPages FSMPageData or IndexFSMPageData
132 /* Name of FSM cache file (relative to $PGDATA) */
133 #define FSM_CACHE_FILENAME "global/pg_fsm.cache"
135 /* Fixed values in header */
136 #define FSM_CACHE_LABEL "FSM"
137 #define FSM_CACHE_ENDIAN 0x01020304
138 #define FSM_CACHE_VERSION 20030305
140 /* File header layout */
141 typedef struct FsmCacheFileHeader
147 } FsmCacheFileHeader;
149 /* Per-relation header */
150 typedef struct FsmCacheRelHeader
152 RelFileNode key; /* hash key (must be first) */
153 bool isIndex; /* if true, we store only page numbers */
154 uint32 avgRequest; /* moving average of space requests */
155 int32 lastPageCount; /* pages passed to RecordRelationFreeSpace */
156 int32 storedPages; /* # of pages stored in arena */
161 * Shared free-space-map objects
163 * The per-relation objects are indexed by a hash table, and are also members
164 * of two linked lists: one ordered by recency of usage (most recent first),
165 * and the other ordered by physical location of the associated storage in
166 * the page-info arena.
168 * Each relation owns one or more chunks of per-page storage in the "arena".
169 * The chunks for each relation are always consecutive, so that it can treat
170 * its page storage as a simple array. We further insist that its page data
171 * be ordered by block number, so that binary search is possible.
173 * Note: we handle pointers to these items as pointers, not as SHMEM_OFFSETs.
174 * This assumes that all processes accessing the map will have the shared
175 * memory segment mapped at the same place in their address space.
177 typedef struct FSMHeader FSMHeader;
178 typedef struct FSMRelation FSMRelation;
180 /* Header for whole map */
183 FSMRelation *usageList; /* FSMRelations in usage-recency order */
184 FSMRelation *usageListTail; /* tail of usage-recency list */
185 FSMRelation *firstRel; /* FSMRelations in arena storage order */
186 FSMRelation *lastRel; /* tail of storage-order list */
187 int numRels; /* number of FSMRelations now in use */
188 double sumRequests; /* sum of requested chunks over all rels */
189 char *arena; /* arena for page-info storage */
190 int totalChunks; /* total size of arena, in chunks */
191 int usedChunks; /* # of chunks assigned */
192 /* NB: there are totalChunks - usedChunks free chunks at end of arena */
196 * Per-relation struct --- this is an entry in the shared hash table.
197 * The hash key is the RelFileNode value (hence, we look at the physical
198 * relation ID, not the logical ID, which is appropriate).
202 RelFileNode key; /* hash key (must be first) */
203 FSMRelation *nextUsage; /* next rel in usage-recency order */
204 FSMRelation *priorUsage; /* prior rel in usage-recency order */
205 FSMRelation *nextPhysical; /* next rel in arena-storage order */
206 FSMRelation *priorPhysical; /* prior rel in arena-storage order */
207 bool isIndex; /* if true, we store only page numbers */
208 Size avgRequest; /* moving average of space requests */
209 int lastPageCount; /* pages passed to RecordRelationFreeSpace */
210 int firstChunk; /* chunk # of my first chunk in arena */
211 int storedPages; /* # of pages stored in arena */
212 int nextPage; /* index (from 0) to start next search at */
216 int MaxFSMRelations; /* these are set by guc.c */
219 static FSMHeader *FreeSpaceMap; /* points to FSMHeader in shared memory */
220 static HTAB *FreeSpaceMapRelHash; /* points to (what used to be) FSMHeader->relHash */
223 static FSMRelation *lookup_fsm_rel(RelFileNode *rel);
224 static FSMRelation *create_fsm_rel(RelFileNode *rel);
225 static void delete_fsm_rel(FSMRelation *fsmrel);
226 static int realloc_fsm_rel(FSMRelation *fsmrel, int nPages, bool isIndex);
227 static void link_fsm_rel_usage(FSMRelation *fsmrel);
228 static void unlink_fsm_rel_usage(FSMRelation *fsmrel);
229 static void link_fsm_rel_storage(FSMRelation *fsmrel);
230 static void unlink_fsm_rel_storage(FSMRelation *fsmrel);
231 static BlockNumber find_free_space(FSMRelation *fsmrel, Size spaceNeeded);
232 static BlockNumber find_index_free_space(FSMRelation *fsmrel);
233 static void fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page,
235 static bool lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page,
237 static void compact_fsm_storage(void);
238 static void push_fsm_rels_after(FSMRelation *afterRel);
239 static void pack_incoming_pages(FSMPageData *newLocation, int newPages,
240 PageFreeSpaceInfo *pageSpaces, int nPages);
241 static void pack_existing_pages(FSMPageData *newLocation, int newPages,
242 FSMPageData *oldLocation, int oldPages);
243 static int fsm_calc_request(FSMRelation *fsmrel);
244 static int fsm_calc_target_allocation(int myRequest);
245 static int fsm_current_chunks(FSMRelation *fsmrel);
246 static int fsm_current_allocation(FSMRelation *fsmrel);
255 * InitFreeSpaceMap -- Initialize the freespace module.
257 * This must be called once during shared memory initialization.
258 * It builds the empty free space map table. FreeSpaceLock must also be
259 * initialized at some point, but is not touched here --- we assume there is
260 * no need for locking, since only the calling process can be accessing shared
264 InitFreeSpaceMap(void)
270 /* Create table header */
271 FreeSpaceMap = (FSMHeader *) ShmemInitStruct("Free Space Map Header",sizeof(FSMHeader),&found);
272 if (FreeSpaceMap == NULL)
274 (errcode(ERRCODE_OUT_OF_MEMORY),
275 errmsg("insufficient shared memory for free space map")));
277 MemSet(FreeSpaceMap, 0, sizeof(FSMHeader));
279 /* Create hashtable for FSMRelations */
280 info.keysize = sizeof(RelFileNode);
281 info.entrysize = sizeof(FSMRelation);
282 info.hash = tag_hash;
284 FreeSpaceMapRelHash = ShmemInitHash("Free Space Map Hash",
285 MaxFSMRelations / 10,
288 (HASH_ELEM | HASH_FUNCTION));
290 if (!FreeSpaceMapRelHash)
292 (errcode(ERRCODE_OUT_OF_MEMORY),
293 errmsg("insufficient shared memory for free space map")));
299 /* Allocate page-storage arena */
300 nchunks = (MaxFSMPages - 1) / CHUNKPAGES + 1;
301 /* This check ensures spareChunks will be greater than zero */
302 if (nchunks <= MaxFSMRelations)
304 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
305 errmsg("max_fsm_pages must exceed max_fsm_relations * %d",
308 FreeSpaceMap->arena = (char *) ShmemAlloc(nchunks * CHUNKBYTES);
309 if (FreeSpaceMap->arena == NULL)
311 (errcode(ERRCODE_OUT_OF_MEMORY),
312 errmsg("insufficient shared memory for free space map")));
314 FreeSpaceMap->totalChunks = nchunks;
315 FreeSpaceMap->usedChunks = 0;
316 FreeSpaceMap->sumRequests = 0;
320 * Estimate amount of shmem space needed for FSM.
323 FreeSpaceShmemSize(void)
329 size = MAXALIGN(sizeof(FSMHeader));
331 /* hash table, including the FSMRelation objects */
332 size += hash_estimate_size(MaxFSMRelations, sizeof(FSMRelation));
334 /* page-storage arena */
335 nchunks = (MaxFSMPages - 1) / CHUNKPAGES + 1;
337 if (nchunks >= (INT_MAX / CHUNKBYTES))
339 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
340 errmsg("max_fsm_pages is too large")));
342 size += MAXALIGN(nchunks * CHUNKBYTES);
348 * GetPageWithFreeSpace - try to find a page in the given relation with
349 * at least the specified amount of free space.
351 * If successful, return the block number; if not, return InvalidBlockNumber.
353 * The caller must be prepared for the possibility that the returned page
354 * will turn out to have too little space available by the time the caller
355 * gets a lock on it. In that case, the caller should report the actual
356 * amount of free space available on that page and then try again (see
357 * RecordAndGetPageWithFreeSpace). If InvalidBlockNumber is returned,
358 * extend the relation.
361 GetPageWithFreeSpace(RelFileNode *rel, Size spaceNeeded)
364 BlockNumber freepage;
366 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
369 * We always add a rel to the hashtable when it is inquired about.
371 fsmrel = create_fsm_rel(rel);
374 * Update the moving average of space requests. This code implements
375 * an exponential moving average with an equivalent period of about 63
376 * requests. Ignore silly requests, however, to ensure that the
377 * average stays sane.
379 if (spaceNeeded > 0 && spaceNeeded < BLCKSZ)
381 int cur_avg = (int) fsmrel->avgRequest;
383 cur_avg += ((int) spaceNeeded - cur_avg) / 32;
384 fsmrel->avgRequest = (Size) cur_avg;
386 freepage = find_free_space(fsmrel, spaceNeeded);
387 LWLockRelease(FreeSpaceLock);
392 * RecordAndGetPageWithFreeSpace - update info about a page and try again.
394 * We provide this combo form, instead of a separate Record operation,
395 * to save one lock and hash table lookup cycle.
398 RecordAndGetPageWithFreeSpace(RelFileNode *rel,
404 BlockNumber freepage;
406 /* Sanity check: ensure spaceAvail will fit into OffsetNumber */
407 AssertArg(oldSpaceAvail < BLCKSZ);
409 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
412 * We always add a rel to the hashtable when it is inquired about.
414 fsmrel = create_fsm_rel(rel);
417 fsm_record_free_space(fsmrel, oldPage, oldSpaceAvail);
420 * Update the moving average of space requests, same as in
421 * GetPageWithFreeSpace.
423 if (spaceNeeded > 0 && spaceNeeded < BLCKSZ)
425 int cur_avg = (int) fsmrel->avgRequest;
427 cur_avg += ((int) spaceNeeded - cur_avg) / 32;
428 fsmrel->avgRequest = (Size) cur_avg;
431 freepage = find_free_space(fsmrel, spaceNeeded);
432 LWLockRelease(FreeSpaceLock);
437 * GetAvgFSMRequestSize - get average FSM request size for a relation.
439 * If the relation is not known to FSM, return a default value.
442 GetAvgFSMRequestSize(RelFileNode *rel)
447 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
448 fsmrel = lookup_fsm_rel(rel);
450 result = fsmrel->avgRequest;
452 result = INITIAL_AVERAGE;
453 LWLockRelease(FreeSpaceLock);
458 * RecordRelationFreeSpace - record available-space info about a relation.
460 * Any pre-existing info about the relation is assumed obsolete and discarded.
462 * The given pageSpaces[] array must be sorted in order by blkno. Note that
463 * the FSM is at liberty to discard some or all of the data.
466 RecordRelationFreeSpace(RelFileNode *rel,
468 PageFreeSpaceInfo *pageSpaces)
472 /* Limit nPages to something sane */
475 else if (nPages > MaxFSMPages)
476 nPages = MaxFSMPages;
478 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
481 * Note we don't record info about a relation unless there's already
482 * an FSM entry for it, implying someone has done GetPageWithFreeSpace
483 * for it. Inactive rels thus will not clutter the map simply by
486 fsmrel = lookup_fsm_rel(rel);
491 FSMPageData *newLocation;
493 curAlloc = realloc_fsm_rel(fsmrel, nPages, false);
494 curAllocPages = curAlloc * CHUNKPAGES;
497 * If the data fits in our current allocation, just copy it;
498 * otherwise must compress.
500 newLocation = (FSMPageData *)
501 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
502 if (nPages <= curAllocPages)
506 for (i = 0; i < nPages; i++)
508 BlockNumber page = pageSpaces[i].blkno;
509 Size avail = pageSpaces[i].avail;
511 /* Check caller provides sorted data */
512 if (i > 0 && page <= pageSpaces[i - 1].blkno)
513 elog(ERROR, "free-space data is not in page order");
514 FSMPageSetPageNum(newLocation, page);
515 FSMPageSetSpace(newLocation, avail);
518 fsmrel->storedPages = nPages;
522 pack_incoming_pages(newLocation, curAllocPages,
524 fsmrel->storedPages = curAllocPages;
527 LWLockRelease(FreeSpaceLock);
531 * GetFreeIndexPage - like GetPageWithFreeSpace, but for indexes
534 GetFreeIndexPage(RelFileNode *rel)
537 BlockNumber freepage;
539 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
542 * We always add a rel to the hashtable when it is inquired about.
544 fsmrel = create_fsm_rel(rel);
546 freepage = find_index_free_space(fsmrel);
547 LWLockRelease(FreeSpaceLock);
552 * RecordIndexFreeSpace - like RecordRelationFreeSpace, but for indexes
555 RecordIndexFreeSpace(RelFileNode *rel,
561 /* Limit nPages to something sane */
564 else if (nPages > MaxFSMPages)
565 nPages = MaxFSMPages;
567 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
570 * Note we don't record info about a relation unless there's already
571 * an FSM entry for it, implying someone has done GetFreeIndexPage for
572 * it. Inactive rels thus will not clutter the map simply by being
575 fsmrel = lookup_fsm_rel(rel);
581 IndexFSMPageData *newLocation;
583 curAlloc = realloc_fsm_rel(fsmrel, nPages, true);
584 curAllocPages = curAlloc * INDEXCHUNKPAGES;
587 * If the data fits in our current allocation, just copy it;
588 * otherwise must compress. But compression is easy: we merely
589 * forget extra pages.
591 newLocation = (IndexFSMPageData *)
592 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
593 if (nPages > curAllocPages)
594 nPages = curAllocPages;
596 for (i = 0; i < nPages; i++)
598 BlockNumber page = pages[i];
600 /* Check caller provides sorted data */
601 if (i > 0 && page <= pages[i - 1])
602 elog(ERROR, "free-space data is not in page order");
603 IndexFSMPageSetPageNum(newLocation, page);
606 fsmrel->storedPages = nPages;
608 LWLockRelease(FreeSpaceLock);
612 * FreeSpaceMapTruncateRel - adjust for truncation of a relation.
614 * We need to delete any stored data past the new relation length, so that
615 * we don't bogusly return removed block numbers.
618 FreeSpaceMapTruncateRel(RelFileNode *rel, BlockNumber nblocks)
622 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
623 fsmrel = lookup_fsm_rel(rel);
628 /* Use lookup to locate first entry >= nblocks */
629 (void) lookup_fsm_page_entry(fsmrel, nblocks, &pageIndex);
630 /* Delete all such entries */
631 fsmrel->storedPages = pageIndex;
632 /* XXX should we adjust rel's lastPageCount and sumRequests? */
634 LWLockRelease(FreeSpaceLock);
638 * FreeSpaceMapForgetRel - forget all about a relation.
640 * This is called when a relation is deleted. Although we could just let
641 * the rel age out of the map, it's better to reclaim and reuse the space
645 FreeSpaceMapForgetRel(RelFileNode *rel)
649 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
650 fsmrel = lookup_fsm_rel(rel);
652 delete_fsm_rel(fsmrel);
653 LWLockRelease(FreeSpaceLock);
657 * FreeSpaceMapForgetDatabase - forget all relations of a database.
659 * This is called during DROP DATABASE. As above, might as well reclaim
660 * map space sooner instead of later.
662 * XXX when we implement tablespaces, target Oid will need to be tablespace
663 * ID not database ID.
666 FreeSpaceMapForgetDatabase(Oid dbid)
671 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
672 for (fsmrel = FreeSpaceMap->usageList; fsmrel; fsmrel = nextrel)
674 nextrel = fsmrel->nextUsage; /* in case we delete it */
675 if (fsmrel->key.tblNode == dbid)
676 delete_fsm_rel(fsmrel);
678 LWLockRelease(FreeSpaceLock);
682 * PrintFreeSpaceMapStatistics - print statistics about FSM contents
684 * The info is sent to ereport() with the specified message level. This is
685 * intended for use during VACUUM.
688 PrintFreeSpaceMapStatistics(int elevel)
696 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
697 /* Count total space used --- tedious, but seems useful */
698 for (fsmrel = FreeSpaceMap->firstRel;
700 fsmrel = fsmrel->nextPhysical)
701 storedPages += fsmrel->storedPages;
702 /* Copy other stats before dropping lock */
703 numRels = FreeSpaceMap->numRels;
704 sumRequests = FreeSpaceMap->sumRequests;
705 LWLockRelease(FreeSpaceLock);
707 /* Convert stats to actual number of page slots needed */
708 needed = (sumRequests + numRels) * CHUNKPAGES;
711 (errmsg("free space map: %d relations, %d pages stored; %.0f total pages needed",
712 numRels, storedPages, needed),
713 errdetail("Allocated FSM size: %d relations + %d pages = %.0f kB shared memory.",
714 MaxFSMRelations, MaxFSMPages,
715 (double) FreeSpaceShmemSize() / 1024.0)));
719 * DumpFreeSpaceMap - dump contents of FSM into a disk file for later reload
721 * This is expected to be called during database shutdown, after updates to
722 * the FSM have stopped. We lock the FreeSpaceLock but that's purely pro
723 * forma --- if anyone else is still accessing FSM, there's a problem.
726 DumpFreeSpaceMap(int code, Datum arg)
729 char cachefilename[MAXPGPATH];
730 FsmCacheFileHeader header;
733 /* Try to create file */
734 snprintf(cachefilename, sizeof(cachefilename), "%s/%s",
735 DataDir, FSM_CACHE_FILENAME);
737 unlink(cachefilename); /* in case it exists w/wrong permissions */
739 fp = AllocateFile(cachefilename, PG_BINARY_W);
742 elog(LOG, "could not write \"%s\": %m", cachefilename);
746 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
748 /* Write file header */
749 MemSet(&header, 0, sizeof(header));
750 strcpy(header.label, FSM_CACHE_LABEL);
751 header.endian = FSM_CACHE_ENDIAN;
752 header.version = FSM_CACHE_VERSION;
753 header.numRels = FreeSpaceMap->numRels;
754 if (fwrite(&header, 1, sizeof(header), fp) != sizeof(header))
757 /* For each relation, in order from least to most recently used... */
758 for (fsmrel = FreeSpaceMap->usageListTail;
760 fsmrel = fsmrel->priorUsage)
762 FsmCacheRelHeader relheader;
765 /* Write relation header */
766 MemSet(&relheader, 0, sizeof(relheader));
767 relheader.key = fsmrel->key;
768 relheader.isIndex = fsmrel->isIndex;
769 relheader.avgRequest = fsmrel->avgRequest;
770 relheader.lastPageCount = fsmrel->lastPageCount;
771 relheader.storedPages = fsmrel->storedPages;
772 if (fwrite(&relheader, 1, sizeof(relheader), fp) != sizeof(relheader))
775 /* Write the per-page data directly from the arena */
776 nPages = fsmrel->storedPages;
783 len = nPages * sizeof(IndexFSMPageData);
785 len = nPages * sizeof(FSMPageData);
787 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
788 if (fwrite(data, 1, len, fp) != len)
794 LWLockRelease(FreeSpaceLock);
801 elog(LOG, "could not write \"%s\": %m", cachefilename);
804 LWLockRelease(FreeSpaceLock);
808 /* Remove busted cache file */
809 unlink(cachefilename);
813 * LoadFreeSpaceMap - load contents of FSM from a disk file
815 * This is expected to be called during database startup, before any FSM
816 * updates begin. We lock the FreeSpaceLock but that's purely pro
817 * forma --- if anyone else is accessing FSM yet, there's a problem.
819 * Notes: no complaint is issued if no cache file is found. If the file is
820 * found, it is deleted after reading. Thus, if we crash without a clean
821 * shutdown, the next cycle of life starts with no FSM data. To do otherwise,
822 * we'd need to do significantly more validation in this routine, because of
823 * the likelihood that what is in the dump file would be out-of-date, eg
824 * there might be entries for deleted or truncated rels.
827 LoadFreeSpaceMap(void)
830 char cachefilename[MAXPGPATH];
831 FsmCacheFileHeader header;
834 /* Try to open file */
835 snprintf(cachefilename, sizeof(cachefilename), "%s/%s",
836 DataDir, FSM_CACHE_FILENAME);
838 fp = AllocateFile(cachefilename, PG_BINARY_R);
842 elog(LOG, "could not read \"%s\": %m", cachefilename);
846 LWLockAcquire(FreeSpaceLock, LW_EXCLUSIVE);
848 /* Read and verify file header */
849 if (fread(&header, 1, sizeof(header), fp) != sizeof(header) ||
850 strcmp(header.label, FSM_CACHE_LABEL) != 0 ||
851 header.endian != FSM_CACHE_ENDIAN ||
852 header.version != FSM_CACHE_VERSION ||
855 elog(LOG, "bogus file header in \"%s\"", cachefilename);
859 /* For each relation, in order from least to most recently used... */
860 for (relno = 0; relno < header.numRels; relno++)
862 FsmCacheRelHeader relheader;
870 /* Read and verify relation header, as best we can */
871 if (fread(&relheader, 1, sizeof(relheader), fp) != sizeof(relheader) ||
872 (relheader.isIndex != false && relheader.isIndex != true) ||
873 relheader.avgRequest >= BLCKSZ ||
874 relheader.lastPageCount < 0 ||
875 relheader.storedPages < 0)
877 elog(LOG, "bogus rel header in \"%s\"", cachefilename);
881 /* Make sure lastPageCount doesn't exceed current MaxFSMPages */
882 if (relheader.lastPageCount > MaxFSMPages)
883 relheader.lastPageCount = MaxFSMPages;
885 /* Read the per-page data */
886 nPages = relheader.storedPages;
887 if (relheader.isIndex)
888 len = nPages * sizeof(IndexFSMPageData);
890 len = nPages * sizeof(FSMPageData);
891 data = (char *) palloc(len + 1); /* +1 to avoid palloc(0) */
892 if (fread(data, 1, len, fp) != len)
894 elog(LOG, "premature EOF in \"%s\"", cachefilename);
900 * Okay, create the FSM entry and insert data into it. Since the
901 * rels were stored in reverse usage order, at the end of the loop
902 * they will be correctly usage-ordered in memory; and if
903 * MaxFSMRelations is less than it used to be, we will correctly
904 * drop the least recently used ones.
906 fsmrel = create_fsm_rel(&relheader.key);
907 fsmrel->avgRequest = relheader.avgRequest;
909 curAlloc = realloc_fsm_rel(fsmrel, relheader.lastPageCount,
911 if (relheader.isIndex)
913 IndexFSMPageData *newLocation;
915 curAllocPages = curAlloc * INDEXCHUNKPAGES;
918 * If the data fits in our current allocation, just copy it;
919 * otherwise must compress. But compression is easy: we
920 * merely forget extra pages.
922 newLocation = (IndexFSMPageData *)
923 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
924 if (nPages > curAllocPages)
925 nPages = curAllocPages;
926 memcpy(newLocation, data, nPages * sizeof(IndexFSMPageData));
927 fsmrel->storedPages = nPages;
931 FSMPageData *newLocation;
933 curAllocPages = curAlloc * CHUNKPAGES;
936 * If the data fits in our current allocation, just copy it;
937 * otherwise must compress.
939 newLocation = (FSMPageData *)
940 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
941 if (nPages <= curAllocPages)
943 memcpy(newLocation, data, nPages * sizeof(FSMPageData));
944 fsmrel->storedPages = nPages;
948 pack_existing_pages(newLocation, curAllocPages,
949 (FSMPageData *) data, nPages);
950 fsmrel->storedPages = curAllocPages;
960 LWLockRelease(FreeSpaceLock);
964 /* Remove cache file before it can become stale; see notes above */
965 unlink(cachefilename);
970 * Internal routines. These all assume the caller holds the FreeSpaceLock.
974 * Lookup a relation in the hash table. If not present, return NULL.
976 * The relation's position in the LRU list is not changed.
979 lookup_fsm_rel(RelFileNode *rel)
983 fsmrel = (FSMRelation *) hash_search(FreeSpaceMapRelHash,
994 * Lookup a relation in the hash table, creating an entry if not present.
996 * On successful lookup, the relation is moved to the front of the LRU list.
999 create_fsm_rel(RelFileNode *rel)
1001 FSMRelation *fsmrel;
1004 fsmrel = (FSMRelation *) hash_search(FreeSpaceMapRelHash,
1010 (errcode(ERRCODE_OUT_OF_MEMORY),
1011 errmsg("out of shared memory")));
1015 /* New hashtable entry, initialize it (hash_search set the key) */
1016 fsmrel->isIndex = false; /* until we learn different */
1017 fsmrel->avgRequest = INITIAL_AVERAGE;
1018 fsmrel->lastPageCount = 0;
1019 fsmrel->firstChunk = -1; /* no space allocated */
1020 fsmrel->storedPages = 0;
1021 fsmrel->nextPage = 0;
1023 /* Discard lowest-priority existing rel, if we are over limit */
1024 if (FreeSpaceMap->numRels >= MaxFSMRelations)
1025 delete_fsm_rel(FreeSpaceMap->usageListTail);
1027 /* Add new entry at front of LRU list */
1028 link_fsm_rel_usage(fsmrel);
1029 fsmrel->nextPhysical = NULL; /* not in physical-storage list */
1030 fsmrel->priorPhysical = NULL;
1031 FreeSpaceMap->numRels++;
1032 /* sumRequests is unchanged because request must be zero */
1036 /* Existing entry, move to front of LRU list */
1037 if (fsmrel->priorUsage != NULL)
1039 unlink_fsm_rel_usage(fsmrel);
1040 link_fsm_rel_usage(fsmrel);
1048 * Remove an existing FSMRelation entry.
1051 delete_fsm_rel(FSMRelation *fsmrel)
1053 FSMRelation *result;
1055 FreeSpaceMap->sumRequests -= fsm_calc_request(fsmrel);
1056 unlink_fsm_rel_usage(fsmrel);
1057 unlink_fsm_rel_storage(fsmrel);
1058 FreeSpaceMap->numRels--;
1059 result = (FSMRelation *) hash_search(FreeSpaceMapRelHash,
1060 (void *) &(fsmrel->key),
1064 elog(ERROR, "FreeSpaceMap hashtable corrupted");
1068 * Reallocate space for a FSMRelation.
1070 * This is shared code for RecordRelationFreeSpace and RecordIndexFreeSpace.
1071 * The return value is the actual new allocation, in chunks.
1074 realloc_fsm_rel(FSMRelation *fsmrel, int nPages, bool isIndex)
1081 * Delete any existing entries, and update request status.
1083 fsmrel->storedPages = 0;
1084 FreeSpaceMap->sumRequests -= fsm_calc_request(fsmrel);
1085 fsmrel->lastPageCount = nPages;
1086 fsmrel->isIndex = isIndex;
1087 myRequest = fsm_calc_request(fsmrel);
1088 FreeSpaceMap->sumRequests += myRequest;
1089 myAlloc = fsm_calc_target_allocation(myRequest);
1092 * Need to reallocate space if (a) my target allocation is more than
1093 * my current allocation, AND (b) my actual immediate need
1094 * (myRequest+1 chunks) is more than my current allocation. Otherwise
1095 * just store the new data in-place.
1097 curAlloc = fsm_current_allocation(fsmrel);
1098 if (myAlloc > curAlloc && (myRequest + 1) > curAlloc && nPages > 0)
1100 /* Remove entry from storage list, and compact */
1101 unlink_fsm_rel_storage(fsmrel);
1102 compact_fsm_storage();
1103 /* Reattach to end of storage list */
1104 link_fsm_rel_storage(fsmrel);
1105 /* And allocate storage */
1106 fsmrel->firstChunk = FreeSpaceMap->usedChunks;
1107 FreeSpaceMap->usedChunks += myAlloc;
1109 /* Watch out for roundoff error */
1110 if (FreeSpaceMap->usedChunks > FreeSpaceMap->totalChunks)
1112 FreeSpaceMap->usedChunks = FreeSpaceMap->totalChunks;
1113 curAlloc = FreeSpaceMap->totalChunks - fsmrel->firstChunk;
1120 * Link a FSMRelation into the LRU list (always at the head).
1123 link_fsm_rel_usage(FSMRelation *fsmrel)
1125 fsmrel->priorUsage = NULL;
1126 fsmrel->nextUsage = FreeSpaceMap->usageList;
1127 FreeSpaceMap->usageList = fsmrel;
1128 if (fsmrel->nextUsage != NULL)
1129 fsmrel->nextUsage->priorUsage = fsmrel;
1131 FreeSpaceMap->usageListTail = fsmrel;
1135 * Delink a FSMRelation from the LRU list.
1138 unlink_fsm_rel_usage(FSMRelation *fsmrel)
1140 if (fsmrel->priorUsage != NULL)
1141 fsmrel->priorUsage->nextUsage = fsmrel->nextUsage;
1143 FreeSpaceMap->usageList = fsmrel->nextUsage;
1144 if (fsmrel->nextUsage != NULL)
1145 fsmrel->nextUsage->priorUsage = fsmrel->priorUsage;
1147 FreeSpaceMap->usageListTail = fsmrel->priorUsage;
1150 * We don't bother resetting fsmrel's links, since it's about to be
1151 * deleted or relinked at the head.
1156 * Link a FSMRelation into the storage-order list (always at the tail).
1159 link_fsm_rel_storage(FSMRelation *fsmrel)
1161 fsmrel->nextPhysical = NULL;
1162 fsmrel->priorPhysical = FreeSpaceMap->lastRel;
1163 if (FreeSpaceMap->lastRel != NULL)
1164 FreeSpaceMap->lastRel->nextPhysical = fsmrel;
1166 FreeSpaceMap->firstRel = fsmrel;
1167 FreeSpaceMap->lastRel = fsmrel;
1171 * Delink a FSMRelation from the storage-order list, if it's in it.
1174 unlink_fsm_rel_storage(FSMRelation *fsmrel)
1176 if (fsmrel->priorPhysical != NULL || FreeSpaceMap->firstRel == fsmrel)
1178 if (fsmrel->priorPhysical != NULL)
1179 fsmrel->priorPhysical->nextPhysical = fsmrel->nextPhysical;
1181 FreeSpaceMap->firstRel = fsmrel->nextPhysical;
1182 if (fsmrel->nextPhysical != NULL)
1183 fsmrel->nextPhysical->priorPhysical = fsmrel->priorPhysical;
1185 FreeSpaceMap->lastRel = fsmrel->priorPhysical;
1187 /* mark as not in list, since we may not put it back immediately */
1188 fsmrel->nextPhysical = NULL;
1189 fsmrel->priorPhysical = NULL;
1190 /* Also mark it as having no storage */
1191 fsmrel->firstChunk = -1;
1192 fsmrel->storedPages = 0;
1196 * Look to see if a page with at least the specified amount of space is
1197 * available in the given FSMRelation. If so, return its page number,
1198 * and advance the nextPage counter so that the next inquiry will return
1199 * a different page if possible; also update the entry to show that the
1200 * requested space is not available anymore. Return InvalidBlockNumber
1204 find_free_space(FSMRelation *fsmrel, Size spaceNeeded)
1207 int pagesToCheck, /* outer loop counter */
1208 pageIndex; /* current page index */
1210 if (fsmrel->isIndex)
1211 elog(ERROR, "find_free_space called for an index relation");
1212 info = (FSMPageData *)
1213 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1214 pageIndex = fsmrel->nextPage;
1215 /* Last operation may have left nextPage pointing past end */
1216 if (pageIndex >= fsmrel->storedPages)
1219 for (pagesToCheck = fsmrel->storedPages; pagesToCheck > 0; pagesToCheck--)
1221 FSMPageData *page = info + pageIndex;
1222 Size spaceAvail = FSMPageGetSpace(page);
1224 /* Check this page */
1225 if (spaceAvail >= spaceNeeded)
1228 * Found what we want --- adjust the entry, and update
1231 FSMPageSetSpace(page, spaceAvail - spaceNeeded);
1232 fsmrel->nextPage = pageIndex + 1;
1233 return FSMPageGetPageNum(page);
1235 /* Advance pageIndex, wrapping around if needed */
1236 if (++pageIndex >= fsmrel->storedPages)
1240 return InvalidBlockNumber; /* nothing found */
1244 * As above, but for index case --- we only deal in whole pages.
1247 find_index_free_space(FSMRelation *fsmrel)
1249 IndexFSMPageData *info;
1253 * If isIndex isn't set, it could be that RecordIndexFreeSpace() has
1254 * never yet been called on this relation, and we're still looking at
1255 * the default setting from create_fsm_rel(). If so, just act as
1256 * though there's no space.
1258 if (!fsmrel->isIndex)
1260 if (fsmrel->storedPages == 0)
1261 return InvalidBlockNumber;
1262 elog(ERROR, "find_index_free_space called for a non-index relation");
1266 * For indexes, there's no need for the nextPage state variable; we
1267 * just remove and return the first available page. (We could save
1268 * cycles here by returning the last page, but it seems better to
1269 * encourage re-use of lower-numbered pages.)
1271 if (fsmrel->storedPages <= 0)
1272 return InvalidBlockNumber; /* no pages available */
1273 info = (IndexFSMPageData *)
1274 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1275 result = IndexFSMPageGetPageNum(info);
1276 fsmrel->storedPages--;
1277 memmove(info, info + 1, fsmrel->storedPages * sizeof(IndexFSMPageData));
1282 * fsm_record_free_space - guts of RecordFreeSpace operation (now only
1283 * provided as part of RecordAndGetPageWithFreeSpace).
1286 fsm_record_free_space(FSMRelation *fsmrel, BlockNumber page, Size spaceAvail)
1290 if (fsmrel->isIndex)
1291 elog(ERROR, "fsm_record_free_space called for an index relation");
1292 if (lookup_fsm_page_entry(fsmrel, page, &pageIndex))
1294 /* Found an existing entry for page; update it */
1297 info = (FSMPageData *)
1298 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1300 FSMPageSetSpace(info, spaceAvail);
1305 * No existing entry; ignore the call. We used to add the page to
1306 * the FSM --- but in practice, if the page hasn't got enough
1307 * space to satisfy the caller who's kicking it back to us, then
1308 * it's probably uninteresting to everyone else as well.
1314 * Look for an entry for a specific page (block number) in a FSMRelation.
1315 * Returns TRUE if a matching entry exists, else FALSE.
1317 * The output argument *outPageIndex is set to indicate where the entry exists
1318 * (if TRUE result) or could be inserted (if FALSE result).
1321 lookup_fsm_page_entry(FSMRelation *fsmrel, BlockNumber page,
1324 /* Check for empty relation */
1325 if (fsmrel->storedPages <= 0)
1331 /* Do binary search */
1332 if (fsmrel->isIndex)
1334 IndexFSMPageData *info;
1338 info = (IndexFSMPageData *)
1339 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1341 high = fsmrel->storedPages - 1;
1347 middle = low + (high - low) / 2;
1348 probe = IndexFSMPageGetPageNum(info + middle);
1351 *outPageIndex = middle;
1354 else if (probe < page)
1359 *outPageIndex = low;
1368 info = (FSMPageData *)
1369 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1371 high = fsmrel->storedPages - 1;
1377 middle = low + (high - low) / 2;
1378 probe = FSMPageGetPageNum(info + middle);
1381 *outPageIndex = middle;
1384 else if (probe < page)
1389 *outPageIndex = low;
1395 * Re-pack the FSM storage arena, dropping data if necessary to meet the
1396 * current allocation target for each relation. At conclusion, all available
1397 * space in the arena will be coalesced at the end.
1400 compact_fsm_storage(void)
1402 int nextChunkIndex = 0;
1403 bool did_push = false;
1404 FSMRelation *fsmrel;
1406 for (fsmrel = FreeSpaceMap->firstRel;
1408 fsmrel = fsmrel->nextPhysical)
1419 * Calculate target allocation, make sure we don't overrun due to
1422 newAlloc = fsm_calc_target_allocation(fsm_calc_request(fsmrel));
1423 if (newAlloc > FreeSpaceMap->totalChunks - nextChunkIndex)
1424 newAlloc = FreeSpaceMap->totalChunks - nextChunkIndex;
1425 if (fsmrel->isIndex)
1426 newAllocPages = newAlloc * INDEXCHUNKPAGES;
1428 newAllocPages = newAlloc * CHUNKPAGES;
1431 * Determine current size, current and new locations
1433 curChunks = fsm_current_chunks(fsmrel);
1434 oldChunkIndex = fsmrel->firstChunk;
1435 oldLocation = FreeSpaceMap->arena + oldChunkIndex * CHUNKBYTES;
1436 newChunkIndex = nextChunkIndex;
1437 newLocation = FreeSpaceMap->arena + newChunkIndex * CHUNKBYTES;
1440 * It's possible that we have to move data down, not up, if the
1441 * allocations of previous rels expanded. This normally means that
1442 * our allocation expanded too (or at least got no worse), and
1443 * ditto for later rels. So there should be room to move all our
1444 * data down without dropping any --- but we might have to push down
1445 * following rels to acquire the room. We don't want to do the push
1446 * more than once, so pack everything against the end of the arena
1449 * In corner cases where we are on the short end of a roundoff choice
1450 * that we were formerly on the long end of, it's possible that we
1451 * have to move down and compress our data too. In fact, even after
1452 * pushing down the following rels, there might not be as much space
1453 * as we computed for this rel above --- that would imply that some
1454 * following rel(s) are also on the losing end of roundoff choices.
1455 * We could handle this fairly by doing the per-rel compactions
1456 * out-of-order, but that seems like way too much complexity to deal
1457 * with a very infrequent corner case. Instead, we simply drop pages
1458 * from the end of the current rel's data until it fits.
1460 if (newChunkIndex > oldChunkIndex)
1462 int limitChunkIndex;
1464 if (newAllocPages < fsmrel->storedPages)
1466 /* move and compress --- just drop excess pages */
1467 fsmrel->storedPages = newAllocPages;
1468 curChunks = fsm_current_chunks(fsmrel);
1470 /* is there enough space? */
1471 if (fsmrel->nextPhysical != NULL)
1472 limitChunkIndex = fsmrel->nextPhysical->firstChunk;
1474 limitChunkIndex = FreeSpaceMap->totalChunks;
1475 if (newChunkIndex + curChunks > limitChunkIndex)
1477 /* not enough space, push down following rels */
1480 push_fsm_rels_after(fsmrel);
1483 /* now is there enough space? */
1484 if (fsmrel->nextPhysical != NULL)
1485 limitChunkIndex = fsmrel->nextPhysical->firstChunk;
1487 limitChunkIndex = FreeSpaceMap->totalChunks;
1488 if (newChunkIndex + curChunks > limitChunkIndex)
1490 /* uh-oh, forcibly cut the allocation to fit */
1491 newAlloc = limitChunkIndex - newChunkIndex;
1493 * If newAlloc < 0 at this point, we are moving the rel's
1494 * firstChunk into territory currently assigned to a later
1495 * rel. This is okay so long as we do not copy any data.
1496 * The rels will be back in nondecreasing firstChunk order
1497 * at completion of the compaction pass.
1501 if (fsmrel->isIndex)
1502 newAllocPages = newAlloc * INDEXCHUNKPAGES;
1504 newAllocPages = newAlloc * CHUNKPAGES;
1505 fsmrel->storedPages = newAllocPages;
1506 curChunks = fsm_current_chunks(fsmrel);
1509 memmove(newLocation, oldLocation, curChunks * CHUNKBYTES);
1511 else if (newAllocPages < fsmrel->storedPages)
1514 * Need to compress the page data. For an index,
1515 * "compression" just means dropping excess pages; otherwise
1516 * we try to keep the ones with the most space.
1518 if (fsmrel->isIndex)
1520 fsmrel->storedPages = newAllocPages;
1521 /* may need to move data */
1522 if (newChunkIndex != oldChunkIndex)
1523 memmove(newLocation, oldLocation, newAlloc * CHUNKBYTES);
1527 pack_existing_pages((FSMPageData *) newLocation,
1529 (FSMPageData *) oldLocation,
1530 fsmrel->storedPages);
1531 fsmrel->storedPages = newAllocPages;
1534 else if (newChunkIndex != oldChunkIndex)
1537 * No compression needed, but must copy the data up
1539 memmove(newLocation, oldLocation, curChunks * CHUNKBYTES);
1541 fsmrel->firstChunk = newChunkIndex;
1542 nextChunkIndex += newAlloc;
1544 Assert(nextChunkIndex <= FreeSpaceMap->totalChunks);
1545 FreeSpaceMap->usedChunks = nextChunkIndex;
1549 * Push all FSMRels physically after afterRel to the end of the storage arena.
1551 * We sometimes have to do this when deletion or truncation of a relation
1552 * causes the allocations of remaining rels to expand markedly. We must
1553 * temporarily push existing data down to the end so that we can move it
1554 * back up in an orderly fashion.
1557 push_fsm_rels_after(FSMRelation *afterRel)
1559 int nextChunkIndex = FreeSpaceMap->totalChunks;
1560 FSMRelation *fsmrel;
1562 FreeSpaceMap->usedChunks = FreeSpaceMap->totalChunks;
1564 for (fsmrel = FreeSpaceMap->lastRel;
1566 fsmrel = fsmrel->priorPhysical)
1574 if (fsmrel == afterRel)
1577 chunkCount = fsm_current_chunks(fsmrel);
1578 nextChunkIndex -= chunkCount;
1579 newChunkIndex = nextChunkIndex;
1580 oldChunkIndex = fsmrel->firstChunk;
1581 if (newChunkIndex < oldChunkIndex)
1583 /* we're pushing down, how can it move up? */
1584 elog(PANIC, "inconsistent entry sizes in FSM");
1586 else if (newChunkIndex > oldChunkIndex)
1588 /* need to move it */
1589 newLocation = FreeSpaceMap->arena + newChunkIndex * CHUNKBYTES;
1590 oldLocation = FreeSpaceMap->arena + oldChunkIndex * CHUNKBYTES;
1591 memmove(newLocation, oldLocation, chunkCount * CHUNKBYTES);
1592 fsmrel->firstChunk = newChunkIndex;
1595 Assert(nextChunkIndex >= 0);
1599 * Pack a set of per-page freespace data into a smaller amount of space.
1601 * The method is to compute a low-resolution histogram of the free space
1602 * amounts, then determine which histogram bin contains the break point.
1603 * We then keep all pages above that bin, none below it, and just enough
1604 * of the pages in that bin to fill the output area exactly.
1606 #define HISTOGRAM_BINS 64
1609 pack_incoming_pages(FSMPageData *newLocation, int newPages,
1610 PageFreeSpaceInfo *pageSpaces, int nPages)
1612 int histogram[HISTOGRAM_BINS];
1619 Assert(newPages < nPages); /* else I shouldn't have been called */
1620 /* Build histogram */
1621 MemSet(histogram, 0, sizeof(histogram));
1622 for (i = 0; i < nPages; i++)
1624 Size avail = pageSpaces[i].avail;
1626 if (avail >= BLCKSZ)
1627 elog(ERROR, "bogus freespace amount");
1628 avail /= (BLCKSZ / HISTOGRAM_BINS);
1631 /* Find the breakpoint bin */
1633 for (i = HISTOGRAM_BINS - 1; i >= 0; i--)
1635 int sum = above + histogram[i];
1642 thresholdL = i * BLCKSZ / HISTOGRAM_BINS; /* low bound of bp bin */
1643 thresholdU = (i + 1) * BLCKSZ / HISTOGRAM_BINS; /* hi bound */
1644 binct = newPages - above; /* number to take from bp bin */
1645 /* And copy the appropriate data */
1646 for (i = 0; i < nPages; i++)
1648 BlockNumber page = pageSpaces[i].blkno;
1649 Size avail = pageSpaces[i].avail;
1651 /* Check caller provides sorted data */
1652 if (i > 0 && page <= pageSpaces[i - 1].blkno)
1653 elog(ERROR, "free-space data is not in page order");
1654 /* Save this page? */
1655 if (avail >= thresholdU ||
1656 (avail >= thresholdL && (--binct >= 0)))
1658 FSMPageSetPageNum(newLocation, page);
1659 FSMPageSetSpace(newLocation, avail);
1664 Assert(newPages == 0);
1668 * Pack a set of per-page freespace data into a smaller amount of space.
1670 * This is algorithmically identical to pack_incoming_pages(), but accepts
1671 * a different input representation. Also, we assume the input data has
1672 * previously been checked for validity (size in bounds, pages in order).
1674 * Note: it is possible for the source and destination arrays to overlap.
1675 * The caller is responsible for making sure newLocation is at lower addresses
1676 * so that we can copy data moving forward in the arrays without problem.
1679 pack_existing_pages(FSMPageData *newLocation, int newPages,
1680 FSMPageData *oldLocation, int oldPages)
1682 int histogram[HISTOGRAM_BINS];
1689 Assert(newPages < oldPages); /* else I shouldn't have been called */
1690 /* Build histogram */
1691 MemSet(histogram, 0, sizeof(histogram));
1692 for (i = 0; i < oldPages; i++)
1694 Size avail = FSMPageGetSpace(oldLocation + i);
1696 /* Shouldn't happen, but test to protect against stack clobber */
1697 if (avail >= BLCKSZ)
1698 elog(ERROR, "bogus freespace amount");
1699 avail /= (BLCKSZ / HISTOGRAM_BINS);
1702 /* Find the breakpoint bin */
1704 for (i = HISTOGRAM_BINS - 1; i >= 0; i--)
1706 int sum = above + histogram[i];
1713 thresholdL = i * BLCKSZ / HISTOGRAM_BINS; /* low bound of bp bin */
1714 thresholdU = (i + 1) * BLCKSZ / HISTOGRAM_BINS; /* hi bound */
1715 binct = newPages - above; /* number to take from bp bin */
1716 /* And copy the appropriate data */
1717 for (i = 0; i < oldPages; i++)
1719 BlockNumber page = FSMPageGetPageNum(oldLocation + i);
1720 Size avail = FSMPageGetSpace(oldLocation + i);
1722 /* Save this page? */
1723 if (avail >= thresholdU ||
1724 (avail >= thresholdL && (--binct >= 0)))
1726 FSMPageSetPageNum(newLocation, page);
1727 FSMPageSetSpace(newLocation, avail);
1732 Assert(newPages == 0);
1736 * Calculate number of chunks "requested" by a rel.
1738 * Rel's lastPageCount and isIndex settings must be up-to-date when called.
1740 * See notes at top of file for details.
1743 fsm_calc_request(FSMRelation *fsmrel)
1747 /* Convert page count to chunk count */
1748 if (fsmrel->isIndex)
1749 chunkCount = (fsmrel->lastPageCount - 1) / INDEXCHUNKPAGES + 1;
1751 chunkCount = (fsmrel->lastPageCount - 1) / CHUNKPAGES + 1;
1752 /* "Request" is anything beyond our one guaranteed chunk */
1753 if (chunkCount <= 0)
1756 return chunkCount - 1;
1760 * Calculate target allocation (number of chunks) for a rel
1762 * Parameter is the result from fsm_calc_request(). The global sumRequests
1763 * and numRels totals must be up-to-date already.
1765 * See notes at top of file for details.
1768 fsm_calc_target_allocation(int myRequest)
1773 spareChunks = FreeSpaceMap->totalChunks - FreeSpaceMap->numRels;
1774 Assert(spareChunks > 0);
1775 if (spareChunks >= FreeSpaceMap->sumRequests)
1777 /* We aren't oversubscribed, so allocate exactly the request */
1782 extra = (int) rint(spareChunks * myRequest / FreeSpaceMap->sumRequests);
1783 if (extra < 0) /* shouldn't happen, but make sure */
1790 * Calculate number of chunks actually used to store current data
1793 fsm_current_chunks(FSMRelation *fsmrel)
1797 /* Make sure storedPages==0 produces right answer */
1798 if (fsmrel->storedPages <= 0)
1800 /* Convert page count to chunk count */
1801 if (fsmrel->isIndex)
1802 chunkCount = (fsmrel->storedPages - 1) / INDEXCHUNKPAGES + 1;
1804 chunkCount = (fsmrel->storedPages - 1) / CHUNKPAGES + 1;
1809 * Calculate current actual allocation (number of chunks) for a rel
1812 fsm_current_allocation(FSMRelation *fsmrel)
1814 if (fsmrel->nextPhysical != NULL)
1815 return fsmrel->nextPhysical->firstChunk - fsmrel->firstChunk;
1816 else if (fsmrel == FreeSpaceMap->lastRel)
1817 return FreeSpaceMap->usedChunks - fsmrel->firstChunk;
1820 /* it's not in the storage-order list */
1821 Assert(fsmrel->firstChunk < 0 && fsmrel->storedPages == 0);
1827 #ifdef FREESPACE_DEBUG
1829 * Dump contents of freespace map for debugging.
1831 * We assume caller holds the FreeSpaceLock, or is otherwise unconcerned
1832 * about other processes.
1837 FSMRelation *fsmrel;
1838 FSMRelation *prevrel = NULL;
1842 for (fsmrel = FreeSpaceMap->usageList; fsmrel; fsmrel = fsmrel->nextUsage)
1845 fprintf(stderr, "Map %d: rel %u/%u isIndex %d avgRequest %u lastPageCount %d nextPage %d\nMap= ",
1846 relNum, fsmrel->key.tblNode, fsmrel->key.relNode,
1847 (int) fsmrel->isIndex, fsmrel->avgRequest,
1848 fsmrel->lastPageCount, fsmrel->nextPage);
1849 if (fsmrel->isIndex)
1851 IndexFSMPageData *page;
1853 page = (IndexFSMPageData *)
1854 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1855 for (nPages = 0; nPages < fsmrel->storedPages; nPages++)
1857 fprintf(stderr, " %u",
1858 IndexFSMPageGetPageNum(page));
1866 page = (FSMPageData *)
1867 (FreeSpaceMap->arena + fsmrel->firstChunk * CHUNKBYTES);
1868 for (nPages = 0; nPages < fsmrel->storedPages; nPages++)
1870 fprintf(stderr, " %u:%u",
1871 FSMPageGetPageNum(page),
1872 FSMPageGetSpace(page));
1876 fprintf(stderr, "\n");
1877 /* Cross-check list links */
1878 if (prevrel != fsmrel->priorUsage)
1879 fprintf(stderr, "DumpFreeSpace: broken list links\n");
1882 if (prevrel != FreeSpaceMap->usageListTail)
1883 fprintf(stderr, "DumpFreeSpace: broken list links\n");
1884 /* Cross-check global counters */
1885 if (relNum != FreeSpaceMap->numRels)
1886 fprintf(stderr, "DumpFreeSpace: %d rels in list, but numRels = %d\n",
1887 relNum, FreeSpaceMap->numRels);
1890 #endif /* FREESPACE_DEBUG */