]> git.hungrycats.org Git - bees/commitdiff
scan-next: keep our own dedupes' references visible until they commit
authorZygo Blaxell <bees@furryterror.org>
Sun, 20 Sep 2026 20:56:16 +0000 (16:56 -0400)
committerZygo Blaxell <bees@furryterror.org>
Sun, 11 Oct 2026 00:48:00 +0000 (20:48 -0400)
An extent that has just served as a dedupe src has gained references
that no LOGICAL_INO walk of the commit root can report until the
transaction commits.  When that extent is then chosen as a dst -- it
arrives by hash match, so neither the crawler's transid discipline nor
the dst lock applies -- the plan is built from the short list, redirects
only the references it can see, and the extent survives the dedupe that
was supposed to free it.  The verification tracker reports these as
failures.  With resolve.commit-root every resolve walks the commit
root, so this happens at every src-then-dst transition inside one
transid: on a 129-ref synthetic corpus, 40 verify failures and 1.6 GiB
less recovered than the live-root run of the same binary.  It is also
possible without the flag, because the kernel silently answers from the
commit root whenever it cannot attach to a running transaction.

The existing repair_refs() mechanism was meant to cover this by merging
the dst's reference list into the src's after each plan.  Instrumenting
it shows it cannot: a dst reference deduped in N segments creates N new
src references at N different item offsets, and the donor carries only
the dst item's old offset, so at most one of the N is represented and
the rest are foreign entries every consumer skips.  Two more gaps: srcs
outside m_src_bytenrs (the temp-file extents behind copy segments) got
no repair at all, and the repaired list did not survive the per-transid
cache clear, whose refetch can land in the window after the crawl
thread sees the new transid and before the kernel swaps the commit
roots, and so comes back one commit staler than the transid suggests.

Replace it with a record of the references bees itself creates.  Every
successful dedupe walks the src file's EXTENT_DATA items over the
deduped range and records, per src extent, the (root, inum, offset) of
the new dst item -- the kernel creates one per src item overlapped,
each at the corresponding dst offset, which is the same key LOGICAL_INO
reports.  refs_fetch unions the record into every result for that
bytenr, whichever tree the kernel walked.

Entries expire after four observed transid changes, counted, not
computed from transid values.  The transid the crawl thread reads is
the generation of the root-tree leaf holding one subvol's item, which
moves only when an item in that leaf is rewritten; it sat still for
thirteen transactions in one run and then jumped, and a first version
of this change that stamped entries with its value expired 168 fresh
entries the moment the thread caught up.  Counting changes is immune:
the first change after an add may only be the thread catching up, every
later one is a transaction the dedupe's has been followed by, and a
transaction is fully committed before the one after its successor can
begin, so the third change is proof and the fourth is margin.

repair_refs and merge_refs go away with their only caller.  The
"recovered less space" observation in the docs and comments predates
this fix and is dropped; the comparison needs re-measuring.

Assisted-by: Claude-Code:claude-fable-5-1
Assisted-by: Claude-Code:claude-opus-5-5
15 files changed:
docs/config-file.md
src/Makefile
src/bees-context.cc
src/bees-extent-layer.cc
src/bees-extent-layer.h
src/bees-extent-tree.cc
src/bees-extent-tree.h
src/bees-pending-refs.cc [new file with mode: 0644]
src/bees-pending-refs.h [new file with mode: 0644]
src/bees-roots.cc
src/bees-scan-next.cc
src/bees-util.cc
src/bees.h
test/Makefile
test/test-bees-borrower.cc

index 4b0ee0f3cd2de62f2d3e2151eb30cdb79b7b2223..64fb073d920a604a58fd6189fbdfcadea512ef57 100644 (file)
@@ -1312,7 +1312,9 @@ The `[resolve]` section controls how bees maps a physical btrfs address back to
 
   With `no`, the kernel walks the running transaction's trees, so the reference list reflects the filesystem as it is at the moment of the call.  To keep that view consistent, the kernel holds a tree mod log sequence for the whole duration of the walk.  While any sequence is live, every node-level change anywhere on the filesystem is journalled into unreclaimable slab, and the journal is only trimmed below the oldest live sequence.  Walks of heavily-shared extents take the longest and therefore hold a sequence the longest, which is also when other work — balance, snapshot deletion — is most likely to be generating tree changes to journal.
 
-  With `yes`, the answer comes from the last committed transaction, so no tree mod log sequence is held.  The cost is that the answer can be up to one transaction (roughly 30 seconds) stale: references created since the last commit are invisible.  bees is built to survive a stale answer — the kernel already falls back to the commit roots on its own whenever it cannot attach to a running transaction, the crawler only hands out extents from committed transactions, and references that vanish between the walk and the dedupe are treated as churn rather than errors — but surviving a stale answer is not the same as being unaffected by one.  A reference bees cannot see is a reference it does not dedupe, so the extent survives a dedupe that was supposed to free it, and the work is repeated on a later pass.
+  With `yes`, the answer comes from the last committed transaction, so no tree mod log sequence is held.  The cost is that the answer can be up to one transaction (roughly 30 seconds) stale: references other writers created since the last commit are invisible.  bees is built to survive that — the kernel already falls back to the commit roots on its own whenever it cannot attach to a running transaction, the crawler only hands out extents from committed transactions, and references that vanish between the walk and the dedupe are treated as churn rather than errors.  A reference bees cannot see is a reference it does not dedupe, so the extent survives a dedupe that was supposed to free it, and the work is repeated on a later pass.
+
+  References bees creates itself are handled separately, because those it cannot afford to miss: an extent that has just served as a dedupe source has gained references no commit-root walk can report yet, and if it is then chosen as a destination, a plan built from the short list would leave it in place.  bees records every reference its own dedupes create and unions them into every resolve of that extent until they have reached the commit root, with either setting.
 
   The option exists so the two can be compared on a single kernel, on a specific workload, without rebuilding.
 
index c6fc88af7f067259613107f6fef90fa4fd65d2dc..6cd949f3d7f2ba52aa5457cff6c23233c2b90ebc 100644 (file)
@@ -39,6 +39,7 @@ BEES_OBJS = \
        bees-heatmap.o \
        bees-lib.o \
        bees-log.o \
+       bees-pending-refs.o \
        bees-plan.o \
        bees-planner-state.o \
        bees-reporter.o \
@@ -69,6 +70,7 @@ REPL_OBJS = \
        bees-heatmap.o \
        bees-lib.o \
        bees-log.o \
+       bees-pending-refs.o \
        bees-plan.o \
        bees-planner-state.o \
        bees-reporter.o \
index 56566df6689e3440bc8a2841513d5820efbdf9a0..1a9cafc34d5758cff45aab7fc66cdae0830d9fe9 100644 (file)
@@ -265,6 +265,16 @@ BeesContext::dedup(const BeesRangePair &brp_in)
                        if (rv) {
                                BEESCOUNT(dedup_hit);
                                BEESCOUNTADD(dedup_bytes, brp.first.size());
+                               // The dst file now holds references to the src
+                               // extents that no resolve can report until they
+                               // commit.  Put them on record so a resolve of those
+                               // extents stays complete in the meantime (see
+                               // bees-pending-refs.h).
+                               const auto dst_fid = brp.second.fid();
+                               for (const auto &created : bees_dedupe_created_refs(m_root_fd, brp)) {
+                                       m_pending_refs.add(created.m_bytenr, dst_fid.root(),
+                                               dst_fid.ino(), created.m_offset);
+                               }
                        } else {
                                BEESCOUNT(dedup_miss);
                                BEESLOGINFO("NO Dedup! " << brp);
@@ -1031,16 +1041,17 @@ BeesContext::logical_ino(const uint64_t logical, const bool all_refs)
        // Walks of heavily shared extents are exactly the ones that take long
        // enough for that to matter.
        //
-       // The cost is that the answer can be up to one transaction stale, and
-       // a stale reference list makes bees plan against references that are
-       // no longer the whole set, so extents survive dedupes that should
-       // have freed them.  bees can tolerate a stale answer -- the kernel
-       // silently answers from the commit root whenever it cannot attach to
-       // a running transaction, so this was always possible, the crawler
-       // only hands out extents from committed transactions, and references
-       // that vanish between the walk and the dedupe are treated as churn
-       // rather than errors -- but tolerating it is not the same as being
-       // unaffected by it.
+       // The cost is that the answer can be up to one transaction stale.
+       // References other writers created since the last commit are
+       // invisible, which bees tolerates:  the kernel silently answers from
+       // the commit root whenever it cannot attach to a running transaction,
+       // so this was always possible, the crawler only hands out extents
+       // from committed transactions, and references that vanish between
+       // the walk and the dedupe are treated as churn rather than errors.
+       // References bees created itself are the exception -- a src it
+       // re-plans as a dst from a list missing them survives the dedupe --
+       // and those it keeps on record and unions into every resolve until
+       // they commit (see bees-pending-refs.h).
        //
        // On by default; the knob exists so the two can be compared on one
        // kernel.
index 67c17ce43d0870ce29b28cd5db324f122cbc606d..d175cc186dc5ac94e140b5a9aa4ca9c8d9a0014f 100644 (file)
@@ -39,12 +39,6 @@ BeesExtentLayer::invalidate_refs(const BeesExtent &)
        // Default no-op — base layers without per-extent ref caches.
 }
 
-void
-BeesExtentLayer::repair_refs(const BeesExtent &, const vector<BeesRef> &)
-{
-       // Default no-op — layers that do not cache ref lists.
-}
-
 Fd
 BeesExtentLayer::open_ref(const BeesRef &ref) const
 {
@@ -306,11 +300,19 @@ BeesBtrfsExtentLayer::refs_fetch(BeesBtrfsExtentNode &node) const
                        THROW_ERRNO("BTRFS_IOC_LOGICAL_INO " << to_hex(node.m_bytenr));
                }
        }
-       const auto count = lio->m_iors.size();
-       BEESCOUNTADD(refs_count, count);
+       BEESCOUNTADD(refs_count, lio->m_iors.size());
        BEESCOUNTADD(refs_ms, refs_timer.age() * 1000);
        lock.reset();
-       if (lio->m_iors.size() == 0) {
+       // The kernel cannot report a reference that has not reached the tree
+       // it walked:  never one from the running transaction under
+       // resolve.commit-root, and none when it fell back to the commit root
+       // on its own.  The references this process created are on record;
+       // union them in so the list is complete either way (see
+       // bees-pending-refs.h).
+       vector<BtrfsInodeOffsetRoot> iors(lio->m_iors.begin(), lio->m_iors.end());
+       BEESCOUNTADD(refs_pending, m_ctx.pending_refs().merge_into(node.m_bytenr, iors));
+       const auto count = iors.size();
+       if (count == 0) {
                BEESCOUNT(refs_zero);
        }
 
@@ -343,8 +345,8 @@ BeesBtrfsExtentLayer::refs_fetch(BeesBtrfsExtentNode &node) const
        }
 
        vector<BeesRef> rv;
-       rv.reserve(lio->m_iors.size());
-       for (const auto &ior : lio->m_iors) {
+       rv.reserve(iors.size());
+       for (const auto &ior : iors) {
                auto ref_node = make_shared<BeesBtrfsRefNode>(ior.m_root, ior.m_inum, ior.m_offset);
                ref_node->m_bytenr = node.m_bytenr;
                ref_node->m_extent = ext_sp;
@@ -1032,51 +1034,6 @@ BeesBtrfsExtentLayer::invalidate_refs(const BeesExtent &extent)
        }
 }
 
-void
-BeesBtrfsExtentLayer::repair_refs(const BeesExtent &extent, const vector<BeesRef> &donors)
-{
-       if (donors.empty() || !extent.bytenr_opt()) {
-               return;
-       }
-
-       // Populate the list first, so the repair is applied on top of whatever
-       // btrfs is willing to report right now.  Virtual: fetches on a miss.
-       extent.refs(*this);
-
-       // LOGICAL_INO answers from the commit root whenever it cannot attach
-       // to a running transaction (fs/btrfs/backref.c: btrfs_attach_transaction
-       // returns -ENOENT, find_parent_nodes then sets search_commit_root and
-       // skips delayed refs).  A dedupe performed since the last commit is
-       // therefore invisible to a refetch that happens to land in a lull, and
-       // nothing in the result distinguishes that case from a genuinely short
-       // ref list.  We know what we just created, so do not ask: the donors
-       // are the dst refs the dedupe redirected onto this extent.  Adding one
-       // btrfs already reported is skipped as a duplicate; adding one
-       // belonging to a different src is harmless, because extent_data_fetch
-       // leaves a foreign ref undetermined and every caller skips it.
-       //
-       // The donors describe file ranges, but their ref nodes still name the
-       // dst extent they came from, so rebase each onto this extent before
-       // handing it over.  Building ref nodes is the layer's job -- it is the
-       // friend that may set their identity, exactly as refs_fetch does.
-       auto ext_sp = extent.extent_sp();
-       vector<BeesRef> rebased;
-       rebased.reserve(donors.size());
-       for (const auto &donor : donors) {
-               auto ref_node = make_shared<BeesBtrfsRefNode>(
-                       donor.root(), donor.inum(), donor.offset());
-               ref_node->m_bytenr = extent.bytenr();
-               ref_node->m_extent = ext_sp;
-               rebased.push_back(BeesRef(static_pointer_cast<BeesBaseRefNode>(ref_node)));
-       }
-
-       // The node owns its ref list and does the merge under its own lock,
-       // skipping any identity it already holds.  Node types with no btrfs
-       // ref list inherit a no-op.
-       const auto added = ext_sp->merge_refs(rebased);
-       BEESCOUNTADD(ref_repaired, added);
-}
-
 void
 BeesBtrfsExtentLayer::invalidate()
 {
@@ -1682,11 +1639,3 @@ BeesOverlayLayer::invalidate_refs(const BeesExtent &extent)
        // Propagate so the base layer drops its per-inode ref cache too.
        m_parent->invalidate_refs(extent);
 }
-
-void
-BeesOverlayLayer::repair_refs(const BeesExtent &extent, const vector<BeesRef> &donors)
-{
-       // The overlay caches no ref lists of its own; the list lives on the
-       // node.  Forward so the base layer performs the merge.
-       m_parent->repair_refs(extent, donors);
-}
index ea978cec4d3f93b2ff4c2ebdfdac2a8f33687c3e..6b9f22928d780f4e0e347043e1eb0c0d096c651e 100644 (file)
@@ -190,15 +190,6 @@ public:
        /// returns without doing anything.  Default: no-op.
        virtual void invalidate_refs(const BeesExtent &extent);
 
-       /// Restore refs to @p extent that a just-completed dedupe created
-       /// but a refetch may not report.  @p donors are the dst-side refs
-       /// the dedupe redirected onto this extent; each is added to the
-       /// extent's ref list if a (root, inum, offset) match is not already
-       /// present.  Needed because LOGICAL_INO falls back to the commit
-       /// root when it cannot attach to a running transaction, making
-       /// uncommitted dedupes invisible to it.  Default: no-op.
-       virtual void repair_refs(const BeesExtent &extent, const vector<BeesRef> &donors);
-
        // -- Transitional: BeesContext access --
 
        /// Return the underlying BeesContext.  Only valid on layers
@@ -269,7 +260,6 @@ public:
        /// Leaves m_extent_cache entries in place because the extent
        /// identity (bytenr + phys_size) is still valid after dedupe.
        void invalidate_refs(const BeesExtent &extent) override;
-       void repair_refs(const BeesExtent &extent, const vector<BeesRef> &donors) override;
 
        BeesContext &ctx() const override;
 
@@ -434,7 +424,6 @@ public:
        /// removes the extent's own neighbor entries plus back-edges from
        /// other extents' neighbor sets.  Propagates to the parent.
        void invalidate_refs(const BeesExtent &extent) override;
-       void repair_refs(const BeesExtent &extent, const vector<BeesRef> &donors) override;
 
 private:
        shared_ptr<BeesExtentLayer> m_parent;
index 1373c9c74f78b44f2584a6ef911b9b7e45a52596..e78192a3eae3413a4ebcb36109b831f0c9282cbd 100644 (file)
@@ -1480,38 +1480,6 @@ BeesBtrfsExtentNode::mark_destroyed()
        m_destroyed = true;
 }
 
-size_t
-BeesBtrfsExtentNode::merge_refs(const vector<BeesRef> &new_refs)
-{
-       unique_lock<recursive_mutex> lock(m_lazy_mutex);
-       auto current = atomic_load(&m_refs);
-       vector<BeesRef> merged;
-       if (current) {
-               merged = *current;
-       }
-       size_t added = 0;
-       for (const auto &nr : new_refs) {
-               bool present = false;
-               for (const auto &have : merged) {
-                       if (have.root() == nr.root() && have.inum() == nr.inum() &&
-                           have.offset() == nr.offset()) {
-                               present = true;
-                               break;
-                       }
-               }
-               if (present) {
-                       continue;
-               }
-               merged.push_back(nr);
-               ++added;
-       }
-       if (added) {
-               atomic_store(&m_refs,
-                       make_shared<const vector<BeesRef>>(std::move(merged)));
-       }
-       return added;
-}
-
 bool
 BeesBtrfsExtentNode::destroyed() const
 {
index db17faca69feb68fb1cb7fa4a28dae1d434ab4f7..807684a1de80361761884ae420e4b1be44283a95 100644 (file)
@@ -548,13 +548,6 @@ public:
        /// block map, and scalar identity intact.  Default: no-op.
        virtual void invalidate_refs() {}
 
-       /// Add @p donors to this node's cached ref list, skipping any whose
-       /// (root, inum, offset) is already present, and return how many were
-       /// added.  Used to restore refs a dedupe created that a refetch does
-       /// not report.  Default: no-op returning 0, for node types that hold
-       /// no btrfs ref list of their own.
-       virtual size_t merge_refs(const vector<BeesRef> &) { return 0; }
-
        /// Mark this extent retired: a dedupe consumed it as dst, so its
        /// refs were redirected to the src and it must take no further part
        /// in dedupe.  Retirement is one-way, and deliberately does NOT drop
@@ -835,8 +828,6 @@ public:
 
        optional<bool> refs_at_ceiling() const override;
 
-       size_t merge_refs(const vector<BeesRef> &donors) override;
-
        ssize_t pread(BeesExtentLayer *layerp, void *buf, size_t len,
                off_t logical_offset, const BeesPreadLogFn &log_fn = {}) const override;
 
diff --git a/src/bees-pending-refs.cc b/src/bees-pending-refs.cc
new file mode 100644 (file)
index 0000000..4f49887
--- /dev/null
@@ -0,0 +1,90 @@
+#include "bees-pending-refs.h"
+
+#include "bees.h"
+
+#include <algorithm>
+
+using namespace crucible;
+using namespace std;
+
+uint64_t
+BeesPendingRefs::add(uint64_t bytenr, uint64_t root, uint64_t inum,
+       uint64_t offset)
+{
+       unique_lock<mutex> lock(m_mutex);
+       m_by_bytenr[bytenr].push_back(Entry{root, inum, offset, m_epoch});
+       ++m_size;
+       BEESCOUNT(pending_ref_add);
+       return m_epoch;
+}
+
+size_t
+BeesPendingRefs::merge_into(uint64_t bytenr,
+       vector<BtrfsInodeOffsetRoot> &iors) const
+{
+       unique_lock<mutex> lock(m_mutex);
+       const auto found = m_by_bytenr.find(bytenr);
+       if (found == m_by_bytenr.end()) {
+               return 0;
+       }
+       // Both lists are short compared to a LOGICAL_INO buffer and the
+       // pending side is usually a few hundred entries at most, so a linear
+       // presence test over the kernel's answer is fine.  A pending entry the
+       // kernel already reports is one that has reached the tree it walked;
+       // it stays recorded until it expires because a later resolve may walk
+       // an older tree than this one did.
+       const size_t kernel_count = iors.size();
+       size_t added = 0;
+       for (const auto &e : found->second) {
+               const auto same = [&](const BtrfsInodeOffsetRoot &ior) {
+                       return ior.m_root == e.m_root && ior.m_inum == e.m_inum
+                               && ior.m_offset == e.m_offset;
+               };
+               if (any_of(iors.begin(), iors.begin() + kernel_count, same)) {
+                       continue;
+               }
+               if (any_of(iors.begin() + kernel_count, iors.end(), same)) {
+                       continue;
+               }
+               iors.push_back(BtrfsInodeOffsetRoot{e.m_inum, e.m_offset, e.m_root});
+               ++added;
+       }
+       return added;
+}
+
+void
+BeesPendingRefs::advance()
+{
+       unique_lock<mutex> lock(m_mutex);
+       ++m_epoch;
+       for (auto it = m_by_bytenr.begin(); it != m_by_bytenr.end(); ) {
+               auto &entries = it->second;
+               const auto keep_from = remove_if(entries.begin(), entries.end(),
+                       [&](const Entry &e) {
+                               return e.m_epoch + EXPIRE_EPOCHS <= m_epoch;
+                       });
+               const auto dropped = static_cast<size_t>(entries.end() - keep_from);
+               entries.erase(keep_from, entries.end());
+               m_size -= dropped;
+               BEESCOUNTADD(pending_ref_expire, dropped);
+               if (entries.empty()) {
+                       it = m_by_bytenr.erase(it);
+               } else {
+                       ++it;
+               }
+       }
+}
+
+uint64_t
+BeesPendingRefs::epoch() const
+{
+       unique_lock<mutex> lock(m_mutex);
+       return m_epoch;
+}
+
+size_t
+BeesPendingRefs::size() const
+{
+       unique_lock<mutex> lock(m_mutex);
+       return m_size;
+}
diff --git a/src/bees-pending-refs.h b/src/bees-pending-refs.h
new file mode 100644 (file)
index 0000000..eedf1d8
--- /dev/null
@@ -0,0 +1,82 @@
+#pragma once
+
+/// @file bees-pending-refs.h
+/// References bees created that a resolve cannot yet report.
+///
+/// A dedupe redirects a dst file range onto a src extent: the dst file gets
+/// a new EXTENT_DATA item naming the src.  Until the transaction that made
+/// it commits, that reference exists only in the running transaction.
+/// LOGICAL_INO answers from the commit root -- always with
+/// resolve.commit-root, and silently without it whenever the kernel cannot
+/// attach to a running transaction -- so a resolve of the src issued in that
+/// window omits every reference bees itself just put there.  A plan that
+/// later takes the src as a dst redirects only the references it can see,
+/// and the extent survives a dedupe that was supposed to free it.
+///
+/// This is the one class of missing reference bees cannot shrug off as
+/// churn, and the one it never needs to ask the kernel about: it made them.
+/// Each created reference is recorded against its src bytenr at dedupe time
+/// and unioned into every resolve of that bytenr until its transaction is
+/// known to have committed.
+///
+/// Expiry counts observed transid changes, not transid values.  The transid
+/// the crawl thread reads is the generation of the root-tree leaf holding
+/// one subvol's item, which moves only when an item in that leaf is
+/// rewritten: it can sit still for a dozen transactions and then jump, so
+/// arithmetic on its value would expire a fresh entry the moment the thread
+/// caught up.  Counting changes is immune to that.  An entry is stamped with
+/// the number of changes observed so far.  The first change observed after
+/// the add may be the thread catching up to a transid that was already
+/// running when the dedupe went in; every change after that is a transid
+/// the dedupe's transaction has been followed by.  A transaction is fully
+/// committed before the one after its successor can begin, so the third
+/// observed change proves the dedupe is in the commit root.  A fourth is
+/// margin.
+
+#include "crucible/fs.h"
+
+#include <cstdint>
+#include <map>
+#include <mutex>
+#include <vector>
+
+class BeesPendingRefs {
+public:
+       /// One reference bees created:  the dst file's new EXTENT_DATA item,
+       /// keyed as LOGICAL_INO reports it, and the observed-change count when
+       /// the dedupe that made it ran.
+       struct Entry {
+               uint64_t m_root;
+               uint64_t m_inum;
+               uint64_t m_offset;
+               uint64_t m_epoch;
+       };
+
+       /// Observed transid changes an entry survives.  See the file comment.
+       static constexpr uint64_t EXPIRE_EPOCHS = 4;
+
+       /// Record a reference created onto @p bytenr, stamped with the current
+       /// epoch.  Returns the stamp.
+       uint64_t add(uint64_t bytenr, uint64_t root, uint64_t inum, uint64_t offset);
+
+       /// Append to @p iors every recorded reference to @p bytenr that it does
+       /// not already contain.  Returns the number appended.
+       size_t merge_into(uint64_t bytenr,
+               std::vector<crucible::BtrfsInodeOffsetRoot> &iors) const;
+
+       /// A transid change has been observed:  advance the epoch and drop
+       /// every entry whose transaction must have committed by now.
+       void advance();
+
+       /// Observed transid changes so far.
+       uint64_t epoch() const;
+
+       /// Entries currently held, across all bytenrs.
+       size_t size() const;
+
+private:
+       mutable std::mutex m_mutex;
+       std::map<uint64_t, std::vector<Entry>> m_by_bytenr;
+       size_t m_size = 0;
+       uint64_t m_epoch = 0;
+};
index 3e2cfc7df6b214e11ea9c03e3ac78618b31bc580..643aa794998cc7566eb9ac587aa58e0d07abcf99 100644 (file)
@@ -2687,6 +2687,10 @@ BeesRoots::crawl_thread()
                        // Always run this even if we have no worker threads.
                        clear_caches();
 
+                       // Our own dedupes' references from far enough back are in
+                       // the commit root now; stop carrying them.
+                       m_ctx->pending_refs().advance();
+
                        // Rotate verification pipelines and dispatch any ready batch.
                        m_ctx->verification().on_transid_change(new_transid, m_ctx);
 
index 6faf6790c5c69eed1e9ca29847891d24a1af6615..f391f92de88d06c20f04c919ff658603e04d1d4c 100644 (file)
@@ -4258,14 +4258,17 @@ Planner::run(const BtrfsTreeItem &bti,
        //   and another file's data.  The BeesExtent object survives
        //   eviction -- the verification tracker holds it, ref list
        //   intact for the delayed removal check, block map dropped so
-       //   the wait costs no memory.  Those same refs are then the
-       //   donor list for repairing the src side.
+       //   the wait costs no memory.
        // - src extents gain refs to the deduped ranges.  Block contents
        //   (and therefore hashes) are unchanged, but every ref-derived
        //   cache entry is now stale: overlay ref map + neighbor edges,
        //   base per-inode ref cache, and the node's own cached refs.
        //   Extent identity and block_map stay intact so the subsequent
        //   push-to-front hash refresh reads a consistent block map.
+       //   The refetch may run before the dedupes commit, but the
+       //   references they created are on record and unioned into every
+       //   resolve until then (bees-pending-refs.h), so dropping the
+       //   list is enough.
        auto hash_table = m_ctx->hash_table();
        auto invalidate_dst_hashes = [&](const BeesExtent &dst) {
                const auto dst_bytenr = dst.bytenr();
@@ -4294,8 +4297,6 @@ Planner::run(const BtrfsTreeItem &bti,
                dst.mark_destroyed();
                m_filter_cache->invalidate(dst_bytenr);
        };
-       // Dst refs redirected by this plan, used to repair the src lists.
-       vector<BeesRef> donor_refs;
        auto invalidate_src_refs = [&](uint64_t src_bytenr) {
                // Pull the extent from the layer cache — identity is
                // still valid, so this is usually a free hit.
@@ -4306,27 +4307,9 @@ Planner::run(const BtrfsTreeItem &bti,
                        // that hits the overlay first sees no stale state.
                        layer.invalidate_refs(src);
                        src.invalidate_refs();
-                       // Refetching alone is not enough.  LOGICAL_INO answers
-                       // from the commit root whenever it cannot attach to a
-                       // running transaction, so a dedupe that has not reached
-                       // a commit can be invisible to the refetch, and the
-                       // result does not say which case it was.  Hand it the
-                       // dst refs the dedupe just redirected here so the list
-                       // is complete either way.
-                       layer.repair_refs(src, donor_refs);
                }
                m_filter_cache->invalidate(src_bytenr);
        };
-       // Collect donors before evicting the dst extents: eviction leaves
-       // the node's ref list alone, but the list is what we need and
-       // reading it first keeps the dependency obvious.
-       for (const auto &dst_plan : plan.m_dst_plans) {
-               const auto dst_refs = dst_plan.m_dst.refs(&layer);
-               if (dst_refs) {
-                       donor_refs.insert(donor_refs.end(),
-                               dst_refs->begin(), dst_refs->end());
-               }
-       }
        for (const auto &dst_plan : plan.m_dst_plans) {
                invalidate_dst_hashes(dst_plan.m_dst);
        }
index c9cbcac66b020ed35d094b2f954956f02d663581..8263076b6064d5662f7cccbaf12e361530cc4f71 100644 (file)
@@ -506,6 +506,48 @@ bees_extent_addr(const Fd &root_fd, const BeesFileRange &bfr)
        return bees_extent_addr(root_fd, fid.root(), fid.ino(), bfr.begin());
 }
 
+vector<BeesCreatedRef>
+bees_dedupe_created_refs(const Fd &root_fd, const BeesRangePair &brp)
+{
+       vector<BeesCreatedRef> rv;
+       const auto src_fid = brp.first.fid();
+       const auto src_begin = ranged_cast<uint64_t>(brp.first.begin());
+       const auto src_end = ranged_cast<uint64_t>(brp.first.end());
+       const auto dst_begin = ranged_cast<uint64_t>(brp.second.begin());
+       uint64_t pos = src_begin;
+       while (pos < src_end) {
+               const auto lookup = bees_extent_data_at(root_fd, src_fid.root(), src_fid.ino(), pos);
+               if (!lookup.bti) {
+                       break;
+               }
+               const auto &bti = lookup.bti;
+               uint64_t item_end, bytenr;
+               try {
+                       const auto type = bti.file_extent_type();
+                       if (type != BTRFS_FILE_EXTENT_REG && type != BTRFS_FILE_EXTENT_PREALLOC) {
+                               break;
+                       }
+                       item_end = bti.offset() + bti.file_extent_logical_bytes();
+                       bytenr = bti.file_extent_bytenr();
+               } catch (const exception &) {
+                       break;
+               }
+               if (item_end <= pos) {
+                       break;
+               }
+               // A hole item names no extent and creates no reference.
+               if (bytenr) {
+                       // The new dst item starts where this src item's coverage
+                       // of the deduped range starts:  the item's own start, or
+                       // the range start when the item began before it.
+                       const auto ref_begin = max(bti.offset(), src_begin);
+                       rv.push_back(BeesCreatedRef{bytenr, dst_begin + (ref_begin - src_begin)});
+               }
+               pos = item_end;
+       }
+       return rv;
+}
+
 bool
 bees_extent_same_bytenr(const Fd &root_fd,
        uint64_t subvol_a, uint64_t inum_a, uint64_t file_offset_a,
index 8cc3cdac769ab2fa70efa616e0d857b420ca0be4..a9adc2932433b73f2c1a83c38369c69e577717e2 100644 (file)
@@ -11,6 +11,7 @@
 #include "bees-lib.h"
 #include "bees-log.h"
 #include "bees-reporter.h"
+#include "bees-pending-refs.h"
 #include "bees-verification.h"
 
 #include "crucible/btrfs-tree.h"
@@ -1608,6 +1609,7 @@ private:
        NamedPtr<Exclusion, uint64_t>                   m_extent_locks;  ///< Per-physical-extent mutex pool.
        NamedPtr<Exclusion, uint64_t>                   m_inode_locks;   ///< Per-inode mutex pool.
        shared_ptr<BeesVerificationTracker>             m_verification;  ///< Delayed verification for purportedly deleted extents; built from loop.verify-delay in set_config().
+       BeesPendingRefs                                 m_pending_refs;  ///< References our own dedupes created that a resolve may not yet report.
 
        /// Planner cost benchmark: counts (Σ block-map regions over the start
        /// extent and all its candidates) against the time from plan start to
@@ -1713,6 +1715,8 @@ public:
        /// Return the delayed verification tracker.  Valid only after set_config()
        /// has constructed it from loop.verify-delay.
        BeesVerificationTracker &verification() { return *m_verification; }
+       /// References this process created that a resolve may not yet report.
+       BeesPendingRefs &pending_refs() { return m_pending_refs; }
 
        /// Return the planner cost-vs-region-count benchmark heatmap.
        BeesHeatmap &plan_regions_heatmap() { return m_plan_regions_heatmap; }
@@ -2042,6 +2046,21 @@ void bees_fsync(int fd);
 /// file_extent_offset() + (file_offset - item.offset()).
 string bees_extent_addr(const Fd &root_fd, uint64_t subvol, uint64_t inum, uint64_t file_offset);
 
+/// One reference a dedupe created:  the src extent it names and the dst
+/// file offset of the new EXTENT_DATA item.
+struct BeesCreatedRef {
+       uint64_t m_bytenr;
+       uint64_t m_offset;
+};
+
+/// The references a successful dedupe of @p brp created in its dst file.
+/// The kernel replaces the dst range with one EXTENT_DATA item per src item
+/// it overlapped, each starting at the dst offset that corresponds to the
+/// src item's coverage of the range.  Walks the src file's items over the
+/// range with TREE_SEARCH_V2; a gap, an inline item, or a lookup failure
+/// ends the walk, so the result may be short but never wrong.
+vector<BeesCreatedRef> bees_dedupe_created_refs(const Fd &root_fd, const BeesRangePair &brp);
+
 /// Convenience overload: looks up the EXTENT_DATA covering @p bfr.begin() in @p bfr.fid().
 string bees_extent_addr(const Fd &root_fd, const BeesFileRange &bfr);
 
index d079be84ffb6bfafc90318e73f8eda5b5309d122..02058592efd9d6db97e739d0c9ca49b78dec5d99 100644 (file)
@@ -52,6 +52,7 @@ REPL_OBJS = \
        ../src/bees-scan-next.o \
        ../src/bees-lib.o \
        ../src/bees-log.o \
+       ../src/bees-pending-refs.o \
        ../src/bees-fdcache.o \
        ../src/bees-filter.o \
        ../src/bees-filter-context.o \
index 14bbfbb8a767195bd7d886f47b495be59a568ccd..571cfc3151a103481537328a1e90731ca73e367d 100644 (file)
@@ -52,7 +52,6 @@ BeesExtentLayer::~BeesExtentLayer() = default;
 void BeesExtentLayer::invalidate(uint64_t) {}
 void BeesExtentLayer::invalidate() {}
 void BeesExtentLayer::invalidate_refs(const BeesExtent &) {}
-void BeesExtentLayer::repair_refs(const BeesExtent &, const vector<BeesRef> &) {}
 Fd BeesExtentLayer::open_ref(const BeesRef &) const { return {}; }
 
 // bees-trace.o references exception_check() from bees-lib.o; stub it here