Room 4 · Transaction groups

When does my write reach the disk?

A write usually reaches the disk a few seconds after the program that made it has moved on. ZFS never overwrites a block that the pool still uses. Each change is written to a new block, the block that points to it is rewritten too, and so on up to the uberblock, the root record from which ZFS finds everything else in the pool. Doing all that for every single write, with a flush of each disk's cache every time, would be very slow.

So ZFS gathers changes in memory into a numbered batch called a transaction group, or txg. Every change joins the txg that is open at that moment. Every five seconds, or sooner when a lot of changed data is waiting or a sync is asked for, ZFS closes the open txg and opens the next one at once, so programs keep writing. It waits for the changes already under way in the closed txg to finish, writes the whole txg to the disks, and ends by writing a new uberblock. Writing the uberblock commits the txg, and from then on the pool starts from it.

After a power cut, the pool comes back at the last committed txg, in a consistent state. Changes in txgs that were not committed yet are lost, usually a few seconds' worth, unless they were also written to the ZIL. A program that cannot lose its changes, such as a database, asks for them to be on disk with fsync. ZFS then writes them to its intent log, the ZIL, a log on disk that it replays when the pool is next imported, without waiting for the txg.

1 Three txgs, one per stage

Each card is a txg. Two writes are under way in txg 41, drawn as dots on the CPUs they run on. Press Next event to move one step at a time. The outlined part of the figure is what that step changed. Left alone, the writes end, and at t = 5 s the five-second timeout runs out and the sync thread asks for the open txg. Txg 41 moves to the middle while txg 42 opens behind it to take the new writes. Its writes have already ended, so it goes straight on to the right, where it is written in three passes. The line On disk changes when its uberblock is written.

Press Reset, then press zpool sync right away. The sync thread does not wait for the five seconds, and txg 41 stays in the middle until its second write ends, at 1.2 s. zpool sync waits for txg 43, so the empty txgs 42 and 43 are synced after it, and they write no uberblock. Writes you add join whichever txg is open. Free a large file while a txg is being written: ZFS asks for the open txg to be closed right away, so that a txg is not filled with frees alone. All three stages are then busy, which is the most the code allows. Play runs the events one after another, in slowed simulated time.

Text version of this figure
  1. Every change to the pool joins a numbered transaction group, a txg. At most three txgs are active at once, one in each stage: open, quiescing, syncing.
  2. A write joins the open txg and stays counted in it, on the CPU it runs on, until it is done.
  3. The sync thread sleeps until 5 seconds have passed since the last sync began, or until someone asks for a sync: zpool sync, or a txg that already holds a lot of changed data.
  4. It then asks the quiesce thread for the open txg. The quiesce thread closes it, opens the next txg at once so that new writes do not wait, and waits until no write is under way in the closed txg. Then it hands the txg over.
  5. The sync thread writes the txg in passes. The first writes the changed data and the metadata above it. Writing takes space, which changes the space maps, so another pass writes those, until a pass changes nothing new. Then the disks are flushed and the new uberblock is written: writing it commits the txg. A txg in which nothing changed usually writes nothing.
  6. Usually the next txg stays open while one syncs. Freeing a large file, once its frees reach a threshold in the open txg, asks for that txg to be closed at once, so that a txg is not filled with frees alone; then all three stages are busy. There is never more than one txg per stage.

In the code

Two kernel threads per pool move txgs along, in txg.c. Open a Source note to see the lines, taken from release zfs-2.4.4.

Joining the open txg

A write first joins a txg with txg_hold_open. It reads the number of the open txg and raises a count of writes in that txg. There is one count per CPU, so writers on different CPUs do not compete for one lock. When the transaction has made its change in memory, the count goes down again.

Source txg_hold_open, txg.c
txg_hold_open Excerpt of module/zfs/txg.c, lines 333–338, OpenZFS zfs-2.4.4. View on GitHub
	mutex_enter(&tc->tc_open_lock);
	txg = tx->tx_open_txg;

	mutex_enter(&tc->tc_lock);
	tc->tc_count[txg & TXG_MASK]++;
	mutex_exit(&tc->tc_lock);
  1. L333–L334 The lock of this CPU, then the open txg's number. dmu_tx_try_assign, under dmu_tx_assign, calls this for every transaction. To close a txg, the quiesce thread takes the lock of every CPU.
  2. L337 This CPU's count for the txg, in an array of 4 indexed by the txg's low two bits. One count per CPU, because a single one “would result in heavy lock contention”. txg_rele_to_sync lowers it when the transaction is done.

When the sync thread wakes up

The sync thread sleeps in a loop. It wakes when five seconds have passed since the last sync began, when someone asks for a txg to be synced (zpool sync, or a txg past the dirty-data threshold), or when a closed txg is ready for it. A running scrub, resilver or background free keeps it from sleeping at all.

Source txg_sync_thread, txg.c
txg_sync_thread Excerpt of module/zfs/txg.c, lines 542–553, OpenZFS zfs-2.4.4. View on GitHub
		timer = (delta >= timeout ? 0 : timeout - delta);
		while (!dsl_scan_active(dp->dp_scan) &&
		    !tx->tx_exiting && timer > 0 &&
		    tx->tx_synced_txg >= tx->tx_sync_txg_waiting &&
		    !txg_has_quiesced_to_sync(dp)) {
			dprintf("waiting; tx_synced=%llu waiting=%llu dp=%p\n",
			    (u_longlong_t)tx->tx_synced_txg,
			    (u_longlong_t)tx->tx_sync_txg_waiting, dp);
			txg_thread_wait(tx, &cpr, &tx->tx_sync_more_cv, timer);
			delta = ddi_get_lbolt() - start;
			timer = (delta > timeout ? 0 : timeout - delta);
		}
  1. L542 timer is the time left until five seconds after start, which is set when the last spa_sync began. The timeout is zfs_txg_timeout, 5 seconds.
  2. L543–L546 It sleeps while all of these hold: no scan is active (a scrub, a resilver, or a background free), the timer has not run out, nobody waits for a txg past the last synced one, and no quiesced txg is waiting.
  3. L545 zpool sync calls txg_wait_synced(dp, 0), which raises tx_sync_txg_waiting to the open txg plus 2. txg_kick raises it to the number of a txg whose dirty data has passed 20% of zfs_dirty_data_max; dsl_pool_dirty_space calls it.

Closing a txg without stopping the writers

The quiesce thread closes the open txg in txg_quiesce. It holds every CPU's lock for an instant, long enough to raise the open txg's number by one. From then on, new writes join the next txg.

Source txg_quiesce, the switch, txg.c
txg_quiesce Excerpt of module/zfs/txg.c, lines 398–402, OpenZFS zfs-2.4.4. View on GitHub
	for (c = 0; c < max_ncpus; c++)
		mutex_enter(&tx->tx_cpu[c].tc_open_lock);

	ASSERT(txg == tx->tx_open_txg);
	tx->tx_open_txg++;
  1. L398–L399 Every CPU's tc_open_lock, the lock txg_hold_open takes before it reads the open txg, and keeps until txg_rele_to_quiesce. No writer can be in the middle of joining the open txg.
  2. L402 The next txg is open. The locks are released right after, so writers do not wait for the old txg to drain.

Waiting for the writes under way

Writes that joined the old txg before the switch still have to finish. The quiesce thread waits until every CPU's count for that txg is back to zero. Then nothing can change the txg any more, and it is handed over to the sync thread.

Source txg_quiesce, the drain, txg.c
txg_quiesce Excerpt of module/zfs/txg.c, lines 422–428, OpenZFS zfs-2.4.4. View on GitHub
	for (c = 0; c < max_ncpus; c++) {
		tx_cpu_t *tc = &tx->tx_cpu[c];
		mutex_enter(&tc->tc_lock);
		while (tc->tc_count[g] != 0)
			cv_wait(&tc->tc_cv[g], &tc->tc_lock);
		mutex_exit(&tc->tc_lock);
	}
  1. L425–L426 It sleeps while this CPU still holds the txg. txg_rele_to_sync wakes it when the count reaches 0.
  2. L428 After the last CPU, the txg is quiesced. The quiesce thread hands it to the sync thread.

One txg per stage

The quiesce thread closes a txg only when someone asks, and only once the txg it closed last has been taken by the sync thread. That is why there is never more than one txg quiescing. Usually the sync thread asks when it is ready for more work, so the next txg stays open while one is written.

Source txg_quiesce_thread, txg.c
txg_quiesce_thread Excerpt of module/zfs/txg.c, lines 638–641, OpenZFS zfs-2.4.4. View on GitHub
		while (!tx->tx_exiting &&
		    (tx->tx_open_txg >= tx->tx_quiesce_txg_waiting ||
		    txg_has_quiesced_to_sync(dp)))
			txg_thread_wait(tx, &cpr, &tx->tx_quiesce_more_cv, 0);
  1. L639 Nobody has asked for a txg past the open one. The sync thread asks when it needs a txg. The other caller is txg_wait_open, which at this release dmu_free_long_range_impl calls, once the frees in the open txg reach a threshold, “to avoid filling up a TXG with just frees”.
  2. L640 The txg quiesced last is still waiting for the sync thread.

Writing until nothing changes

spa_sync writes the txg in passes. The first writes the changed data and the metadata above it. Writing takes space, and the space maps that record it are themselves metadata, so the next pass writes them, and so on. The loop ends when a pass leaves nothing new to write.

Source spa_sync_iterate_to_convergence, spa.c
spa_sync_iterate_to_convergence Excerpt of module/zfs/spa.c, lines 10749–10765, OpenZFS zfs-2.4.4. View on GitHub
		if (pass == 1 &&
		    BP_GET_LOGICAL_BIRTH(&spa->spa_uberblock.ub_rootbp) < txg &&
		    !dmu_objset_is_dirty(mos, txg)) {
			/*
			 * Nothing changed on the first pass, therefore this
			 * TXG is a no-op. Avoid syncing deferred frees, so
			 * that we can keep this TXG as a no-op.
			 */
			ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
			ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
			ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
			ASSERT(txg_list_empty(&dp->dp_early_sync_tasks, txg));
			break;
		}

		spa_sync_deferred_frees(spa, tx);
	} while (dmu_objset_is_dirty(mos, txg));
  1. L10749–L10761 After pass 1, if the root block pointer was not born in this txg and the MOS, the pool's own metadata, is clean, nothing changed: the txg is a no-op.
  2. L10765 Another pass while the MOS is dirty in this txg. Only the first pass writes user data. The later ones are kept small so the loop ends: from pass 2, a block written earlier in this txg is overwritten where it is.

The commit, or nothing at all

Once the passes are done, vdev_config_sync flushes the disks and writes the new uberblock. The room on the tree and the uberblock follows that write. A txg in which nothing changed stops here, before the flush: an idle pool goes through a txg every five seconds without writing to its disks.

Source vdev_config_sync, vdev_label.c
vdev_config_sync Excerpt of module/zfs/vdev_label.c, lines 2071–2077, OpenZFS zfs-2.4.4. View on GitHub
	if (ub->ub_txg < txg) {
		boolean_t changed = uberblock_update(ub, spa->spa_root_vdev,
		    txg, spa->spa_mmp.mmp_delay);

		if (!changed && list_is_empty(&spa->spa_config_dirty_list) &&
		    !spa_multihost(spa))
			return (0);
  1. L2072–L2073 The new uberblock takes this txg's number. changed is true if the root block pointer was born in this txg.
  2. L2075–L2077 Nothing changed, no vdev configuration is dirty, multihost protection is off: return before the flush and the label and uberblock writes. spa_sync calls it through spa_sync_rewrite_vdev_config after the passes.

What the figure leaves out

The figure runs the two threads' wait conditions as the code writes them, over the same variables. It draws 4 CPUs. Each write is one block, and the threshold that starts a sync early is scaled to 4 blocks (20% of a 20-block zfs_dirty_data_max). Time is slowed, and the length of a write or a pass is made up. It leaves out the write throttle (writers delayed as dirty data grows), the short wait of a writer while a txg closes, scrubs and resilvers, administrative tasks that run inside a sync, the ZIL, and pool suspension. A real large free asks for a new txg only once its frees reach a threshold, and the uberblock is written to several labels on several disks. Pass sizes are illustrative: a txg with data always takes three passes here.