Issue #3495 has been reported by marietto.
----------------------------------------
Bug #3495: HAMMER2: defects found while porting it to FreeBSD as a root file
system -- seven of them also look present in DragonFly
http://bugs.dragonflybsd.org/issues/3495
* Author: marietto
* Status: New
* Priority: Normal
* Target version: 6.6
* Start date: 2026-12-04
----------------------------------------
Hello,
I have ported HAMMER2 to FreeBSD 16-CURRENT (amd64) as a native root
file system, starting from Tomohiro Kusumi's freebsd_hammer2 v1.2.13:
kernel, mountroot, GEOM label, a new reader for the boot loader, fsck at
boot, boot environments as PFS snapshots, and makefs -t hammer2.
Over two weeks of testing, about thirty defects were found and fixed.
Most are specific to the FreeBSD port, but for the seven below the
corresponding DragonFly code is the same as ours before the fix. I
would like to ask whether you are already aware of them, whether some
are intended behaviour, and whether you would like the fixes.
Important caveat: I have NOT reproduced anything on DragonFly. All
statements about DragonFly come from reading master (commit
21db3295516e, 2026-12-03; sys/vfs/hammer2 has not changed since
2026-11-23), finding the same code paths. Line numbers below refer to
that commit. The fixes are separate commits on a public branch (links
at the end), each with the test that found the problem.
The on-disk format was not changed. A DragonFly 6.4.2 VM and the
FreeBSD port read and write each other's volumes, snapshots and bulkfree
included, with clean fsck_hammer2 on both sides and identical file
manifests (up to 125,119 entries).
How the problems were found
---------------------------
- A crash loop: a bhyve VM killed at a random point (every 5-60 s,
over a thousand kills on the final kernels) while it writes files as
write -> fsync -> rename -> fsync(dir), runs fsx, copies and removes
trees, and runs hammer2 bulkfree every few seconds. After every
kill, with the volumes not mounted, fsck_hammer2 -f checks ALL FOUR
volume header zones (not only the best one), then every confirmed
file is verified by sha256.
- pjdfstest, fsx and FreeBSD's stress2 for 24 hours each, a soak of
three buildworlds on a HAMMER2 root, KASAN, KMSAN, UBSan, WITNESS.
- A new HAMMER2 reader for the FreeBSD boot loader, compared with the
kernel on 61,420 files in all compression and check combinations,
and fuzzed with libFuzzer.
Some of these settings are much harsher than normal use: bulkfree every
few seconds, thousands of fsyncs, fsck of the non-best zones. Several
problems below damage only the OLDER volume roots, the ones the mount
code falls back to when the best header is unusable. In normal use
they would go unnoticed until a fallback is actually needed.
1. fsync does not make a newly created file durable
---------------------------------------------------
DragonFly: hammer2_vnops.c, hammer2_vop_fsync(). The comment at :253
says:
"NOTE! We are not in a flush transaction. The inode remains on
the sideq so the filesystem syncer can synchronize it to the
volume root."
Observed (FreeBSD port, same code): after fsync() had returned, 57 of
170 confirmed files were missing after the first crash, and fsck was
clean. The volume simply came back at the last periodic sync point.
fsync flushes the inode's chains, but nothing links them to a new
volume root, and new inodes are not even inserted in their directory
until the sync.
Our change (44039cf01): for MNT_WAIT fsync, also run the PFS sync down
to the volume header (hammer2_vfs_sync_pmp), so that fsync() returning
implies the data is reachable from a volume header. Since then, more
than 1.7 million verified markers in over a thousand crash cycles: none
missing.
The price, measured later: 4 KiB writes with an fsync after each one
run at 222 IOPS, against 545 on ZFS and 3,130 on UFS on the same disk
(4.5 ms per write + fsync).
Question: is the current DragonFly behaviour intentional, i.e. is fsync
not meant to guarantee durability across a crash until the syncer runs?
If durability is intended, a cheaper way than a full PFS sync would be
welcome.
2. A freemap block can be rewritten more than once per fchain flush,
overwriting the copy of the oldest volume root
--------------------------------------------------------------------
DragonFly:
- hammer2_disk.h:215-218: "There are FOUR volume roots representing
the last four synchronization points, so the freemap must be
consistent no matter which volume root is chosen by the mount code";
- each modification of a freemap block moves it to the next of
HAMMER2_NFREEMAPS (8) reserved copies, hammer2_freemap.c:92-109;
- hammer2_flush_core() scans a parent's children a second time
(hammer2_flush.c:607-620) when ONFLUSH was set again during the
first scan.
Observed: after 221 clean kills, fsck_hammer2 -f reported "Bad
HAMMER2_CHECK_FREEMAP" on freemap leaf 0, only in the OLDEST of the four
zones. On the media, three newer versions of that leaf had been written
after the last volume header; the third one went over the oldest
header's copy.
Measured with DTrace, no crash, 180 s: 89 of 704 fchain flushes wrote
some freemap block more than once, and a new reservation reached a
distance of 8 copies from the oldest header's copy 7 times.
Mechanism: hammer2_flush_recurse() releases the parent while it flushes
a child, and frontend allocations modify a leaf the flush has just
written. The flusher itself sets ONFLUSH on the grandparent when it
updates a parent's blockref, so the second scan runs on every flush that
writes a leaf. With w writes of a block per flush, a reservation can
reach 4w+1 copies past the oldest header's copy, so w must be 1. This
seems to date back to the removal of the sync_tid / delete-duplicate
deferral in 2014 (a71db85d9a).
Our fix (91e427df0): for FREEMAP and FREEMAP_NODE parents, scan the
children once. A child modified again after its write stays MODIFIED
for the next flush; ONFLUSH is then recomputed from the children without
writing. After the fix: 0 of 672 flushes wrote a block twice, maximum
distance 5.
3. bulkfree can let a block be reused while an older volume root still
references it
----------------------------------------------------------------------
DragonFly:
- hammer2_ioctl.c:1088-1164 (hammer2_ioctl_bulkfree_scan) does ONE
sync, then takes the snapshot, then runs the pass;
- the pass stages blocks 11 -> 10 and frees them 10 -> 00 on the next
pass.
Observed: fsck_hammer2 -f reported "Bad HAMMER2_CHECK_XXHASH64" on a
data block that only the OLDEST volume root (header N) referenced. The
freemap had the block as 11 in header N and as 10 already in N+1, N+2
and N+3; it had been freed and overwritten before header N+4. Only 2-3
headers separated the last header that referenced the block from its
reuse, while the media keeps 4. A sync writes a header only if
something changed, so "one sync per pass" does not even guarantee one
header per pass on an idle file system.
Our fix (b0e0cb29e): count the volume headers actually written; before
a pass frees staged blocks, sync (at most 4 times) until 4 more headers
have been written since the previous pass's snapshot; otherwise leave
the blocks staged for a later pass; on ENOSPC free as before. On an
idle volume the syncs wrote no header, so a follow-up (b1c5c694e) marks
the volume data modified before each of those syncs. Over 126 passes
every freeing pass had at least 4 headers since the previous snapshot,
and frees still happened in 127 of 128 passes.
4. hammer2_chain_repchange() leaves reptrack->spin locked
---------------------------------------------------------
DragonFly: hammer2_chain.c, hammer2_chain_repchange() (:2309-2336).
hammer2_spin_ex(&reptrack->spin) has no matching unlock.
hammer2_chain_repparent() later takes the same spinlock when it follows
a reptrack that has moved, so that path would spin forever. The debug
kprintf in the function suggests the path is rare.
We never observed it: under our load repchange ran 30,919 times and
never had a reptrack attached. The fix (part of 1f450a073) is a single
hammer2_spin_unex(&reptrack->spin) after the reptrack is moved.
5. Metadata blocks referenced by a volume header can still be only in
memory when the header is written
--------------------------------------------------------------------
DragonFly:
- _hammer2_io_putblk() turns a DIRTY dio into a delayed write (bdwrite)
only on its last release (hammer2_io.c:388-500); while any reference
is held, the buffer stays locked with BUF_KERNPROC and is not
B_DELWRI;
- the flush computes check codes for INDIRECT, FREEMAP, DIRENT and
INODE blocks ("Buffer I/O will be cleaned up when the volume is
flushed", hammer2_flush.c:866-875), then does VOP_FSYNC(devvp,
MNT_WAIT) and writes the header (:1462-1472).
If another thread holds another chain in the same 64 KB buffer when the
flush reaches VOP_FSYNC, the buffer is not on the vnode's dirty list.
It is not written, and the header goes out first. A lookup, a create,
the bulkfree scan or the xop queue is enough. A crash before the last
release leaves the header pointing at the block's previous content.
_hammer2_io_bwrite() also defers its write to the last release, so file
data written via IO_SYNC has the same exposure.
Observed twice: an INDIRECT block of the SECOND-NEWEST volume root had a
bad check code; in the two older roots the block was free (00); the
media still held its previous content, an indirect block ~270-390 syncs
older.
Measured with an in-kernel audit, no crash (before each volume header,
every block whose check code the same flush recorded is reread from the
media if its buffer is still held or delayed, and its XXH64 compared),
30 minutes each:
- unfixed: 17 blocks in 7 different headers were NOT on the media when
their header was written, out of 4.58 million checked;
- fixed: 0 out of 5.48 million.
The fix (c14bf5afa, designed with an external review): flag a dio
whenever a check code of a block in it is recorded; keep flagged dios on
a per-device list until their last release; just before VOP_FSYNC(devvp)
write the still-referenced flagged buffers with a direct BIO_WRITE,
holding a reference until the write completes; a failed write keeps the
header from being written.
6. Check mode NONE plus live dedup returns stale or zeroed data,
silently (new since the first report)
----------------------------------------------------------------
DragonFly:
- hammer2_chain_modify() (hammer2_chain.c:1436 ff.) overwrites a DATA
block in place when its check mode is NONE and it is not
CHAIN_DEDUPABLE (:1503-1515);
- hammer2_dedup_record() refuses to offer such blocks for dedup, but
hammer2_assign_physical() (hammer2_strategy.c:717, lookup at :760)
still lets a file with check mode NONE adopt ANOTHER file's block
through hammer2_dedup_lookup();
- whether a block is shared is known only while the chain stays in
memory (CHAIN_DEDUPABLE). Once it is reloaded from the media, the
next write overwrites it in place, into the other file's data;
- separately, when hammer2_dedup_lookup() finds the new data in an
existing block and the chain is already MODIFIED and not DEDUPABLE,
hammer2_chain_modify() (:1538) ignores dedup_off and keeps the chain's
own block, which still holds the previous data. With a check code
this shows as a check error on the next read; with check DISABLED
(never registered for dedup, so never DEDUPABLE) the old data is
returned silently.
Observed: files in a "hammer2 setcheck none" directory read back after a
remount with the old data, or with the tail of a block zeroed, and no
error. The new boot-loader reader found it, because it disagreed with
the kernel; fsx confirmed it.
Our fixes: in hammer2_assign_physical(), no dedup lookup for a file
whose check mode is NONE (6a7a41691); in hammer2_chain_modify(), a
dedup request always gets a new allocation, as the DEDUPABLE case does,
and never an in-place overwrite (e5c019647). fsx clean afterwards.
7. Three undefined behaviours found by UBSan (new)
--------------------------------------------------
Harmless on amd64 in practice, but undefined:
- LZ4 decoder, hammer2_lz4.c:400 and :481: dec64table is size_t and
holds (size_t)-1, so "ref -= dec64" wraps a pointer around. Making
the table and the variable intptr_t fixes it (e53c77e33). Found by
the fuzzer.
- hammer2_freemap_try_alloc(), hammer2_freemap.c:412 and :456:
bmap = &chain->data->bmdata[n] is computed before checking that n is
inside the array; even computing a pointer outside it is undefined.
Compute it only for a valid index (bdd3cf9db).
- hammer2_update_time() stores a uint64_t through a pointer to a field
of the __packed inode meta (hammer2_inode.c:1070 and :1184,
hammer2_vnops.c:1210): a possibly misaligned store. We go through an
aligned local (bdd3cf9db; UBSan flagged the PFS-creation case under
makefs).
Smaller points and suggestions
------------------------------
- hammer2_vop_readdir() (hammer2_vnops.c:598): when the buffer cannot
hold even one entry, vop_write_dirent() returns non-zero, the
function jumps to done and returns 0 with no entry and eofflag 0.
To the caller this looks like the end of the directory. On FreeBSD,
INVARIANTS kernels now assert against it, so any user could panic
the kernel with getdirentries(2) and an 8-byte buffer. We return
EINVAL in that case, as tmpfs does (034e8aafa). On DragonFly it may
only be worth a look.
- vfs.hammer2.bulkfree_tps (hammer2_vfsops.c:76, used at
hammer2_bulkfree.c:815) defaults to 5000 non-leaf blockrefs per
second. On a 1 TB volume with a million files a pass took 215 s, of
which about 10 s were work (4 s of system time); at 100000 it took
10.4 s, with no measurable change in the latency of stat, small
reads, create+fsync and readdir sampled every 100 ms. Since no
overwritten block is reused before bulkfree, long passes matter: a
64 GB volume under a write-heavy load with frequent snapshots filled
up in minutes. We raised the default to 100000 (192d2f187); you may
want to measure it on your side.
- Not yet understood, FreeBSD port: after a full volume was cleaned up
with emergency-mode-enable / rm / emergency-mode-disable / bulkfree,
creating files in the one directory where the in-place deletions had
happened returned ENOSPC with 50 GB free; the rest of the volume was
writable, and a reboot cleared it. We have not reproduced it yet; I
mention it in case it rings a bell.
Found in the FreeBSD port only (for completeness)
-------------------------------------------------
These do not apply to DragonFly: dio->refs updated without the lock in
some paths (DragonFly uses cmpset loops); the stack reptrack's lock
initialised without SX_NEW; RB_SCAN not tracking removals; a mutex not
released in hammer2_io_getquick(); truncate not zeroing the tail of the
block across EOF (DragonFly uses nvtruncbuf); SEEK_DATA ignoring data
still in buffers; a read past the mount source string; a wrong lock
assertion in rename; renameat2(2) flags ignored; vget() on a vnode not
held (FreeBSD's vget semantics differ); bufdaemon stalls and lock
order reversals specific to FreeBSD's buffer cache.
What I am asking
----------------
1. Are you aware of items 1-7? Are any of them intentional, item 1 in
particular?
2. Do fixes exist already?
3. Would diffs be useful? They are against the FreeBSD port, but the
changes for items 2-7 are local to hammer2_flush.c,
hammer2_ioctl.c, hammer2_bulkfree.c, hammer2_chain.c, hammer2_io.c,
hammer2_strategy.c, hammer2_freemap.c, hammer2_inode.c and
hammer2_lz4.c. DTrace scripts and preserved disk images are
available too.
The branch, with every fix as its own commit and the test reports:
https://github.com/Marietto2008/freebsd-src/tree/hammer2-root
(commits are referred to by hash above; the reports are under
hammer2-project/rapporti/, mostly in Italian, with English summaries)
The analysis, measurements and fixes were done by an AI assistant
(Claude, by Anthropic) working on my machine; an external reviewer
checked items 2 and 5 against the code. I am happy to rerun anything
you suggest.
Thank you.
--
You have received this notification because you have either subscribed to it,
or are involved in it.
To change your notification preferences, please click here:
http://bugs.dragonflybsd.org/my/account