Room 9 · Metaslabs and space maps

How does ZFS know which space is free?

ZFS never overwrites a block in place. Every write needs new free space, and every change frees the old copy of a block unless a snapshot still holds it, so the pool allocates and frees space all the time and must still know what is free after a reboot. The obvious record is a bitmap with one bit per sector of the pool. On a pool of 16 TiB with 4 KiB sectors that bitmap is 512 MiB, and keeping it on disk would mean rewriting it in place on every change, which is what ZFS avoids everywhere else.

Instead, ZFS cuts each top-level vdev (a disk, a mirror or a RAID-Z group) into a few hundred regions called metaslabs, and writes into a few of them at a time, chosen for their large free segments. In memory, the free space of a metaslab is a sorted tree of free ranges, so finding room for a block is a short search. On disk, each metaslab has a space map, a log that ZFS only appends to. When a transaction group (the batch of changes ZFS commits every few seconds) is written out, ZFS appends one entry for each range it allocated and one for each range it freed. When ZFS needs a metaslab again, after a reboot for example, it loads it: it rebuilds the tree by replaying the log from the start.

Space freed in one transaction group can be used again only two groups later. That way, if the pool has to go back to a slightly older state, the blocks that state points to are still intact. Because the log only grows, ZFS rewrites it from the tree once it is about twice the size the free tree would take if written out alone. This is called condensing.

1 Write, delete, sync

The figure shows a vdev of 8 GiB cut into 16 metaslabs of 512 MiB, with metaslab 2 drawn large below it. Two files are already there: A, 32 MiB, and B, 4 MiB. The tape is the metaslab’s space map on disk, one 64-bit word per box; select a box to see its bits. After each action, the line under the buttons says what happened, and everything the action changed is outlined.

Delete A. Its range turns red: it is freed in the open transaction group but still allocated. Sync, and a FREE entry joins the tape while A turns green, waiting. Two more syncs make it free again.

Then write 160 MiB. Its 128 KiB blocks land after B, not in A’s hole, because the allocator searches forward from a cursor. A run that long takes a two-word entry on the tape. Load rebuilds the free tree from the tape alone and finds the same tree.

Condense is refused while the map is short. Rewrite db once: db is a 64 MiB file whose blocks are rewritten at random, and the rewriting stops by itself when the test says yes. Then condense.

Open txg 12. Free: 476 MiB in 1 segment. Space map: 32 bytes, 2 entries. Condense: no.

Metaslab 2 is the active metaslab: every block goes there while its largest free segment can hold the block. ZFS ranks the metaslabs of a vdev by weight, the size class of their largest free segments and their count. When the active one is too small, ZFS activates the first in rank whose largest free segment fits.

  • free (ms_allocatable)
  • allocated, on the map
  • allocated in the open txg
  • freed in the open txg
  • freed, deferred
  • dynamic-fit cursor
  • range of the selected tape entry
  • changed by the last action

In memory

  • ms_allocatable 476 MiB, 1 segment
  • ms_allocating[0] empty
  • ms_freeing empty
  • ms_defer[] empty
  • ms_lbas[17] 0x42400000 where the next 128 KiB block is looked for

Files

  • A 32 MiB · 1 extent · on the map
  • B 4 MiB · 1 extent · on the map

On disk: the space map of metaslab 2

smp_length 32 bytes (4 words, in 1 block of 16 KiB) · smp_alloc 36 MiB

  1. txg 10 ALLOC
  2. ALLOC 32 MiB
  3. txg 11 ALLOC
  4. ALLOC 4 MiB

ALLOC 4 MiB, at word 3, 1 word

word 3 0x00000000200003FF

prefixbits 63 (1)0offsetbits 62–16 (47)0x2000typebits 15 (1)0run − 1bits 14–0 (15)0x3FF

ALLOC: offset 0x2000, in units of 4 KiB from the start of the metaslab (32 MiB, vdev offset 0x42000000), run 1,024 units (4 MiB). The run fits in 15 bits (at most 32,768 units, 128 MiB): one word.

Condense?

  • no At least twice the optimal size, 24 bytes (zfs_condense_pct 200): 32 bytes against 48
  • no Longer than four blocks of 16 KiB (zfs_metaslab_condense_block_threshold): 32 bytes against 65,536

Verdict: no. The map keeps growing.

Text version of this figure

A vdev of 16 metaslabs; metaslab 2 starts at 0x40000000. Open txg: 12.

  • Free tree (ms_allocatable), 476 MiB: [0x42400000, 0x60000000).
  • Open txg 12: allocated none; freed none.
  • Nothing deferred.
  • Files: A (32 MiB: [0x40000000, 0x42000000)); B (4 MiB: [0x42000000, 0x42400000)).
  • Space map: smp_length 32 bytes (4 words, in 1 block of 16 KiB) · smp_alloc 36 MiB. Last words: 0x800400000000000A (txg 10 ALLOC, a debug word at word 0: ALLOC entries follow); 0x0000000000001FFF (ALLOC 32 MiB, at word 1, 1 word); 0x800400000000000B (txg 11 ALLOC, a debug word at word 2: ALLOC entries follow); 0x00000000200003FF (ALLOC 4 MiB, at word 3, 1 word).

Open txg 12. Free: 476 MiB in 1 segment. Space map: 32 bytes, 2 entries. Condense: no.

In the code

The figure follows eight places in metaslab.c and space_map.c. Open a Source note to see the lines, taken from release zfs-2.4.4.

Choosing a metaslab

Each vdev keeps its metaslabs in a tree sorted by weight. By default the weight records the size class of the metaslab’s largest free segments, and how many segments of that class it has. An allocator keeps writing to its active metaslab. When that metaslab cannot hold a block, the allocator walks the tree from the top and activates the first metaslab whose largest free segment is big enough.

Source metaslab_compare, metaslab.c
metaslab_compare Excerpt of module/zfs/metaslab.c, lines 947–960, OpenZFS zfs-2.4.4. View on GitHub
	/*
	 * Sort inactive metaslabs first, then primaries, then secondaries. When
	 * selecting a metaslab to allocate from, an allocator first tries its
	 * primary, then secondary active metaslab. If it doesn't have active
	 * metaslabs, or can't allocate from them, it searches for an inactive
	 * metaslab to activate. If it can't find a suitable one, it will steal
	 * a primary or secondary metaslab from another allocator.
	 */
	if (sort1 < sort2)
		return (-1);
	if (sort1 > sort2)
		return (1);

	int cmp = TREE_CMP(m2->ms_weight, m1->ms_weight);
  1. L947–L954 The policy, in the comment: the primary active metaslab first, then the secondary, then an inactive one to activate.
  2. L955–L958 Inactive metaslabs sort before active ones, so the search for a new one walks them first.
  3. L960 Then the higher weight first. It is segment-based by default: metaslab_segment_weight encodes the largest size class of free segments the metaslab has, and their count. find_valid_metaslab skips a metaslab whose largest free segment is too small.

Choosing a place in the metaslab

The default allocator, dynamic fit, keeps a cursor for each power-of-two block size and searches forward from it for the first free segment that fits. Space freed behind the cursor is therefore not reused right away, and blocks written one after another land side by side. When nothing fits after the cursor, or less than 4% of the metaslab is free, or no free segment is 128 KiB or larger, it takes the smallest free segment that fits instead.

Source metaslab_df_alloc, metaslab.c
metaslab_df_alloc Excerpt of module/zfs/metaslab.c, lines 1917–1924, OpenZFS zfs-2.4.4. View on GitHub
	if (metaslab_largest_allocatable(msp) < metaslab_df_alloc_threshold ||
	    free_pct < metaslab_df_free_pct) {
		align = size & -size;
		cursor = &msp->ms_lbas[highbit64(align) - 1];
		offset = -1;
	} else {
		offset = metaslab_block_picker(rt, cursor, size, max_size,
		    metaslab_df_max_search, found_size);
  1. L1917–L1921 No free segment of 128 KiB, or under 4% free: no forward search, and the fallback takes the smallest free segment at least as large as the request. It also runs when the forward search finds nothing.
  2. L1923–L1924 Otherwise metaslab_block_picker: the first free segment at or after the cursor that fits, searched at most 16 MiB past the first candidate and always at least 100 segments. The cursor moves to the end of what was taken.

Taking the block

metaslab_block_alloc moves the block’s range from the free tree to a tree that belongs to the open transaction group. Nothing is written to the space map yet: the map changes only when that group is written out.

Source metaslab_block_alloc, metaslab.c
metaslab_block_alloc Excerpt of module/zfs/metaslab.c, lines 4877–4884, OpenZFS zfs-2.4.4. View on GitHub
		zfs_range_tree_remove(rt, start, size);
		zfs_range_tree_clear(msp->ms_trim, start, size);

		if (zfs_range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
			vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);

		zfs_range_tree_add(msp->ms_allocating[txg & TXG_MASK], start,
		    size);
  1. L4877 The range leaves ms_allocatable, the free tree. No allocation comes from a metaslab whose map is being condensed.
  2. L4880–L4881 The first allocation of a txg in this metaslab marks it dirty, so that txg’s sync visits it.
  3. L4883–L4884 The range goes into ms_allocating for this txg. Adjacent ranges merge, so a file written in one txg is one range, and one entry on the map.

Appending to the map

When the transaction group is written out, metaslab_sync appends its allocations, then its frees, to the metaslab’s space map. Each entry holds an offset and a length in one 64-bit word, or in two when the range is longer than 32,768 sectors (128 MiB here).

Source metaslab_sync, metaslab.c
metaslab_sync Excerpt of module/zfs/metaslab.c, lines 4400–4403, OpenZFS zfs-2.4.4. View on GitHub
		space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
		    SM_NO_VDEVID, tx);
		space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
		    SM_NO_VDEVID, tx);
  1. L4400–L4401 The txg’s allocations as ALLOC entries, after a debug word that records the txg. An entry takes two words when its run does not fit in 15 bits; the words are written here. A metaslab with no change in the txg is not visited.
  2. L4402–L4403 Then the txg’s frees as FREE entries. Nothing already on disk is rewritten.

Two transaction groups of grace

At the end of each sync, the space freed two transaction groups earlier goes back to the free tree, and the frees of this group take its place. A comment in metaslab_impl.h calls this a safety net for rolling back to an older uberblock, the root record the pool reads first.

Source metaslab_sync_done, metaslab.c
metaslab_sync_done Excerpt of module/zfs/metaslab.c, lines 4630–4633, OpenZFS zfs-2.4.4. View on GitHub
	zfs_range_tree_vacate(*defer_tree,
	    msp->ms_loaded ? zfs_range_tree_add : NULL, msp->ms_allocatable);
	if (defer_allowed) {
		zfs_range_tree_swap(&msp->ms_freed, defer_tree);
  1. L4630–L4631 The deferred tree, ms_defer[txg % TXG_DEFER_SIZE], goes back into the free tree. TXG_DEFER_SIZE is 2, “a safety net for uberblock rollback”.
  2. L4632–L4633 This txg’s frees take its place. The one exception: when the pool is almost full, or a vdev is being removed or expanded, they go straight back to the free tree.

Replaying the map

Loading a metaslab starts from a tree that holds the whole metaslab and replays the map in order. A FREE entry adds its range, an ALLOC entry removes it. What remains still counts the frees that are waiting out their two transaction groups as free, so metaslab_load removes them afterwards.

Source space_map_load_callback, space_map.c
space_map_load_callback Excerpt of module/zfs/space_map.c, lines 405–413, OpenZFS zfs-2.4.4. View on GitHub
	if (sme->sme_type == smla->smla_type) {
		VERIFY3U(zfs_range_tree_space(smla->smla_rt) + sme->sme_run, <=,
		    smla->smla_sm->sm_size);
		zfs_range_tree_add(smla->smla_rt, sme->sme_offset,
		    sme->sme_run);
	} else {
		zfs_range_tree_remove(smla->smla_rt, sme->sme_offset,
		    sme->sme_run);
	}
  1. L405–L409 When free space is loaded, the range of a FREE entry is added to the tree, which starts as the whole metaslab.
  2. L410–L413 The range of an ALLOC entry is removed. metaslab_load replays up to the length at the last sync, then removes the deferred trees.

Deciding to condense

In the first pass of each sync, a loaded metaslab with changes asks metaslab_should_condense whether its map has grown too long. The function compares the map’s length with an estimate of the free tree written alone.

Source metaslab_should_condense, metaslab.c
metaslab_should_condense Excerpt of module/zfs/metaslab.c, lines 3855–3861, OpenZFS zfs-2.4.4. View on GitHub
	uint64_t record_size = MAX(sm->sm_blksz, vdev_blocksize);
	uint64_t object_size = space_map_length(sm);
	uint64_t optimal_size = space_map_estimate_optimal_size(sm,
	    msp->ms_allocatable, SM_NO_VDEVID);

	return (object_size >= (optimal_size * zfs_condense_pct / 100) &&
	    object_size > zfs_metaslab_condense_block_threshold * record_size);
  1. L3855 A record is the larger of the map’s block size, 16 KiB here, and a sector.
  2. L3857–L3858 The size of the free tree written alone, estimated from the sizes of its segments.
  3. L3860–L3861 Condense when the map is at least 200% of that and longer than 4 records, 64 KiB here. metaslab_sync asks before it appends.

Rewriting the map short

metaslab_condense empties the map and writes it again from the tree: one ALLOC entry for the whole metaslab, then one FREE entry for each free segment. Replaying the short map gives the same tree as replaying the long one.

Source metaslab_condense, metaslab.c
metaslab_condense Excerpt of module/zfs/metaslab.c, lines 4009–4012, OpenZFS zfs-2.4.4. View on GitHub
	zfs_range_tree_add(tmp_tree, msp->ms_start, msp->ms_size);
	space_map_write(sm, tmp_tree, SM_ALLOC, SM_NO_VDEVID, tx);
	space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
	space_map_write(sm, condense_tree, SM_FREE, SM_NO_VDEVID, tx);
  1. L4009–L4010 The map was truncated and the metaslab marked as condensing. First one ALLOC entry for the whole metaslab.
  2. L4011 One FREE entry per free segment.
  3. L4012 Then the deferred frees and the allocations of the txgs in flight, which are free as far as the old map knows. This txg’s own entries follow, as usual.

What the figure leaves out

The figure runs the functions above on one metaslab of one vdev, with 4 KiB sectors. Every block is 128 KiB, so there is one cursor, and one transaction group is in flight at a time, synced at once in one pass. Metaslab 2 stays the active metaslab: a write that does not fit is refused instead of moving to the next metaslab in rank, and the other fifteen are drawn empty. Allocation throttling, gang blocks, extra copies of metadata, checkpoints, trim and the histogram kept with each space map are left out. The rewrites stop just before a sync that would condense, so the condense can be watched, and Load is shown on a transaction group with nothing pending.

A pool created today also has the log space map feature. Each transaction group’s changes for every metaslab then go to one log for the whole pool, and in each transaction group only a few metaslabs write those changes to their own maps. Such a pool also uses map blocks of 128 KiB, so its condense threshold is higher than the figure’s 64 KiB. This saves writes when random rewrites free a little space in many metaslabs at once. The figure shows a metaslab’s own map written at every sync, because the entries are the same: the pool-wide log only delays and gathers them. The rest of the visit is in Transaction groups for when a group is written out, and in Snapshots and clones for when a block is actually freed.