LCOV - code coverage report
Current view: top level - src/backend/storage/freespace - freespace.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 208 222 93.7 %
Date: 2020-05-25 06:06:29 Functions: 21 21 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * freespace.c
       4             :  *    POSTGRES free space map for quickly finding free space in relations
       5             :  *
       6             :  *
       7             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
       8             :  * Portions Copyright (c) 1994, Regents of the University of California
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/storage/freespace/freespace.c
      12             :  *
      13             :  *
      14             :  * NOTES:
      15             :  *
      16             :  *  Free Space Map keeps track of the amount of free space on pages, and
      17             :  *  allows quickly searching for a page with enough free space. The FSM is
      18             :  *  stored in a dedicated relation fork of all heap relations, and those
      19             :  *  index access methods that need it (see also indexfsm.c). See README for
      20             :  *  more information.
      21             :  *
      22             :  *-------------------------------------------------------------------------
      23             :  */
      24             : #include "postgres.h"
      25             : 
      26             : #include "access/htup_details.h"
      27             : #include "access/xlogutils.h"
      28             : #include "miscadmin.h"
      29             : #include "storage/freespace.h"
      30             : #include "storage/fsm_internals.h"
      31             : #include "storage/lmgr.h"
      32             : #include "storage/smgr.h"
      33             : 
      34             : 
      35             : /*
      36             :  * We use just one byte to store the amount of free space on a page, so we
      37             :  * divide the amount of free space a page can have into 256 different
      38             :  * categories. The highest category, 255, represents a page with at least
      39             :  * MaxFSMRequestSize bytes of free space, and the second highest category
      40             :  * represents the range from 254 * FSM_CAT_STEP, inclusive, to
      41             :  * MaxFSMRequestSize, exclusive.
      42             :  *
      43             :  * MaxFSMRequestSize depends on the architecture and BLCKSZ, but assuming
      44             :  * default 8k BLCKSZ, and that MaxFSMRequestSize is 8164 bytes, the
      45             :  * categories look like this:
      46             :  *
      47             :  *
      48             :  * Range     Category
      49             :  * 0    - 31   0
      50             :  * 32   - 63   1
      51             :  * ...    ...  ...
      52             :  * 8096 - 8127 253
      53             :  * 8128 - 8163 254
      54             :  * 8164 - 8192 255
      55             :  *
      56             :  * The reason that MaxFSMRequestSize is special is that if MaxFSMRequestSize
      57             :  * isn't equal to a range boundary, a page with exactly MaxFSMRequestSize
      58             :  * bytes of free space wouldn't satisfy a request for MaxFSMRequestSize
      59             :  * bytes. If there isn't more than MaxFSMRequestSize bytes of free space on a
      60             :  * completely empty page, that would mean that we could never satisfy a
      61             :  * request of exactly MaxFSMRequestSize bytes.
      62             :  */
      63             : #define FSM_CATEGORIES  256
      64             : #define FSM_CAT_STEP    (BLCKSZ / FSM_CATEGORIES)
      65             : #define MaxFSMRequestSize   MaxHeapTupleSize
      66             : 
      67             : /*
      68             :  * Depth of the on-disk tree. We need to be able to address 2^32-1 blocks,
      69             :  * and 1626 is the smallest number that satisfies X^3 >= 2^32-1. Likewise,
      70             :  * 216 is the smallest number that satisfies X^4 >= 2^32-1. In practice,
      71             :  * this means that 4096 bytes is the smallest BLCKSZ that we can get away
      72             :  * with a 3-level tree, and 512 is the smallest we support.
      73             :  */
      74             : #define FSM_TREE_DEPTH  ((SlotsPerFSMPage >= 1626) ? 3 : 4)
      75             : 
      76             : #define FSM_ROOT_LEVEL  (FSM_TREE_DEPTH - 1)
      77             : #define FSM_BOTTOM_LEVEL 0
      78             : 
      79             : /*
      80             :  * The internal FSM routines work on a logical addressing scheme. Each
      81             :  * level of the tree can be thought of as a separately addressable file.
      82             :  */
      83             : typedef struct
      84             : {
      85             :     int         level;          /* level */
      86             :     int         logpageno;      /* page number within the level */
      87             : } FSMAddress;
      88             : 
      89             : /* Address of the root page. */
      90             : static const FSMAddress FSM_ROOT_ADDRESS = {FSM_ROOT_LEVEL, 0};
      91             : 
      92             : /* functions to navigate the tree */
      93             : static FSMAddress fsm_get_child(FSMAddress parent, uint16 slot);
      94             : static FSMAddress fsm_get_parent(FSMAddress child, uint16 *slot);
      95             : static FSMAddress fsm_get_location(BlockNumber heapblk, uint16 *slot);
      96             : static BlockNumber fsm_get_heap_blk(FSMAddress addr, uint16 slot);
      97             : static BlockNumber fsm_logical_to_physical(FSMAddress addr);
      98             : 
      99             : static Buffer fsm_readbuf(Relation rel, FSMAddress addr, bool extend);
     100             : static void fsm_extend(Relation rel, BlockNumber fsm_nblocks);
     101             : 
     102             : /* functions to convert amount of free space to a FSM category */
     103             : static uint8 fsm_space_avail_to_cat(Size avail);
     104             : static uint8 fsm_space_needed_to_cat(Size needed);
     105             : static Size fsm_space_cat_to_avail(uint8 cat);
     106             : 
     107             : /* workhorse functions for various operations */
     108             : static int  fsm_set_and_search(Relation rel, FSMAddress addr, uint16 slot,
     109             :                                uint8 newValue, uint8 minValue);
     110             : static BlockNumber fsm_search(Relation rel, uint8 min_cat);
     111             : static uint8 fsm_vacuum_page(Relation rel, FSMAddress addr,
     112             :                              BlockNumber start, BlockNumber end,
     113             :                              bool *eof);
     114             : 
     115             : 
     116             : /******** Public API ********/
     117             : 
     118             : /*
     119             :  * GetPageWithFreeSpace - try to find a page in the given relation with
     120             :  *      at least the specified amount of free space.
     121             :  *
     122             :  * If successful, return the block number; if not, return InvalidBlockNumber.
     123             :  *
     124             :  * The caller must be prepared for the possibility that the returned page
     125             :  * will turn out to have too little space available by the time the caller
     126             :  * gets a lock on it.  In that case, the caller should report the actual
     127             :  * amount of free space available on that page and then try again (see
     128             :  * RecordAndGetPageWithFreeSpace).  If InvalidBlockNumber is returned,
     129             :  * extend the relation.
     130             :  */
     131             : BlockNumber
     132      219920 : GetPageWithFreeSpace(Relation rel, Size spaceNeeded)
     133             : {
     134      219920 :     uint8       min_cat = fsm_space_needed_to_cat(spaceNeeded);
     135             : 
     136      219920 :     return fsm_search(rel, min_cat);
     137             : }
     138             : 
     139             : /*
     140             :  * RecordAndGetPageWithFreeSpace - update info about a page and try again.
     141             :  *
     142             :  * We provide this combo form to save some locking overhead, compared to
     143             :  * separate RecordPageWithFreeSpace + GetPageWithFreeSpace calls. There's
     144             :  * also some effort to return a page close to the old page; if there's a
     145             :  * page with enough free space on the same FSM page where the old one page
     146             :  * is located, it is preferred.
     147             :  */
     148             : BlockNumber
     149      240036 : RecordAndGetPageWithFreeSpace(Relation rel, BlockNumber oldPage,
     150             :                               Size oldSpaceAvail, Size spaceNeeded)
     151             : {
     152      240036 :     int         old_cat = fsm_space_avail_to_cat(oldSpaceAvail);
     153      240036 :     int         search_cat = fsm_space_needed_to_cat(spaceNeeded);
     154             :     FSMAddress  addr;
     155             :     uint16      slot;
     156             :     int         search_slot;
     157             : 
     158             :     /* Get the location of the FSM byte representing the heap block */
     159      240036 :     addr = fsm_get_location(oldPage, &slot);
     160             : 
     161      240036 :     search_slot = fsm_set_and_search(rel, addr, slot, old_cat, search_cat);
     162             : 
     163             :     /*
     164             :      * If fsm_set_and_search found a suitable new block, return that.
     165             :      * Otherwise, search as usual.
     166             :      */
     167      240036 :     if (search_slot != -1)
     168       17970 :         return fsm_get_heap_blk(addr, search_slot);
     169             :     else
     170      222066 :         return fsm_search(rel, search_cat);
     171             : }
     172             : 
     173             : /*
     174             :  * RecordPageWithFreeSpace - update info about a page.
     175             :  *
     176             :  * Note that if the new spaceAvail value is higher than the old value stored
     177             :  * in the FSM, the space might not become visible to searchers until the next
     178             :  * FreeSpaceMapVacuum call, which updates the upper level pages.
     179             :  */
     180             : void
     181      199426 : RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
     182             : {
     183      199426 :     int         new_cat = fsm_space_avail_to_cat(spaceAvail);
     184             :     FSMAddress  addr;
     185             :     uint16      slot;
     186             : 
     187             :     /* Get the location of the FSM byte representing the heap block */
     188      199426 :     addr = fsm_get_location(heapBlk, &slot);
     189             : 
     190      199426 :     fsm_set_and_search(rel, addr, slot, new_cat, 0);
     191      199426 : }
     192             : 
     193             : /*
     194             :  * XLogRecordPageWithFreeSpace - like RecordPageWithFreeSpace, for use in
     195             :  *      WAL replay
     196             :  */
     197             : void
     198       62668 : XLogRecordPageWithFreeSpace(RelFileNode rnode, BlockNumber heapBlk,
     199             :                             Size spaceAvail)
     200             : {
     201       62668 :     int         new_cat = fsm_space_avail_to_cat(spaceAvail);
     202             :     FSMAddress  addr;
     203             :     uint16      slot;
     204             :     BlockNumber blkno;
     205             :     Buffer      buf;
     206             :     Page        page;
     207             : 
     208             :     /* Get the location of the FSM byte representing the heap block */
     209       62668 :     addr = fsm_get_location(heapBlk, &slot);
     210       62668 :     blkno = fsm_logical_to_physical(addr);
     211             : 
     212             :     /* If the page doesn't exist already, extend */
     213       62668 :     buf = XLogReadBufferExtended(rnode, FSM_FORKNUM, blkno, RBM_ZERO_ON_ERROR);
     214       62668 :     LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
     215             : 
     216       62668 :     page = BufferGetPage(buf);
     217       62668 :     if (PageIsNew(page))
     218          44 :         PageInit(page, BLCKSZ, 0);
     219             : 
     220       62668 :     if (fsm_set_avail(page, slot, new_cat))
     221       62036 :         MarkBufferDirtyHint(buf, false);
     222       62668 :     UnlockReleaseBuffer(buf);
     223       62668 : }
     224             : 
     225             : /*
     226             :  * GetRecordedFreeSpace - return the amount of free space on a particular page,
     227             :  *      according to the FSM.
     228             :  */
     229             : Size
     230          14 : GetRecordedFreeSpace(Relation rel, BlockNumber heapBlk)
     231             : {
     232             :     FSMAddress  addr;
     233             :     uint16      slot;
     234             :     Buffer      buf;
     235             :     uint8       cat;
     236             : 
     237             :     /* Get the location of the FSM byte representing the heap block */
     238          14 :     addr = fsm_get_location(heapBlk, &slot);
     239             : 
     240          14 :     buf = fsm_readbuf(rel, addr, false);
     241          14 :     if (!BufferIsValid(buf))
     242           0 :         return 0;
     243          14 :     cat = fsm_get_avail(BufferGetPage(buf), slot);
     244          14 :     ReleaseBuffer(buf);
     245             : 
     246          14 :     return fsm_space_cat_to_avail(cat);
     247             : }
     248             : 
     249             : /*
     250             :  * FreeSpaceMapPrepareTruncateRel - prepare for truncation of a relation.
     251             :  *
     252             :  * nblocks is the new size of the heap.
     253             :  *
     254             :  * Return the number of blocks of new FSM.
     255             :  * If it's InvalidBlockNumber, there is nothing to truncate;
     256             :  * otherwise the caller is responsible for calling smgrtruncate()
     257             :  * to truncate the FSM pages, and FreeSpaceMapVacuumRange()
     258             :  * to update upper-level pages in the FSM.
     259             :  */
     260             : BlockNumber
     261         122 : FreeSpaceMapPrepareTruncateRel(Relation rel, BlockNumber nblocks)
     262             : {
     263             :     BlockNumber new_nfsmblocks;
     264             :     FSMAddress  first_removed_address;
     265             :     uint16      first_removed_slot;
     266             :     Buffer      buf;
     267             : 
     268         122 :     RelationOpenSmgr(rel);
     269             : 
     270             :     /*
     271             :      * If no FSM has been created yet for this relation, there's nothing to
     272             :      * truncate.
     273             :      */
     274         122 :     if (!smgrexists(rel->rd_smgr, FSM_FORKNUM))
     275           0 :         return InvalidBlockNumber;
     276             : 
     277             :     /* Get the location in the FSM of the first removed heap block */
     278         122 :     first_removed_address = fsm_get_location(nblocks, &first_removed_slot);
     279             : 
     280             :     /*
     281             :      * Zero out the tail of the last remaining FSM page. If the slot
     282             :      * representing the first removed heap block is at a page boundary, as the
     283             :      * first slot on the FSM page that first_removed_address points to, we can
     284             :      * just truncate that page altogether.
     285             :      */
     286         122 :     if (first_removed_slot > 0)
     287             :     {
     288          62 :         buf = fsm_readbuf(rel, first_removed_address, false);
     289          62 :         if (!BufferIsValid(buf))
     290           0 :             return InvalidBlockNumber;  /* nothing to do; the FSM was already
     291             :                                          * smaller */
     292          62 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
     293             : 
     294             :         /* NO EREPORT(ERROR) from here till changes are logged */
     295          62 :         START_CRIT_SECTION();
     296             : 
     297          62 :         fsm_truncate_avail(BufferGetPage(buf), first_removed_slot);
     298             : 
     299             :         /*
     300             :          * Truncation of a relation is WAL-logged at a higher-level, and we
     301             :          * will be called at WAL replay. But if checksums are enabled, we need
     302             :          * to still write a WAL record to protect against a torn page, if the
     303             :          * page is flushed to disk before the truncation WAL record. We cannot
     304             :          * use MarkBufferDirtyHint here, because that will not dirty the page
     305             :          * during recovery.
     306             :          */
     307          62 :         MarkBufferDirty(buf);
     308          62 :         if (!InRecovery && RelationNeedsWAL(rel) && XLogHintBitIsNeeded())
     309           8 :             log_newpage_buffer(buf, false);
     310             : 
     311          62 :         END_CRIT_SECTION();
     312             : 
     313          62 :         UnlockReleaseBuffer(buf);
     314             : 
     315          62 :         new_nfsmblocks = fsm_logical_to_physical(first_removed_address) + 1;
     316             :     }
     317             :     else
     318             :     {
     319          60 :         new_nfsmblocks = fsm_logical_to_physical(first_removed_address);
     320          60 :         if (smgrnblocks(rel->rd_smgr, FSM_FORKNUM) <= new_nfsmblocks)
     321           0 :             return InvalidBlockNumber;  /* nothing to do; the FSM was already
     322             :                                          * smaller */
     323             :     }
     324             : 
     325         122 :     return new_nfsmblocks;
     326             : }
     327             : 
     328             : /*
     329             :  * FreeSpaceMapVacuum - update upper-level pages in the rel's FSM
     330             :  *
     331             :  * We assume that the bottom-level pages have already been updated with
     332             :  * new free-space information.
     333             :  */
     334             : void
     335         184 : FreeSpaceMapVacuum(Relation rel)
     336             : {
     337             :     bool        dummy;
     338             : 
     339             :     /* Recursively scan the tree, starting at the root */
     340         184 :     (void) fsm_vacuum_page(rel, FSM_ROOT_ADDRESS,
     341             :                            (BlockNumber) 0, InvalidBlockNumber,
     342             :                            &dummy);
     343         184 : }
     344             : 
     345             : /*
     346             :  * FreeSpaceMapVacuumRange - update upper-level pages in the rel's FSM
     347             :  *
     348             :  * As above, but assume that only heap pages between start and end-1 inclusive
     349             :  * have new free-space information, so update only the upper-level slots
     350             :  * covering that block range.  end == InvalidBlockNumber is equivalent to
     351             :  * "all the rest of the relation".
     352             :  */
     353             : void
     354       18128 : FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
     355             : {
     356             :     bool        dummy;
     357             : 
     358             :     /* Recursively scan the tree, starting at the root */
     359       18128 :     if (end > start)
     360       18128 :         (void) fsm_vacuum_page(rel, FSM_ROOT_ADDRESS, start, end, &dummy);
     361       18128 : }
     362             : 
     363             : /******** Internal routines ********/
     364             : 
     365             : /*
     366             :  * Return category corresponding x bytes of free space
     367             :  */
     368             : static uint8
     369      502130 : fsm_space_avail_to_cat(Size avail)
     370             : {
     371             :     int         cat;
     372             : 
     373             :     Assert(avail < BLCKSZ);
     374             : 
     375      502130 :     if (avail >= MaxFSMRequestSize)
     376        7838 :         return 255;
     377             : 
     378      494292 :     cat = avail / FSM_CAT_STEP;
     379             : 
     380             :     /*
     381             :      * The highest category, 255, is reserved for MaxFSMRequestSize bytes or
     382             :      * more.
     383             :      */
     384      494292 :     if (cat > 254)
     385           0 :         cat = 254;
     386             : 
     387      494292 :     return (uint8) cat;
     388             : }
     389             : 
     390             : /*
     391             :  * Return the lower bound of the range of free space represented by given
     392             :  * category.
     393             :  */
     394             : static Size
     395          14 : fsm_space_cat_to_avail(uint8 cat)
     396             : {
     397             :     /* The highest category represents exactly MaxFSMRequestSize bytes. */
     398          14 :     if (cat == 255)
     399          14 :         return MaxFSMRequestSize;
     400             :     else
     401           0 :         return cat * FSM_CAT_STEP;
     402             : }
     403             : 
     404             : /*
     405             :  * Which category does a page need to have, to accommodate x bytes of data?
     406             :  * While fsm_space_avail_to_cat() rounds down, this needs to round up.
     407             :  */
     408             : static uint8
     409      459956 : fsm_space_needed_to_cat(Size needed)
     410             : {
     411             :     int         cat;
     412             : 
     413             :     /* Can't ask for more space than the highest category represents */
     414      459956 :     if (needed > MaxFSMRequestSize)
     415           0 :         elog(ERROR, "invalid FSM request size %zu", needed);
     416             : 
     417      459956 :     if (needed == 0)
     418           0 :         return 1;
     419             : 
     420      459956 :     cat = (needed + FSM_CAT_STEP - 1) / FSM_CAT_STEP;
     421             : 
     422      459956 :     if (cat > 255)
     423           0 :         cat = 255;
     424             : 
     425      459956 :     return (uint8) cat;
     426             : }
     427             : 
     428             : /*
     429             :  * Returns the physical block number of a FSM page
     430             :  */
     431             : static BlockNumber
     432     1031658 : fsm_logical_to_physical(FSMAddress addr)
     433             : {
     434             :     BlockNumber pages;
     435             :     int         leafno;
     436             :     int         l;
     437             : 
     438             :     /*
     439             :      * Calculate the logical page number of the first leaf page below the
     440             :      * given page.
     441             :      */
     442     1031658 :     leafno = addr.logpageno;
     443     1991592 :     for (l = 0; l < addr.level; l++)
     444      959934 :         leafno *= SlotsPerFSMPage;
     445             : 
     446             :     /* Count upper level nodes required to address the leaf page */
     447     1031658 :     pages = 0;
     448     4126632 :     for (l = 0; l < FSM_TREE_DEPTH; l++)
     449             :     {
     450     3094974 :         pages += leafno + 1;
     451     3094974 :         leafno /= SlotsPerFSMPage;
     452             :     }
     453             : 
     454             :     /*
     455             :      * If the page we were asked for wasn't at the bottom level, subtract the
     456             :      * additional lower level pages we counted above.
     457             :      */
     458     1031658 :     pages -= addr.level;
     459             : 
     460             :     /* Turn the page count into 0-based block number */
     461     1031658 :     return pages - 1;
     462             : }
     463             : 
     464             : /*
     465             :  * Return the FSM location corresponding to given heap block.
     466             :  */
     467             : static FSMAddress
     468      575466 : fsm_get_location(BlockNumber heapblk, uint16 *slot)
     469             : {
     470             :     FSMAddress  addr;
     471             : 
     472      575466 :     addr.level = FSM_BOTTOM_LEVEL;
     473      575466 :     addr.logpageno = heapblk / SlotsPerFSMPage;
     474      575466 :     *slot = heapblk % SlotsPerFSMPage;
     475             : 
     476      575466 :     return addr;
     477             : }
     478             : 
     479             : /*
     480             :  * Return the heap block number corresponding to given location in the FSM.
     481             :  */
     482             : static BlockNumber
     483       30874 : fsm_get_heap_blk(FSMAddress addr, uint16 slot)
     484             : {
     485             :     Assert(addr.level == FSM_BOTTOM_LEVEL);
     486       30874 :     return ((unsigned int) addr.logpageno) * SlotsPerFSMPage + slot;
     487             : }
     488             : 
     489             : /*
     490             :  * Given a logical address of a child page, get the logical page number of
     491             :  * the parent, and the slot within the parent corresponding to the child.
     492             :  */
     493             : static FSMAddress
     494      111542 : fsm_get_parent(FSMAddress child, uint16 *slot)
     495             : {
     496             :     FSMAddress  parent;
     497             : 
     498             :     Assert(child.level < FSM_ROOT_LEVEL);
     499             : 
     500      111542 :     parent.level = child.level + 1;
     501      111542 :     parent.logpageno = child.logpageno / SlotsPerFSMPage;
     502      111542 :     *slot = child.logpageno % SlotsPerFSMPage;
     503             : 
     504      111542 :     return parent;
     505             : }
     506             : 
     507             : /*
     508             :  * Given a logical address of a parent page and a slot number, get the
     509             :  * logical address of the corresponding child page.
     510             :  */
     511             : static FSMAddress
     512       65548 : fsm_get_child(FSMAddress parent, uint16 slot)
     513             : {
     514             :     FSMAddress  child;
     515             : 
     516             :     Assert(parent.level > FSM_BOTTOM_LEVEL);
     517             : 
     518       65548 :     child.level = parent.level - 1;
     519       65548 :     child.logpageno = parent.logpageno * SlotsPerFSMPage + slot;
     520             : 
     521       65548 :     return child;
     522             : }
     523             : 
     524             : /*
     525             :  * Read a FSM page.
     526             :  *
     527             :  * If the page doesn't exist, InvalidBuffer is returned, or if 'extend' is
     528             :  * true, the FSM file is extended.
     529             :  */
     530             : static Buffer
     531      968868 : fsm_readbuf(Relation rel, FSMAddress addr, bool extend)
     532             : {
     533      968868 :     BlockNumber blkno = fsm_logical_to_physical(addr);
     534             :     Buffer      buf;
     535             : 
     536      968868 :     RelationOpenSmgr(rel);
     537             : 
     538             :     /*
     539             :      * If we haven't cached the size of the FSM yet, check it first.  Also
     540             :      * recheck if the requested block seems to be past end, since our cached
     541             :      * value might be stale.  (We send smgr inval messages on truncation, but
     542             :      * not on extension.)
     543             :      */
     544      968868 :     if (rel->rd_smgr->smgr_fsm_nblocks == InvalidBlockNumber ||
     545      803112 :         blkno >= rel->rd_smgr->smgr_fsm_nblocks)
     546             :     {
     547      245678 :         if (smgrexists(rel->rd_smgr, FSM_FORKNUM))
     548      105770 :             rel->rd_smgr->smgr_fsm_nblocks = smgrnblocks(rel->rd_smgr,
     549             :                                                          FSM_FORKNUM);
     550             :         else
     551      139908 :             rel->rd_smgr->smgr_fsm_nblocks = 0;
     552             :     }
     553             : 
     554             :     /* Handle requests beyond EOF */
     555      968868 :     if (blkno >= rel->rd_smgr->smgr_fsm_nblocks)
     556             :     {
     557      140504 :         if (extend)
     558       17068 :             fsm_extend(rel, blkno + 1);
     559             :         else
     560      123436 :             return InvalidBuffer;
     561             :     }
     562             : 
     563             :     /*
     564             :      * Use ZERO_ON_ERROR mode, and initialize the page if necessary. The FSM
     565             :      * information is not accurate anyway, so it's better to clear corrupt
     566             :      * pages than error out. Since the FSM changes are not WAL-logged, the
     567             :      * so-called torn page problem on crash can lead to pages with corrupt
     568             :      * headers, for example.
     569             :      *
     570             :      * The initialize-the-page part is trickier than it looks, because of the
     571             :      * possibility of multiple backends doing this concurrently, and our
     572             :      * desire to not uselessly take the buffer lock in the normal path where
     573             :      * the page is OK.  We must take the lock to initialize the page, so
     574             :      * recheck page newness after we have the lock, in case someone else
     575             :      * already did it.  Also, because we initially check PageIsNew with no
     576             :      * lock, it's possible to fall through and return the buffer while someone
     577             :      * else is still initializing the page (i.e., we might see pd_upper as set
     578             :      * but other page header fields are still zeroes).  This is harmless for
     579             :      * callers that will take a buffer lock themselves, but some callers
     580             :      * inspect the page without any lock at all.  The latter is OK only so
     581             :      * long as it doesn't depend on the page header having correct contents.
     582             :      * Current usage is safe because PageGetContents() does not require that.
     583             :      */
     584      845432 :     buf = ReadBufferExtended(rel, FSM_FORKNUM, blkno, RBM_ZERO_ON_ERROR, NULL);
     585      845432 :     if (PageIsNew(BufferGetPage(buf)))
     586             :     {
     587           8 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
     588           8 :         if (PageIsNew(BufferGetPage(buf)))
     589           8 :             PageInit(BufferGetPage(buf), BLCKSZ, 0);
     590           8 :         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
     591             :     }
     592      845432 :     return buf;
     593             : }
     594             : 
     595             : /*
     596             :  * Ensure that the FSM fork is at least fsm_nblocks long, extending
     597             :  * it if necessary with empty pages. And by empty, I mean pages filled
     598             :  * with zeros, meaning there's no free space.
     599             :  */
     600             : static void
     601       17068 : fsm_extend(Relation rel, BlockNumber fsm_nblocks)
     602             : {
     603             :     BlockNumber fsm_nblocks_now;
     604             :     PGAlignedBlock pg;
     605             : 
     606       17068 :     PageInit((Page) pg.data, BLCKSZ, 0);
     607             : 
     608             :     /*
     609             :      * We use the relation extension lock to lock out other backends trying to
     610             :      * extend the FSM at the same time. It also locks out extension of the
     611             :      * main fork, unnecessarily, but extending the FSM happens seldom enough
     612             :      * that it doesn't seem worthwhile to have a separate lock tag type for
     613             :      * it.
     614             :      *
     615             :      * Note that another backend might have extended or created the relation
     616             :      * by the time we get the lock.
     617             :      */
     618       17068 :     LockRelationForExtension(rel, ExclusiveLock);
     619             : 
     620             :     /* Might have to re-open if a cache flush happened */
     621       17068 :     RelationOpenSmgr(rel);
     622             : 
     623             :     /*
     624             :      * Create the FSM file first if it doesn't exist.  If smgr_fsm_nblocks is
     625             :      * positive then it must exist, no need for an smgrexists call.
     626             :      */
     627       17068 :     if ((rel->rd_smgr->smgr_fsm_nblocks == 0 ||
     628           6 :          rel->rd_smgr->smgr_fsm_nblocks == InvalidBlockNumber) &&
     629       17062 :         !smgrexists(rel->rd_smgr, FSM_FORKNUM))
     630       17060 :         smgrcreate(rel->rd_smgr, FSM_FORKNUM, false);
     631             : 
     632       17068 :     fsm_nblocks_now = smgrnblocks(rel->rd_smgr, FSM_FORKNUM);
     633             : 
     634       68252 :     while (fsm_nblocks_now < fsm_nblocks)
     635             :     {
     636       51184 :         PageSetChecksumInplace((Page) pg.data, fsm_nblocks_now);
     637             : 
     638       51184 :         smgrextend(rel->rd_smgr, FSM_FORKNUM, fsm_nblocks_now,
     639             :                    pg.data, false);
     640       51184 :         fsm_nblocks_now++;
     641             :     }
     642             : 
     643             :     /* Update local cache with the up-to-date size */
     644       17068 :     rel->rd_smgr->smgr_fsm_nblocks = fsm_nblocks_now;
     645             : 
     646       17068 :     UnlockRelationForExtension(rel, ExclusiveLock);
     647       17068 : }
     648             : 
     649             : /*
     650             :  * Set value in given FSM page and slot.
     651             :  *
     652             :  * If minValue > 0, the updated page is also searched for a page with at
     653             :  * least minValue of free space. If one is found, its slot number is
     654             :  * returned, -1 otherwise.
     655             :  */
     656             : static int
     657      441204 : fsm_set_and_search(Relation rel, FSMAddress addr, uint16 slot,
     658             :                    uint8 newValue, uint8 minValue)
     659             : {
     660             :     Buffer      buf;
     661             :     Page        page;
     662      441204 :     int         newslot = -1;
     663             : 
     664      441204 :     buf = fsm_readbuf(rel, addr, true);
     665      441204 :     LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
     666             : 
     667      441204 :     page = BufferGetPage(buf);
     668             : 
     669      441204 :     if (fsm_set_avail(page, slot, newValue))
     670      188748 :         MarkBufferDirtyHint(buf, false);
     671             : 
     672      441204 :     if (minValue != 0)
     673             :     {
     674             :         /* Search while we still hold the lock */
     675      240036 :         newslot = fsm_search_avail(buf, minValue,
     676      240036 :                                    addr.level == FSM_BOTTOM_LEVEL,
     677             :                                    true);
     678             :     }
     679             : 
     680      441204 :     UnlockReleaseBuffer(buf);
     681             : 
     682      441204 :     return newslot;
     683             : }
     684             : 
     685             : /*
     686             :  * Search the tree for a heap page with at least min_cat of free space
     687             :  */
     688             : static BlockNumber
     689      441986 : fsm_search(Relation rel, uint8 min_cat)
     690             : {
     691      441986 :     int         restarts = 0;
     692      441986 :     FSMAddress  addr = FSM_ROOT_ADDRESS;
     693             : 
     694             :     for (;;)
     695       30162 :     {
     696             :         int         slot;
     697             :         Buffer      buf;
     698      472148 :         uint8       max_avail = 0;
     699             : 
     700             :         /* Read the FSM page. */
     701      472148 :         buf = fsm_readbuf(rel, addr, false);
     702             : 
     703             :         /* Search within the page */
     704      472148 :         if (BufferIsValid(buf))
     705             :         {
     706      349312 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
     707      349312 :             slot = fsm_search_avail(buf, min_cat,
     708      349312 :                                     (addr.level == FSM_BOTTOM_LEVEL),
     709             :                                     false);
     710      349312 :             if (slot == -1)
     711      307988 :                 max_avail = fsm_get_max_avail(BufferGetPage(buf));
     712      349312 :             UnlockReleaseBuffer(buf);
     713             :         }
     714             :         else
     715      122836 :             slot = -1;
     716             : 
     717      472148 :         if (slot != -1)
     718             :         {
     719             :             /*
     720             :              * Descend the tree, or return the found block if we're at the
     721             :              * bottom.
     722             :              */
     723       41324 :             if (addr.level == FSM_BOTTOM_LEVEL)
     724       12904 :                 return fsm_get_heap_blk(addr, slot);
     725             : 
     726       28420 :             addr = fsm_get_child(addr, slot);
     727             :         }
     728      430824 :         else if (addr.level == FSM_ROOT_LEVEL)
     729             :         {
     730             :             /*
     731             :              * At the root, failure means there's no page with enough free
     732             :              * space in the FSM. Give up.
     733             :              */
     734      429082 :             return InvalidBlockNumber;
     735             :         }
     736             :         else
     737             :         {
     738             :             uint16      parentslot;
     739             :             FSMAddress  parent;
     740             : 
     741             :             /*
     742             :              * At lower level, failure can happen if the value in the upper-
     743             :              * level node didn't reflect the value on the lower page. Update
     744             :              * the upper node, to avoid falling into the same trap again, and
     745             :              * start over.
     746             :              *
     747             :              * There's a race condition here, if another backend updates this
     748             :              * page right after we release it, and gets the lock on the parent
     749             :              * page before us. We'll then update the parent page with the now
     750             :              * stale information we had. It's OK, because it should happen
     751             :              * rarely, and will be fixed by the next vacuum.
     752             :              */
     753        1742 :             parent = fsm_get_parent(addr, &parentslot);
     754        1742 :             fsm_set_and_search(rel, parent, parentslot, max_avail, 0);
     755             : 
     756             :             /*
     757             :              * If the upper pages are badly out of date, we might need to loop
     758             :              * quite a few times, updating them as we go. Any inconsistencies
     759             :              * should eventually be corrected and the loop should end. Looping
     760             :              * indefinitely is nevertheless scary, so provide an emergency
     761             :              * valve.
     762             :              */
     763        1742 :             if (restarts++ > 10000)
     764           0 :                 return InvalidBlockNumber;
     765             : 
     766             :             /* Start search all over from the root */
     767        1742 :             addr = FSM_ROOT_ADDRESS;
     768             :         }
     769             :     }
     770             : }
     771             : 
     772             : 
     773             : /*
     774             :  * Recursive guts of FreeSpaceMapVacuum
     775             :  *
     776             :  * Examine the FSM page indicated by addr, as well as its children, updating
     777             :  * upper-level nodes that cover the heap block range from start to end-1.
     778             :  * (It's okay if end is beyond the actual end of the map.)
     779             :  * Return the maximum freespace value on this page.
     780             :  *
     781             :  * If addr is past the end of the FSM, set *eof_p to true and return 0.
     782             :  *
     783             :  * This traverses the tree in depth-first order.  The tree is stored
     784             :  * physically in depth-first order, so this should be pretty I/O efficient.
     785             :  */
     786             : static uint8
     787       55440 : fsm_vacuum_page(Relation rel, FSMAddress addr,
     788             :                 BlockNumber start, BlockNumber end,
     789             :                 bool *eof_p)
     790             : {
     791             :     Buffer      buf;
     792             :     Page        page;
     793             :     uint8       max_avail;
     794             : 
     795             :     /* Read the page if it exists, or return EOF */
     796       55440 :     buf = fsm_readbuf(rel, addr, false);
     797       55440 :     if (!BufferIsValid(buf))
     798             :     {
     799         600 :         *eof_p = true;
     800         600 :         return 0;
     801             :     }
     802             :     else
     803       54840 :         *eof_p = false;
     804             : 
     805       54840 :     page = BufferGetPage(buf);
     806             : 
     807             :     /*
     808             :      * If we're above the bottom level, recurse into children, and fix the
     809             :      * information stored about them at this level.
     810             :      */
     811       54840 :     if (addr.level > FSM_BOTTOM_LEVEL)
     812             :     {
     813             :         FSMAddress  fsm_start,
     814             :                     fsm_end;
     815             :         uint16      fsm_start_slot,
     816             :                     fsm_end_slot;
     817             :         int         slot,
     818             :                     start_slot,
     819             :                     end_slot;
     820       36600 :         bool        eof = false;
     821             : 
     822             :         /*
     823             :          * Compute the range of slots we need to update on this page, given
     824             :          * the requested range of heap blocks to consider.  The first slot to
     825             :          * update is the one covering the "start" block, and the last slot is
     826             :          * the one covering "end - 1".  (Some of this work will be duplicated
     827             :          * in each recursive call, but it's cheap enough to not worry about.)
     828             :          */
     829       36600 :         fsm_start = fsm_get_location(start, &fsm_start_slot);
     830       36600 :         fsm_end = fsm_get_location(end - 1, &fsm_end_slot);
     831             : 
     832       91500 :         while (fsm_start.level < addr.level)
     833             :         {
     834       54900 :             fsm_start = fsm_get_parent(fsm_start, &fsm_start_slot);
     835       54900 :             fsm_end = fsm_get_parent(fsm_end, &fsm_end_slot);
     836             :         }
     837             :         Assert(fsm_start.level == addr.level);
     838             : 
     839       36600 :         if (fsm_start.logpageno == addr.logpageno)
     840       36600 :             start_slot = fsm_start_slot;
     841           0 :         else if (fsm_start.logpageno > addr.logpageno)
     842           0 :             start_slot = SlotsPerFSMPage;   /* shouldn't get here... */
     843             :         else
     844           0 :             start_slot = 0;
     845             : 
     846       36600 :         if (fsm_end.logpageno == addr.logpageno)
     847       36306 :             end_slot = fsm_end_slot;
     848         294 :         else if (fsm_end.logpageno > addr.logpageno)
     849         294 :             end_slot = SlotsPerFSMPage - 1;
     850             :         else
     851           0 :             end_slot = -1;      /* shouldn't get here... */
     852             : 
     853     1345338 :         for (slot = start_slot; slot <= end_slot; slot++)
     854             :         {
     855             :             int         child_avail;
     856             : 
     857     1308738 :             CHECK_FOR_INTERRUPTS();
     858             : 
     859             :             /* After we hit end-of-file, just clear the rest of the slots */
     860     1308738 :             if (!eof)
     861       37128 :                 child_avail = fsm_vacuum_page(rel, fsm_get_child(addr, slot),
     862             :                                               start, end,
     863             :                                               &eof);
     864             :             else
     865     1271610 :                 child_avail = 0;
     866             : 
     867             :             /* Update information about the child */
     868     1308738 :             if (fsm_get_avail(page, slot) != child_avail)
     869             :             {
     870       33856 :                 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
     871       33856 :                 fsm_set_avail(page, slot, child_avail);
     872       33856 :                 MarkBufferDirtyHint(buf, false);
     873       33856 :                 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
     874             :             }
     875             :         }
     876             :     }
     877             : 
     878             :     /* Now get the maximum value on the page, to return to caller */
     879       54840 :     max_avail = fsm_get_max_avail(page);
     880             : 
     881             :     /*
     882             :      * Reset the next slot pointer. This encourages the use of low-numbered
     883             :      * pages, increasing the chances that a later vacuum can truncate the
     884             :      * relation.  We don't bother with a lock here, nor with marking the page
     885             :      * dirty if it wasn't already, since this is just a hint.
     886             :      */
     887       54840 :     ((FSMPage) PageGetContents(page))->fp_next_slot = 0;
     888             : 
     889       54840 :     ReleaseBuffer(buf);
     890             : 
     891       54840 :     return max_avail;
     892             : }

Generated by: LCOV version 1.13