man postgres-internals/free-space-map

lesson 4 of 30 · Storage

The free space map

lib / PostgreSQL internals, by building tinypg 31 mindraft

checked against: PostgreSQL 19.0, Python 3.15.2

code: toothywalrus/tinypg@lesson-04

So far every row tinypg inserted went to the last page, and a new page was added when that one was full. PostgreSQL does that too, as long as nothing is ever deleted. Once rows are deleted and VACUUM has run, there is room in the middle of the table, and an INSERT should use it before the file grows. Reading every page to find it would make each INSERT cost a scan. Instead a table gets a second file, the free space map, with one byte per heap page; it is created the first time there is something to record in it. This lesson reads that file: what the byte means, how the bytes are arranged so a search touches only a few, who writes them, and why the map is allowed to be wrong.

Every psql and shell output below comes from one run of tools/record_fsm.py in the tinypg repository (tag lesson-04) against PostgreSQL 19.0 on 64-bit ARM macOS, pasted as the script recorded it. The script reads pages with get_raw_page, which goes through shared buffers, so it sees pages as the server has them in memory, written to disk or not.

The experiment

One table, cards, with rows of 232 bytes: a 24-byte header, an int, and 200 characters behind a 4-byte varlena header. A page takes 34 of them. One INSERT writes 260 rows, from one session:

CREATE TABLE cards (id int, body text) WITH (autovacuum_enabled = off);
CREATE TABLE
WITH ins AS (INSERT INTO cards SELECT i, repeat('x', 200)
             FROM generate_series(1, 260) AS i RETURNING xmin)
SELECT count(*), min(xmin::text) AS xmin FROM ins;
 count | xmin 
-------+------
   260 | 1666
(1 row)

That fills seven pages and part of an eighth, and creates the map, a fork of three 8 KB pages (_fsm after the table’s file name):

SELECT pg_relation_size('cards') / 8192 AS heap_pages,
       pg_relation_size('cards', 'fsm') / 8192 AS fsm_pages;
 heap_pages | fsm_pages 
------------+-----------
          8 |         3
(1 row)

SELECT b AS blk, lower, upper, upper - lower - 4 AS free, flags
FROM generate_series(0, pg_relation_size('cards') / 8192 - 1) AS b,
     page_header(get_raw_page('cards', b));
 blk | lower | upper | free | flags 
-----+-------+-------+------+-------
   0 |   160 |   304 |  140 |     0
   1 |   160 |   304 |  140 |     0
   2 |   160 |   304 |  140 |     0
   3 |   160 |   304 |  140 |     0
   4 |   160 |   304 |  140 |     0
   5 |   160 |   304 |  140 |     0
   6 |   160 |   304 |  140 |     0
   7 |   112 |  3088 | 2972 |     0
(8 rows)

free is the gap between pd_lower and pd_upper, minus 4 bytes for the line pointer a new row would need, which on these pages is what PageGetHeapFreeSpace() returns. A full page has 140 bytes left, not enough for another 232-byte row.

One byte per page: categories

A page’s free space, up to 8164 bytes, does not fit in a byte, so the map stores it divided by 32 and rounded down, a category:

#define FSM_CATEGORIES  256
#define FSM_CAT_STEP    (BLCKSZ / FSM_CATEGORIES)
#define MaxFSMRequestSize   MaxHeapTupleSize

src/backend/storage/freespace/freespace.c, lines 64–66

static uint8
fsm_space_avail_to_cat(Size avail)
{
    int         cat;

    Assert(avail < BLCKSZ);

    if (avail >= MaxFSMRequestSize)
        return 255;

    cat = avail / FSM_CAT_STEP;

    /*
     * The highest category, 255, is reserved for MaxFSMRequestSize bytes or
     * more.
     */
    if (cat > 254)
        cat = 254;

    return (uint8) cat;
}

src/backend/storage/freespace/freespace.c, lines 391–411

255 is kept for a page that can take the largest possible tuple, 8160 bytes (MaxHeapTupleSize). A request is converted the other way, rounding up, so that any page whose category is high enough is sure to have room:

static uint8
fsm_space_needed_to_cat(Size needed)
{
    int         cat;

    /* Can't ask for more space than the highest category represents */
    if (needed > MaxFSMRequestSize)
        elog(ERROR, "invalid FSM request size %zu", needed);

    if (needed == 0)
        return 1;

    cat = (needed + FSM_CAT_STEP - 1) / FSM_CAT_STEP;

    if (cat > 255)
        cat = 255;

    return (uint8) cat;
}

src/backend/storage/freespace/freespace.c, lines 431–449

So a full cards page, with 140 bytes, is category 4, and a new row of 232 bytes asks for category 8. The rounding wastes up to 31 bytes on each side: a page with 255 bytes free (category 7) is never offered for one of these 232-byte rows (category 8), though it would fit.

A binary tree inside a page

An FSM page is an ordinary page header followed by this:

typedef struct
{
    /*
     * fsm_search_avail() tries to spread the load of multiple backends by
     * returning different pages to different backends in a round-robin
     * fashion. fp_next_slot points to the next slot to be returned (assuming
     * there's enough space on it for the request). It's defined as an int,
     * because it's updated without an exclusive lock. uint16 would be more
     * appropriate, but int is more likely to be atomically
     * fetchable/storable.
     */
    int         fp_next_slot;

    /*
     * fp_nodes contains the binary tree, stored in array. The first
     * NonLeafNodesPerPage elements are upper nodes, and the following
     * LeafNodesPerPage elements are leaf nodes. Unused nodes are zero.
     */
    uint8       fp_nodes[FLEXIBLE_ARRAY_MEMBER];
} FSMPageData;

src/include/storage/fsm_internals.h, lines 24–43

#define NodesPerPage (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - \
                      offsetof(FSMPageData, fp_nodes))

#define NonLeafNodesPerPage (BLCKSZ / 2 - 1)
#define LeafNodesPerPage (NodesPerPage - NonLeafNodesPerPage)

src/include/storage/fsm_internals.h, lines 51–55

After the 24-byte header and the 4-byte fp_next_slot, the remaining 8164 bytes are nodes of a binary tree stored as an array, as a heap is: node n has children 2n + 1 and 2n + 2. Nodes 0 to 4094 are inner nodes; 4095 onwards are leaves, 4069 of them, one per heap page. Slot s is node 4095 + s. Every inner node holds the larger of its two children, so node 0 says how much room the best page has. Setting a leaf walks up to fix its ancestors, and stops at the first one that does not change:

bool
fsm_set_avail(Page page, int slot, uint8 value)
{
    int         nodeno = NonLeafNodesPerPage + slot;
    FSMPage     fsmpage = (FSMPage) PageGetContents(page);
    uint8       oldvalue;

    Assert(slot < LeafNodesPerPage);

    oldvalue = fsmpage->fp_nodes[nodeno];

    /* If the value hasn't changed, we don't need to do anything */
    if (oldvalue == value && value <= fsmpage->fp_nodes[0])
        return false;

    fsmpage->fp_nodes[nodeno] = value;

    /*
     * Propagate up, until we hit the root or a node that doesn't need to be
     * updated.
     */
    do
    {
        uint8       newvalue = 0;
        int         lchild;
        int         rchild;

        nodeno = parentof(nodeno);
        lchild = leftchild(nodeno);
        rchild = lchild + 1;

        newvalue = fsmpage->fp_nodes[lchild];
        if (rchild < NodesPerPage)
            newvalue = Max(newvalue,
                           fsmpage->fp_nodes[rchild]);

        oldvalue = fsmpage->fp_nodes[nodeno];
        if (oldvalue == newvalue)
            break;

        fsmpage->fp_nodes[nodeno] = newvalue;
    } while (nodeno > 0);

src/backend/storage/freespace/fsmpage.c, lines 62–103

Here is the map after the INSERT, read with pageinspect, which prints the non-zero nodes:

SELECT b AS fsm_block, lower, upper, special
FROM generate_series(0, 2) AS b, page_header(get_raw_page('cards', 'fsm', b));
 fsm_block | lower | upper | special 
-----------+-------+-------+---------
         0 |    24 |  8192 |    8192
         1 |     0 |     0 |       0
         2 |    24 |  8192 |    8192
(3 rows)

SELECT b AS fsm_block, fsm_page_contents(get_raw_page('cards', 'fsm', b))
FROM generate_series(0, pg_relation_size('cards', 'fsm') / 8192 - 1) AS b;
 fsm_block | fsm_page_contents 
-----------+-------------------
         0 | fp_next_slot: 0  +
           | 
         1 | 
         2 | 0: 4             +
           | 1: 4             +
           | 3: 4             +
           | 7: 4             +
           | 15: 4            +
           | 31: 4            +
           | 63: 4            +
           | 127: 4           +
           | 255: 4           +
           | 511: 4           +
           | 1023: 4          +
           | 1024: 4          +
           | 2047: 4          +
           | 2048: 4          +
           | 2049: 4          +
           | 2050: 4          +
           | 4095: 4          +
           | 4096: 4          +
           | 4097: 4          +
           | 4098: 4          +
           | 4099: 4          +
           | 4100: 4          +
           | 4101: 4          +
           | fp_next_slot: 0  +
           | 
(3 rows)

Block 2 has leaves 4095 to 4101 (heap blocks 0 to 6) at category 4, and the chain of their ancestors up to node 0: 2047 to 2050, 1023 and 1024, 511, then 255, 127 and so on, one node per level, the leftmost of each. Heap block 7 has no entry: it is the page the INSERT was still filling. Blocks 0 and 1 are something else.

A tree of pages

One page holds 4069 leaves, and a table can have 2³² − 1 blocks. So the map is itself a tree, of pages: a leaf of an upper page holds the value of node 0 of a page below it.

/*
 * Depth of the on-disk tree. We need to be able to address 2^32-1 blocks,
 * and 1626 is the smallest number that satisfies X^3 >= 2^32-1. Likewise,
 * 256 is the smallest number that satisfies X^4 >= 2^32-1. In practice,
 * this means that 4096 bytes is the smallest BLCKSZ that we can get away
 * with a 3-level tree, and 512 is the smallest we support.
 */
#define FSM_TREE_DEPTH  ((SlotsPerFSMPage >= 1626) ? 3 : 4)

#define FSM_ROOT_LEVEL  (FSM_TREE_DEPTH - 1)
#define FSM_BOTTOM_LEVEL 0

src/backend/storage/freespace/freespace.c, lines 68–78

4069³ is over 67 billion, so three levels always suffice. The pages are stored depth first: block 0 is the root, block 1 the first page of the middle level, block 2 the first bottom page, covering heap blocks 0 to 4068; the next bottom page is block 3 and covers 4069 to 8137. A table under 4069 pages has exactly this three-page map. Its root and middle pages each use one leaf, slot 0, which says what the one page below them can offer.

In the output above, block 2 is the bottom page and is filled in. Block 0, the root, has a page header (upper 8192) and nothing else. Block 1 is all zeros, not even a header. Neither knows anything about the heap. Why that is follows from who writes the map.

Writing the map: the INSERT

An INSERT asks for a page in RelationGetBufferForTuple(). It starts with the block this backend inserted into last, which the relation cache keeps. Without one it asks the map, and if the map has nothing it tries the last page of the table:

if (bistate && bistate->current_buf != InvalidBuffer)
    targetBlock = BufferGetBlockNumber(bistate->current_buf);
else
    targetBlock = RelationGetTargetBlock(relation);

if (targetBlock == InvalidBlockNumber && use_fsm)
{
    /*
     * We have no cached target page, so ask the FSM for an initial
     * target.
     */
    targetBlock = GetPageWithFreeSpace(relation, targetFreeSpace);
}

/*
 * If the FSM knows nothing of the rel, try the last page before we give
 * up and extend.  This avoids one-tuple-per-page syndrome during
 * bootstrapping or in a recently-started system.
 */
if (targetBlock == InvalidBlockNumber)
{
    BlockNumber nblocks = RelationGetNumberOfBlocks(relation);

    if (nblocks > 0)
        targetBlock = nblocks - 1;
}

src/backend/access/heap/hio.c, lines 574–599

If the chosen page turns out to be too full, the INSERT records what that page really has, and asks again:

else
{
    /*
     * Update FSM as to condition of this page, and ask for another
     * page to try.
     */
    targetBlock = RecordAndGetPageWithFreeSpace(relation,
                                                targetBlock,
                                                pageFreeSpace,
                                                targetFreeSpace);
}

src/backend/access/heap/hio.c, lines 755–765

When there is no candidate left, the table grows. An INSERT passes no bulk-insert state (COPY does), and no other backend was inserting into cards, so nobody waited for the extension lock and the table grows by one page; that page goes into the backend’s cache, not the map:

/*
 * Remember the new page as our target for future insertions.
 *
 * XXX should we enter the new page into the free space map immediately,
 * or just keep it for this backend's exclusive use in the short run
 * (until VACUUM sees it)?  Seems to depend on whether you expect the
 * current backend to make more insertions or not, which is probably a
 * good bet most of the time.  So for now, don't add it to FSM yet.
 */
RelationSetTargetBlock(relation, targetBlock);

src/backend/access/heap/hio.c, lines 875–884

Follow the 260-row INSERT. Rows 1 to 34 go to block 0, the cached target. Row 35 does not fit: block 0 has 140 bytes. RecordAndGetPageWithFreeSpace() sets heap block 0’s leaf to category 4. The leaf lives in bottom page 0, physical block 2, and asking for block 2 of a fork that does not exist creates the fork with three zeroed pages; reading block 2 gives it a page header first:

if (PageIsNew(BufferGetPage(buf)))
{
    LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    if (PageIsNew(BufferGetPage(buf)))
        PageInit(BufferGetPage(buf), BLCKSZ, 0);
    LockBuffer(buf, BUFFER_LOCK_UNLOCK);
}

src/backend/storage/freespace/freespace.c, lines 613–619

Searching that same page for category 8 finds nothing. Then fsm_search() starts again from the root. Reading block 0 gives it a header too, its node 0 is 0, and the search ends there:

else if (addr.level == FSM_ROOT_LEVEL)
{
    /*
     * At the root, failure means there's no page with enough free
     * space in the FSM. Give up.
     */
    return InvalidBlockNumber;
}

src/backend/storage/freespace/freespace.c, lines 753–760

The table grows to block 1, which becomes the target, and the same happens at rows 69, 103 and so on, each time with the next leaf. The middle page is never read, because the search fails at the root, so it stays all zeros. Only the bottom page was written; the root and middle are not told. The comment on RecordPageWithFreeSpace() says so:

/*
 * RecordPageWithFreeSpace - update info about a page.
 *
 * Note that if the new spaceAvail value is higher than the old value stored
 * in the FSM, the space might not become visible to searchers until the next
 * FreeSpaceMapVacuum call, which updates the upper level pages.
 */

src/backend/storage/freespace/freespace.c, lines 186–192

The same is true of RecordAndGetPageWithFreeSpace(). Until something updates the upper levels, a search from the root cannot find the space the bottom page records. Here that changes nothing, since no page has category 8, but it is the first sign of the map’s character: it is a hint, written as cheaply as possible, and allowed to lag.

VACUUM fills in the map

Now delete 34 rows that fill block 2 and every other row of block 5, and vacuum:

WITH d AS (DELETE FROM cards WHERE id BETWEEN 69 AND 102 OR (id BETWEEN 171 AND 204 AND id % 2 = 1) RETURNING id)
SELECT count(*), pg_current_xact_id() AS xid FROM d;
 count | xid  
-------+------
    51 | 1667
(1 row)

VACUUM cards;
VACUUM
SELECT b AS blk, lower, upper, upper - lower - 4 AS free, flags
FROM generate_series(0, pg_relation_size('cards') / 8192 - 1) AS b,
     page_header(get_raw_page('cards', b));
 blk | lower | upper | free | flags 
-----+-------+-------+------+-------
   0 |   160 |   304 |  140 |     4
   1 |   160 |   304 |  140 |     4
   2 |    24 |  8192 | 8164 |     4
   3 |   160 |   304 |  140 |     4
   4 |   160 |   304 |  140 |     4
   5 |   160 |  4248 | 4084 |     5
   6 |   160 |   304 |  140 |     4
   7 |   112 |  3088 | 2972 |     4
(8 rows)

SELECT b AS fsm_block, fsm_page_contents(get_raw_page('cards', 'fsm', b))
FROM generate_series(0, pg_relation_size('cards', 'fsm') / 8192 - 1) AS b;
 fsm_block | fsm_page_contents 
-----------+-------------------
         0 | 0: 255           +
           | 1: 255           +
           | 3: 255           +
           | 7: 255           +
           | 15: 255          +
           | 31: 255          +
           | 63: 255          +
           | 127: 255         +
           | 255: 255         +
           | 511: 255         +
           | 1023: 255        +
           | 2047: 255        +
           | 4095: 255        +
           | fp_next_slot: 0  +
           | 
         1 | 0: 255           +
           | 1: 255           +
           | 3: 255           +
           | 7: 255           +
           | 15: 255          +
           | 31: 255          +
           | 63: 255          +
           | 127: 255         +
           | 255: 255         +
           | 511: 255         +
           | 1023: 255        +
           | 2047: 255        +
           | 4095: 255        +
           | fp_next_slot: 0  +
           | 
         2 | 0: 255           +
           | 1: 255           +
           | 3: 255           +
           | 7: 255           +
           | 15: 255          +
           | 31: 255          +
           | 63: 255          +
           | 127: 255         +
           | 255: 255         +
           | 511: 255         +
           | 1023: 255        +
           | 1024: 127        +
           | 2047: 4          +
           | 2048: 255        +
           | 2049: 127        +
           | 2050: 92         +
           | 4095: 4          +
           | 4096: 4          +
           | 4097: 255        +
           | 4098: 4          +
           | 4099: 4          +
           | 4100: 127        +
           | 4101: 4          +
           | 4102: 92         +
           | fp_next_slot: 0  +
           | 
(3 rows)

cards has no index, so VACUUM’s first pass over a page is its only one, and it records the page’s free space right there:

if (vacrel->nindexes == 0
    || !vacrel->do_index_vacuuming
    || !has_lpdead_items)
{
    Size        freespace = PageGetHeapFreeSpace(page);

    UnlockReleaseBuffer(buf);
    RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);

src/backend/access/heap/vacuumlazy.c, lines 1561–1568

Block 2 is empty: 8164 bytes, category 255. Its pd_lower is back to 24: on a table without indexes VACUUM’s pruning marks the deleted rows’ line pointers unused at once, and PageRepairFragmentation() then drops unused line pointers from the end of the array, here all of them. Block 5 has 4084 bytes, category 127; its 17 freed line pointers stay, marked unused, and flag 1 (PD_HAS_FREE_LINES) says so. Block 7, never recorded, gets its 2972 bytes, category 92. Every page also has flag 4, PD_ALL_VISIBLE.

Then, at the end, VACUUM updates the levels above:

if (rel_pages > next_fsm_block_to_vacuum)
    FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);

src/backend/access/heap/vacuumlazy.c, lines 1629–1630

FreeSpaceMapVacuumRange() walks the tree of pages from the root, and on each page sets the leaf for each child page to that child’s node 0. Now the root and middle pages hold 255 in slot 0, all the way up to node 0. On the way out it also does this to every page it visits:

/*
 * Try to reset the next slot pointer. This encourages the use of
 * low-numbered pages, increasing the chances that a later vacuum can
 * truncate the relation. We don't bother with marking the page dirty if
 * it wasn't already, since this is just a hint.
 */
LockBuffer(buf, BUFFER_LOCK_SHARE);
if (BufferBeginSetHintBits(buf))
{
    ((FSMPage) PageGetContents(page))->fp_next_slot = 0;
    BufferFinishSetHintBits(buf, false, false);
}

src/backend/storage/freespace/freespace.c, lines 906–917

Searching: fp_next_slot

With the map up to date, six single-row INSERTs, each in a new psql session so none has a cached target. After each, the script prints fp_next_slot of the three map pages:

INSERT INTO cards VALUES (1001, repeat('y', 200)) RETURNING ctid, xmin;
 ctid  | xmin 
-------+------
 (2,1) | 1668
(1 row)

INSERT 0 1
   fp_next_slot   
------------------
 0: 0, 1: 0, 2: 3
(1 row)

INSERT INTO cards VALUES (1002, repeat('y', 200)) RETURNING ctid, xmin;
 ctid  | xmin 
-------+------
 (5,1) | 1669
(1 row)

INSERT 0 1
   fp_next_slot   
------------------
 0: 0, 1: 0, 2: 6
(1 row)

INSERT INTO cards VALUES (1003, repeat('y', 200)) RETURNING ctid, xmin;
  ctid  | xmin 
--------+------
 (7,23) | 1670
(1 row)

INSERT 0 1
   fp_next_slot   
------------------
 0: 0, 1: 0, 2: 8
(1 row)

INSERT INTO cards VALUES (1004, repeat('y', 200)) RETURNING ctid, xmin;
 ctid  | xmin 
-------+------
 (2,2) | 1671
(1 row)

INSERT 0 1
   fp_next_slot   
------------------
 0: 0, 1: 0, 2: 3
(1 row)

INSERT INTO cards VALUES (1005, repeat('y', 200)) RETURNING ctid, xmin;
 ctid  | xmin 
-------+------
 (5,3) | 1672
(1 row)

INSERT 0 1
   fp_next_slot   
------------------
 0: 0, 1: 0, 2: 6
(1 row)

INSERT INTO cards VALUES (1006, repeat('y', 200)) RETURNING ctid, xmin;
  ctid  | xmin 
--------+------
 (7,24) | 1673
(1 row)

INSERT 0 1
   fp_next_slot   
------------------
 0: 0, 1: 0, 2: 8
(1 row)

The rows land on blocks 2, 5, 7, 2, 5, 7. Not 2 six times, though block 2 has room for 33 more. Each search starts at fp_next_slot and leaves it one past the slot it returned:

target = fsmpage->fp_next_slot;
if (target < 0 || target >= LeafNodesPerPage)
    target = 0;
target += NonLeafNodesPerPage;

src/backend/storage/freespace/fsmpage.c, lines 181–184

From there it climbs, but not straight up. At each step it moves one node right, then to that node’s parent, so the subtree it has covered doubles each time and always extends to the right of the start:

nodeno = target;
while (nodeno > 0)
{
    if (fsmpage->fp_nodes[nodeno] >= minvalue)
        break;

    /*
     * Move to the right, wrapping around on same level if necessary, then
     * climb up.
     */
    nodeno = parentof(rightneighbor(nodeno));
}

src/backend/storage/freespace/fsmpage.c, lines 227–238

At a node with enough room it goes down, taking the left child when both have enough:

while (nodeno < NonLeafNodesPerPage)
{
    int         childnodeno = leftchild(nodeno);

    if (childnodeno < NodesPerPage &&
        fsmpage->fp_nodes[childnodeno] >= minvalue)
    {
        nodeno = childnodeno;
        continue;
    }

src/backend/storage/freespace/fsmpage.c, lines 245–254

fsmpage->fp_next_slot = slot + (advancenext ? 1 : 0);

src/backend/storage/freespace/fsmpage.c, line 308

advancenext is true only on the bottom level. On the root and middle pages fp_next_slot stays 0, which is right: they have one child page each.

The first INSERT starts at slot 0, node 4095, category 4. Right to 4096 and up to its parent 2047: category 4. Right to 2048 and up to 1023: 255, enough. Down: the left child, 2047, has 4, the right child, 2048, has 255, and its left child is 4097, heap block 2. fp_next_slot becomes 3. The second starts at slot 3 (node 4098, category 4), goes right and up to 2049 (127) and down to 4100, block 5. The third starts at 6 and finds 4102, block 7, leaving fp_next_slot at 8. Slot 8 is past the last heap block, but it is still a leaf on the page (node 4103, zero), and the climb from there goes right and up, all the way to the root, before coming down the left side to block 2 again. That is the “wrapping around” in the comment.

The comment on fp_next_slot gives the reason: to spread the load of several backends over different pages, round robin, rather than hand all of them the same one. VACUUM resets it to 0 so that, between vacuums, inserts favour the start of the table, which leaves the end free to be truncated.

The fifth row went to (5,3), not to a new line pointer at the end. Block 5’s PD_HAS_FREE_LINES made PageAddItem() look for an unused line pointer first, and it takes the lowest:

for (offsetNumber = FirstOffsetNumber;
     offsetNumber < limit;  /* limit is maxoff+1 */
     offsetNumber++)
{
    itemId = PageGetItemId(page, offsetNumber);

    /*
     * We check for no storage as well, just to be paranoid;
     * unused items should never have storage.  Assert() that the
     * invariant is respected too.
     */
    Assert(ItemIdIsUsed(itemId) || !ItemIdHasStorage(itemId));

    if (!ItemIdIsUsed(itemId) && !ItemIdHasStorage(itemId))
        break;
}

src/backend/storage/page/bufpage.c, lines 263–278

Row 1002 took line pointer 1, the first odd row deleted from block 5. Row 1005 took 3.

The map is allowed to be wrong

After those six rows the heap and the map disagree:

SELECT b AS blk, lower, upper, upper - lower - 4 AS free, flags
FROM generate_series(0, pg_relation_size('cards') / 8192 - 1) AS b,
     page_header(get_raw_page('cards', b));
 blk | lower | upper | free | flags 
-----+-------+-------+------+-------
   0 |   160 |   304 |  140 |     4
   1 |   160 |   304 |  140 |     4
   2 |    32 |  7728 | 7692 |     0
   3 |   160 |   304 |  140 |     4
   4 |   160 |   304 |  140 |     4
   5 |   160 |  3784 | 3620 |     1
   6 |   160 |   304 |  140 |     4
   7 |   120 |  2624 | 2500 |     0
(8 rows)

SELECT fsm_page_contents(get_raw_page('cards', 'fsm', 2));
 fsm_page_contents 
-------------------
 0: 255           +
 1: 255           +
 3: 255           +
 7: 255           +
 15: 255          +
 31: 255          +
 63: 255          +
 127: 255         +
 255: 255         +
 511: 255         +
 1023: 255        +
 1024: 127        +
 2047: 4          +
 2048: 255        +
 2049: 127        +
 2050: 92         +
 4095: 4          +
 4096: 4          +
 4097: 255        +
 4098: 4          +
 4099: 4          +
 4100: 127        +
 4101: 4          +
 4102: 92         +
 fp_next_slot: 8  +
 
(1 row)

Block 2 has 7692 bytes and the map still says 255, which promises 8160. Block 7 has 2500 and the map says 92 (2944). No INSERT here updated the map: each found room on the page it was offered. Between vacuums the map learns that a page has less than it said only when an INSERT is turned away from it, and that INSERT corrects the leaf, as at row 35 above. Saying too much costs one wasted visit; saying too little would hide the page until the next VACUUM. VACUUM is the main writer that raises values. In PostgreSQL 19, pruning while reading a page also records its free space when it makes the page all-visible, because VACUUM may skip all-visible pages later:

/*
 * If this prune newly set the page all-visible, VACUUM may later
 * skip the page and not update the free space map (FSM) for it.
 * Keep the FSM from going stale by recording it now. We do not
 * want to update the freespace map otherwise, to reserve
 * freespace on this page for HOT updates.
 */
if (presult.newly_all_visible)
{
    record_free_space = true;
    freespace = PageGetHeapFreeSpace(page);
}

src/backend/access/heap/pruneheap.c, lines 389–400

tinypg does not model this.

Being a hint also decides how the map is stored. It is not WAL-logged as its own kind of record. A change to a node marks the buffer dirty the way a hint bit does, with MarkBufferDirtyHint(), and that writes a full-page image to the WAL when the change is the first since the last checkpoint and data checksums (or wal_log_hints) are on:

/*
 * If we need to protect hint bit updates from torn writes, WAL-log a
 * full page image of the page. This full page image is only necessary
 * if the hint bit update is the first change to the page since the
 * last checkpoint.
 *
 * We don't check full_page_writes here because that logic is included
 * when we call XLogInsert() since the value changes dynamically.
 */
if (XLogHintBitIsNeeded() && (lockstate & BM_PERMANENT))

src/backend/storage/buffer/bufmgr.c, lines 5751–5760

A move of fp_next_slot does not even mark the page dirty; it reaches the disk only if something else does.

This server has checksums on, and the WAL shows one full-page image per map page, each page’s pd_lsn pointing at the end of its own:

SHOW data_checksums;
 data_checksums 
----------------
 on
(1 row)

SELECT end_lsn, record_type, relblocknumber AS fsm_block, block_fpi_length
FROM pg_get_wal_block_info('0/094598C8', pg_current_wal_insert_lsn())
WHERE relfilenode = pg_relation_filenode('cards') AND relforknumber = 1
ORDER BY end_lsn;
  end_lsn   | record_type  | fsm_block | block_fpi_length 
------------+--------------+-----------+------------------
 0/094759E8 | FPI_FOR_HINT |         2 |             8192
 0/09489208 | FPI_FOR_HINT |         1 |             8192
 0/0948B258 | FPI_FOR_HINT |         0 |             8192
(3 rows)

SELECT b AS fsm_block, lsn FROM generate_series(0, 2) AS b,
     page_header(get_raw_page('cards', 'fsm', b));
 fsm_block |    lsn     
-----------+------------
         0 | 0/0948B258
         1 | 0/09489208
         2 | 0/094759E8
(3 rows)

Block 2 got its image when the INSERT first wrote it (it is the only map page with an LSN after the INSERT; the comparison further down shows four bytes of pd_lsn differing on one page); blocks 1 and 0 got theirs when VACUUM first changed them. Later changes, every move of fp_next_slot included, wrote no WAL. After a crash the map may be older than the table, and readers are ready for that: a search that reaches a block past the end of the table clears the leaf and starts again.

tinypg: fsm.py

tinypg/fsm.py is the map: categories, a page’s tree, the depth-first page numbering, the search from the root, and VACUUM’s half (record() and vacuum_range()). Moving right with wrap-around is the C code’s bit trick: a node x with x + 1 a power of two is the first node of a level.

def rightneighbor(x):
    """The next node to the right on the same level, wrapping around."""
    x += 1
    if ((x + 1) & x) == 0:        # stepped onto the next level's first node
        x = parentof(x)
    return x

tinypg/fsm.py, lines 76–81

HeapFile now picks a page the way RelationGetBufferForTuple() does, with a target block per session (new_session() forgets it, as a new backend would):

    def page_for_tuple(self, length):
        """RelationGetBufferForTuple(): a block with room for the tuple.

        First the page this session last inserted into; with none, ask the
        free space map; if it knows of nothing, try the last page. A page
        that turns out too full is recorded in the map with what it really
        has, and the map is asked again. When it has nothing, add a page.
        (fillfactor is left out: tinypg's tables keep no space free.)
        """
        need = maxalign(length)
        if need > MAX_HEAP_TUPLE_SIZE:
            raise ValueError(f"row is too big: size {need}, maximum size {MAX_HEAP_TUPLE_SIZE}")
        target = self.target_block
        if target is None:
            target = self.fsm.get_page_with_free_space(need)
        if target is None and self.nblocks() > 0:
            target = self.nblocks() - 1
        while target is not None:
            page = self.read_page(target)
            free = page.heap_free_space()
            if need <= free:
                self.target_block = target
                return target, page
            target = self.fsm.record_and_get(target, free, need)
        blkno = self.nblocks()                  # RelationAddBlocks(): one new page
        self.write_page(blkno, Page())
        self.target_block = blkno
        return blkno, self.read_page(blkno)

tinypg/heapfile.py, lines 67–94

    def record_and_get(self, old_page, old_avail, needed):
        """RecordAndGetPageWithFreeSpace(): note that old_page has only
        old_avail bytes, and find another page; one on the same bottom FSM
        page is preferred, searched while it is at hand."""
        addr, slot = get_location(old_page)
        search_cat = needed_to_cat(needed)
        search_slot = self.set_and_search(addr, slot, avail_to_cat(old_avail), search_cat)
        if search_slot != -1:
            blk = get_heap_blk(addr, search_slot)
            if blk < self.heap_nblocks():
                return blk
        return self.search(search_cat)

tinypg/fsm.py, lines 290–301

The figure replays the recording. The bottom page is drawn as its tree over heap blocks 0 to 7, with node 0 standing for the chain above node 511.

The free space map through the recording, from python3 -m tinypg trace-fsm tests/fixtures/pg19_fsm.json (tag lesson-04). Outlined nodes are the last search’s path on the bottom page; the filled leaf and heap block are where the row went. The bottom row compares that block with the one PostgreSQL chose.

The comparison replays the 260-row INSERT and checks the heap and the map, then the six single INSERTs, each in a new session, checking the block each row went to and the map after it. tinypg has no VACUUM yet, so for that step it takes the heap pages the server’s VACUUM left and does only the map’s part: record each page’s free space, then update the upper levels.

$ python3 -m tinypg compare tests/fixtures/pg19_fsm.json
one INSERT of 260 rows: PostgreSQL wrote 8 heap pages and 3 FSM pages, tinypg 8 and 3
block 0: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 0000000098394709, tinypg 0000000000000000; 4 bytes differ
block 1: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 00000000107d4709, tinypg 0000000000000000; 4 bytes differ
block 2: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 0000000050a04709, tinypg 0000000000000000; 4 bytes differ
block 3: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 0000000078c34709, tinypg 0000000000000000; 4 bytes differ
block 4: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 00000000a0e64709, tinypg 0000000000000000; 4 bytes differ
block 5: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 00000000c8094809, tinypg 0000000000000000; 4 bytes differ
block 6: 34 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 00000000f02c4809, tinypg 0000000000000000; 4 bytes differ
block 7: 22 tuples, 8188 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 00000000b8434809, tinypg 0000000000000000; 4 bytes differ
  FSM: PostgreSQL 3 pages, tinypg 3; 24572 of 24576 bytes identical, all but pd_lsn
DELETE and VACUUM: tinypg records the free space of the server's vacuumed pages, then updates the upper levels
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
new session, INSERT (1001, ...): PostgreSQL chose (2,1), tinypg (2,1) (same)
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
new session, INSERT (1002, ...): PostgreSQL chose (5,1), tinypg (5,1) (same)
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
new session, INSERT (1003, ...): PostgreSQL chose (7,23), tinypg (7,23) (same)
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
new session, INSERT (1004, ...): PostgreSQL chose (2,2), tinypg (2,2) (same)
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
new session, INSERT (1005, ...): PostgreSQL chose (5,3), tinypg (5,3) (same)
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
new session, INSERT (1006, ...): PostgreSQL chose (7,24), tinypg (7,24) (same)
  FSM: PostgreSQL 3 pages, tinypg 3; 24564 of 24576 bytes identical, all but pd_lsn
the heap after the one-row INSERTs:
block 0: 34 tuples, 8192 of 8192 bytes identical
block 1: 34 tuples, 8192 of 8192 bytes identical
block 2: 2 tuples, 8190 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 0000000008ba4809, tinypg 0000000058704809; 2 bytes differ
block 3: 34 tuples, 8192 of 8192 bytes identical
block 4: 34 tuples, 8192 of 8192 bytes identical
block 5: 34 tuples, 8191 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 0000000038bb4809, tinypg 0000000038714809; 1 bytes differ
block 6: 34 tuples, 8192 of 8192 bytes identical
block 7: 24 tuples, 8190 of 8192 bytes identical
  pd_lsn (bytes 0-7): postgres 0000000068bc4809, tinypg 00000000b8714809; 2 bytes differ

Every row lands on the same block and line pointer, and the map pages are identical except pd_lsn. In the last part, fewer bytes of pd_lsn differ: tinypg’s pages there are the server’s VACUUM output, LSN included, and only the server’s six INSERTs moved them on. tinypg also reads the server’s own _fsm file, after a CHECKPOINT has written it:

$ python3 -m tinypg fsm "$PGDATA/base/16420/40577_fsm"
block 0 (level 2): 0: 255, 1: 255, 3: 255, 7: 255, 15: 255, 31: 255, 63: 255, 127: 255, 255: 255, 511: 255, 1023: 255, 2047: 255, 4095: 255; fp_next_slot: 0
block 1 (level 1): 0: 255, 1: 255, 3: 255, 7: 255, 15: 255, 31: 255, 63: 255, 127: 255, 255: 255, 511: 255, 1023: 255, 2047: 255, 4095: 255; fp_next_slot: 0
block 2 (level 0): 0: 255, 1: 255, 3: 255, 7: 255, 15: 255, 31: 255, 63: 255, 127: 255, 255: 255, 511: 255, 1023: 255, 1024: 127, 2047: 4, 2048: 255, 2049: 127, 2050: 92, 4095: 4, 4096: 4, 4097: 255, 4098: 4, 4099: 4, 4100: 127, 4101: 4, 4102: 92; fp_next_slot: 8

What tinypg leaves out: locking, which is where the round robin pays off; extending by more than one page when other backends are waiting, and the bulk-insert state COPY uses, which keeps its new pages out of the map; fillfactor; truncating the map with its table; the pruning that records free space; and the repairs a search makes when a page’s inner nodes disagree with its leaves, which tinypg reports as an error instead.

You can see the map’s size in the browser too. The box runs in PGlite (PostgreSQL 19.0 compiled to WebAssembly), on a cards table filled by the same INSERT:

SELECT pg_relation_size('cards') / 8192 AS heap_pages,
       pg_relation_size('cards', 'fsm') / 8192 AS fsm_pages;
 heap_pages | fsm_pages 
------------+-----------
          8 |         3
(1 row)

Try it yourself

With a PostgreSQL 19 server and pageinspect, start from cards after the 260-row INSERT, or after the DELETE and VACUUM, as the question says.

  1. Right after the INSERT, before any DELETE, a new session inserts one more 232-byte row. Where does it go?

    Answer

    To (7,23), the last page. The new backend has no target block, so it asks the map, and the root page’s node 0 is 0: GetPageWithFreeSpace() gives up without looking further. Then RelationGetBufferForTuple() tries the last page, which has 2972 bytes. The map is unchanged. tinypg, with a new session, puts it at (7, 23) too.

  2. After the DELETE and VACUUM, a new session inserts 40 rows in one statement. Where do they go, and what is in the map afterwards?

    Answer

    Rows 1 to 34 to (2,1)–(2,34): the first search returns block 2 and sets fp_next_slot to 3, and block 2 stays the target. Row 35 does not fit (140 bytes left), so RecordAndGetPageWithFreeSpace() sets block 2’s leaf to 4 and searches the same bottom page from slot 3: block 5. Rows 35 to 40 take its unused line pointers, (5,1), (5,3), … (5,11). The bottom page then has leaf 4097 = 4, node 2048 = 4, and fp_next_slot 6; node 0 is 127. Checked on the server and with tinypg.

  3. A table like cards with 170,000 rows has 5000 pages. How many pages does its map have, and which block holds heap block 4999’s byte?

    Answer

    Four. Heap blocks 0 to 4068 are on bottom page 0 (block 2); 4069 to 4999 are on bottom page 1, which is stored right after it, as block 3. Heap block 4999 is slot 930 there. The server’s map has four pages already after the INSERT, before VACUUM, because the INSERT recorded pages beyond 4068 as they filled. tinypg’s get_location(4999) gives page (0, 1), slot 930, and logical_to_physical block 3.

  4. Why does the map store 255 for a page with 8164 bytes, but 254 for one with 8159?

    Answer

    8159 / 32 is 254.97, rounded down to 254. 255 is only for pages that can take a tuple of MaxHeapTupleSize, 8160 bytes. A request for 8160 bytes asks for category 255, and a page has 8160 bytes free only if it has no tuples at all.

The tinypg side, once the repository is public:

git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-04
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_fsm.json
python3 -m tinypg trace-fsm tests/fixtures/pg19_fsm.json

To record your own: tools/record_fsm.py --out DIR with the usual PGHOST, PGPORT, PGUSER and PGDATABASE. It drops and recreates the table cards, and creates the pg_walinspect extension if it is missing.

Sources

All PostgreSQL code is quoted from tag REL_19_0 (commit 5c839a2a08b9), with tabs expanded to four spaces and the common indentation removed.

ls postgres-internals/

Storage

Buffers and durability

  • 05 Shared buffers: a page cache with pins and locks plannedThe buffer table, buffer descriptors, pins, content locks, and clock-sweep eviction.
  • 06 The write-ahead log: records and LSNs plannedWAL record layout, pd_lsn, and the rule that a page may not reach disk before its log does.
  • 07 Checkpoints, full-page writes and checksums plannedWhat a checkpoint guarantees, why the first change after one logs the whole page, and how pd_checksum is computed.
  • 08 Crash recovery: replaying the log plannedStarting from the last checkpoint's redo point and replaying records whose LSN is newer than the page's.

MVCC

  • 09 Transaction IDs and the commit log plannedAssigning xids, and pg_xact: two bits of commit status per transaction.
  • 10 xmin, xmax and the life of a row version plannedWhat UPDATE and DELETE really write, and following ctid chains to the newest version.
  • 11 Snapshots: what a transaction can see plannedxmin, xmax and the in-progress list, and when READ COMMITTED and REPEATABLE READ take them.
  • 12 Visibility rules and hint bits plannedHeapTupleSatisfiesMVCC case by case, and why reading a row can write to its page.
  • 13 HOT updates and page pruning plannedHeap-only tuples, redirect line pointers, and cleaning a page while reading it.
  • 14 VACUUM: removing dead tuples plannedScanning the heap, cleaning indexes, and marking line pointers unused.
  • 15 The visibility map plannedThe _vm fork's all-visible and all-frozen bits, and what index-only scans and VACUUM get from them.
  • 16 Freezing and transaction ID wraparound plannedWhy 32-bit xids wrap around, what freezing writes, and multixacts.

Indexes

  • 17 B-tree pages and the Lehman–Yao tree plannedSpecial space, high keys and right links: a B-tree you can search while it changes.
  • 18 B-tree insertion and page splits plannedDescending the tree, choosing a split point, and finishing a split in the parent.
  • 19 Deduplication and bottom-up deletion plannedPosting lists for duplicate keys, and deleting old versions before a page has to split.
  • 20 Hash indexes plannedBuckets, overflow pages and linear-hashing splits.
  • 21 GIN and GiST, briefly plannedAn inverted index and a balanced tree of predicates: what each stores and when each fits.

Queries

  • 22 From text to parse tree plannedThe grammar, the raw parse tree, and why parsing needs no catalog.
  • 23 Analysis and rewriting plannedResolving names against the catalog, the Query tree, and the rewriter's views and rules.
  • 24 The planner: paths and the cost model plannedseq_page_cost, random_page_cost and cpu_tuple_cost, and how the cheapest path wins.
  • 25 Statistics and selectivity plannedWhat ANALYZE samples, most common values, histograms, and estimating a WHERE clause.
  • 26 Join algorithms and join order plannedNested loop, hash and merge joins, and searching the join orders.
  • 27 The executor: Volcano-style iterators plannedPlan nodes that each return one row per call, from a sequential scan up to a sort.

Concurrency and the server

  • 28 Locks: heavyweight, row-level and lightweight plannedThe lock manager, row locks stored in xmax, LWLocks and spinlocks, and deadlock detection.
  • 29 Processes and shared memory plannedThe postmaster, one backend per connection, the background workers, and what they share.
  • 30 Streaming replication plannedShipping WAL to a standby, replaying it there, and replication slots.