# TDD Plan: Fix Dnode Block Corruption in Block Clone (BRT Write)

## Problem Statement (Corrected 2026-09-25)

**Root cause remains unidentified.** Dump recheck found two errors in the earlier diagnosis:

1. The clone dirty record is correctly linked to its own dbuf (not mislinked into dnode block dbuf's dirty list)
2. Its block pointer describes ordinary file data (plain file, LZ4-compressed), not a BRT ZAP block

This removes the basis for the proposed ARC-reuse fix. The root cause remains unidentified.

**Current state**: Corruption of dnode block 25484 slot 0 (object 815488) with two block pointers matching BRT entries. The crashed kernel has `vfs.vnode.param.can_skip_requeue=0`. Disabling block cloning and enabling requeue skipping are unproven mitigations.

## Test Environment

**Test VM**: `test-zfs2` (FreeBSD 15.1-RELEASE-p3 GENERIC, cloud-init ZFS image)
- 2 CPUs, 1 GiB RAM, ~16 GiB boot disk
- SSH: `ssh -i ~/.ssh/test-zfs2 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@192.168.3.225`
- Reports `vfs.vnode.param.can_skip_requeue=0`, `vfs.zfs.bclone_enabled=1`, `feature@block_cloning=active`
- Disk expanded, ~10 GiB available on `/usr/src`

**Build Host**: Current machine (compile only, no testing)
- Source: `/home/wongk/freebsd-src` (releng/15.1, commit 88e7371d9dc2)
- Kernel target: GENERIC-DEBUG with ZFS_DEBUG enabled

## Phase 0: Build Test Kernels on Build Host

```sh
# On build host:
cd /home/wongk/freebsd-src
make buildkernel KERNCONF=GENERIC-DEBUG -j$(nproc)
```

## Phase 0: Reproduction Attempts (Active)

### Current Reproduction Status (2026-09-26)

| Attempt | Date | Method | Config Changes | Result | Notes |
|---------|------|--------|----------------|--------|-------|
| 1 | 2026-09-25 | 100x copy_file_range (128KB) | block_clone=on, 2 vdevs | No panic | SHA256 matched, BRT stable |
| 2 | 2026-09-25 | 100x copy_file_range (128KB) | Original crash kernel | No panic | SHA256 matched, BRT stable |
| 3 | 2026-09-26 | copy_file_range 128KB, 2 vdevs, block_clone=on | 1000 | No panic | SHA256 mismatch (only 128KB copied per iter), BRT stable, no panic |

### Next Reproduction Attempts (in priority order)

| # | Approach | Rationale |
|---|----------|-----------|
| 3 | Fill pool to >90% capacity before cloning | Force specific DVA layout matching crash dump DVAs (88, 482663448 / 24, 482663544) |
| 4 | Multiple concurrent clone threads | Increase contention on dnode block |
| 5 | Disable brt_zap_prefetch (`sysctl vfs.zfs.brt.brt_zap_prefetch=0`) | Isolate prefetch path |
| 8 | Clone into same file (self-clone) | Different code path in dmu_brt_clone |
| 9 | Mix clone + fsync + sync in tight loop | Maximize sync activity during clone |
| 10 | Run with vfs.zfs.bclone_wait_dirty=1 | Wait for dirty blocks to sync |

### Reproduction Attempts Log

| # | Date | Config | Iterations | Result | Notes |
|---|------|--------|------------|--------|-------|
| 1 | 2026-09-25 | copy_file_range 128KB, 2 vdevs, block_clone=on | 100 | No panic | SHA256 matched, BRT stable |
| 2 | 2026-09-25 | Original crash kernel | 100 | No panic | SHA256 matched, BRT stable |
| 3 | 2026-09-26 | copy_file_range 128KB, 2 vdevs, block_clone=on | 1000 | No panic | SHA256 mismatch (only 128KB copied per iter), BRT stable, no panic |

### Next Reproduction Attempts (in priority order)

1. **Fill pool to >90% capacity, then clone** - Force specific DVA layout matching crash dump DVAs (88, 482663448 / 24, 482663544)
2. **Concurrent clone threads** - Multiple threads cloning simultaneously to increase contention on dnode block
3. **Disable brt_zap_prefetch** - `sysctl vfs.zfs.brt.brt_zap_prefetch=0` to isolate prefetch path
4. **Self-clone test** - Clone file into itself (different code path in dmu_brt_clone)
5. **Mix clone + fsync + sync in tight loop** - Maximize sync activity during clone
6. **Run with vfs.zfs.bclone_wait_dirty=1** - Wait for dirty blocks to sync
7. **Run with vfs.vnode.param.can_skip_requeue=1** - Test if vnode requeue affects timing

### Reproduction Attempts Log

| # | Date | Config | Iterations | Result | Notes |
|---|------|--------|------------|--------|-------|
| 1 | 2026-09-25 | copy_file_range 128KB, 2 vdevs, block_clone=on | 100 | No panic | SHA256 matched, BRT stable |
| 2 | 2026-09-25 | Original crash kernel | 100 | No panic | SHA256 matched, BRT stable |
| 3 | 2026-09-26 | copy_file_range 128KB, 2 vdevs, block_clone=on | 1000 | No panic | SHA256 mismatch (only 128KB copied per iter), BRT stable, no panic |

### Next Reproduction Attempts (in priority order)

1. **Fill pool to >90% capacity, then clone** - Force specific DVA layout matching crash dump DVAs (88, 482663448 / 24, 482663544)
2. **Concurrent clone threads** - Multiple threads cloning simultaneously to increase contention on dnode block
3. **Disable brt_zap_prefetch** - `sysctl vfs.zfs.brt.brt_zap_prefetch=0` to isolate prefetch path
4. **Self-clone test** - Clone file into itself (different code path in dmu_brt_clone)
5. **Mix clone + fsync + sync in tight loop** - Maximize sync activity during clone
6. **Run with vfs.zfs.bclone_wait_dirty=1** - Wait for dirty blocks to sync
7. **Run with vfs.vnode.param.can_skip_requeue=1** - Test if vnode requeue affects timing

## Phase 1: Verification Tests (Green - Detection)

### Test 1.1: Early Dnode Check Assertion
- Apply `early-dnode-check.patch` (already in `src/patches/`)
- Boot test VM with patched kernel
- Run reproducer (see Phase 2)
- Expect: `ASSERT` failure in `dbuf_write()` with clear message
- NOT: Silent corruption → later panic in `dnode_verify()`

### Test 1.2: Instrumentation for High-Value Leads

Per code review, the strongest clue is that slot 0 contains two valid file-data block pointers matching BRT entries. This suggests a writer copied a BP-containing structure into the dnode-block data buffer. Likely places to instrument:

1. **dmu_brt_clone() and clone dirty-record setup**: log source/destination dbuf addresses and every copied BP.

2. **dbuf_write_ready() / dbuf_sync_leaf()**: assert each db_data, db_blkptr, parent dbuf, and dnode relationship before writing.

3. **ARC/ABD copy and release paths**: log only when source or destination overlaps the 16 KiB dnode block.

3. **Add a checksum/canary for this dnode block when dirtied**; on its first unexpected change, panic and preserve curthread plus a stack trace.

### Test 1.3: fd/mqueue Separate Lead
The fd/mqueue failures are a separate high-priority lead: if they recur independently of cloning, prioritize a generic kernel memory corruption or lifetime bug over ZFS.

## Phase 2: Reproduction Test (Red)

### Test 2.1: Minimal Reproducer - Block Clone Corruption
```c
// sys/tests/zfs/t_brt_clone_dnode_corruption.c
// 1. Create pool with block cloning enabled (2 vdevs)
// 2. Create source file with multiple blocks tracked in BRT
// 3. Clone range into destination file
// 4. Sync and verify dnode block integrity
// 5. Before fix: panic in dnode_verify() with slot 0 = 0x58
// 6. After fix: no panic, dnode slots remain valid
```

**Setup on test VM:**
```sh
zpool create testpool /dev/md0 /dev/md1
zfs set block_clone=on testpool
zfs create testpool/test
# Write source file, sync, clone via copy_file_range or FICLONERANGE
# Multiple iterations to try to hit the race
```

### Test 2.2: Vnode Contention Trigger Test
```c
// sys/tests/zfs/t_vnode_requeue_contention.c
// Test if vnode LRU requeue contention triggers the corruption
// Compare can_skip_requeue=0 vs 1 workloads
```

## Phase 2: Root Cause Investigation (Ongoing)

### Investigation 3.1: Identify the Writer
- Add live watchpoint on slot 0 immediately after allocation/zeroing
- Instrument every metadata write destination with dnode block, object, and block-pointer provenance
- Compare exact source tree with newer OpenZFS fixes and backports

### Investigation 3.2: Hypothesis Testing
1. **Stale/corrupt `db_blkptr` in a metadata write** — a legitimate data-write completion stores a blkptr via `db->db_blkptr` in `dbuf_write_ready()`. A stale/corrupt `db_blkptr` is a concrete mechanism for a 128-byte block pointer landing in the wrong place.
2. **Lifetime corruption / use-after-free** — the 0xdeadc0de pattern in dirty records suggests freed memory reuse.
3. **fd-table/mqueue interaction** — earlier panics showed invalid `struct file *` and Capsicum rights-mask values; a shared allocator/lifetime bug remains possible.
4. **On-disk corruption / hardware fault** — weaker; structured bytes, valid geometry.

## Phase 3: Regression Tests (After Root Cause Found)

### Test 3.1: Stress Test - Concurrent Clones + Dnode Allocation
Multiple threads doing block clones while dnodes allocated; run 1000 iterations, verify no corruption.

### Test 3.2: Minidump Verification
After induced panic (with fix disabled), verify:
1. early-dnode-check.patch catches it
2. Core dump shows assertion, not dnode_verify() panic

### Test 3.3: fd-table/mqueue Interaction Test
Run fd stressor + block clone simultaneously; verify no shared corruption (separate bug or same root cause).

## Phase 3: Build & Deploy Verification

### Test 5.1: Compile Check on Build Host
```sh
# On build host:
cd /home/wongk/freebsd-src
make buildkernel KERNCONF=GENERIC-DEBUG -j$(nproc)
git apply --check investigation/early-dnode-check.patch
```

### Test 5.2: Install on Test VM
```sh
# On test VM:
doas cp /boot/kernel/kernel /boot/kernel/kernel.orig
doas cp /boot/kernel/zfs.ko /boot/kernel/zfs.ko.orig
doas cp /tmp/kernel.new /boot/kernel/kernel
doas cp /tmp/zfs.ko.new /boot/kernel/zfs.ko
reboot
```

### Test 5.3: Run Test Suite
```sh
# On test VM:
kyua test -k /usr/tests/Kyuafile -o results.db fs/zfs
# Filter for brt_clone tests
kyua report --verbose --results-filter=brt_clone
```

## Working Hypotheses (Investigation Order)

1. **Stale/miscomputed `db_blkptr`/metadata destination** — legitimate write landed at dnode block start
2. **Lifetime corruption / use-after-free** — 0xdeadc0de pattern suggests freed memory reuse
3. **fd-table/mqueue interaction** — possibly explains earlier panics with invalid `struct file *`
4. **On-disk corruption / hardware fault** — weaker; structured bytes, valid geometry

## Mitigations (Not Proven Fixes)

1. **Disable block cloning**: `zfs set block_clone=off <pool/fs>`
2. **Enable vnode requeue skip**: `sysctl vfs.vnode.param.can_skip_requeue=1`
3. **Apply `early-dnode-check.patch`** — catches corruption at sync time in `dbuf_write()`

## Files to Modify (Pending Root Cause)

1. `sys/contrib/openzfs/module/zfs/dbuf.c` — Diagnostic assertions (early-dnode-check.patch)
2. `sys/contrib/openzfs/module/zfs/dbuf.c` — Destination validation (if clone path confirmed)
3. `sys/contrib/openzfs/module/zfs/arc.c` — Buffer ownership tracing (defensive)
4. `sys/contrib/openzfs/module/zfs/brt.c` — Dedicated BRT buffers (defensive)
5. `sys/tests/zfs/t_brt_clone_dnode_corruption.c` — Test 2.1
6. `sys/tests/zfs/t_vnode_requeue_contention.c` — Test 2.2

## Commands Reference

```sh
# Build host SSH to test VM:
ssh -i ~/.ssh/test-zfs2 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@192.168.3.225

# On build host:
cd /home/wongk/freebsd-src
git apply /home/wongk/zfs-crash/src/patches/early-dnode-check.patch
make buildkernel KERNCONF=GENERIC-DEBUG -j8

# On test VM (after disk expansion):
gpart recover vtbd0 && gpart resize -i 5 vtbd0 && zpool online -e zroot vtbd0p5
pkg install -y FreeBSD-kyua atf

# Run tests:
kyua test -k /usr/tests/Kyuafile -o results.db fs/zfs
```