diff --git a/include/bitcoin/database/define.hpp b/include/bitcoin/database/define.hpp index 7a19a344e..a60f54ccd 100644 --- a/include/bitcoin/database/define.hpp +++ b/include/bitcoin/database/define.hpp @@ -21,8 +21,8 @@ #include -// map is able to support 32 bit, but because the database -// requires a larger file this is neither validated nor supported. +// map supports 32 bit, but as database requires larger file +// this is neither validated nor supported. ////static_assert(sizeof(void*) == sizeof(uint64_t), "Not a 64 bit system!"); namespace libbitcoin { diff --git a/include/bitcoin/database/file/advice.hpp b/include/bitcoin/database/file/advice.hpp index d973fb6bf..bcf5af70c 100644 --- a/include/bitcoin/database/file/advice.hpp +++ b/include/bitcoin/database/file/advice.hpp @@ -24,10 +24,10 @@ namespace libbitcoin { namespace database { -/// Expected read pattern of mapped storage, guiding kernel page advice. This -/// is independent of the write pattern (structural): bodies are appended -/// sequentially but read randomly by validation, so advising the kernel from -/// the write pattern invites eviction of the read set under memory pressure. +/// Expected read pattern of mapped storage, guiding kernel page advice. +/// Independent of write pattern (structural): bodies appended sequentially but +/// read randomly by validation, so advising kernel from write pattern invites +/// eviction of read set under memory pressure. enum class advice : uint8_t { /// Let the operating system decide (mixed or unpredictable access). @@ -40,8 +40,8 @@ enum class advice : uint8_t sequential, /// Random access (suppresses read ahead) without preload, for maps too - /// large to reside: scattered reads otherwise fault a full read-ahead - /// window each, and that manufactured cache displaces the head set. + /// large to reside: scattered reads otherwise fault full read-ahead window + /// each, and that manufactured cache displaces head set. scattered }; diff --git a/include/bitcoin/database/file/rotator.hpp b/include/bitcoin/database/file/rotator.hpp index 6bffcc747..66b8b1f4a 100644 --- a/include/bitcoin/database/file/rotator.hpp +++ b/include/bitcoin/database/file/rotator.hpp @@ -35,7 +35,7 @@ struct ofstream_wrap }; /// Simple two file rotating stream with configurable size and file names. -/// Files are rotated after full and writes are contiguous across them. +/// Files rotated after full, writes contiguous across them. class BCD_API rotator_sink : public system::device { diff --git a/include/bitcoin/database/file/utilities.hpp b/include/bitcoin/database/file/utilities.hpp index e5a9283b3..266491e3a 100644 --- a/include/bitcoin/database/file/utilities.hpp +++ b/include/bitcoin/database/file/utilities.hpp @@ -71,7 +71,7 @@ BCD_API code copy_ex(const path& from, const path& to) NOEXCEPT; BCD_API bool copy_directory(const path& from, const path& to) NOEXCEPT; BCD_API code copy_directory_ex(const path& from, const path& to) NOEXCEPT; -/// Discharge directory files from the page cache (posix, otherwise no-op), +/// Discharge directory files from page cache (posix, otherwise no-op), /// synchronizing pending writeback first. False on access/sync error. BCD_API bool discharge_directory(const path& to) NOEXCEPT; BCD_API code discharge_directory_ex(const path& to) NOEXCEPT; diff --git a/include/bitcoin/database/impl/memory/mmap.ipp b/include/bitcoin/database/impl/memory/mmap.ipp index 355fa770a..a155d9d99 100644 --- a/include/bitcoin/database/impl/memory/mmap.ipp +++ b/include/bitcoin/database/impl/memory/mmap.ipp @@ -31,9 +31,9 @@ namespace database { // Constructors. // ---------------------------------------------------------------------------- -// A managed head is an unstaged scalar instance under the anonymous model: -// page-tracked, transferred by its worker, released and shared by currency. -// Unstaged aggregates transfer in full, and shared heads map their files. +// Managed head, unstaged scalar instance under anonymous model: page-tracked, +// transferred by its worker, released and shared by currency. Unstaged +// aggregates transfer in full, shared heads map their files. TEMPLATE CLASS::mmap(const path& filename, const storage_settings& settings, bool random, bool staged, bool shared) NOEXCEPT @@ -144,15 +144,14 @@ size_t CLASS::to_capacity(size_t required) const NOEXCEPT return std::max(minimum_, ceilinged_add(required, growth)); } -// Commitment growth target for the capacity slow paths. Unlike to_capacity -// this never floors to the configured minimum: under lazy commitment that -// floor would commit the full provisioning on first growth (the load failure -// this design exists to prevent, moved from create to first touch). Growth is -// chunked to bound slow path frequency, and clamped so that small tables do -// not over-commit (the provisioned file requires no memory until committed). -// The commit chunk is scaled to memory (bounded by commit_chunk), as the -// committed but unused overhang is otherwise up to one full chunk for every -// instance, an outsized share of a small system under memory pressure. +// Commitment growth target for capacity slow paths. Unlike to_capacity, never +// floors to configured minimum: under lazy commitment that floor would commit +// full provisioning on first growth (load failure this design prevents, moved +// from create to first touch). Growth chunked to bound slow path frequency, and +// clamped so small tables do not over-commit (provisioned file requires no +// memory until committed). Commit chunk scaled to memory (bounded by +// commit_chunk), as committed but unused overhang is otherwise up to one full +// chunk per instance, an outsized share of small system under memory pressure. TEMPLATE size_t CLASS::to_chunk() NOEXCEPT { @@ -178,8 +177,8 @@ size_t CLASS::to_growth(size_t required) const NOEXCEPT #endif } -// Disk provisioning: the configured minimum is a file reservation, ensuring -// that allocation within it cannot fail for space (disk full is detected at +// Disk provisioning: configured minimum is file reservation, ensuring +// allocation within it cannot fail for space (disk full detected at // provisioning, where it remains recoverable). TEMPLATE size_t CLASS::to_provision() const NOEXCEPT @@ -187,11 +186,11 @@ size_t CLASS::to_provision() const NOEXCEPT return std::max(logical_.load(), minimum_); } -// Memory commitment follows use, not provisioning. Committing the configured +// Memory commitment follows use, not provisioning. Committing configured // minimum would demand that much memory (Linux charges the commit) before any // row is written, failing load on any machine smaller than its store sizing. -// Growth commits in chunks within the standing reservation (no remap), so the -// cost is a syscall per chunk over the life of the store. +// Growth commits in chunks within standing reservation (no remap), so cost is a +// syscall per chunk over life of store. TEMPLATE size_t CLASS::to_commitment() const NOEXCEPT { @@ -204,7 +203,7 @@ size_t CLASS::to_commitment() const NOEXCEPT #endif } -// The counter chain is the spine of the design (debug assertion only): +// Counter chain is spine of design (debug assertion only): // // settled_ <= frontier_ <= logical_ <= capacity_ <= file_ // @@ -214,9 +213,9 @@ size_t CLASS::to_commitment() const NOEXCEPT // capacity: rows claimable (committed memory). // file: rows provisioned on disk (fallocate extent). // -// Lower bounds are read first: the lock-free fast path can advance logical_ -// concurrently, so stale-low reads of lower bounds cannot falsify the chain, -// while upper bounds only grow under locks held at every call site. +// Lower bounds read first: lock-free fast path can advance logical_ +// concurrently, so stale-low reads of lower bounds cannot falsify chain, while +// upper bounds only grow under locks held at every call site. TEMPLATE void CLASS::check_invariants_() const NOEXCEPT { diff --git a/include/bitcoin/database/impl/memory/mmap_body.ipp b/include/bitcoin/database/impl/memory/mmap_body.ipp index dc91aade2..f30bf6ab1 100644 --- a/include/bitcoin/database/impl/memory/mmap_body.ipp +++ b/include/bitcoin/database/impl/memory/mmap_body.ipp @@ -74,10 +74,9 @@ bool CLASS::settle_write_(size_t from, size_t to, // ---------------------------------------------------------------------------- // private -// Convert flushed rows [from, to) to a read-only shared file mapping, page -// floored so the settle boundary page remains anonymous with its settled -// bytes retained. Releases the covered anonymous pages. Failure results in -// unmapped. +// Convert flushed rows [from, to) to read-only shared file mapping, page +// floored so settle boundary page remains anonymous with its settled bytes +// retained. Releases covered anonymous pages. Failure results in unmapped. TEMPLATE template bool CLASS::settle_(size_t from, size_t to) NOEXCEPT @@ -104,11 +103,11 @@ bool CLASS::settle_(size_t from, size_t to) NOEXCEPT return false; } - // Demote the settled extent to reclaim-first order: cached for imminent - // re-read (validation follows archival) but reclaimed under pressure - // before active pages and anonymous heads (head residency priority). - // Ample hosts skip demotion: with nothing contesting memory it only - // converts warm cache into re-read faults (see demote_memory). + // Demote settled extent to reclaim-first order: cached for imminent re-read + // (validation follows archival) but reclaimed under pressure before active + // pages and anonymous heads (head residency priority). Ample hosts skip + // demotion: with nothing contesting memory it only converts warm cache into + // re-read faults (see demote_memory). static const auto ample = system_memory() > demote_memory; if (!ample && (mmap_cold(address, end - begin) == fail)) { @@ -120,9 +119,9 @@ bool CLASS::settle_(size_t from, size_t to) NOEXCEPT return true; } -// Revert settled pages at/above rows to committed anonymous memory and -// restore the retained bytes below rows from the file (truncation below the -// settle boundary). Failure results in unmapped. +// Revert settled pages at/above rows to committed anonymous memory and restore +// retained bytes below rows from file (truncation below settle boundary). +// Failure results in unmapped. TEMPLATE template bool CLASS::unsettle_(size_t rows) NOEXCEPT @@ -150,13 +149,13 @@ bool CLASS::unsettle_(size_t rows) NOEXCEPT return true; } -// Release cached pages of settled rows [from, to), page floored within the +// Release cached pages of settled rows [from, to), page floored within // converted read-only mapping (its pages cannot be dirtied, and any pending -// settle write-back is synced by the release). Cost follows residency, so -// re-eviction is idempotent and free. The mapping is unaffected (a later -// read faults the page back from the file). Failure faults the store -// (advisory-class failures have no benign modes) but leaves it mapped, as -// the shared-lock caller cannot tear down under live accessors. +// settle write-back is synced by release). Cost follows residency, so +// re-eviction is idempotent and free. Mapping unaffected (later read +// faults page back from file). Failure faults store (advisory-class +// failures have no benign modes) but leaves it mapped, as shared-lock +// caller cannot tear down under live accessors. TEMPLATE template bool CLASS::evict_(size_t from, size_t to) NOEXCEPT @@ -179,11 +178,11 @@ bool CLASS::evict_(size_t from, size_t to) NOEXCEPT // ---------------------------------------------------------------------------- // private -// Delay the caller while staging exceeds its memory bound (write throttle). -// Signaled as the worker drains; a fault or worker stop releases the caller -// into the normal allocation path (which fails on fault/unload). The relieved -// state is lock-free for the common (unparked) case; notifiers synchronize on -// throttle_mutex_ so a parked caller cannot miss its signal. +// Delay caller while staging exceeds its memory bound (write throttle). +// Signaled as worker drains; fault or worker stop releases caller into normal +// allocation path (which fails on fault/unload). Relieved state lock-free for +// common (unparked) case; notifiers synchronize on throttle_mutex_ so parked +// caller cannot miss its signal. TEMPLATE void CLASS::throttle_() NOEXCEPT { @@ -203,8 +202,8 @@ void CLASS::throttle_() NOEXCEPT throttle_cv_.wait(throttle_lock, relieved); } -// Wake throttled callers, synchronized so a parking caller cannot miss the -// signal between its relieved check and its wait. +// Wake throttled callers, synchronized so parking caller cannot miss signal +// between its relieved check and its wait. TEMPLATE void CLASS::signal_() NOEXCEPT { @@ -217,15 +216,15 @@ void CLASS::signal_() NOEXCEPT // ---------------------------------------------------------------------------- // private -// Pressure-paced draining (the windows model): drain intensity follows memory -// conditions, settled pages remain cached, writers delay only at the staging -// memory bound (write throttle), sustained stillness drains the residual (the -// lazy writer) so a quiescent map converges to fully settled. +// Pressure-paced draining (windows model): drain intensity follows memory +// conditions, settled pages remain cached, writers delay only at staging memory +// bound (write throttle), sustained stillness drains residual (lazy writer) so +// quiescent map converges to fully settled. TEMPLATE void CLASS::body_run_() NOEXCEPT { // Tiers derive from physical memory, pressure and compression occupancy - // (a pressure precursor: the kernel compresses without raising level). + // (pressure precursor: kernel compresses without raising level). const auto memory = system_memory(); const auto urgent = memory / urgent_factor; const auto active = memory / active_factor; @@ -254,10 +253,10 @@ void CLASS::body_run_() NOEXCEPT still = (top == mark) ? std::min(add1(still), idle_seconds) : zero; mark = top; - // Scarcity is read directly: clean cache is reclaimable, so the - // kernel pressure level does not raise while free memory exhausts. - // Once current, reads are not write-ordered, so linux reclaims - // (darwin exhausts its free target without the sweep). + // Scarcity read directly: clean cache is reclaimable, so kernel + // pressure level does not raise while free memory exhausts. Once + // current, reads are not write-ordered, so linux reclaims (darwin + // exhausts its free target without sweep). #if defined(HAVE_LINUX) if (!current_.load() && (system_free() < scarce)) #else @@ -294,9 +293,9 @@ void CLASS::body_run_() NOEXCEPT } } -// Settle up to chunk completed rows: write under the shared remap lock -// (completed extents are immutable, writers proceed), convert under a brief -// exclusive. Durability remains a snapshot property (no sync here). +// Settle up to chunk completed rows: write under shared remap lock (completed +// extents immutable, writers proceed), convert under brief exclusive. +// Durability remains a snapshot property (no sync here). TEMPLATE bool CLASS::settle_next_(size_t chunk) NOEXCEPT { @@ -335,13 +334,13 @@ bool CLASS::settle_next_(size_t chunk) NOEXCEPT return settle_all_(target, sequence{}); } -// Evict up to chunk settled rows under memory scarcity: a wrapping sweep -// from the oldest offset (offset is write age in an append-only body, and -// re-read probability decays with it). Scarcity-driven release keeps the -// machine out of the exhausted-cache regime, where the kernel periodic -// sync walk (cost follows resident pages, not dirty) otherwise degrades -// fault service. A wrong eviction costs one cold read, so the sweep needs -// no precision. Runs under the shared remap lock (readers proceed). +// Evict up to chunk settled rows under memory scarcity: wrapping sweep +// from oldest offset (offset is write age in append-only body, and +// re-read probability decays with it). Scarcity-driven release keeps +// machine out of exhausted-cache regime, where kernel periodic sync +// walk (cost follows resident pages, not dirty) otherwise degrades +// fault service. Wrong eviction costs one cold read, so sweep needs no +// precision. Runs under shared remap lock (readers proceed). TEMPLATE bool CLASS::evict_next_(size_t chunk, size_t& cursor) NOEXCEPT { @@ -353,12 +352,11 @@ bool CLASS::evict_next_(size_t chunk, size_t& cursor) NOEXCEPT // A truncated boundary self-heals here (the cursor clamps to a lap). const auto end = settled_.load(); - // Confine the lap to the recently settled tail: cache holds what was - // just written (and what validation just read), while the body below - // is long evicted, so a full-body lap sweeps unresident rows for most - // of its length and the tail refills faster than the cursor returns. - // A lap can hold no more than physical memory, as nothing else is - // resident to evict. + // Confine lap to recently settled tail: cache holds what was just written + // (and what validation just read), while body below is long evicted, so + // full-body lap sweeps unresident rows for most of its length and tail + // refills faster than cursor returns. Lap can hold no more than physical + // memory, as nothing else is resident to evict. using namespace system; const auto span = greater(chunk, limit(system_memory() / stride)); const auto floor = (end > span) ? (end - span) : zero; diff --git a/include/bitcoin/database/impl/memory/mmap_extent.ipp b/include/bitcoin/database/impl/memory/mmap_extent.ipp index 92b2f9919..38fe16729 100644 --- a/include/bitcoin/database/impl/memory/mmap_extent.ipp +++ b/include/bitcoin/database/impl/memory/mmap_extent.ipp @@ -27,7 +27,7 @@ namespace libbitcoin { namespace database { // Write-completion accounting (staged instances). Extents chase completions, -// closing the gaps, settling the completed prefix. +// closing gaps, settling completed prefix. // ---------------------------------------------------------------------------- TEMPLATE @@ -38,18 +38,18 @@ void CLASS::complete(size_t STAGING_ONLY(offset), if (!staged_ || is_zero(count)) return; - // The covering extent is immobile while this completion is pending and - // cannot refuse a consistent claim, so a failed pass raced a recycle - // (torn navigation or stale snapshot): rescan against a fresh window. + // Covering extent is immobile while this completion is pending and cannot + // refuse a consistent claim, so failed pass raced a recycle (torn + // navigation or stale snapshot): rescan against fresh window. for (;;) { - // Acquire-ordered window snapshot (published entries are immobile; - // the packed word precludes observing a torn head/size pair). + // Acquire-ordered window snapshot (published entries immobile; packed + // word precludes observing torn head/size pair). const auto window = window_.load(std::memory_order_acquire); const auto [head, size] = system::unpack_word(window); - // Lock-free binary search of the sorted window (relaxed navigation - // is heuristic only; claim_ verifies cover under the generation). + // Lock-free binary search of sorted window (relaxed navigation is + // heuristic only; claim_ verifies cover under generation). auto high = size; for (size_t low{}; low < high;) { @@ -77,8 +77,8 @@ void CLASS::complete(size_t STAGING_ONLY(offset), } // Contention can record extents out of start order (allocation claim - // and recording are not one atomic step), transiently breaking search - // order. Contiguity guarantees a unique cover: scan linearly. + // and recording not one atomic step), transiently breaking search + // order. Contiguity guarantees unique cover: scan linearly. for (size_t index{}; index < size; ++index) if (claim_(ring_[(head + index) % extents], offset, count)) return; @@ -103,17 +103,16 @@ size_t CLASS::frontier() const NOEXCEPT // ---------------------------------------------------------------------------- // private -// Claim completion of count rows against the extent, by cas decrement of the -// packed state under a cover check ordered by that state's own acquire: the -// publishing release sequences start/count before state, so both read after -// it belong to the observed generation (a live outstanding precludes a -// recycle in progress, as slots re-record only after retirement). A range -// match read before the acquire can be torn across a recycle and debit the -// slot's successor extent, pinning the true cover's frontier forever. False -// implies the slot does not (or no longer does) cover the offset, or is -// drained (recycle in flight): the caller rescans. The true covering extent -// cannot refuse: its generation is stable and its outstanding covers every -// pending completion while any remains. +// Claim completion of count rows against extent, by cas decrement of packed +// state under cover check ordered by that state's own acquire: publishing +// release sequences start/count before state, so both read after it belong to +// observed generation (live outstanding precludes recycle in progress, as slots +// re-record only after retirement). Range match read before acquire can be torn +// across recycle and debit slot's successor extent, pinning true cover's +// frontier forever. False implies slot does not (or no longer does) cover +// offset, or is drained (recycle in flight): caller rescans. True covering +// extent cannot refuse: its generation is stable and its outstanding covers +// every pending completion while any remains. TEMPLATE bool CLASS::claim_(extent& record, size_t offset, size_t count) NOEXCEPT { @@ -126,8 +125,8 @@ bool CLASS::claim_(extent& record, size_t offset, size_t count) NOEXCEPT const auto outstanding = bit_and(state, outstanding_mask); const auto start = record.start.load(relaxed); - // An outstanding below the claim is a recycle in flight or a drained - // slot (never the covering extent), refused rather than wrapped. + // Outstanding below claim is recycle in flight or drained slot (never + // covering extent), refused rather than wrapped. if ((outstanding < count) || (offset < start) || (offset >= (start + record.count.load(relaxed)))) return false; @@ -136,8 +135,8 @@ bool CLASS::claim_(extent& record, size_t offset, size_t count) NOEXCEPT pack_extent_(generation, outstanding - count), std::memory_order_acq_rel, std::memory_order_acquire)) { - // Extent completion is allocation-coarse, so maintenance is - // cheap here and the element write fast path takes no lock. + // Extent completion is allocation-coarse, so maintenance is cheap + // here and element write fast path takes no lock. if (outstanding == count) { std::unique_lock extent_lock(extent_mutex_, std::try_to_lock); @@ -153,9 +152,8 @@ bool CLASS::claim_(extent& record, size_t offset, size_t count) NOEXCEPT } } -// Claim and record an extent under one lock: a claim never exists outside -// the ring and the ring is start-ordered, so the frontier can never pass an -// unwritten extent (claim-then-record raced the frontier past the claim). +// Claim and record extent under one lock: claim never exists outside ring and +// ring is start-ordered, so frontier can never pass an unwritten extent. // Returns eof (unclaimed) on insufficient capacity, fault, or disk full. TEMPLATE size_t CLASS::record_(size_t count) NOEXCEPT @@ -170,10 +168,10 @@ size_t CLASS::record_(size_t count) NOEXCEPT using namespace system; auto [head, size] = unpack_word(window_.load(relaxed)); - // A full ring waits on its oldest incomplete extent (head-of-line). + // Full ring waits on its oldest incomplete extent (head-of-line). // Completions are lock-free, so waiting needs only this thread's own - // maintenance; fault or disk full releases the wait unclaimed (the write - // then fails fast). + // maintenance; fault or disk full releases wait unclaimed + // (write then fails fast). while (size == extents) { if (fault_.load() || !is_zero(space_.load())) @@ -196,9 +194,9 @@ size_t CLASS::record_(size_t count) NOEXCEPT record.start.store(start, relaxed); record.count.store(count, relaxed); - // Publish the state (pairs with the acquire in claim_): a claim against - // the stale generation now fails its cas, and one against this - // generation observes the new start and count through the release. + // Publish state (pairs with acquire in claim_): claim against stale + // generation now fails its cas, and one against this generation observes + // new start and count through release. record.state.store(pack_extent_(generation, count * columns), std::memory_order_release); @@ -232,7 +230,7 @@ void CLASS::maintain_() NOEXCEPT } // Discard all extents, requires quiescent writers (locked). Any extent then -// outstanding is an abandoned write (unreferenced), safe to settle as is. +// outstanding is abandoned write (unreferenced), safe to settle as is. TEMPLATE void CLASS::discard_() NOEXCEPT { @@ -246,8 +244,8 @@ void CLASS::discard_() NOEXCEPT check_invariants_(); } -// Discard extents above the truncation and clamp any overlap, requires -// quiescent writers (locked). +// Discard extents above truncation and clamp any overlap, +// requires quiescent writers (locked). TEMPLATE void CLASS::trim_(size_t count) NOEXCEPT { @@ -273,8 +271,8 @@ void CLASS::trim_(size_t count) NOEXCEPT const auto trimmed = count - start; tail.count.store(trimmed, relaxed); - // Clamp outstanding within the state, generation unchanged - // (the extent is trimmed, not recycled; writers quiescent). + // Clamp outstanding within state, generation unchanged (extent + // trimmed, not recycled; writers quiescent). const auto limit = trimmed * columns; const auto state = tail.state.load(relaxed); if (bit_and(state, outstanding_mask) > limit) diff --git a/include/bitcoin/database/impl/memory/mmap_head.ipp b/include/bitcoin/database/impl/memory/mmap_head.ipp index d1218f7e9..bd52bc6f2 100644 --- a/include/bitcoin/database/impl/memory/mmap_head.ipp +++ b/include/bitcoin/database/impl/memory/mmap_head.ipp @@ -29,8 +29,8 @@ namespace libbitcoin { namespace database { -// Write declaration and marking (managed head instances). Marks drive the -// dirty transfer, declarations restore released pages ahead of the write. +// Write declaration and marking (managed head instances). Marks drive dirty +// transfer, declarations restore released pages ahead of write. // ---------------------------------------------------------------------------- TEMPLATE @@ -41,15 +41,15 @@ void CLASS::prepare(size_t STAGING_ONLY(offset), if (is_zero(size) || !managed_) return; - // Count the writer before loading released below (sequentially - // consistent), pairing with the release protocol: release either observes - // the count (and aborts) or this writer observes released (and restores). - // Intent bits age (hot sampling), so they cannot protect a write held - // in flight across passes; the count persists until mark. - // A settle transition pairs the same way, but the writer waits UNCOUNTED - // (it retires its count and does not retake one until the transition - // clears), so the count drains monotonically and the transition is - // guaranteed to observe zero rather than merely likely to. + // Count writer before loading released below (sequentially consistent), + // pairing with release protocol: release either observes count (and aborts) + // or this writer observes released (and restores). + // Intent bits age (hot sampling), so cannot protect a write held in flight + // across passes; count persists until mark. + // Settle transition pairs same way, but writer waits UNCOUNTED (it retires + // its count and does not retake one until transition clears), so count + // drains monotonically and transition is guaranteed to observe zero rather + // than merely likely to. auto& writers = writer_slot_(); for (;;) { @@ -70,8 +70,8 @@ void CLASS::prepare(size_t STAGING_ONLY(offset), if (!engaged_.load(relaxed) && !lazy_.load(relaxed)) return; - // Declare intent before the write (sequentially consistent, pairing with - // the release protocol), then restore any released page in the range. + // Declare intent before write (sequentially consistent, pairing with + // release protocol), then restore any released page in range. auto restore = false; auto page = offset / page_; const auto end = (offset + sub1(size)) / page_; @@ -98,19 +98,18 @@ void CLASS::mark(size_t STAGING_ONLY(offset), return; // Marks follow content writes; transfer clears before reading, so pages - // remarked during a transfer are simply rewritten by the next pass. A - // settled head writes through its mapping, so its marks count only (the - // worker reads the rate); no transition intervenes (the writer is - // counted), so the path matches prepare. + // remarked during transfer are rewritten by next pass. Settled head writes + // through its mapping, so its marks count only (worker reads the rate); no + // transition intervenes (writer is counted), so path matches prepare. if (shared_.load()) marks_.fetch_add(one, relaxed); else remark_(offset, size); - // Uncount the writer after its marks (sequentially consistent), so a - // release pass loading a drained count observes the dirty bits. Only - // prepare() counts, so only mark() may uncount (transfer failure restores - // marks by remark_, as an unpaired uncount here corrupts the count). + // Uncount writer after its marks (sequentially consistent), so release pass + // loading drained count observes dirty bits. Only prepare() counts, so only + // mark() may uncount (transfer failure restores marks by remark_, as + // unpaired uncount here corrupts count). writer_slot_().fetch_sub(one); #endif } @@ -127,10 +126,10 @@ void CLASS::current(bool state) NOEXCEPT // ---------------------------------------------------------------------------- // private -// Head-creation fill: the fill is file content, written sequentially to the -// file (page cache, no mapping involvement) and installed released, so -// creation contributes no memory residency (an in-memory backfill of the -// head set is the store's largest allocation transient). +// Head-creation fill: fill is file content, written sequentially +// to file (page cache, no mapping involvement) and installed +// released, so creation contributes no memory residency (in-memory +// backfill of head set is store's largest allocation transient). TEMPLATE size_t CLASS::allocate_filled_(size_t count) NOEXCEPT { @@ -177,10 +176,10 @@ size_t CLASS::allocate_filled_(size_t count) NOEXCEPT return start; } -// Install the managed head lazily over its current logical span: a released -// (read-only file) full-page prefix restored to anonymous per segment on -// first write, an anonymous populated tail, and clean page tracking sized to -// a replacement reservation. Caller holds exclusive remap (or is loading). +// Install managed head lazily over its current logical span: released +// (read-only file) full-page prefix restored to anonymous per segment on first +// write, anonymous populated tail, and clean page tracking sized to replacement +// reservation. Caller holds exclusive remap (or is loading). TEMPLATE bool CLASS::lazy_install_() NOEXCEPT { @@ -255,8 +254,8 @@ bool CLASS::lazy_install_() NOEXCEPT // ---------------------------------------------------------------------------- // private -// Dirty marking without the writer uncount (no paired prepare), for internal -// mark restoration (mark() pairs with prepare() and uncounts its writer). +// Dirty marking without writer uncount (no paired prepare), for internal mark +// restoration (mark() pairs with prepare() and uncounts its writer). TEMPLATE void CLASS::remark_(size_t offset, size_t size) NOEXCEPT { @@ -271,10 +270,10 @@ void CLASS::remark_(size_t offset, size_t size) NOEXCEPT marks_.fetch_add(one, relaxed); } -// Transfer dirty pages within [0, bytes), clearing marks before content -// reads so that concurrently remarked pages transfer on the next pass. -// Marks beyond bytes are retained (backfill above logical transfers when -// logical grows over it). Adjacent dirty pages coalesce into single writes. +// Transfer dirty pages within [0, bytes), clearing marks before content reads +// so concurrently remarked pages transfer on next pass. Marks beyond bytes +// retained (backfill above logical transfers when logical grows over it). +// Adjacent dirty pages coalesce into single writes. TEMPLATE template bool CLASS::transfer_(size_t bytes) NOEXCEPT @@ -329,9 +328,9 @@ bool CLASS::transfer_(size_t bytes) NOEXCEPT if (!write()) { - // Restore claimed marks (the failed range, the page that - // ended it, and this word's unwritten remainder) so failure - // is retryable, not lossy. + // Restore claimed marks (failed range, page that + // ended it, and this word's unwritten remainder) + // so failure is retryable, not lossy. remark_(from, to - from); remark_(start, end - start); dirty_[word].fetch_or(bits, relaxed); @@ -356,16 +355,15 @@ bool CLASS::transfer_(size_t bytes) NOEXCEPT // ---------------------------------------------------------------------------- // private -// Idle transfer for unstaged (rewrite-in-place head) instances: sustained -// mark stillness drains dirty pages (the lazy writer) so a quiescent map -// converges to persisted and snapshot/close transfer approximately nothing. -// Requires no write exclusion: marks follow writes and transfer clears -// before reading, so racing writes remark and transfer on the next pass -// (torn disk pages are unreachable, as live heads are only trusted -// following a clean close). +// Idle transfer for unstaged (rewrite-in-place head) instances: sustained mark +// stillness drains dirty pages (lazy writer) so quiescent map converges to +// persisted and snapshot/close transfer approximately nothing. Requires no +// write exclusion: marks follow writes and transfer clears before reading, so +// racing writes remark and transfer on next pass (torn disk pages unreachable, +// as live heads are only trusted following clean close). // -// Memory scarcity additionally pages the head to its own file (the windows -// model): transfer, then release cold clean pages to read-only file mappings +// Memory scarcity additionally pages head to its own file (windows model): +// transfer, then release cold clean pages to read-only file mappings // (reclaimable cache), restored to anonymous by prepare() before any write. // Release waits one pass after engagement so all writers declare intent. TEMPLATE @@ -401,27 +399,25 @@ void CLASS::head_run_() NOEXCEPT continue; } - // A drained head settles to its file mapping while the store is - // current (settled pages are droppable, anonymous pages are not). + // Drained head settles to its file mapping while store is current + // (settled pages droppable, anonymous pages not). if (current_.load() && (transferred == top) && share_(transferred)) continue; - // Touch pass: assert working-set residency at a bounded rate. - // Hash-uniform probing is per-page sparse in every phase, so the - // kernel ages head pages cold and swaps them under cache pressure, - // though the set is the process working set (and head misses are - // unshieldable serial faults on the probe path). A read sets the - // page-table accessed bit without dirtying the page; volatile - // prevents elision. The unprivileged equivalent of mlock, and soft: - // under true extremity the kernel can still take the pages. The - // per-tick budget revisits every page each touch_seconds regardless - // of instance size (a whole-instance lap gave the largest head a - // proportionally longer revisit, which lost the aging race first). - // Residency-guarded so the touch never faults: a swapped page that - // nothing probes rests in swap, one the workload needs returns by - // its own fault and is defended thereafter. - // Residency is only contested under scarcity, so at plenty the tick - // costs a counter test (the aging race has no other runner). + // Touch pass: assert working-set residency at bounded rate. + // Hash-uniform probing is per-page sparse in every phase, so kernel + // ages head pages cold and swaps them under cache pressure, though the + // set is process working set (and head misses are unshieldable serial + // faults on probe path). A read sets page-table accessed bit without + // dirtying page; volatile prevents elision. Unprivileged equivalent of + // mlock, and soft: under true extremity kernel can still take pages. + // Per-tick budget revisits every page each touch_seconds regardless of + // instance size. + // Residency-guarded so touch never faults: swapped page that nothing + // probes rests in swap, one workload needs returns by its own fault and + // is defended thereafter. + // Residency only contested under scarcity, so at plenty tick costs a + // counter test (aging race has no other runner). if (system_available() < (system_memory() / sweep_factor)) { using namespace system; @@ -432,8 +428,7 @@ void CLASS::head_run_() NOEXCEPT auto budget = ceilinged_divide(pages, touch_seconds); #if !defined(HAVE_APPLE) // Probe buffer and map alias, declared with the touch they - // serve (excluded on darwin below), as they are otherwise - // unused there. + // serve (excluded on darwin below), as otherwise unused there. unsigned char resident[touch_span]; const volatile auto* map = memory_map_[zero]; #endif @@ -447,8 +442,8 @@ void CLASS::head_run_() NOEXCEPT #if !defined(HAVE_APPLE) // Darwin excluded: mincore hides compressed pages from - // the guard, and unguarded touching measured as pure - // decompression churn; release is the darwin mechanism. + // guard, and unguarded touching measured as pure + // decompression churn; release is darwin mechanism. const auto at = touched * page_; if (mmap_resident(std::next(memory_map_[zero], at), count * page_, resident) == 0) @@ -463,20 +458,20 @@ void CLASS::head_run_() NOEXCEPT } } - // Available includes reclaimable file cache, which a loaded store - // keeps large while the kernel swaps cold anonymous pages, so free - // exhaustion also signals scarcity (anon is being displaced). - // A sync writes every head hot (a converted run restores at the next - // burst), so release engages only while the store is current. + // Available includes reclaimable file cache, which loaded store keeps + // large while kernel swaps cold anonymous pages, so free exhaustion + // also signals scarcity (anon being displaced). + // Sync writes every head hot (converted run restores at next burst), so + // release engages only while store is current. const auto scarcity = head_release && managed_ && current_.load() && ((system_available() < scarce) || (system_free() < scarce)); - // Once engaged, a quiet instance converts independent of momentary - // scarcity: the signal clears as swap absorbs the hot set, but the - // swapped pages remain anonymous, so reads fault them back one at a - // time (a serial swap-in per probe). Conversion instead settles - // clean pages without read-back (the file holds their content), - // freeing swap and routing reads through the file mapping. + // Once engaged, quiet instance converts independent of momentary + // scarcity: signal clears as swap absorbs hot set, but swapped + // pages remain anonymous, so reads fault them back one at a time + // (serial swap-in per probe). Conversion instead settles clean + // pages without read-back (file holds their content), freeing + // swap and routing reads through file mapping. const auto engaged = engaged_.load(); const auto quiet = writes < release_quiet; const auto draining = engaged && quiet; @@ -484,17 +479,16 @@ void CLASS::head_run_() NOEXCEPT ((still < idle_seconds) || (transferred == top))) continue; - // A write-hot instance neither transfers nor releases under - // scarcity: transferred pages re-dirty immediately (write - // amplification without release payoff, as hash-scattered writes - // into released pages each cost a segment restore, and the sweep - // otherwise re-releases restored segments every pass). Its - // anonymous set is left to swap (dirty-exempt) until quiescence, - // typically the phase change. + // Write-hot instance neither transfers nor releases under scarcity: + // transferred pages re-dirty immediately (write amplification without + // release payoff, as hash-scattered writes into released pages each + // cost a segment restore, and sweep otherwise re-releases restored + // segments every pass). Its anonymous set is left to swap + // (dirty-exempt) until quiescence, typically phase change. #if !defined(HAVE_APPLE) // EXPERIMENT: darwin releases while write-hot (page-level intent and - // dirty filters remain) to price segment restores against the - // measured compressed-hot crawl. + // dirty filters remain) to price segment restores + // against measured compressed-hot crawl. if (scarcity && !quiet) continue; #endif @@ -510,8 +504,8 @@ void CLASS::head_run_() NOEXCEPT engaged_.store(true); // Scarcity passes pace writeback for release: settle maps page - // cache content, and durability remains a clean close property, - // so sync applies only to idle draining. + // cache content, and durability remains clean close property, so + // sync applies only to idle draining. if (!transfer_(to_width(logical_.load())) || (!scarcity && !sync_())) { @@ -519,14 +513,14 @@ void CLASS::head_run_() NOEXCEPT continue; } - // Discard the page cache copy of the transfer: the anonymous - // head is the live copy, so caching the file doubles it. + // Discard page cache copy of transfer: anonymous head is live copy, + // so caching file doubles it. file_discard(opened_[zero]); - // Quiet is assured here (hot scarcity skipped above, and idle - // draining implies sixty still seconds). - // Lazy head load engages restore on all platforms; the release - // sweep remains a darwin response (see head_release). + // Quiet assured here (hot scarcity skipped above, and idle draining + // implies sixty still seconds). + // Lazy head load engages restore on all platforms; release sweep + // remains darwin response (see head_release). if constexpr (head_release) if (engaged && !release_pages_()) continue; @@ -541,8 +535,8 @@ void CLASS::head_run_() NOEXCEPT // ---------------------------------------------------------------------------- // private -// Declare the full-page prefix below logical released and engage the restore -// protocol (prepare restores a released segment before its write). +// Declare full-page prefix below logical released and engage restore protocol +// (prepare restores released segment before its write). TEMPLATE void CLASS::declare_released_() NOEXCEPT { @@ -551,8 +545,9 @@ void CLASS::declare_released_() NOEXCEPT for (size_t word{}; word < ceilinged_divide(flags, page_bound); ++word) { const auto first = word * page_bound; - released_[word].store((flags >= (first + page_bound)) ? - bit_all : unmask_right(flags - first)); + const auto full = (flags >= (first + page_bound)); + const auto partial = unmask_right(flags - first); + released_[word].store(full ? bit_all : partial); } lazy_.store(true); @@ -561,12 +556,12 @@ void CLASS::declare_released_() NOEXCEPT // Release cold clean head page runs to read-only file mappings (reclaimable), // full pages below logical only. Conversion is run-granular (release_chunk // minimum) as each conversion splits a mapping: page granularity fragments -// the address space beyond what host memory management tolerates. Writer -// synchronization is a per-page bit protocol: prepare() declares intent then -// loads released; release stores released then loads intent (both -// sequentially consistent), so a run converts only when no write can land on -// it unrestored. A wrong release costs one restore. Conversion excludes -// restore on restore_mutex_. +// address space beyond what host memory management tolerates. +// Writer synchronization is per-page bit protocol: prepare() +// declares intent then loads released; release stores released then +// loads intent (both sequentially consistent), so run converts only +// when no write can land on it unrestored. Wrong release costs one +// restore. Conversion excludes restore on restore_mutex_. TEMPLATE bool CLASS::release_pages_() NOEXCEPT { @@ -578,9 +573,8 @@ bool CLASS::release_pages_() NOEXCEPT std::unique_lock restore_lock(restore_mutex_); - // Materialize candidacy (hot aging clears only the snapshot bits, so a - // concurrent declaration on a candidate page is retained for the live - // rechecks below). + // Materialize candidacy (hot aging clears only snapshot bits, so concurrent + // declaration on candidate page is retained for live rechecks below). for (size_t word{}; word < bound; ++word) { const auto hot = intent_[word].load(); @@ -590,13 +584,13 @@ bool CLASS::release_pages_() NOEXCEPT pages, word * page_bound); } - // Convert maximal candidate runs of at least chunk pages, clamped to - // chunk bounds. Restore is chunk-aligned and chunk-granular, so a - // partially released chunk places unreleased pages inside a restored - // span. The bit protocol guards released pages only: a writer to an - // unreleased page observes released clear, so it neither restores nor - // takes restore_mutex_, and its write is dropped by the copy-install - // window. Whole chunks make the restored span exactly the released set. + // Convert maximal candidate runs of at least chunk pages, clamped + // to chunk bounds. Restore is chunk-aligned and chunk-granular, so + // partially released chunk places unreleased pages inside restored + // span. Bit protocol guards released pages only: writer to + // unreleased page observes released clear, so neither restores nor + // takes restore_mutex_, and its write is dropped by copy-install + // window. Whole chunks make restored span exactly the released set. for (auto run = next_run(sweep_.get(), pages, zero); run.first < pages; run = next_run(sweep_.get(), pages, run.second)) { @@ -617,10 +611,10 @@ bool CLASS::release_pages_() NOEXCEPT for (auto word = begin; word <= end; ++word) released_[word].fetch_or(mask(word)); - // An in-flight writer (counted, unaged) or raced intent or mark - // invalidates the conversion (whole run). The count loads first: a - // writer counted later observes released and restores, one drained - // earlier has published its marks (both sequentially consistent). + // In-flight writer (counted, unaged) or raced intent or mark + // invalidates conversion (whole run). Count loads first: writer counted + // later observes released and restores, one drained earlier has + // published its marks (both sequentially consistent). auto raced = is_nonzero(writers_count_()); for (auto word = begin; (word <= end) && !raced; ++word) raced = !is_zero(bit_and(mask(word), @@ -650,11 +644,11 @@ bool CLASS::release_pages_() NOEXCEPT } // Restore released pages overlapping [offset, offset+size) to writable -// anonymous memory (content preserved by atomic installation), before a -// declared write. Restoration is segmented at release_chunk alignment: the -// containing segment restores whole (unifying any fragmentation within it) -// but never more, as released runs consolidate without bound and restoring -// a maximal run copies gigabytes per scattered write (a restore convoy). +// anonymous memory (content preserved by atomic installation), before declared +// write. Restoration segmented at release_chunk alignment: containing segment +// restores whole (unifying any fragmentation within it) but never more, as +// released runs consolidate without bound and restoring maximal run copies +// gigabytes per scattered write (restore convoy). TEMPLATE void CLASS::restore_(size_t offset, size_t size) NOEXCEPT { @@ -662,7 +656,7 @@ void CLASS::restore_(size_t offset, size_t size) NOEXCEPT std::shared_lock restore_lock(restore_mutex_); // Segments clamp to full pages below logical (as does release candidacy): - // the reservation above commitment is inaccessible (installation reads). + // reservation above commitment is inaccessible (installation reads). const auto pages = to_width(logical_.load()) / page_; const auto span = std::max(one, release_chunk / page_); const auto last = (offset + sub1(size)) / page_; @@ -731,8 +725,8 @@ void CLASS::writers_reset_() NOEXCEPT shard.count.store(zero); } -// Exclude head writers across a share transition: they write through raw -// pointers under no lock, so only the writer count can exclude them. +// Exclude head writers across share transition: they write through raw pointers +// under no lock, so only writer count can exclude them. TEMPLATE void CLASS::quiesce_() NOEXCEPT { @@ -741,19 +735,17 @@ void CLASS::quiesce_() NOEXCEPT std::this_thread::yield(); } -// Settle a quiescent managed head to a writable mapping of its file over the -// committed span (as a shared head loads): pages drop under pressure and -// writes dirty page cache for kernel writeback, so page tracking idles (it -// remains allocated, as writers read it unlocked). Exclusive remap excludes -// accessors and the transition excludes counted head writers (raw pointer -// writes hold no lock), so a mark count still at the drained count proves -// the file current (a write landing after the drain snapshot would otherwise -// be lost to the remap). -// The remap lock precedes the drain: a writer holding an accessor waits -// uncounted at the transition, so a drain that preceded the lock would return -// on its own and the lock would then wait on that writer forever. Every -// counted writer either holds no lock or took its accessor before its count, -// so under the lock the count drains. +// Settle quiescent managed head to writable mapping of its file over committed +// span (as shared head loads): pages drop under pressure and writes dirty page +// cache for kernel writeback, so page tracking idles (remains allocated, as +// writers read it unlocked). Exclusive remap excludes accessors and transition +// excludes counted head writers (raw pointer writes hold no lock), so mark +// count still at drained count proves file current (write landing after drain +// snapshot would otherwise be lost to remap). +// Remap lock precedes drain: writer holding accessor waits uncounted at +// transition, so drain that preceded lock would return on its own and lock +// would then wait on that writer forever. Every counted writer either holds no +// lock or took its accessor before its count, so under lock count drains. TEMPLATE bool CLASS::share_(size_t transferred) NOEXCEPT { @@ -763,8 +755,8 @@ bool CLASS::share_(size_t transferred) NOEXCEPT auto shared = false; if (loaded_.load() && !fault_.load() && (marks_.load() == transferred)) { - // The drain transfers below logical; the committed fill above it is - // content (a raised logical exposes it unwritten). + // Drain transfers below logical; committed fill above it is content + // (raised logical exposes it unwritten). const auto logical = to_width(logical_.load()); const auto span = to_width(capacity_.load()); const auto persisted = (span <= logical) || pwrite_all(opened_[zero], @@ -788,12 +780,12 @@ bool CLASS::share_(size_t transferred) NOEXCEPT return shared; } -// Return a settled head to the anonymous model without a bulk remap: every -// full page declares released (the shared mapping is droppable file content), -// so tracked writers restore segments to anonymous before writing, and the -// tail above the full-page floor restores here (as the load commits it), so -// no dirty page is ever transferred from the file mapping (a self-copy, which -// darwin serves as an uninterruptible wait). Cold pages remain mapped. +// Return settled head to anonymous model without bulk remap: every full page +// declares released (shared mapping is droppable file content), so tracked +// writers restore segments to anonymous before writing, and tail above +// full-page floor restores here (as load commits it), so no dirty page is ever +// transferred from file mapping (a self-copy, which darwin serves as +// uninterruptible wait). Cold pages remain mapped. TEMPLATE void CLASS::unshare_() NOEXCEPT { diff --git a/include/bitcoin/database/impl/memory/mmap_native.ipp b/include/bitcoin/database/impl/memory/mmap_native.ipp index 972cc205a..67a6408c1 100644 --- a/include/bitcoin/database/impl/memory/mmap_native.ipp +++ b/include/bitcoin/database/impl/memory/mmap_native.ipp @@ -72,8 +72,8 @@ bool CLASS::map_() NOEXCEPT else { // Cannot map empty file, want minimum capacity, expand as required. - // The classic mapping is file-backed, so commitment is provisioning. - // disk_full: space is set but no code is set with false return. + // Classic mapping is file-backed, so commitment is provisioning. + // disk_full: space set but no code set with false return. const auto size = to_provision(); if (!resize_(size)) return false; @@ -168,8 +168,8 @@ bool CLASS::release_(size_t size) NOEXCEPT set_first_code(error::munmap_failure); // loaded_ is caller-owned: unmap_ publishes unloaded, remap_ remains - // loaded across replacement (lock-free allocate guards must not - // observe a transient unload). + // loaded across replacement + // (lock-free allocate guards must not observe transient unload). memory_map_[Column] = {}; return success; } @@ -198,9 +198,8 @@ bool CLASS::finalize_() NOEXCEPT // ---------------------------------------------------------------------------- // private -// Remove the pages of rows [from, to) from the working set. The mapping is -// unaffected (a later read faults the page back). Advisory: failure alters -// nothing and is not a fault. +// Remove pages of rows [from, to) from working set. Mapping unaffected (later +// read faults page back). Advisory: failure alters nothing and is not a fault. TEMPLATE template bool CLASS::evict_(size_t from, size_t to) NOEXCEPT @@ -246,9 +245,9 @@ void CLASS::scan_run_() NOEXCEPT while (tick_()) { - // Steering is only useful against a trim, and a trim only happens - // under contention, so at plenty the tick is a counter test. This - // also bounds the idle cost to the wait itself. + // Steering is only useful against a trim, and trim only happens under + // contention, so at plenty tick is a counter test. Also bounds idle + // cost to wait itself. if (system_available() >= (system_memory() / sweep_factor)) continue; @@ -257,8 +256,8 @@ void CLASS::scan_run_() NOEXCEPT continue; // Revisit every head page each touch_seconds regardless of instance - // size. A read sets the access bit without dirtying the page; - // volatile prevents elision. + // size. A read sets access bit without + // dirtying page; volatile prevents elision. const auto pages = to_width(logical_.load()) / page; const volatile auto* map = memory_map_[zero]; auto budget = ceilinged_divide(pages, touch_seconds); @@ -269,7 +268,8 @@ void CLASS::scan_run_() NOEXCEPT touched = zero; const auto at = touched * page; - const auto count = std::min({ touch_span, pages - touched, budget }); + const auto remaining = pages - touched; + const auto count = std::min({ touch_span, remaining, budget }); for (size_t index{}; index < count; ++index) (void)map[at + index * page]; diff --git a/include/bitcoin/database/impl/memory/mmap_private.ipp b/include/bitcoin/database/impl/memory/mmap_private.ipp index d7ab4cb22..8b018bd5c 100644 --- a/include/bitcoin/database/impl/memory/mmap_private.ipp +++ b/include/bitcoin/database/impl/memory/mmap_private.ipp @@ -123,8 +123,8 @@ template bool CLASS::remap_all_(size_t capacity, std::index_sequence, bool final) NOEXCEPT { - // Probed before touching any column file: a refused wave then retains no - // surplus provisioning (a partial wave cannot be trimmed, as msc cannot + // Probed before touching any column file: refused wave then retains no + // surplus provisioning (partial wave cannot be trimmed, as msc cannot // shrink a mapped file). if (!probe_(capacity)) { @@ -141,19 +141,19 @@ bool CLASS::remap_all_(size_t capacity, std::index_sequence, if (!(remap_(capacity, final) && ...)) { - // A non-final refusal leaves the maps and capacity intact for the - // caller's reduced retry (columns already grown by the refused - // attempt harmlessly retain surplus commitment or provisioning). + // Non-final refusal leaves maps and capacity intact for caller's + // reduced retry (columns already grown by refused attempt harmlessly + // retain surplus commitment or provisioning). if (final) capacity_.store(zero); return false; } - // Growth beyond the provisioned file extends it (resize_ is a no-op - // within), so the extent tracks the high water of provisioning. - // Migration copies only to logical, so fill from logical (writers are - // excluded by the remap lock, claims publish only below logical). + // Growth beyond provisioned file extends it (resize_ is a no-op within), so + // extent tracks high water of provisioning. + // Migration copies only to logical, so fill from logical (writers excluded + // by remap lock, claims publish only below logical). backfill_all_(logical_.load(), capacity, sequence{}); file_.store(std::max(file_.load(), capacity)); capacity_.store(capacity); @@ -161,16 +161,15 @@ bool CLASS::remap_all_(size_t capacity, std::index_sequence, return true; } -// Iterated growth (callers hold the remap lock). Growth asks are amortized -// (rate surplus over the necessity), and each is admitted only while it -// leaves the configured headroom of the backing resource unclaimed (probed -// with the ask, released on grant), so exhaustion never consumes the -// system's final bytes. A large amortization step can be refused while the -// necessity fits, so iterate: halve the refused surplus toward the -// necessity. Refusal of the necessity is exhaustion, not store damage: -// published as disk full (space set, store intact, writes fail fast until -// cleared), it clears by settle drainage or operator relief, where teardown -// would convert a shortage into a restore. +// Iterated growth (callers hold remap lock). Growth asks are amortized (rate +// surplus over necessity), and each admitted only while it leaves configured +// headroom of backing resource unclaimed (probed with ask, released on grant), +// so exhaustion never consumes system's final bytes. Large amortization step +// can be refused while necessity fits, so iterate: halve refused surplus toward +// necessity. Refusal of necessity is exhaustion, not store damage: published as +// disk full (space set, store intact, writes fail fast until cleared), it +// clears by settle drainage or operator relief, where teardown would convert a +// shortage into a restore. TEMPLATE bool CLASS::grow_(size_t end) NOEXCEPT { @@ -206,8 +205,8 @@ void CLASS::zero_all_(size_t from, size_t to, size_t fresh, (zero_(from, to, fresh), ...); } -// Zero column bytes of rows [from, to), less the page floored [from, fresh) -// already zero (the settle boundary page is anonymous and retains its bytes). +// Zero column bytes of rows [from, to), less page floored [from, fresh) already +// zero (settle boundary page is anonymous and retains its bytes). TEMPLATE template void CLASS::zero_(size_t from, size_t to, size_t STAGING_ONLY(fresh)) NOEXCEPT @@ -258,10 +257,10 @@ void CLASS::backfill_(size_t from, size_t to) NOEXCEPT } } -// The wave probe reserves the whole extension plus headroom on the store -// volume (column widths sum to the stride) leaves the headroom unclaimed. -// An unmeasurable volume admits the wave: growth failure is the store's own -// disk full detection, and a query failure is not an exhaustion signal. +// Wave probe reserves whole extension plus headroom on store volume (column +// widths sum to stride) leaves headroom unclaimed. Unmeasurable volume admits +// wave: growth failure is store's own disk full detection, and query failure is +// not an exhaustion signal. TEMPLATE bool CLASS::probe_(size_t capacity) NOEXCEPT { @@ -290,8 +289,8 @@ bool CLASS::resize_(size_t size, bool final) NOEXCEPT } else { - // The file is provisioned ahead of commitment, so growth within the - // provisioned extent requires no disk operation (space is reserved). + // File provisioned ahead of commitment, so growth within provisioned + // extent requires no disk operation (space reserved). const auto extent = file_.load(); if (size <= extent) return true; @@ -300,17 +299,18 @@ bool CLASS::resize_(size_t size, bool final) NOEXCEPT const auto target = to_width(size); const auto capacity = to_width(extent); - // Disk full detection, any other failure is an abort. The wave probe + // Disk full detection, any other failure is an abort. Wave probe // (remap_all_) precedes, so refusal here is a raced foreign consumer. #if !defined(WITHOUT_FALLOCATE) - if (::fallocate(opened_[Column], 0, capacity, target - capacity) == fail) + const auto growth = target - capacity; + if (::fallocate(opened_[Column], 0, capacity, growth) == fail) #else if (::ftruncate(opened_[Column], target) == fail) #endif { - // Disk full is the only restartable store failure (leave mapped). - // A non-final refusal is not published: the caller retries reduced. - // The published requirement includes the headroom (a retry probes). + // Disk full is only restartable store failure (leave mapped). + // Non-final refusal not published: caller retries reduced. + // Published requirement includes headroom (a retry probes). if (errno == ENOSPC) { if (final) @@ -347,7 +347,7 @@ void CLASS::worker_start_() NOEXCEPT limit_ = system_memory() / throttle_factor; #else // Managed heads steer residency and bounded bodies release cache; other - // bodies and a shared head are the cache manager's to place. + // bodies and shared head are cache manager's to place. if (head_shared_ || (staged_ && is_zero(reserve_) && is_zero(ceiling_))) return; #endif @@ -421,9 +421,9 @@ bool CLASS::exceeded_() const NOEXCEPT (!is_zero(ceiling_) && (process_resident() > ceiling_)); } -// Release the cache of the body by chunk until no memory bound is exceeded: -// a wrapping sweep of at most one lap, by chunk under the shared remap lock -// (readers proceed, a remap waits one chunk). A wrong release costs one read. +// Release cache of body by chunk until no memory bound is exceeded: wrapping +// sweep of at most one lap, by chunk under shared remap lock (readers proceed, +// remap waits one chunk). Wrong release costs one read. TEMPLATE void CLASS::reclaim_(size_t& cursor) NOEXCEPT { diff --git a/include/bitcoin/database/impl/memory/mmap_staging.ipp b/include/bitcoin/database/impl/memory/mmap_staging.ipp index b5747d239..561a05243 100644 --- a/include/bitcoin/database/impl/memory/mmap_staging.ipp +++ b/include/bitcoin/database/impl/memory/mmap_staging.ipp @@ -48,9 +48,9 @@ bool CLASS::flush_(size_t rows) NOEXCEPT return success; } -// Persist rows below to: settled rows are already on disk (staged appends -// the remainder), a shared head synchronizes its mapping (writes through), -// an anonymous head transfers its dirty pages. +// Persist rows below to: settled rows already on disk (staged appends +// remainder), shared head synchronizes its mapping (writes through), anonymous +// head transfers its dirty pages. TEMPLATE template bool CLASS::persist_(size_t to) NOEXCEPT @@ -135,9 +135,9 @@ bool CLASS::remap_(size_t size, bool final) NOEXCEPT if (is_zero(size)) size = minimum_; - // The file is preallocated to capacity, preserving disk full detection at + // File preallocated to capacity, preserving disk full detection at // allocation, and growth commits reserved anonymous pages in place, so no - // mapping is released and the map base is stable within the reservation. + // mapping is released and map base is stable within reservation. if (!resize_(size, final)) return false; @@ -150,18 +150,18 @@ TEMPLATE template bool CLASS::stage_() NOEXCEPT { - // Provision the file in full (disk reserved, so allocation within cannot - // fail for space), but commit only what is in use; committing provisioned - // rows would charge that memory before anything is written. - // disk_full: space is set but no code is set with false return. + // Provision file in full (disk reserved, so allocation within cannot fail + // for space), but commit only what is in use; committing provisioned rows + // would charge that memory before anything is written. + // disk_full: space set but no code set with false return. const auto provision = to_provision(); if (!resize_(provision)) return false; - // Managed heads load released: the file holds the content and pages - // restore to anonymous per segment on first write, so load contributes - // no residency (an eager head population is the store's largest - // memory transient, the full head set at open). + // Managed heads load released: file holds content and pages + // restore to anonymous per segment on first write, so load + // contributes no residency (eager head population is + // store's largest memory transient, full head set at open). if (managed_) { if (!lazy_install_()) @@ -175,7 +175,7 @@ bool CLASS::stage_() NOEXCEPT } // Reserve address space with generous multiple of capacity (costless), so - // that commitment growth never migrates the mapping (base is stable). + // commitment growth never migrates mapping (base is stable). const auto reserved = page_ceiling(to_width( to_reservation(provision))); const auto base = mmap_reserve(reserved); @@ -193,8 +193,8 @@ bool CLASS::stage_() NOEXCEPT const auto size = to_commitment(); const auto target = to_width(size); - // A shared head maps its file in place of commitment (content is the - // mapping, so there is nothing to populate). + // Shared head maps its file in place of commitment + // (content is mapping, so nothing to populate). if (head_shared_) { if (mmap_share(memory_map_[Column], target, opened_[Column], @@ -205,7 +205,6 @@ bool CLASS::stage_() NOEXCEPT } #if !defined(WITHOUT_MADVISE) - // Heads read randomly, so the mapping advises as the file opens. if (!advise_(memory_map_[Column], target)) { teardown_(error::madvise_failure); @@ -227,15 +226,14 @@ bool CLASS::stage_() NOEXCEPT return false; } - // Populate anonymous memory from the file (unstaged content in full, - // staged only the settle boundary page remainder). + // Populate anonymous memory from file (unstaged content in full, staged + // only settle boundary page remainder). const auto logical = to_width(logical_.load()); - // The read streams its own page cache discard: a whole-column read - // caches the column (the head resident twice), and that transient - // stacked over the growing anonymous set forces reclaim during staging - // (measured: the eldest staged columns swap before the store is open). - // Chunking caps the duplicate at settle_chunk. + // Read streams its own page cache discard: whole-column read caches column + // (head resident twice), and that transient stacked over growing anonymous + // set forces reclaim during staging (measured: eldest staged columns swap + // before store is open). Chunking caps duplicate at settle_chunk. for (auto at = settled; at < logical; ) { const auto chunk = std::min(logical - at, settle_chunk); @@ -254,8 +252,8 @@ bool CLASS::stage_() NOEXCEPT if (!settle_(zero, settled_.load())) return false; - // Attribute the anonymous span (above the settled file mapping) for - // diagnostics: smaps then decomposes anonymous memory by table. + // Attribute anonymous span (above settled file mapping) for diagnostics: + // smaps then decomposes anonymous memory by table. mmap_name(std::next(memory_map_[Column], settled), reserved_[Column] - settled, filenames_[Column].filename().string().c_str()); @@ -264,14 +262,14 @@ bool CLASS::stage_() NOEXCEPT return true; } -// Commit failure results in unmapped when final (the default); a non-final +// Commit failure results in unmapped when final (the default); non-final // refusal (in-reservation commit, replacement reservation, or replacement -// commit) returns false with the standing mapping untouched, so the caller -// may iterate a reduced request (admission is evaluated per request, so a -// refused amortization step does not imply exhaustion). -// Growth within the reservation commits pages in place (stable map base); an -// exhausted reservation is replaced and its unsettled content copied, under -// the exclusive remap lock held by the caller. +// commit) returns false with standing mapping untouched, so caller may iterate +// reduced request (admission evaluated per request, so refused amortization +// step does not imply exhaustion). +// Growth within reservation commits pages in place (stable map base); exhausted +// reservation is replaced and its unsettled content copied, under exclusive +// remap lock held by caller. TEMPLATE template bool CLASS::commit_(size_t size, bool final) NOEXCEPT @@ -280,8 +278,8 @@ bool CLASS::commit_(size_t size, bool final) NOEXCEPT if (target <= reserved_[Column]) { - // A shared head extends its file mapping over the growth (the file is - // provisioned to capacity, so the extension is already allocated). + // Shared head extends its file mapping over growth (file provisioned to + // capacity, so extension is already allocated). if (head_shared_ || (!staged_ && shared_.load())) { const auto grown = page_floor(to_width(capacity_.load())); @@ -297,14 +295,14 @@ bool CLASS::commit_(size_t size, bool final) NOEXCEPT return true; } - // Never commit below the settle boundary page floor (the settled - // prefix is a read-only file mapping); recommit is idempotent. + // Never commit below settle boundary page floor (settled prefix is + // read-only file mapping); recommit is idempotent. const auto settled = page_floor(to_width(settled_.load())); const auto current = page_floor(to_width(capacity_.load())); const auto from = std::max(settled, current); - if ((target > from) && (mmap_commit(std::next(memory_map_[Column], from), - target - from, commit_headroom_) == fail)) + if ((target > from) && (mmap_commit(std::next(memory_map_[Column], + from), target - from, commit_headroom_) == fail)) { if (final) teardown_(error::mmap_failure); @@ -339,8 +337,8 @@ bool CLASS::commit_(size_t size, bool final) NOEXCEPT const auto base = pointer_cast(replace); const auto settled = page_floor(to_width(settled_.load())); - // A shared head remaps its file onto the replacement (the file is the - // content, so migration copies nothing). + // Shared head remaps its file onto replacement + // (file is content, so migration copies nothing). if (head_shared_ || (!staged_ && shared_.load())) { if (mmap_share(replace, target, opened_[Column], zero) == fail) @@ -365,11 +363,11 @@ bool CLASS::commit_(size_t size, bool final) NOEXCEPT return true; } - // The replacement commit spans the unsettled prefix, transiently charged - // over the standing reservation, so its refusal is the largest single - // admission of the design: non-final refusal leaves the standing mapping - // untouched for the caller's reduced retry (a reduced ask fits within - // the standing reservation), and settle drainage shrinks the span, so a + // Replacement commit spans unsettled prefix, transiently charged + // over standing reservation, so its refusal is largest single + // admission of design: non-final refusal leaves standing mapping + // untouched for caller's reduced retry (reduced ask fits within + // standing reservation), and settle drainage shrinks span, so // necessity refusal pauses recoverable rather than tearing down. if (mmap_commit(std::next(base, settled), target - settled, commit_headroom_) == fail) @@ -409,8 +407,8 @@ bool CLASS::commit_(size_t size, bool final) NOEXCEPT } #endif - // Regrow dirty tracking with the reservation (marks are excluded by the - // remap lock, as unstaged mutations hold protected accessors). + // Regrow dirty tracking with reservation (marks excluded by remap lock, as + // unstaged mutations hold protected accessors). if (managed_) { const auto pages = ceilinged_divide(reserved, page_); @@ -423,8 +421,8 @@ bool CLASS::commit_(size_t size, bool final) NOEXCEPT dirty_ = std::move(grown); words_ = words; - // The replacement reservation is fully anonymous (content was - // copied above), so released and intent page state resets. + // Replacement reservation is fully anonymous (content copied above), so + // released and intent page state resets. intent_ = std::make_unique(words); released_ = std::make_unique(words); sweep_ = std::make_unique(words); @@ -468,13 +466,13 @@ void CLASS::teardown_(const error::error_t& ec) NOEXCEPT TEMPLATE bool CLASS::advise_(uint8_t* map, size_t size) const NOEXCEPT { - // Advice is elective (normal is the kernel default) and configured from - // the read pattern (see database::advice); random_ is structural. + // Advice is elective (normal is kernel default) and configured from read + // pattern (see database::advice); random_ is structural. if (access_ == advice::normal) return true; - // Order follows the advice enumeration (scattered is random without the - // preload, which this path does not apply in any case). + // Order follows advice enumeration (scattered is random without preload, + // which this path does not apply in any case). static constexpr std::array advices { MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_RANDOM @@ -493,7 +491,7 @@ bool CLASS::advise_(uint8_t* map, size_t size) const NOEXCEPT #endif // WITHOUT_MADVISE // Reservation is address space only (costless), so multiply for headroom; -// exhaustion is handled by reservation replacement. +// exhaustion handled by reservation replacement. TEMPLATE size_t CLASS::to_reservation(size_t rows) const NOEXCEPT { diff --git a/include/bitcoin/database/impl/memory/mmap_storage.ipp b/include/bitcoin/database/impl/memory/mmap_storage.ipp index b110eff05..e03298d24 100644 --- a/include/bitcoin/database/impl/memory/mmap_storage.ipp +++ b/include/bitcoin/database/impl/memory/mmap_storage.ipp @@ -118,9 +118,9 @@ code CLASS::close() NOEXCEPT // map, flush, unmap. // ---------------------------------------------------------------------------- -// Each accessor holds a shared lock on remap_mutex_ (read/write access to map). -// Exclusive lock on remap_mutex_ ensures there are open accessor objects, -// which allows for safely remapping the memory map. +// Each accessor holds shared lock on remap_mutex_ (read/write access to map). +// Exclusive lock on remap_mutex_ ensures there are open accessor objects, which +// allows safely remapping memory map. TEMPLATE code CLASS::load() NOEXCEPT @@ -165,9 +165,9 @@ code CLASS::reload() NOEXCEPT } #if defined(MANAGE_STAGING) - // The store reload transactor implies quiescent writers, so remaining - // extents are orphans of abandoned writes, stalling the frontier (in - // any table, not just those that faulted). Discard to unjam settling. + // Store reload transactor implies quiescent writers, so remaining + // extents are orphans of abandoned writes, stalling frontier (in any + // table, not just those that faulted). Discard to unjam settling. discard_(); #endif @@ -213,9 +213,9 @@ code CLASS::flush() NOEXCEPT if (!loaded_.load()) return error::flush_unloaded; - // The suspend-writes contract implies remaining extents are complete - // or abandoned (as reload), so the ring is discarded to reconcile the - // frontier, which settling to the flushed top would otherwise pass. + // Suspend-writes contract implies remaining extents are complete or + // abandoned (as reload), so ring is discarded to reconcile frontier, + // which settling to flushed top would otherwise pass. discard_(); if (!settle_all_(rows, sequence{})) @@ -378,7 +378,7 @@ bool CLASS::truncate(size_t count) NOEXCEPT auto fresh = count; #if defined(MANAGE_STAGING) - // Truncation below the settle boundary reverts settled rows to anonymous + // Truncation below settle boundary reverts settled rows to anonymous // memory, as append-only bodies may re-append after reorganization. if (staged_ && loaded_.load() && (count < settled_.load())) { @@ -392,8 +392,7 @@ bool CLASS::truncate(size_t count) NOEXCEPT trim_(count); #endif - // Released rows are filled (or zeroed), so an allocation reads the fill - // until written. + // Released rows filled (or zeroed), so allocation reads fill until written. if (zeroed_ && loaded_.load()) { if (fill_.has_value()) @@ -455,11 +454,11 @@ bool CLASS::reserve(size_t count) NOEXCEPT return true; } -// The slow path waits until all access pointers are destructed. Will deadlock -// if any access pointer is waiting on allocation. Lock safety requires that -// access pointers are short-lived and do not block on allocation. Relies on -// the suspend-writes contract of shrinking transitions (truncate/unload/ -// shrink/close), as the fast path does not serialize against them. +// Slow path waits until all access pointers are destructed. Will deadlock if +// any access pointer is waiting on allocation. Lock safety requires access +// pointers be short-lived and not block on allocation. Relies on suspend-writes +// contract of shrinking transitions (truncate/unload/shrink/close), as fast +// path does not serialize against them. TEMPLATE size_t CLASS::allocate(size_t count) NOEXCEPT { @@ -470,8 +469,8 @@ size_t CLASS::allocate(size_t count) NOEXCEPT throttle_(); // Staged claims serialize with extent recording (record_ locks on every - // claim regardless, so this adds no contention): a claim never exists - // outside the ring, so the frontier can never pass an unwritten extent. + // claim regardless, so this adds no contention): claim never exists outside + // ring, so frontier can never pass an unwritten extent. if (staged_) { while (true) @@ -501,7 +500,7 @@ size_t CLASS::allocate(size_t count) NOEXCEPT } #endif // MANAGE_STAGING - // Fast path: claim rows within published capacity (no locks). A failed + // Fast path: claim rows within published capacity (no locks). Failed // exchange implies another claim succeeded, so every retry is progress. auto start = logical_.load(); while (true) @@ -517,7 +516,7 @@ size_t CLASS::allocate(size_t count) NOEXCEPT } // Slow path: serialize capacity growth (at most one grower). Fast paths - // continue claiming under the old capacity; the growth target covers them. + // continue claiming under old capacity; growth target covers them. std::unique_lock field_lock(field_mutex_); start = logical_.load(); @@ -544,9 +543,9 @@ size_t CLASS::allocate(size_t count) NOEXCEPT } } -// Filled allocation (head creation). A managed head writes the fill to its -// file and maps it released, so the fill is never memory-resident; otherwise -// capacity is filled as it is committed. +// Filled allocation (head creation). Managed head writes fill to its file and +// maps it released, so fill is never memory-resident; otherwise capacity is +// filled as it is committed. TEMPLATE size_t CLASS::allocate_filled(size_t count) NOEXCEPT { diff --git a/include/bitcoin/database/impl/primitives/arrayhead.ipp b/include/bitcoin/database/impl/primitives/arrayhead.ipp index 588616db8..1d8f95161 100644 --- a/include/bitcoin/database/impl/primitives/arrayhead.ipp +++ b/include/bitcoin/database/impl/primitives/arrayhead.ipp @@ -67,9 +67,9 @@ bool CLASS::clear() NOEXCEPT return false; // Retains head size, since head is array not map, and resets body logical - // count to zero, which is picked up in arraymap::reset(). Body file size - // remains unchanged and subject to initialization size at each startup. So - // there is no reduction until restart, which can include config change. + // count to zero, picked up in arraymap::reset(). Body file size remains + // unchanged and subject to initialization size at each startup, so no + // reduction until restart, which can include config change. file_.prepare(zero, size()); std::fill_n(ptr.data(), size(), system::bit_all); file_.mark(zero, size()); @@ -116,9 +116,9 @@ bool CLASS::get_body_count(Link& count) const NOEXCEPT if (!ptr || Link::size > size()) return false; - // Body count is written as the first value in link size, but since - // offsetting is a multiple of cell size, a full cell is consumed for it. - // In case of nomap or disabled there are no cells, so file is link size. + // Body count written as first value in link size, but since offsetting is a + // multiple of cell size, a full cell is consumed for it. For nomap or + // disabled there are no cells, so file is link size. count = to_array(ptr.data()); return true; } @@ -130,9 +130,9 @@ bool CLASS::set_body_count(const Link& count) NOEXCEPT if (!ptr || Link::size > size()) return false; - // Body count is written as the first value in link size, but since - // offsetting is a multiple of cell size, a full cell is consumed for it. - // In case of nomap or disabled there are no cells, so file is link size. + // Body count written as first value in link size, but since offsetting is a + // multiple of cell size, a full cell is consumed for it. For nomap or + // disabled there are no cells, so file is link size. file_.prepare(zero, Link::size); to_array(ptr.data()) = count; file_.mark(zero, Link::size); diff --git a/include/bitcoin/database/impl/primitives/arraymap.ipp b/include/bitcoin/database/impl/primitives/arraymap.ipp index 1ee55d665..b0b58d6ec 100644 --- a/include/bitcoin/database/impl/primitives/arraymap.ipp +++ b/include/bitcoin/database/impl/primitives/arraymap.ipp @@ -50,12 +50,11 @@ bool CLASS::close() NOEXCEPT TEMPLATE bool CLASS::clear() NOEXCEPT { - // Head is nullified and its body reference is zeroized. Body memory - // recovery requires truncate/unload/load, which should be preceded by a - // snapshot as all existing snapshots will be invalidated by the truncate. - // An intervening snapshot will capture the zero count body reference (and - // null head links) and will therefore be recoverable whether or not the - // truncation succeeds. + // Head is nullified and its body reference zeroized. Body memory recovery + // requires truncate/unload/load, which should be preceded by snapshot as + // all existing snapshots are invalidated by truncate. Intervening snapshot + // captures zero count body reference (and null head links) and is therefore + // recoverable whether or not truncation succeeds. return head_.clear(); } @@ -182,7 +181,10 @@ inline bool CLASS::get(const Link& link, Element& element) const NOEXCEPT iostream stream{ ptr }; reader source{ stream }; - if constexpr (!is_slab) { BC_DEBUG_ONLY(source.set_limit(RowSize * element.count());) } + if constexpr (!is_slab) + { + BC_DEBUG_ONLY(source.set_limit(RowSize * element.count());) + } return element.from_data(source); } @@ -232,7 +234,10 @@ bool CLASS::write(const Link& link, size_t key, iostream stream{ ptr }; finalizer sink{ stream }; - if constexpr (!is_slab) { BC_DEBUG_ONLY(sink.set_limit(RowSize * element.count());) } + if constexpr (!is_slab) + { + BC_DEBUG_ONLY(sink.set_limit(RowSize * element.count());) + } return element.to_data(sink) && head_.push(link, head_.index(key)); } diff --git a/include/bitcoin/database/impl/primitives/body.ipp b/include/bitcoin/database/impl/primitives/body.ipp index 440f9937b..a2bdc265a 100644 --- a/include/bitcoin/database/impl/primitives/body.ipp +++ b/include/bitcoin/database/impl/primitives/body.ipp @@ -153,8 +153,8 @@ Link CLASS::allocate(const Link& count) NOEXCEPT // visible records (relative), return absolute record link of first. const auto start = files_.allocate(link_to_elements(count)); - // Guards addition overflow in cast_link (start must be valid). The eof - // sentinel is in file denomination, so must be detected before conversion. + // Guards addition overflow in cast_link (start must be valid). Eof sentinel + // is in file denomination, so must be detected before conversion. if (start == storage::eof) return Link::terminal; @@ -270,9 +270,9 @@ constexpr size_t CLASS::link_to_elements(const Link& link) NOEXCEPT { using namespace system; - // Single column: file elements are bytes (width one). Records convert - // by stride (slab passes through, slab links are already byte offsets). - // Aggregate: file rows are the shared record count (no conversion). + // Single column: file elements are bytes (width one). Records convert by + // stride (slab passes through, slab links already byte offsets). Aggregate: + // file rows are shared record count (no conversion). if constexpr (is_one(columns)) return link_to_position(link); else @@ -298,9 +298,9 @@ constexpr CLASS::integer CLASS::cast_link(size_t link) NOEXCEPT constexpr auto ceiling = limit(terminal); // link limit is sub1(terminal), where terminal is 2^((8*Link::bytes)-1). - // It is ok for the payload to exceed link limit (link is identity only). - // A link above the limit is a table sizing violation and is deliberately - // not mapped to terminal, as that would present it as not found/not put. + // Payload may exceed link limit (link is identity only). Link above limit + // is table sizing violation and deliberately not mapped to terminal, as + // that would present it as not found/not put. return link == ceiling ? terminal : possible_narrow_cast(link); } diff --git a/include/bitcoin/database/impl/primitives/hashhead.ipp b/include/bitcoin/database/impl/primitives/hashhead.ipp index 769a08639..a5acd604c 100644 --- a/include/bitcoin/database/impl/primitives/hashhead.ipp +++ b/include/bitcoin/database/impl/primitives/hashhead.ipp @@ -22,8 +22,8 @@ #include #include -// Heads are not subject to resize/remap and therefore do not require memory -// smart pointer with shared remap lock. Using get_raw() saves that allocation. +// Heads not subject to resize/remap, so do not require memory smart pointer +// with shared remap lock. get_raw() saves that allocation. namespace libbitcoin { namespace database { @@ -64,8 +64,8 @@ bool CLASS::create() NOEXCEPT if (is_nonzero(file_.size())) return false; - // The fill is file content: a managed head writes it to the file and - // maps it released, so creation contributes no memory residency. + // Fill is file content: managed head writes it to file and maps it + // released, so creation contributes no memory residency. if (file_.allocate_filled(size()) == storage::eof) return false; @@ -203,8 +203,8 @@ double CLASS::bloom_false_positive(size_t k, size_t n) NOEXCEPT return std::pow(1.0 - value, to_floating(k)); } -// Poisson mass is negligible past ten deviations of the mean. The minimum -// floors the bound for small means where deviations are near zero. +// Poisson mass negligible past ten deviations of mean. Minimum floors bound for +// small means where deviations are near zero. TEMPLATE size_t CLASS::poisson_span(double load_factor) NOEXCEPT { @@ -255,9 +255,9 @@ bool CLASS::get_body_count(Link& count) const NOEXCEPT if (!ptr) return false; - // Body count is written as the first value in link size, but since - // offsetting is a multiple of sell size, a full cell is consumed for it. - // In case of disabled there are no cells, so file is link size. + // Body count written as first value in link size, but since offsetting is a + // multiple of cell size, a full cell is consumed for it. If disabled there + // are no cells, so file is link size. count = link_array(ptr.data()); return true; } @@ -269,9 +269,9 @@ bool CLASS::set_body_count(const Link& count) NOEXCEPT if (!ptr) return false; - // Body count is written as the first value in link size, but since - // offsetting is a multiple of sell size, a full cell is consumed for it. - // In case of disabled there are no cells, so file is link size. + // Body count written as first value in link size, but since offsetting is a + // multiple of cell size, a full cell is consumed for it. If disabled there + // are no cells, so file is link size. file_.prepare(zero, Link::size); link_array(ptr.data()) = count; file_.mark(zero, Link::size); @@ -300,8 +300,8 @@ inline Link CLASS::top(const Key& key) const NOEXCEPT if (screened(value, keys::thumb(key))) return to_link(value); - // Conflict (body) search is bypassed by filter when key is not screened. - // If terminal here it is assured that table does not contain the key. + // Conflict (body) search bypassed by filter when key not screened. If + // terminal here, table assuredly does not contain key. return {}; } @@ -379,10 +379,10 @@ inline bool CLASS::set_cell(bool& collision, bytes& next, const Link& current, cell update{}; do { - // Compiler could order this after top.store, which would expose key - // to search before next entry is linked. Thread fence imposes order. - // A release fence ensures that all prior writes (like next) are - // completed before any subsequent atomic store. + // Compiler could order this after top.store, exposing key + // to search before next entry is linked. Thread fence + // imposes order. Release fence ensures all prior writes + // (like next) complete before any subsequent atomic store. const auto value = native_from_little_end(head); next = Link{ to_link(value) }; update = native_to_little_end(next_cell(collision, value, current, diff --git a/include/bitcoin/database/impl/primitives/hashmap.ipp b/include/bitcoin/database/impl/primitives/hashmap.ipp index b88f7000f..9db675906 100644 --- a/include/bitcoin/database/impl/primitives/hashmap.ipp +++ b/include/bitcoin/database/impl/primitives/hashmap.ipp @@ -296,8 +296,11 @@ Key CLASS::get_key(const Link& link) NOEXCEPT shift_left(key.at(hash_size + 2), 2 * byte_bits)); constexpr uint32_t truncated_null = 0x00ffffff; - return { array_cast(key), - index == truncated_null ? chain::point::null_index : index }; + return + { + array_cast(key), + index == truncated_null ? chain::point::null_index : index + }; } else { @@ -599,7 +602,10 @@ bool CLASS::read(const memory& ptr, const Link& link, Element& element) NOEXCEPT reader source{ stream }; source.skip_bytes(index_size); - if constexpr (!is_slab) { BC_DEBUG_ONLY(source.set_limit(RowSize * element.count());) } + if constexpr (!is_slab) + { + BC_DEBUG_ONLY(source.set_limit(RowSize * element.count());) + } return element.from_data(source); } @@ -641,7 +647,10 @@ bool CLASS::write(Link& previous, const memory& ptr, const Link& link, keys::write(sink, key); // Commit element to body. - if constexpr (!is_slab) { BC_DEBUG_ONLY(sink.set_limit(RowSize * element.count());) } + if constexpr (!is_slab) + { + BC_DEBUG_ONLY(sink.set_limit(RowSize * element.count());) + } auto& next = unsafe_array_cast(offset); if (!element.to_data(sink)) return false; diff --git a/include/bitcoin/database/impl/primitives/hashmaps.ipp b/include/bitcoin/database/impl/primitives/hashmaps.ipp index 47c8db3dc..5269ec3f5 100644 --- a/include/bitcoin/database/impl/primitives/hashmaps.ipp +++ b/include/bitcoin/database/impl/primitives/hashmaps.ipp @@ -269,8 +269,8 @@ inline Link CLASS::allocate(const Link& size) NOEXCEPT { const auto link = body_.allocate(size); - // A disabled spine is never committed, so its share of the allocation - // completes here (write completion is accounted for each column). + // Disabled spine is never committed, so its share of allocation completes + // here (write completion accounted for each column). if (!link.is_terminal() && !enabled()) body_.complete(link, size); @@ -705,7 +705,10 @@ bool CLASS::read(const memory& ptr, const Link& link, Element& element) NOEXCEPT reader source{ stream }; source.skip_bytes(index_size); - if constexpr (!is_slab) { BC_DEBUG_ONLY(source.set_limit(RowSize * element.count());) } + if constexpr (!is_slab) + { + BC_DEBUG_ONLY(source.set_limit(RowSize * element.count());) + } return element.from_data(source); } @@ -747,7 +750,10 @@ bool CLASS::write(Link& previous, const memory& ptr, const Link& link, keys::write(sink, key); // Commit element to body. - if constexpr (!is_slab) { BC_DEBUG_ONLY(sink.set_limit(RowSize * element.count());) } + if constexpr (!is_slab) + { + BC_DEBUG_ONLY(sink.set_limit(RowSize * element.count());) + } auto& next = unsafe_array_cast(offset); if (!element.to_data(sink)) return false; diff --git a/include/bitcoin/database/impl/primitives/keys.ipp b/include/bitcoin/database/impl/primitives/keys.ipp index 8e6f42739..bc2de8ad1 100644 --- a/include/bitcoin/database/impl/primitives/keys.ipp +++ b/include/bitcoin/database/impl/primitives/keys.ipp @@ -102,7 +102,7 @@ INLINE uint64_t hash(const Key& key) NOEXCEPT } else if constexpr (is_std_array) { - // Produces an almost perfect 100% Poisson distribution for sha256. + // Produces almost perfect 100% Poisson distribution for sha256. // Assumes sufficient uniqueness in low order bytes (ok for all). // sequentially-valued keys should have no more buckets than values. constexpr auto bytes = std::min(size(), sizeof(uint64_t)); @@ -123,20 +123,20 @@ INLINE uint64_t thumb(const Key& key) NOEXCEPT } else if constexpr (is_same_type) { - // spread point.index across point.hash extraction, as otherwise the - // unlikely bucket collisions of points of the same hash will not be - // differentiated by filters. This has a very small impact on false - // positives (-5,789 out of ~2.6B) but w/o material computational cost. + // spread point.index across point.hash extraction, as otherwise + // unlikely bucket collisions of points of same hash are not + // differentiated by filters. Very small impact on false positives + // (-5,789 out of ~2.6B) but w/o material computational cost. return fnv1a_combine(thumb(key.hash()), key.index()); ////return thumb(key.hash()); } else if constexpr (is_std_array) { // Assumes sufficient uniqueness in second-low order bytes (ok for all). - // The thumb(key) starts at the next byte following hash(key). - // If key is to short then thumb aligns to the end of the key. - // This is intended to minimize overlap to the extent possible, while - // also avoiding the high order bits in the case of block hashes. + // thumb(key) starts at next byte following hash(key). + // If key is too short then thumb aligns to end of key. + // Intended to minimize overlap to extent possible, while also avoiding + // high order bits in case of block hashes. constexpr auto bytes = std::min(size(), sizeof(uint64_t)); constexpr auto offset = std::min(size() - bytes, bytes); diff --git a/include/bitcoin/database/impl/primitives/nohead.ipp b/include/bitcoin/database/impl/primitives/nohead.ipp index 32af862ab..040e87415 100644 --- a/include/bitcoin/database/impl/primitives/nohead.ipp +++ b/include/bitcoin/database/impl/primitives/nohead.ipp @@ -59,9 +59,9 @@ bool CLASS::clear() NOEXCEPT return false; // Retains head size, since head is array not map, and resets body logical - // count to zero, which is picked up in arraymap::reset(). Body file size - // remains unchanged and subject to initialization size at each startup. So - // there is no reduction until restart, which can include config change. + // count to zero, picked up in arraymap::reset(). Body file size remains + // unchanged and subject to initialization size at each startup, so no + // reduction until restart, which can include config change. file_.prepare(zero, size()); std::fill_n(ptr.data(), size(), system::bit_all); file_.mark(zero, size()); @@ -107,9 +107,9 @@ bool CLASS::get_body_count(Link& count) const NOEXCEPT if (!ptr || Link::size > size()) return false; - // Body count is written as the first value in link size, but since - // offsetting is a multiple of cell size, a full cell is consumed for it. - // In case of nomap or disabled there are no cells, so file is link size. + // Body count written as first value in link size, but since offsetting is a + // multiple of cell size, a full cell is consumed for it. For nomap or + // disabled there are no cells, so file is link size. count = to_array(ptr.data()); return true; } @@ -121,9 +121,9 @@ bool CLASS::set_body_count(const Link& count) NOEXCEPT if (!ptr || Link::size > size()) return false; - // Body count is written as the first value in link size, but since - // offsetting is a multiple of cell size, a full cell is consumed for it. - // In case of nomap or disabled there are no cells, so file is link size. + // Body count written as first value in link size, but since offsetting is a + // multiple of cell size, a full cell is consumed for it. For nomap or + // disabled there are no cells, so file is link size. file_.prepare(zero, Link::size); to_array(ptr.data()) = count; file_.mark(zero, Link::size); diff --git a/include/bitcoin/database/impl/query/address/address_balance.ipp b/include/bitcoin/database/impl/query/address/address_balance.ipp index 21d2ae688..6702c5902 100644 --- a/include/bitcoin/database/impl/query/address/address_balance.ipp +++ b/include/bitcoin/database/impl/query/address/address_balance.ipp @@ -35,10 +35,10 @@ code CLASS::get_unconfirmed_balance(const stopper& , uint64_t& out, const hash_digest& , size_t , bool ) const NOEXCEPT { // While duplicates are easily filtered out, conflict resolution is murky. - // An output may have multiple directly or indirectly conflicting spends, - // and other spends and receives may not be visible. An unconfirmed balance - // is therefore inherehtly ambiguous. Given the lack of tx pooling, - // presently we just return zero unconfirmed. + // Output may have multiple directly or indirectly conflicting + // spends, and other spends and receives may not be visible. + // Unconfirmed balance is therefore inherently ambiguous. + // Given lack of tx pooling, returns zero unconfirmed. out = zero; return error::success; } diff --git a/include/bitcoin/database/impl/query/address/address_history.ipp b/include/bitcoin/database/impl/query/address/address_history.ipp index 75924e576..1727cb66f 100644 --- a/include/bitcoin/database/impl/query/address/address_history.ipp +++ b/include/bitcoin/database/impl/query/address/address_history.ipp @@ -65,8 +65,8 @@ code CLASS::get_confirmed_history(const stopper& cancel, height_link& cursor, if (const auto ec = get_address_txs(cancel, txs, key, limit, turbo)) return ec; - // Cursor is still advanced in the case of (integrity) failure. - // End is required because of the possiblity of intervening organization. + // Cursor still advanced in case of (integrity) failure. + // End required because of possibility of intervening organization. const auto start = cursor.is_terminal() ? zero : cursor.value; const auto end = get_top_confirmed(); cursor = system::possible_narrow_cast(add1(end)); @@ -93,8 +93,8 @@ code CLASS::get_history(const stopper& cancel, height_link& cursor, if (const auto ec = get_address_txs(cancel, txs, key, limit, turbo)) return ec; - // Cursor is still advanced in the case of (integrity) failure. - // End is required because of the possiblity of intervening organization. + // Cursor still advanced in case of (integrity) failure. + // End required because of possibility of intervening organization. const auto start = cursor.is_terminal() ? zero : cursor.value; const auto end = get_top_confirmed(); cursor = system::possible_narrow_cast(add1(end)); diff --git a/include/bitcoin/database/impl/query/address/address_outpoints.ipp b/include/bitcoin/database/impl/query/address/address_outpoints.ipp index a52aa6a43..bbc27d6f5 100644 --- a/include/bitcoin/database/impl/query/address/address_outpoints.ipp +++ b/include/bitcoin/database/impl/query/address/address_outpoints.ipp @@ -45,8 +45,6 @@ code CLASS::get_unconfirmed_unspent_outpoints(const stopper& cancel, return parallel_outpoint_transform(cancel, turbo, out, links, [this](const output_link& link, auto& cancel, auto& fail) NOEXCEPT { - // Confirmed and spent must be filtered out. An unconfirmed output - // can only be spent by an unconfirmed tx, so is_spent() suffices. if (cancel || fail || is_confirmed_output(link) || is_spent(link)) return outpoint{}; diff --git a/include/bitcoin/database/impl/query/address/address_unspent.ipp b/include/bitcoin/database/impl/query/address/address_unspent.ipp index 845b66511..5fda2d81f 100644 --- a/include/bitcoin/database/impl/query/address/address_unspent.ipp +++ b/include/bitcoin/database/impl/query/address/address_unspent.ipp @@ -27,7 +27,7 @@ namespace database { // Address unspent. // ---------------------------------------------------------------------------- -// A list of all unspent output transactions in canonical order. +// List of all unspent output transactions in canonical order. // Unconfirmed unspent are included at end of list in consistent order. // ununsed @@ -46,9 +46,9 @@ code CLASS::get_unconfirmed_unspent(const stopper& cancel, unspent_outputs& out, return parallel_unspent_transform(cancel, turbo, out, outs, [this](const output_link& link, auto& cancel, auto& fail) NOEXCEPT { - // Exclude if spent by any tx. Given that output must be confirmed - // this is only unconfirmeds, but checking both via is_spent() is - // much faster than calling is_unconfirmed_spent(). + // Exclude if spent by any tx. Given output must be confirmed this + // is only unconfirmeds, but checking both via is_spent() is much + // faster than calling is_unconfirmed_spent(). if (cancel || fail || is_spent(link)) return unspent_output{}; diff --git a/include/bitcoin/database/impl/query/archive/chain_reader.ipp b/include/bitcoin/database/impl/query/archive/chain_reader.ipp index 0049f922f..ad06844a2 100644 --- a/include/bitcoin/database/impl/query/archive/chain_reader.ipp +++ b/include/bitcoin/database/impl/query/archive/chain_reader.ipp @@ -273,7 +273,7 @@ typename CLASS::input::cptr CLASS::get_input(const ins_link& link, ); // Node only (cheap so always include). - // Internally-populated points will have default link of max_uint32. + // Internally-populated points have default link of max_uint32. ptr->metadata.point_link = link; return ptr; } diff --git a/include/bitcoin/database/impl/query/archive/chain_writer.ipp b/include/bitcoin/database/impl/query/archive/chain_writer.ipp index 350e1dffb..0f44947b2 100644 --- a/include/bitcoin/database/impl/query/archive/chain_writer.ipp +++ b/include/bitcoin/database/impl/query/archive/chain_writer.ipp @@ -159,7 +159,7 @@ code CLASS::set_code(const tx_link& tx_fk, const transaction& tx, return error::tx_output_put; // Allocate ins/point rows and contiguously store input links. - // Point elements are set into the same rows following tx set, below. + // Point elements set into same rows following tx set, below. auto ins_fk = store_.ins.allocate(inputs); if (ins_fk.is_terminal()) return error::tx_ins_put; @@ -173,13 +173,12 @@ code CLASS::set_code(const tx_link& tx_fk, const transaction& tx, insert.reset(); // Allocate outs/address rows and contiguously store output links. - // Address spine elements are committed into the same rows, below. + // Address spine elements committed into same rows, below. auto outs_fk = store_.outs.allocate(outputs); if (outs_fk.is_terminal()) return error::tx_outs_put; - // Outs put is unguarded, the accessor guards its rows against remap - // (the puts column accessor, as the spine is unbacked when disabled). + // Outs put is unguarded, the accessor guards its rows against remap. auto outsert = store_.outs.template get_memory(); if (!outsert || !store_.outs.puts.put(outs_fk, table::outs::put_ref{ {}, out_fk, tx })) @@ -214,12 +213,12 @@ code CLASS::set_code(const tx_link& tx_fk, const transaction& tx, } else { - // If dirty we must guard against duplicates. Dirty is caused by disk, - // full, disorganized or reorganized block, and tx pooling. It is set - // to true at runtime by any of these and in case of header table with - // multiple rows at startup. disorg/reorg indicated by candidate pop. - // Must be set after tx.set and before tx.commit, since searchable and - // produces association to tx.link, and is also an integral part of tx. + // If dirty, must guard against duplicates. Dirty is caused by disk, + // full, disorganized or reorganized block, and tx pooling. Set true at + // runtime by any of these and in case of header table with multiple + // rows at startup. disorg/reorg indicated by candidate pop. Must be set + // after tx.set and before tx.commit, since searchable and produces + // association to tx.link, and also integral part of tx. if (store_.is_dirty() || !bypass) { // Collect duplicates to store in duplicate table. @@ -238,7 +237,6 @@ code CLASS::set_code(const tx_link& tx_fk, const transaction& tx, ptr.reset(); - // tx_duplicate_put implies link domain overflow (2^24). for (const auto& twin: twins) if (!store_.duplicate.exists(twin)) if (!store_.duplicate.put(twin, table::duplicate::record{})) @@ -268,8 +266,8 @@ code CLASS::set_code(const tx_link& tx_fk, const transaction& tx, // Commit tx to search (hashmap). // tx.get_hash() assumes cached or is not thread safe. - return store_.tx.commit(tx_fk, tx.get_hash(false)) ? - error::success : error::tx_tx_commit; + const auto committed = store_.tx.commit(tx_fk, tx.get_hash(false)); + return committed ? error::success : error::tx_tx_commit; } // set header @@ -396,9 +394,9 @@ code CLASS::set_code(header_link& out_fk, const block& block, // set txs from block // ---------------------------------------------------------------------------- -// This sets only the txs of a block with header/context already archived. -// Block MUST be kept in scope until all transactions are written. ~block() -// releases all memory for parts of itself, due to the custom allocator. +// Sets only txs of block with header/context already archived. Block MUST be +// kept in scope until all transactions are written. ~block() releases all +// memory for parts of itself, due to custom allocator. TEMPLATE code CLASS::set_code(const block& block, bool strong, bool bypass, diff --git a/include/bitcoin/database/impl/query/archive/wire_reader.ipp b/include/bitcoin/database/impl/query/archive/wire_reader.ipp index 354e63b41..94b755966 100644 --- a/include/bitcoin/database/impl/query/archive/wire_reader.ipp +++ b/include/bitcoin/database/impl/query/archive/wire_reader.ipp @@ -27,12 +27,12 @@ namespace database { // Reader directly from store to wire-encoded buffer (store to network). // ---------------------------------------------------------------------------- -// Due to the stoopid segwit serialization of witness after output there is are -// duplicated navigations to store_.ins and store_.input by the witness reader. -// This normalized approach is also the most efficient. +// Due to segwit serialization of witness after output there are duplicated +// navigations to store_.ins and store_.input by witness reader. This normalized +// approach is also most efficient. -// The stored tx is presumed to have the txid of the tx, so only the witness -// may differ. Stored witnesses are wire encoded, so are compared in place. +// Stored tx presumed to have txid of tx, so only witness may differ. Stored +// witnesses are wire encoded, so compared in place. TEMPLATE bool CLASS::is_witness_match(const tx_link& link, const transaction& tx) const NOEXCEPT @@ -75,8 +75,10 @@ bool CLASS::is_witness_match(const tx_link& link, return true; const auto witnesses = tx.witnesses(); - table::input::match_witness match{ {}, witnesses.data(), - witnesses.size() }; + table::input::match_witness match + { + {}, witnesses.data(), witnesses.size() + }; // Point links are contiguous (computed). const auto ins_begin = record.point_fk; @@ -414,9 +416,9 @@ void CLASS::page_wire_block(const wire_accessors& ptrs, cold_reads_.release(); } -// These convenience wrappers are made practical by size caching for block and -// tx for both nominal and witness wire encodings (and fixed size headers). -// Intermediate objects (input, output, witness) have a size prefix. +// Convenience wrappers made practical by size caching for block and tx for both +// nominal and witness wire encodings (and fixed size headers). Intermediate +// objects (input, output, witness) have a size prefix. TEMPLATE data_chunk CLASS::get_wire_header(const header_link& link) const NOEXCEPT @@ -487,8 +489,8 @@ bool CLASS::get_wire_block(const system::data_slab& out, if (txs.empty()) return false; - // Tx sizes, converted in place to offsets. Tasks read through the held - // accessors, as a task taking a held lock could wait behind a remap. + // Tx sizes, converted in place to offsets. Tasks read through held + // accessors, as task taking a held lock could wait behind a remap. const auto ptrs = get_wire_accessors(); page_wire_block(ptrs, txs); @@ -513,8 +515,8 @@ bool CLASS::get_wire_block(const system::data_slab& out, if (is_zero(scale) || (scale * bytes != out.size())) return false; - // Txs are written in ranges, one task each, as each task costs a wakeup, - // and a block of two ranges or fewer is written without tasks. + // Txs written in ranges, one task each, as each task costs a wakeup, and + // block of two ranges or fewer is written without tasks. constexpr size_t range_txs = 256; const auto ranges = ceilinged_divide(txs.size(), range_txs); if (ranges <= two) diff --git a/include/bitcoin/database/impl/query/archive/wire_writer.ipp b/include/bitcoin/database/impl/query/archive/wire_writer.ipp index d9567d82c..7897c60e8 100644 --- a/include/bitcoin/database/impl/query/archive/wire_writer.ipp +++ b/include/bitcoin/database/impl/query/archive/wire_writer.ipp @@ -26,9 +26,9 @@ namespace database { // set transaction_view // ---------------------------------------------------------------------------- -// This is the only multitable write query (except initialize/genesis). -// The caller holds the transactor and all table accessors, with all table rows -// preallocated by the block writer. No allocation may occur under accessors. +// Only multitable write query (except initialize/genesis). Caller holds +// transactor and all table accessors, with all table rows preallocated by block +// writer. No allocation may occur under accessors. TEMPLATE code CLASS::set_code(std::vector& twins, const accessors& ptrs, @@ -39,7 +39,7 @@ code CLASS::set_code(std::vector& twins, const accessors& ptrs, using ix = linkage; // View parser treats empty as invalid, so there is no empty state. - // As a result this condition should never be hit (deserialization fails). + // Condition should never be hit (deserialization fails). if (!tx.is_valid()) return error::tx_empty; @@ -58,14 +58,14 @@ code CLASS::set_code(std::vector& twins, const accessors& ptrs, return error::tx_output_put; // Contiguously store input links (preallocated, rows shared with points). - // Point elements are set into the same rows following tx set, below. - // The caller's ins accessor guards raw sequence writes against remap. + // Point elements set into same rows following tx set, below. + // Caller's ins accessor guards raw sequence writes against remap. if (!store_.ins.sequence.put(fks.ins_fk, table::ins_sequence::put_view{ {}, fks.in_fk, fks.tx_fk, tx })) return error::tx_ins_put; - // Contiguously store output links (preallocated, rows shared with the - // address spine). The caller's outs accessor guards against remap. + // Contiguously store output links (preallocated, rows shared with address + // spine). Caller's outs accessor guards against remap. if (!store_.outs.puts.put(fks.outs_fk, table::outs::put_view{ {}, fks.out_fk, tx })) return error::tx_outs_put; @@ -172,8 +172,8 @@ code CLASS::set_code(std::vector& twins, const accessors& ptrs, } // Commit tx to search (hashmap). - return store_.tx.commit(ptrs.tx, fks.tx_fk, tx.hash(false)) ? - error::success : error::tx_tx_commit; + const auto committed = store_.tx.commit(ptrs.tx, fks.tx_fk, tx.hash(false)); + return committed ? error::success : error::tx_tx_commit; } TEMPLATE @@ -200,9 +200,9 @@ tx_link CLASS::to_pooled(const transaction_view& tx) const NOEXCEPT // set txs from block // ---------------------------------------------------------------------------- -// This sets only the txs of a block with header/context already archived. -// Block MUST be kept in scope until all transactions are written. ~block() -// releases all memory for parts of itself, due to the custom allocator. +// Sets only txs of block with header/context already archived. Block MUST be +// kept in scope until all transactions are written. ~block() releases all +// memory for parts of itself, due to custom allocator. TEMPLATE code CLASS::set_code(const block_view& block, bool strong, bool bypass, @@ -307,7 +307,7 @@ code CLASS::set_code(const block_view& block, const header_link& key, if (fks.outs_fk.is_terminal()) return error::tx_outs_put; - // Guard all tables against remap for the duration of the block write. + // Guard all tables against remap for duration of block write. // No table may be allocated while any of these accessors are held. accessors ptrs{}; ptrs.tx = store_.tx.get_memory(); @@ -335,6 +335,8 @@ code CLASS::set_code(const block_view& block, const header_link& key, if ((ec = set_code(twins, ptrs, fks, tx, bypass, prune))) return ec; + const auto in_bytes = tx.input_table_size(prune); + // Output rows are parent fk prefixed (see table::output::put_view). const auto out_bytes = tx.outputs() * tx_link::size + tx.output_table_size(); @@ -342,7 +344,7 @@ code CLASS::set_code(const block_view& block, const header_link& key, *it = fks.tx_fk++; fks.ins_fk += possible_narrow_cast(tx.inputs()); fks.outs_fk += possible_narrow_cast(tx.outputs()); - fks.in_fk += possible_narrow_cast(tx.input_table_size(prune)); + fks.in_fk += possible_narrow_cast(in_bytes); fks.out_fk += possible_narrow_cast(out_bytes); } diff --git a/include/bitcoin/database/impl/query/batch/silent.ipp b/include/bitcoin/database/impl/query/batch/silent.ipp index 3899e1136..97f93a157 100644 --- a/include/bitcoin/database/impl/query/batch/silent.ipp +++ b/include/bitcoin/database/impl/query/batch/silent.ipp @@ -29,7 +29,7 @@ namespace database { TEMPLATE bool CLASS::scan_silent(const stopper& cancel, const system::scan::batch::receiver& keys, - const silent_handler& callback) NOEXCEPT + const silent_handler& callback) const NOEXCEPT { return scan_silent(cancel, keys, zero, store_.scan.count(), callback); } @@ -38,7 +38,7 @@ bool CLASS::scan_silent(const stopper& cancel, TEMPLATE bool CLASS::scan_silent(const stopper& cancel, const system::scan::batch::receiver& keys, size_t first, size_t last, - const silent_handler& callback) NOEXCEPT + const silent_handler& callback) const NOEXCEPT { const auto guard = store_.scan.guard(); const auto prefix_ptr = store_.scan_prefix.get_memory(); @@ -75,14 +75,14 @@ bool CLASS::scan_silent(const stopper& cancel, return !cancel; } -// Rows are in validation order, so the rows of confirmed blocks in the cut are -// selected by tx link from the range, along with all unconfirmed rows, and only -// the selected rows are scanned. A block's txs are a few runs of consecutive -// links, so membership is a search of runs. +// Rows are in validation order, so rows of confirmed blocks in cut are selected +// by tx link from range, along with all unconfirmed rows, and only selected +// rows are scanned. Block's txs are a few runs of consecutive links, so +// membership is a search of runs. TEMPLATE bool CLASS::scan_silent(const stopper& cancel, const system::scan::batch::receiver& keys, size_t first, size_t last, - size_t start, size_t stop, const silent_handler& callback) NOEXCEPT + size_t start, size_t stop, const silent_handler& callback) const NOEXCEPT { using namespace system; using link_t = tx_link::integer; @@ -207,8 +207,8 @@ bool CLASS::scan_silent(const stopper& cancel, } // Confirmation is strong association, otherwise height is zero (unconfirmed). -// A tx archived only on a stale branch reports as unconfirmed, and one also -// archived there before the store began pooling may report twice (benign). +// Tx archived only on stale branch reports as unconfirmed, and one also +// archived there before store began pooling may report twice (benign). TEMPLATE bool CLASS::get_silent_matches(silent_matches& out, const stopper& cancel, const system::scan::batch::receiver& keys, size_t first, size_t last, @@ -303,11 +303,11 @@ bool CLASS::set_scan_start(const header_link& link, // ======================================================================== } -// A block's rows link above its coinbase, so the first row linked above the -// lowest coinbase at or above a height starts the rows of blocks at or above -// it. Rows of blocks archived after a mapped ancestor link above its coinbase -// and so follow its start, otherwise the seek is from the first row. Headers -// are written top down, so genesis is mapped only by a complete map. +// Block's rows link above its coinbase, so first row linked above lowest +// coinbase at or above a height starts rows of blocks at or above it. Rows of +// blocks archived after a mapped ancestor link above its coinbase and so follow +// its start, otherwise seek is from first row. Headers written top down, so +// genesis is mapped only by complete map. TEMPLATE bool CLASS::set_scan_starts(const stopper& cancel, const header_link& top, size_t bound, bool remap) NOEXCEPT @@ -370,10 +370,7 @@ scan_link CLASS::get_scan_floor(size_t height) const NOEXCEPT // setters // ---------------------------------------------------------------------------- -// Caller (node) controls which txs are indexed (e.g. by confirmed height). -// The coinbase is the first tx archived for a block, so txs linked below it -// were archived before it, as pooled (and indexed) or by another block (and -// indexed only if that block was), so a tx below it is indexed if not pooled. +// Tx linked below coinbase was archived before it, so is indexed unless pooled. TEMPLATE bool CLASS::set_silent(const header_link& link, const block& block) NOEXCEPT @@ -449,7 +446,8 @@ bool CLASS::set_presilent(const header_link& link, bool bank) NOEXCEPT const auto scope = get_transactor(); // Clean single allocation failure (e.g. disk full). - return store_.presilent_bank(bank).put(table::presilent::record{ {}, link }); + const table::presilent::record element{ {}, link }; + return store_.presilent_bank(bank).put(element); // ======================================================================== } @@ -555,12 +553,11 @@ bool CLASS::get_prevouts_(data_chunk& prevouts, std::vector& selected, return !!sink; } -// The bank is quiescent (drain claimed, no writers), so it is read across the -// scan write, which is sourced directly from its columns. Scan rows are -// allocated for every bank tx and prefix, so the prefixes and outputs are -// written in parallel while points compute on gpu (or after they compute on -// cpu), and each tx is then published by its correlate -// (an invalid tx with no outputs). +// Bank is quiescent (drain claimed, no writers), so read across scan write, +// which is sourced directly from its columns. Scan rows allocated for every +// bank tx and prefix, so prefixes and outputs are written in parallel while +// points compute on gpu (or after they compute on cpu), and each tx is then +// published by its correlate (an invalid tx with no outputs). TEMPLATE code CLASS::compute_silents(const stopper& cancel, bool& used_gpu, bool bank) NOEXCEPT @@ -612,8 +609,8 @@ code CLASS::compute_silents(const stopper& cancel, bool& used_gpu, using prefix_int = prefix_link::integer; using outputs_record = table::scan_outputs::record; - // Bank prefixes are contiguous, so scan prefix rows are at the same - // offsets from the allocation, and each tx writes only its own. + // Bank prefixes are contiguous, so scan prefix rows are at same offsets + // from allocation, and each tx writes only its own. std::atomic_bool failed{}; std_vector indexes(txs); std::iota(indexes.begin(), indexes.end(), zero); @@ -641,7 +638,6 @@ code CLASS::compute_silents(const stopper& cancel, bool& used_gpu, std::for_each(policy, indexes.cbegin(), indexes.cend(), put); }; - // Write is concurrent with gpu, after cpu. data_chunk valid(txs); const silent::batch in{ { sums, txs }, { hashes, txs } }; if (!silent::batch::compute(cancel, used_gpu, points, valid, in, write)) @@ -726,8 +722,8 @@ bool CLASS::set_silent_(const tx_link& link, const Transaction& tx) NOEXCEPT // ======================================================================== } -// Caller holds the transactor. Prefixes are allocated before txs, as they are -// reached only through txs, and the correlate publishes each tx last. +// Caller holds transactor. Prefixes allocated before txs, as they are reached +// only through txs, and correlate publishes each tx last. TEMPLATE bool CLASS::put_scan_(const system::wallet::silent_payment::rows& rows, const std::span& links) NOEXCEPT @@ -824,8 +820,8 @@ bool CLASS::set_silents_(size_t& count, const header_link& link, if (!store_.presilent_bank(bank).put(table::presilent::record{ {}, link })) return false; - // Allocate the block's outputs, then its txs across all columns. Outputs - // are reached only through txs, so failure strands no unwritten tx. + // Allocate block's outputs, then its txs across all columns. Outputs + // reached only through txs, so failure strands no unwritten tx. const auto pk = bank_prefix.allocate( possible_narrow_cast(count)); if (pk.is_terminal()) diff --git a/include/bitcoin/database/impl/query/confirmed.ipp b/include/bitcoin/database/impl/query/confirmed.ipp index 1bb341575..9200fdced 100644 --- a/include/bitcoin/database/impl/query/confirmed.ipp +++ b/include/bitcoin/database/impl/query/confirmed.ipp @@ -175,8 +175,8 @@ bool CLASS::is_spent(const output_link& link) const NOEXCEPT TEMPLATE bool CLASS::is_spent(const point& prevout) const NOEXCEPT { - // *Any* tx spends the point. Note that this could even be a tx that is in - // conflict with another long-confirmed tx, or a valid tx in invalid block. + // *Any* tx spends the point. Could even be a tx in conflict with another + // long-confirmed tx, or valid tx in invalid block. return store_.ins.exists(prevout); } diff --git a/include/bitcoin/database/impl/query/consensus/consensus_block.ipp b/include/bitcoin/database/impl/query/consensus/consensus_block.ipp index 4cd7d9fe4..6f1ef8c16 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_block.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_block.ipp @@ -113,10 +113,10 @@ code CLASS::block_confirmable(const header_link& link) const NOEXCEPT // Called by validator for a current block, prior to block production. // ---------------------------------------------------------------------------- -// Each non-coinbase tx is validated under its pooled context, which is -// sufficient for the block (absolute locktime is monotonic under bip113). What -// remains is the coinbase, the block checks over all txs, and the prevouts -// record, from which block_confirmable performs the chain checks. +// Each non-coinbase tx is validated under its pooled context, sufficient for +// block (absolute locktime is monotonic under bip113). What remains is +// coinbase, block checks over all txs, and prevouts record, from which +// block_confirmable performs chain checks. TEMPLATE code CLASS::validate_pooled(const header_link& link, const chain_context& ctx, @@ -217,8 +217,8 @@ code CLASS::check_pooled_block(pooled_block& block) const NOEXCEPT if (!store_.ins.sequence.get(fk, input)) return error::integrity; - // An internal spend (by hash) is terminal, as confirmation of the - // pooled parent would otherwise be required. + // Internal spend (by hash) is terminal, as confirmation of pooled + // parent would otherwise be required. auto merged = prevout::tx::terminal; if (const auto it = block.positions.find(point.hash()); it == block.positions.end()) @@ -325,8 +325,8 @@ system::error::transaction_error_t CLASS::spendable(const memory& strong, { const auto bip68 = ctx.is_enabled(system::chain::flags::bip68_rule); - // A spend internal to the block has zero age and a non-coinbase parent - // (the merged coinbase bit of a terminal point is not meaningful). + // Spend internal to block has zero age and non-coinbase parent (merged + // coinbase bit of terminal point is not meaningful). if (point.tx.is_terminal()) { if (bip68 && @@ -367,14 +367,13 @@ system::error::transaction_error_t CLASS::spendable(const memory& strong, } // **************************************************************************** -// CONSENSUS: To reproduce the behavior of a UTXO accumulator when reorganizing -// a BIP30 exception block, the first instance of the reorganized coinbase tx -// must be set unstrong, despite its block being strong. This creates the odd -// situation where there is a confirmed block with unconfirmed txs. Otherwise -// the txs are spendable, but in the satoshi client their outputs no longer -// exist (de-accumulated). There is discussion about fixing this issue in the -// satoshi client, which would likely result in our behavior without this -// special handling. This is moot given the existence of checkpoints, so +// CONSENSUS: To reproduce behavior of a UTXO accumulator when reorganizing a +// BIP30 exception block, first instance of reorganized coinbase tx must be set +// unstrong, despite its block being strong. This creates the odd situation of a +// confirmed block with unconfirmed txs. Otherwise txs are spendable, but in +// satoshi client their outputs no longer exist (de-accumulated). There is +// discussion about fixing this in satoshi client, which would likely result in +// our behavior without this special handling. Moot given checkpoints, so // presently not consensus. // **************************************************************************** diff --git a/include/bitcoin/database/impl/query/consensus/consensus_chain_state.ipp b/include/bitcoin/database/impl/query/consensus/consensus_chain_state.ipp index 605be74df..2f41be7c7 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_chain_state.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_chain_state.ipp @@ -159,8 +159,8 @@ bool CLASS::populate_signal(chain_state::data::signal& signal, }; // Periods below a boundary with median time past below start are defined. - // A period is counted only if its opening boundary is at/above start and - // the boundary below that is below timeout, as otherwise it is not started. + // Period counted only if its opening boundary is at/above start and + // boundary below that is below timeout, as otherwise it is not started. auto boundary = map.high; uint32_t current{}; if (!median(current, boundary)) diff --git a/include/bitcoin/database/impl/query/consensus/consensus_compact.ipp b/include/bitcoin/database/impl/query/consensus/consensus_compact.ipp index 92e8b1c84..2a6562769 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_compact.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_compact.ipp @@ -77,8 +77,8 @@ code CLASS::get_compact_links(tx_links& out, return error::success; } -// Scan the id columns, resolving tx links only after the guards release. -// The columns are little-endian words, hashed in place across vector lanes. +// Scan id columns, resolving tx links only after guards release. Columns are +// little-endian words, hashed in place across vector lanes. TEMPLATE bool CLASS::get_compact_matches(compact_matches& out, const std::unordered_map& positions, diff --git a/include/bitcoin/database/impl/query/consensus/consensus_forks.ipp b/include/bitcoin/database/impl/query/consensus/consensus_forks.ipp index e0e21e6d1..9f0d1590d 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_forks.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_forks.ipp @@ -150,8 +150,8 @@ header_states CLASS::get_validated_fork(size_t& fork_point) const NOEXCEPT // ---------------------------------------------------------------------------- // private -// Without both interlocks, or caller controlling one side with the other -// locked, this is unsafe, since the compare of heights requires atomicity. +// Without both interlocks, or caller controlling one side with other locked, +// this is unsafe, since compare of heights requires atomicity. TEMPLATE size_t CLASS::get_fork_() const NOEXCEPT { diff --git a/include/bitcoin/database/impl/query/consensus/consensus_populate.ipp b/include/bitcoin/database/impl/query/consensus/consensus_populate.ipp index a230ce290..5e04bd4ba 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_populate.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_populate.ipp @@ -24,14 +24,14 @@ namespace libbitcoin { namespace database { -// Input population is not expected to be called publicly, tx population (chain -// true) is expected to be called (tx pool validation), and block population is -// called for full block validation/confirmation (chain false). +// Input population not expected to be called publicly, tx population (chain +// true) expected to be called (tx pool validation), and block population called +// for full block validation/confirmation (chain false). // populate_with_metadata // ---------------------------------------------------------------------------- -// These are used when performing confirmation, either directly (chain true) or -// caching metadata (chain false) in validation stage for later confirmation. +// Used when performing confirmation, either directly (chain true) or caching +// metadata (chain false) in validation stage for later confirmation. TEMPLATE bool CLASS::populate_with_metadata(const block& block, @@ -78,9 +78,8 @@ bool CLASS::populate_with_metadata(const input& input, bool chain, // Null point would return nullptr and be interpreted as missing. BC_ASSERT(!input.point().is_null()); - // If read via the store for store confirmation, then... - // input.metadata.point_link is set earlier in get_input(). - // So this assertion no longer holds. + // If read via store for store confirmation, input.metadata.point_link is + // set earlier in get_input(), so this assertion does not hold. ////BC_ASSERT(input.metadata.point_link == max_uint32); if (input.prevout) @@ -96,11 +95,11 @@ bool CLASS::populate_with_metadata(const input& input, bool chain, // Node only (cheap so always include). input.metadata.parent_tx = tx; - // This is used by node for unconfirmed tx validation (expensive). - // There are three consensus-relevant heights. These are the height of the - // presumed next block (pool), the height of the block containing previous - // output's transaction, and the height of a block containing a previous - // spender of the previous output. median-time-past is of the prevout. + // Used by node for unconfirmed tx validation (expensive). + // Three consensus-relevant heights: height of presumed next block (pool), + // height of block containing previous output's transaction, and height of + // block containing a previous spender of previous output. median-time-past + // is of the prevout. if (chain) { auto& metadata = input.metadata; @@ -119,8 +118,8 @@ bool CLASS::populate_with_metadata(const input& input, bool chain, metadata.median_time_past = max_uint32; } - // The genesis coinbase is unspendable, so no confirmed spender is at - // zero, which therefore distinguishes an unconfirmed spender. + // Genesis coinbase is unspendable, so no confirmed spender is at zero, + // which therefore distinguishes unconfirmed spender. if (pool && !is_spent(input.point())) { // Any spender (including duplicate tx) not found. @@ -145,9 +144,9 @@ bool CLASS::populate_with_metadata(const input& input, bool chain, // populate_pooled // ---------------------------------------------------------------------------- -// This is used in validation of a block containing a tx validated in the pool, -// caching the pool's metadata for later confirmation. A block-internal spend -// is populated by the block, so its metadata remains that of internal spend. +// Used in validation of block containing a tx validated in pool, caching pool's +// metadata for later confirmation. Block-internal spend is populated by block, +// so its metadata remains that of internal spend. TEMPLATE code CLASS::populate_pooled(pooled_tx& out, const transaction& tx, @@ -174,10 +173,9 @@ code CLASS::populate_pooled(pooled_tx& out, const transaction& tx, // populate_without_metadata // ---------------------------------------------------------------------------- -// These are used when not performing confirmation. This also implies that -// validation is not being performed, so is used for populating prevouts for -// the purpose of computing client filters in the validation stage. So these -// are not used for in consensus but are kept here for close similarity. +// Used when not performing confirmation. Also implies validation is not being +// performed, so used for populating prevouts to compute client filters in +// validation stage. Not used in consensus but kept here for close similarity. TEMPLATE bool CLASS::populate_without_metadata(const block& block) const NOEXCEPT diff --git a/include/bitcoin/database/impl/query/consensus/consensus_prevouts.ipp b/include/bitcoin/database/impl/query/consensus/consensus_prevouts.ipp index ff15522e1..08148e6fe 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_prevouts.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_prevouts.ipp @@ -26,8 +26,8 @@ namespace libbitcoin { namespace database { // Prevouts caching. -// Prevouts are cached during validation and read during confirmation. -// The table is purged once per process execution when node is coalesced. +// Prevouts cached during validation and read during confirmation. +// Table purged once per process execution when node is coalesced. // ---------------------------------------------------------------------------- TEMPLATE diff --git a/include/bitcoin/database/impl/query/consensus/consensus_states.ipp b/include/bitcoin/database/impl/query/consensus/consensus_states.ipp index ad0d918d3..596843b56 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_states.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_states.ipp @@ -64,8 +64,8 @@ TEMPLATE inline bool CLASS::is_sufficient(const context& current, const context& evaluated) const NOEXCEPT { - // Past evaluation at a lesser height and mtp is sufficient, provided that - // absolute locktime is evaluated against mtp (not block timestamp). + // Past evaluation at lesser height and mtp is sufficient, provided absolute + // locktime is evaluated against mtp (not block timestamp). return system::pool::algorithm::is_sufficient( { evaluated.flags, evaluated.height, evaluated.mtp }, { current.flags, current.height, current.mtp }, diff --git a/include/bitcoin/database/impl/query/consensus/consensus_strong.ipp b/include/bitcoin/database/impl/query/consensus/consensus_strong.ipp index e55ebcfab..512d143c0 100644 --- a/include/bitcoin/database/impl/query/consensus/consensus_strong.ipp +++ b/include/bitcoin/database/impl/query/consensus/consensus_strong.ipp @@ -43,7 +43,7 @@ bool CLASS::is_strong_block(const header_link& link) const NOEXCEPT // find_strong // ---------------------------------------------------------------------------- -// Return the tx.link for same tx.hash with strong association to block. +// Return tx.link for same tx.hash with strong association to block. TEMPLATE tx_link CLASS::find_strong_tx(const tx_link& link) const NOEXCEPT diff --git a/include/bitcoin/database/impl/query/extent.ipp b/include/bitcoin/database/impl/query/extent.ipp index ccb9ef859..ff5196e01 100644 --- a/include/bitcoin/database/impl/query/extent.ipp +++ b/include/bitcoin/database/impl/query/extent.ipp @@ -252,9 +252,9 @@ DEFINE_RECORDS(filter_bk) // Counters (archive slabs). // ---------------------------------------------------------------------------- -// Also txs, ins and outs, but these can be derived instead of counting. -// txs elements is equivalent to header_records, ins elements is inputs, and -// outs elements is outputs. +// Also txs, ins and outs, but these can be derived instead +// of counted. txs elements equivalent to header_records, +// ins elements is inputs, outs elements is outputs. TEMPLATE size_t CLASS::input_count(const tx_link& link) const NOEXCEPT diff --git a/include/bitcoin/database/impl/query/merkle.ipp b/include/bitcoin/database/impl/query/merkle.ipp index 73c18b627..1e7ecee16 100644 --- a/include/bitcoin/database/impl/query/merkle.ipp +++ b/include/bitcoin/database/impl/query/merkle.ipp @@ -204,12 +204,12 @@ hash_digest CLASS::partial_subroot(hashes&& tree, size_t span) NOEXCEPT if (is_zero(depth)) return tree.front(); - // merkle_root() treats a single hash as top/complete, but for a partial - // depth subtree, an odd leaf (including a single) requires duplication. + // merkle_root() treats single hash as top/complete, but for partial depth + // subtree, odd leaf (including single) requires duplication. if (is_odd(tree.size())) tree.push_back(tree.back()); - // Log2 of the evened breadth gives the elevation by merkle_root. + // Log2 of evened breadth gives elevation by merkle_root. // Partial cannot exceed depth, since tree.size() <= span (a power of 2). auto partial = ceilinged_log2(tree.size()); if (is_subtract_overflow(depth, partial)) diff --git a/include/bitcoin/database/impl/query/navigate/navigate_hashmap.ipp b/include/bitcoin/database/impl/query/navigate/navigate_hashmap.ipp index b3d3eb180..c72eb2180 100644 --- a/include/bitcoin/database/impl/query/navigate/navigate_hashmap.ipp +++ b/include/bitcoin/database/impl/query/navigate/navigate_hashmap.ipp @@ -31,7 +31,8 @@ TEMPLATE header_link CLASS::top_header(size_t bucket) const NOEXCEPT { using namespace system; - return store_.header.top(possible_narrow_cast(bucket)); + const auto index = possible_narrow_cast(bucket); + return store_.header.top(index); } TEMPLATE diff --git a/include/bitcoin/database/impl/query/navigate/navigate_natural.ipp b/include/bitcoin/database/impl/query/navigate/navigate_natural.ipp index f84cd28d4..7a0f8f33f 100644 --- a/include/bitcoin/database/impl/query/navigate/navigate_natural.ipp +++ b/include/bitcoin/database/impl/query/navigate/navigate_natural.ipp @@ -63,8 +63,8 @@ inline tx_link CLASS::to_tx(const hash_digest& key) const NOEXCEPT return store_.tx.first(key); } -// A pooled tx by witness hash, otherwise an unsegregated tx (txid == wtxid). -// Candidates are verified against the pool following iterator disposal. +// Pooled tx by witness hash, otherwise unsegregated tx (txid == wtxid). +// Candidates verified against pool following iterator disposal. TEMPLATE inline tx_link CLASS::to_witness_tx(const hash_digest& key) const NOEXCEPT { diff --git a/include/bitcoin/database/impl/query/navigate/navigate_reverse.ipp b/include/bitcoin/database/impl/query/navigate/navigate_reverse.ipp index 0c5fd5c1f..a2b680760 100644 --- a/include/bitcoin/database/impl/query/navigate/navigate_reverse.ipp +++ b/include/bitcoin/database/impl/query/navigate/navigate_reverse.ipp @@ -28,7 +28,7 @@ namespace database { // block->block[parent] // ---------------------------------------------------------------------------- -// Presumed to guaranee consistency as headers are not duplicated by the node. +// Presumed to guarantee consistency as headers are not duplicated by node. TEMPLATE header_link CLASS::to_parent(const header_link& link) const NOEXCEPT @@ -65,8 +65,8 @@ header_link CLASS::to_confirmed_child(const header_link& link) const NOEXCEPT // address->outputs[receivers] // ---------------------------------------------------------------------------- -// There can be multiple spenders of the same output (due to conflicts) and -// multiple instances of an output under distinct links (due to tx dups). +// Can be multiple spenders of same output (due to conflicts) and multiple +// instances of output under distinct links (due to tx dups). TEMPLATE code CLASS::to_touched_txs(tx_links& out, @@ -116,7 +116,8 @@ code CLASS::to_touched_txs(const stopper& cancel, tx_links& out, return txs; txs.push_back(parent); - for (const auto& input: std::views::reverse(to_spenders(parent, output))) + const auto spenders = to_spenders(parent, output); + for (const auto& input: std::views::reverse(spenders)) { const auto tx = to_input_tx(input); if (tx.is_terminal()) @@ -163,7 +164,7 @@ code CLASS::to_address_outputs(const stopper& cancel, outs_link& cursor, parents.clear(); // Limit bounds candidates, verified following iterator disposal. - // The iterator guards the aggregate, so puts is read unguarded. + // Iterator guards aggregate, so puts is read unguarded. code deferred{ error::success }; output_links candidates{}; auto found = cursor.is_terminal(); @@ -253,8 +254,8 @@ tx_link CLASS::to_prevout_tx(const ins_link& link) const NOEXCEPT // output->inputs[spenders] // ---------------------------------------------------------------------------- // get_spenders(point) is deduped, but to_spenders(output) is not, it returns -// links to ALL spenders of the output including duplicates and double spends. -// This allows result to be navigated via to_block() to find any strong spend. +// links to ALL spenders of output including duplicates and double spends. +// Allows result to be navigated via to_block() to find any strong spend. TEMPLATE ins_links CLASS::to_spenders(const output_link& link) const NOEXCEPT @@ -319,10 +320,10 @@ tx_links CLASS::to_duplicates(const hash_digest& tx_hash) const NOEXCEPT // ---------------------------------------------------------------------------- // protected (logically hazardous) -// to_block() is ONLY the association from tx link to its associating block. -// This will be terminal when link is not of the associated instance of the -// "same" transaction. Tx links in the txs association are always consistent -// with the strong association, as strong is set using txs links. +// to_block() is ONLY association from tx link to its associating block. +// Terminal when link is not of associated instance of "same" transaction. Tx +// links in txs association are always consistent with strong association, as +// strong is set using txs links. TEMPLATE header_link CLASS::to_block(const tx_link& link) const NOEXCEPT diff --git a/include/bitcoin/database/impl/query/pool/pool_coverage.ipp b/include/bitcoin/database/impl/query/pool/pool_coverage.ipp index 225eda7bc..abc6a0fd5 100644 --- a/include/bitcoin/database/impl/query/pool/pool_coverage.ipp +++ b/include/bitcoin/database/impl/query/pool/pool_coverage.ipp @@ -49,11 +49,10 @@ code CLASS::get_pool_coverage(bool& out, maximum_outcomes); } -// Candidates are rows and inputs numbered from the table counts. A parent -// among the candidates is found by hash, a pooled parent by link, and any -// other parent is none. An input joins the ring of a pooled spender of its -// point by a bridge from that input, or a ring of candidate spenders if there -// is none. +// Candidates are rows and inputs numbered from table counts. Parent among +// candidates is found by hash, pooled parent by link, and any other parent is +// none. Input joins ring of a pooled spender of its point by a bridge from that +// input, or a ring of candidate spenders if there is none. TEMPLATE code CLASS::get_pool_candidate(pool_graph& out, const transaction& tx, const context& ctx) const NOEXCEPT @@ -144,8 +143,8 @@ code CLASS::get_pool_candidate(pool_graph& out, const transaction& tx, else { auto& ring = out.rivals.at(at->second - inputs); - out.rivals.back() = (algorithm::from_column(ring) == none) ? - algorithm::to_column(at->second) : ring; + const auto vacant = (algorithm::from_column(ring) == none); + out.rivals.back() = vacant ? algorithm::to_column(at->second) : ring; ring = algorithm::to_column(input); } @@ -244,8 +243,8 @@ code CLASS::get_pool_coverage(bool& out, const pool_graph& graph, components.push_back(component); } - // A pooled parent's surplus pays for its child (parent pays for child), - // in a family within a block, beyond which each component pays its own. + // Pooled parent's surplus pays for its child (parent pays for child), in a + // family within a block, beyond which each component pays its own. uint64_t fee{}, bytes{}; const auto bounded = algorithm::family(fee, bytes, g, measured, limit.size, bytes_per_sigop, maximum_outcomes); diff --git a/include/bitcoin/database/impl/query/pool/pool_estimate.ipp b/include/bitcoin/database/impl/query/pool/pool_estimate.ipp index 7ad3ccae8..b3d56c7bd 100644 --- a/include/bitcoin/database/impl/query/pool/pool_estimate.ipp +++ b/include/bitcoin/database/impl/query/pool/pool_estimate.ipp @@ -79,8 +79,8 @@ code CLASS::get_pool_continuation(pool_projection& projection, size_t count, return error::success; } -// A row arrives at the height of its context, and counts while it can confirm -// or has confirmed. Rows of the top height are of the open interval. +// Row arrives at height of its context, and counts while it can confirm or has +// confirmed. Rows of top height are of open interval. TEMPLATE code CLASS::get_pool_arrivals(pool_arrivals& out, size_t top, size_t count, uint32_t bytes_per_sigop) const NOEXCEPT diff --git a/include/bitcoin/database/impl/query/pool/pool_index.ipp b/include/bitcoin/database/impl/query/pool/pool_index.ipp index 5a2fcb43c..ccc24ede4 100644 --- a/include/bitcoin/database/impl/query/pool/pool_index.ipp +++ b/include/bitcoin/database/impl/query/pool/pool_index.ipp @@ -24,10 +24,10 @@ namespace libbitcoin { namespace database { -// The pool index is rebuilt from the compacted pool. Retained rows are -// confirmable, so none has a stored cause of absence. Inputs follow row order, -// so a row joins only the rings of the rows rebuilt before it. A parent may -// follow its child, so all rows are set before any input is linked. +// Pool index rebuilt from compacted pool. Retained rows are confirmable, so +// none has a stored cause of absence. Inputs follow row order, so row joins +// only rings of rows rebuilt before it. Parent may follow its child, so all +// rows are set before any input is linked. TEMPLATE bool CLASS::set_pool_index() NOEXCEPT { @@ -100,7 +100,7 @@ bool CLASS::set_pool_index() NOEXCEPT } // protected -// The cell and children head of each row in the range. +// Cell and children head of each row in range. TEMPLATE bool CLASS::set_pool_rows(system::pool::algorithm::link_t begin, system::pool::algorithm::link_t end) NOEXCEPT @@ -123,9 +123,9 @@ bool CLASS::set_pool_rows(system::pool::algorithm::link_t begin, } // protected -// Each input's parent row, sibling (joining the list of inputs spending its -// parent) and rival (joining the ring of inputs spending its point at a pooled -// spender of it). +// Each input's parent row, +// sibling (joining list of inputs spending its parent) and +// rival (joining ring of inputs spending its point at a pooled spender of it). TEMPLATE bool CLASS::set_pool_links(system::pool::algorithm::link_t start, const pool_links& parents, const pool_links& mates) NOEXCEPT @@ -183,8 +183,7 @@ bool CLASS::set_pool_links(system::pool::algorithm::link_t start, } // protected -// The index heads hold no count cell, so each column is a plain array of -// cells. +// Index heads hold no count cell, so each column is a plain array of cells. TEMPLATE bool CLASS::get_pool_columns(system::pool::algorithm::columns_t& out, pool_guards& guards) const NOEXCEPT @@ -264,7 +263,7 @@ bool CLASS::get_pool_columns(system::pool::algorithm::columns_t& out, } // protected -// A point archived with one spender is not in the duplicate table. +// Point archived with one spender is not in duplicate table. TEMPLATE bool CLASS::get_pooled_spender(system::pool::algorithm::link_t& out, bool& conflicted, const point& point, const tx_link& self, @@ -313,7 +312,7 @@ bool CLASS::get_pooled_spender(system::pool::algorithm::link_t& out, } // protected -// The first tx is the coinbase, which spends nothing. +// First tx is coinbase, which spends nothing. TEMPLATE bool CLASS::get_pool_conflicts(tx_links& out, const tx_links& txs) const NOEXCEPT @@ -358,11 +357,11 @@ bool CLASS::is_pool_conflicted(bool& out, const tx_link& link, return true; } -// The conflicts of the block's txs are the archived spenders of its points as -// of the transition, as a tx may be pooled after the block's prevouts are -// cached. They include the block's own txs, as each spends a conflicted point. -// A conflict is cleared at a reorganization only if no other confirmed tx -// spends a point of the row. +// Conflicts of block's txs are archived spenders of its points +// as of transition, as a tx may be pooled after block's prevouts +// are cached. They include block's own txs, as each spends a +// conflicted point. Conflict is cleared at reorganization only +// if no other confirmed tx spends a point of row. TEMPLATE bool CLASS::set_pool_block(const header_link& link, bool confirmed) NOEXCEPT { diff --git a/include/bitcoin/database/impl/query/pool/pool_reader.ipp b/include/bitcoin/database/impl/query/pool/pool_reader.ipp index 2fbd6a384..85fad0971 100644 --- a/include/bitcoin/database/impl/query/pool/pool_reader.ipp +++ b/include/bitcoin/database/impl/query/pool/pool_reader.ipp @@ -100,7 +100,7 @@ code CLASS::get_pooled(pooled_tx& out, const tx_link& link, } // protected -// The tx of an uncommitted record (its key does not resolve to it) is terminal. +// Tx of uncommitted record (its key does not resolve to it) is terminal. TEMPLATE tx_link CLASS::to_pool_tx(const pool_link& link) const NOEXCEPT { diff --git a/include/bitcoin/database/impl/query/pool/pool_suffice.ipp b/include/bitcoin/database/impl/query/pool/pool_suffice.ipp index bdd718f0d..aeffd104b 100644 --- a/include/bitcoin/database/impl/query/pool/pool_suffice.ipp +++ b/include/bitcoin/database/impl/query/pool/pool_suffice.ipp @@ -127,9 +127,9 @@ bool CLASS::set_pooled_context(const tx_link& link, const context& ctx, // ======================================================================== } -// A tx spending an output of the block (coinbase included) may depend on its -// confirmation, so it is not sufficient under any context until revalidated. -// Its flags are kept, as its sigops are counted under them. +// Tx spending an output of block (coinbase included) may depend on its +// confirmation, so not sufficient under any context until revalidated. Its +// flags are kept, as its sigops are counted under them. TEMPLATE bool CLASS::set_pool_unvalidated(size_t& out, const header_link& link) NOEXCEPT diff --git a/include/bitcoin/database/impl/query/pool/pool_writer.ipp b/include/bitcoin/database/impl/query/pool/pool_writer.ipp index fe9206cc0..754f5cefa 100644 --- a/include/bitcoin/database/impl/query/pool/pool_writer.ipp +++ b/include/bitcoin/database/impl/query/pool/pool_writer.ipp @@ -39,8 +39,8 @@ bool CLASS::set_pooled(const tx_link& link, const transaction& tx, return set_pooled(repooled, link, tx, ctx, time); } -// A pooled spender of the tx (pooled while the tx was confirmed) holds a lower -// row, so it and its pooled descendants are purged and pooled after the tx. +// Pooled spender of tx (pooled while tx was confirmed) holds lower row, so it +// and its pooled descendants are purged and pooled after tx. TEMPLATE bool CLASS::set_pooled(size_t& repooled, const tx_link& link, const transaction& tx, const context& ctx, uint32_t time) NOEXCEPT @@ -174,8 +174,8 @@ bool CLASS::set_pool_row(const tx_link& link, const transaction& tx, if (!get_pool_columns(columns, guards)) return false; - // A conflict with a confirmed spender is absent for it, and a component - // over the member limit is labeled by the columns. + // Conflict with confirmed spender is absent for it, and component over + // member limit is labeled by columns. if (!algorithm::admit(columns, row, conflicted)) system::pool::label(columns); diff --git a/include/bitcoin/database/impl/query/properties_block.ipp b/include/bitcoin/database/impl/query/properties_block.ipp index 4ae205775..7d86f1800 100644 --- a/include/bitcoin/database/impl/query/properties_block.ipp +++ b/include/bitcoin/database/impl/query/properties_block.ipp @@ -170,8 +170,8 @@ bool CLASS::get_context(system::chain::context& ctx, if (!store_.header.get(link, header)) return false; - // Context for header.check and header.accept are filled from chain_state. - // So these are not populated here as they are not expected to be used. + // Context for header.check and header.accept filled from chain_state, so + // not populated here as not expected to be used. ctx = { // [block.check, .accept, .connect] @@ -283,8 +283,8 @@ hashes CLASS::get_wtxids(const header_link& link) const NOEXCEPT return hashes; } -// The coinbase commits to the witness root, otherwise the block is -// unsegregated and its witness root is the header merkle root. +// Coinbase commits to witness root, otherwise block is unsegregated and its +// witness root is header merkle root. TEMPLATE bool CLASS::is_witness_committed(const hash_digest& witness_root, const header_link& link) const NOEXCEPT diff --git a/include/bitcoin/database/impl/query/properties_tx.ipp b/include/bitcoin/database/impl/query/properties_tx.ipp index 2b7c2aa68..90b13650c 100644 --- a/include/bitcoin/database/impl/query/properties_tx.ipp +++ b/include/bitcoin/database/impl/query/properties_tx.ipp @@ -60,8 +60,8 @@ inline bool CLASS::is_tx_segregated(const tx_link& link) const NOEXCEPT return get_tx_sizes(light, heavy, link) && heavy != light; } -// The pool id columns hold the witness hash of a pooled tx, otherwise (such as -// for any coinbase) the witness hash is computed from the stored tx. +// Pool id columns hold witness hash of pooled tx, otherwise (such as for any +// coinbase) witness hash is computed from stored tx. TEMPLATE hash_digest CLASS::get_wtxid(const tx_link& link) const NOEXCEPT { diff --git a/include/bitcoin/database/impl/query/query.ipp b/include/bitcoin/database/impl/query/query.ipp index 06fc70597..3e7d48aba 100644 --- a/include/bitcoin/database/impl/query/query.ipp +++ b/include/bitcoin/database/impl/query/query.ipp @@ -23,46 +23,43 @@ // Error handling: // Negative (false/empty/nullptr) return implies error or not found condition. -// Interpretation may depend on context. The presumption is of store integrity, -// as there is no validation (such as checksumming) of the store. Given that -// the blockchain is a cache of public data, this is a sufficient loss guard. -// If a validated link is passed and the result is negative, the integrity -// presumption implies that the result is negative - unless there are no such -// conditions. In that case the failure result implies loss of store integrity. -// Given the integrity presumption, such a possibility can be ignored. On the -// other hand, if a possible negative result from one call is cascaded to -// another call, the presumption on a final negative is that a negative result -// was propagated, or that a positive propagated, followed by a negative. In -// this case the original cause of the negative is presumed to be unimportant. -// Store integrity is not assured if the indexes are empty (no genesis block), -// and therefore assertions are provided for these limited situations, as -// error handling would be unnecessarily costly. The integrity presumption -// does not hold given faults in the underlying store interface. Consequently -// these are managed independently through the logging interface. Note that -// cascading failures from terminal to search key is an unnecessary perf hit. -// Note that expected stream invalidation may occur (index validation). Store -// read (paging) failures will result in an unhandled exception (termination). -// This can happen from drive disconnection (for example). Store write failures -// can result from memory remap failure, such as when the disk is full. These -// are caught and propagated to write failures and then query failures. Given -// a reliable disk, disk full is the only commonly-expected fault condition. +// Interpretation may depend on context. Presumption is of store integrity, +// as there is no validation (such as checksumming) of store. Given +// blockchain is a cache of public data, this is a sufficient loss guard. If +// a validated link is passed and result is negative, integrity presumption +// implies result is negative - unless there are no such conditions. In that +// case failure result implies loss of store integrity. Given integrity +// presumption, such a possibility can be ignored. On the other hand, if a +// possible negative result from one call is cascaded to another call, +// presumption on a final negative is that a negative result was propagated, +// or that a positive propagated, followed by a negative. In this case +// original cause of negative is presumed unimportant. Store integrity not +// assured if indexes are empty (no genesis block), so assertions are +// provided for these limited situations, as error handling would be +// unnecessarily costly. Integrity presumption does not hold given faults in +// underlying store interface, so these are managed independently through +// logging interface. Cascading failures from terminal to search key is an +// unnecessary perf hit. Expected stream invalidation may occur (index +// validation). Store read (paging) failures result in unhandled exception +// (termination), as from drive disconnection (for example). Store write +// failures can result from memory remap failure, such as when disk is full. +// These are caught and propagated to write failures and then query failures. +// Given reliable disk, disk full is only commonly-expected fault condition. // // Remapping: -// During any write operation, the store may be forced to unload and remap the +// During any write operation, store may be forced to unload and remap // underlying backing file of one or more table bodies (headers do not resize). -// This invalidates all memory pointers, but does not invalidate links. -// Pointers are short-lived and managed internally by tables. However iterators -// encapsulate pointers and therefore should be be used with caution. Holding -// an iterator on a table while also invoking a write on that table will result -// in deadlock in the case where the write invokes a remap (blocked by the -// iterator). +// This invalidates all memory pointers, but not links. Pointers are +// short-lived and managed internally by tables. However iterators +// encapsulate pointers and therefore should be used with caution. +// Holding an iterator on a table while also invoking a write on that +// table deadlocks where write invokes a remap (blocked by iterator). // // Transactionality: -// The query interface uses the underlying store's transactor to provide an -// assurance that writes are consistent when the transactor is unlocked. This -// is provided so that store-wide archival may proceed with writes suspended at -// a point of consistency, while also allowing reads to proceed. Query callers -// should expect writes to be blocked during store hot backup. +// Query interface uses underlying store's transactor to assure writes are +// consistent when transactor is unlocked, so store-wide archival may proceed +// with writes suspended at a point of consistency, while also allowing reads to +// proceed. Query callers should expect writes blocked during store hot backup. namespace libbitcoin { namespace database { diff --git a/include/bitcoin/database/impl/store/store.ipp b/include/bitcoin/database/impl/store/store.ipp index 3d12c0522..11504fc1b 100644 --- a/include/bitcoin/database/impl/store/store.ipp +++ b/include/bitcoin/database/impl/store/store.ipp @@ -190,8 +190,8 @@ CLASS::store(const settings& config) NOEXCEPT { envelope_.set(config); - // Filter k derives from configured expected/buckets, envelope records it - // at create and overrides it at open (stored values govern the store). + // Filter k derives from configured expected/buckets, envelope records it at + // create, overrides it at open (stored values govern store). using namespace system; envelope_.header_k = possible_narrow_cast(header.filter_k()); envelope_.ins_k = possible_narrow_cast(ins.filter_k()); diff --git a/include/bitcoin/database/impl/store/store_backup.ipp b/include/bitcoin/database/impl/store/store_backup.ipp index 6aeae90c1..2237a53be 100644 --- a/include/bitcoin/database/impl/store/store_backup.ipp +++ b/include/bitcoin/database/impl/store/store_backup.ipp @@ -117,9 +117,9 @@ code CLASS::backup(const event_handler& handler, bool prune) NOEXCEPT // Rename /temporary to /primary (atomic). if ((ec = file::rename_ex(temporary, primary))) return ec; - // Delete the rotated /secondary, superseded by the new /primary. Best - // effort, as the snapshot is committed (a remnant is deleted by the next - // backup or restore, and is unreachable while /primary exists). + // Delete rotated /secondary, superseded by new /primary. Best effort, as + // snapshot is committed (remnant deleted by next backup or restore, and + // unreachable while /primary exists). if (file::is_directory(secondary)) { /* bool */ file::clear_directory(secondary); diff --git a/include/bitcoin/database/impl/store/store_close.ipp b/include/bitcoin/database/impl/store/store_close.ipp index 9d8f7e6ae..d7b9b10e2 100644 --- a/include/bitcoin/database/impl/store/store_close.ipp +++ b/include/bitcoin/database/impl/store/store_close.ipp @@ -91,8 +91,7 @@ code CLASS::close(const event_handler& handler) NOEXCEPT if (!process_lock_.try_unlock()) ec = error::process_unlock; - // fault overrides unlock errors, leaves behind flush_lock and fault locks - // the store. + // fault overrides unlock errors, leaves flush_lock and fault locks store. if (get_fault()) { /* bool */ set_fault_lock(); diff --git a/include/bitcoin/database/impl/store/store_dump.ipp b/include/bitcoin/database/impl/store/store_dump.ipp index 1981f22e1..46d525323 100644 --- a/include/bitcoin/database/impl/store/store_dump.ipp +++ b/include/bitcoin/database/impl/store/store_dump.ipp @@ -26,7 +26,7 @@ namespace database { // public // Dump memory maps of /heads to new files in /temporary. -// Heads are copied from RAM, not flushed to disk and copied as files. +// Heads copied from RAM, not flushed to disk and copied as files. TEMPLATE code CLASS::dump(const path& folder, const event_handler& handler) NOEXCEPT diff --git a/include/bitcoin/database/impl/store/store_open.ipp b/include/bitcoin/database/impl/store/store_open.ipp index 0a22a0fe5..fdaf63152 100644 --- a/include/bitcoin/database/impl/store/store_open.ipp +++ b/include/bitcoin/database/impl/store/store_open.ipp @@ -156,8 +156,8 @@ void CLASS::store_envelope(code& ec) NOEXCEPT ec = error::create_table; } -// The head is expanded before the envelope is rewritten, so a failed expansion -// (disk full) leaves the stored envelope unchanged. +// Head expanded before envelope rewritten, so failed expansion (disk full) +// leaves stored envelope unchanged. TEMPLATE code CLASS::put_envelope(const database::envelope& stored) NOEXCEPT { @@ -176,9 +176,8 @@ code CLASS::put_envelope(const database::envelope& stored) NOEXCEPT // ---------------------------------------------------------------------------- // public -// The stored envelope is read in, migrated by each step from its schema, and -// written out. A failure once the store is changed leaves the fault and flush -// locks. +// Stored envelope read in, migrated by each step from its schema, and written +// out. Failure once store is changed leaves fault and flush locks. TEMPLATE code CLASS::migrate(system::config::version& original, const database::envelope& configured, @@ -466,10 +465,10 @@ code CLASS::migrate_4_0_31_to_4_0_32(database::envelope& stored, return error::success; } -// Each pruned block, with each of its txs, is flagged in its heavy size in -// place, found by the sizes of its coinbase. A tx of no block (archived before -// a failed association, as on disk full) is found once its block is archived -// again, as the points it spends are then duplicated. +// Each pruned block, with each of its txs, flagged in its heavy size in place, +// found by sizes of its coinbase. Tx of no block (archived before failed +// association, as on disk full) found once its block archived again, as points +// it spends are then duplicated. TEMPLATE code CLASS::migrate_4_0_32_to_4_0_33(const event_handler& handler) NOEXCEPT { @@ -534,8 +533,8 @@ code CLASS::migrate_4_0_32_to_4_0_33(const event_handler& handler) NOEXCEPT load(ec, duplicate_head_, table_t::duplicate_head); load(ec, duplicate_body_, table_t::duplicate_body); - // Rows are rewritten in place, so the bodies are mapped rewritable (a - // staged body is append-only, its settled rows read-only). + // Rows rewritten in place, so bodies mapped rewritable (staged body is + // append-only, its settled rows read-only). const auto restage = [&handler](code& ec, auto& file, table_t table) NOEXCEPT { @@ -550,8 +549,8 @@ code CLASS::migrate_4_0_32_to_4_0_33(const event_handler& handler) NOEXCEPT restage(ec, tx_body_, table_t::tx_body); restage(ec, txs_body_, table_t::txs_body); - // Each header bucket is an associated block or terminal. A block is - // pruned as a unit, so its coinbase (first tx) decides all of its txs. + // Each header bucket is associated block or terminal. Block pruned as unit, + // so its coinbase (first tx) decides all of its txs. const auto count = tx.count().value; std::vector associated(count); if (!ec) @@ -675,8 +674,8 @@ code CLASS::migrate_4_0_32_to_4_0_33(const event_handler& handler) NOEXCEPT return ec; } -// A pruned tx stores every input script and witness empty (only the first -// input link is valid), so its stored nominal size is short of its archived. +// Pruned tx stores every input script and witness empty (only first input link +// valid), so its stored nominal size is short of its archived. TEMPLATE code CLASS::get_pruned(bool& pruned, const table::transaction::record& record) const NOEXCEPT @@ -718,9 +717,9 @@ code CLASS::get_pruned(bool& pruned, } // public -// The schema is deserialized before it is validated, so the record holds it -// when envelope deserialization fails. The stored argument provides the -// configured values for a migrated envelope. +// Schema deserialized before validated, so record holds +// it when envelope deserialization fails. Stored argument +// provides configured values for migrated envelope. TEMPLATE code CLASS::read_envelope(database::envelope& stored) NOEXCEPT { @@ -774,8 +773,8 @@ code CLASS::load_schema() NOEXCEPT error::schema_version; } -// The schema is deserialized before it is validated, so the record holds it -// when envelope deserialization fails. +// Schema deserialized before validated, +// so record holds it when envelope deserialization fails. TEMPLATE bool CLASS::get_schema(system::config::version& schema) const NOEXCEPT { diff --git a/include/bitcoin/database/impl/store/store_prune.ipp b/include/bitcoin/database/impl/store/store_prune.ipp index a90647a08..0ff1d8b14 100644 --- a/include/bitcoin/database/impl/store/store_prune.ipp +++ b/include/bitcoin/database/impl/store/store_prune.ipp @@ -31,8 +31,8 @@ namespace database { TEMPLATE code CLASS::prune(const event_handler& handler) NOEXCEPT { - // Transactor lock generally only covers writes, but in this case prevout - // reads must also be guarded since the body shrinks and head is cleared. + // Transactor lock generally only covers writes, but here prevout reads must + // also be guarded, as body shrinks and head is cleared. while (!transactor_mutex_.try_lock_for(std::chrono::seconds(1))) { handler(event_t::wait_lock, table_t::store); @@ -56,8 +56,8 @@ code CLASS::prune(const event_handler& handler) NOEXCEPT ec = error::prune_table; // Snapshot with nullified head and zero body count. - // The 'prune' parameter signals to not reset body count. - // Success deletes the pre-prune snapshot (trim strands nothing). + // 'prune' parameter signals not to reset body count. + // Success deletes pre-prune snapshot (trim strands nothing). if (!ec) ec = snapshot(handler, true); @@ -125,10 +125,10 @@ code CLASS::prune(const event_handler& handler) NOEXCEPT } // protected -// Each kept record moves down to the row of its rank, as do its spends, over -// records that are dropped. A staged body is not rewritable, so the pool and -// spends bodies are mapped shared for the move. Requires that nothing is -// reading the pool, and a failure leaves the pool undefined. +// Each kept record moves down to row of its rank, as do its +// spends, over dropped records. Staged body is not rewritable, +// so pool and spends bodies are mapped shared for move. Requires +// nothing reading pool, and failure leaves pool undefined. TEMPLATE code CLASS::compact(const event_handler& handler) NOEXCEPT { @@ -208,7 +208,7 @@ code CLASS::compact(const event_handler& handler) NOEXCEPT } // protected -// The retained records in row order (a record is the first of its key). +// Retained records in row order (record is first of its key). TEMPLATE bool CLASS::retain_pool(retentions& out) NOEXCEPT { @@ -237,9 +237,7 @@ bool CLASS::retain_pool(retentions& out) NOEXCEPT } // protected -// A tx is retained if it is confirmable and every unconfirmed ancestor is -// pooled. Ancestors are found by key, so link order is not assumed, and an -// ancestor already retained (kept is in row order) ends its walk. +// Tx retained if confirmable and every unconfirmed ancestor is pooled. TEMPLATE bool CLASS::is_retained(bool& out, const tx_link& link, const retentions& kept) NOEXCEPT @@ -292,8 +290,8 @@ bool CLASS::is_retained(bool& out, const tx_link& link, } // protected -// Runs are disjoint, so in the order of their records each moves down over -// dropped records only. +// Runs disjoint, so in order of their records +// each moves down over dropped records only. TEMPLATE bool CLASS::move_spends(retentions& keep) NOEXCEPT { @@ -323,8 +321,8 @@ bool CLASS::move_spends(retentions& keep) NOEXCEPT } // protected -// Records are kept in row order, so each moves down over dropped records -// only, and is committed to the cleared head at its new row. +// Records kept in row order, so each moves down over dropped records only, and +// is committed to cleared head at its new row. TEMPLATE bool CLASS::move_pool(const retentions& keep) NOEXCEPT { @@ -372,8 +370,8 @@ bool CLASS::move_pool(const retentions& keep) NOEXCEPT } // protected -// A wtxid record is that of its pool row, so the index is rebuilt from the -// witness hash of each row. +// Wtxid record is that of its pool row, +// so index is rebuilt from witness hash of each row. TEMPLATE bool CLASS::index_pool() NOEXCEPT { diff --git a/include/bitcoin/database/impl/store/store_reload.ipp b/include/bitcoin/database/impl/store/store_reload.ipp index 9cd264ea4..b73266647 100644 --- a/include/bitcoin/database/impl/store/store_reload.ipp +++ b/include/bitcoin/database/impl/store/store_reload.ipp @@ -47,8 +47,8 @@ code CLASS::reload(const event_handler& handler) NOEXCEPT } // Reload all storages, as staged instances must discard extents - // orphaned by abandoned writes (which may span into tables that - // did not themselves fault). Returns any storage fault as failure. + // orphaned by abandoned writes (which may span into tables that did + // not themselves fault). Returns any storage fault as failure. ec = file.reload(); } }; diff --git a/include/bitcoin/database/impl/store/store_restore.ipp b/include/bitcoin/database/impl/store/store_restore.ipp index bbc69794f..42c88e292 100644 --- a/include/bitcoin/database/impl/store/store_restore.ipp +++ b/include/bitcoin/database/impl/store/store_restore.ipp @@ -67,8 +67,8 @@ code CLASS::restore(const event_handler& handler) NOEXCEPT if (file::is_directory(primary)) { // Clear invalid /heads and clone /primary (retained) to /heads. - // The snapshot is never vacated, so no fault leaves /heads as the - // only copy (which the recreation below would otherwise clear). + // Snapshot never vacated, so no fault leaves /heads as only copy (which + // recreation below would otherwise clear). ec = file::clear_directory_ex(heads); if (!ec) ec = file::remove_ex(heads); if (!ec) ec = file::copy_directory_ex(primary, heads); @@ -150,12 +150,12 @@ code CLASS::restore(const event_handler& handler) NOEXCEPT // ecdsa, schnorr, silent, prevalid, and presilent are dropped. //--------------------------------------------------------------------- - // Signatures could be retained and verified, but this just becomes - // redundant work unless prevalid is retained. That would require flush - // of batched_ at snapshot (requires handle message and send complete). - // Would also require an external transactor or terminal prefills in - // threshold batched rows to prevent recovering unpopulated rows. The - // extra complexity isn't probably worth saving the batch for a snap. + // Signatures could be retained and verified, but this becomes redundant + // work unless prevalid is retained. That would require flush of + // batched_ at snapshot (requires handle message and send complete). + // Would also require external transactor or terminal prefills in + // threshold batched rows to prevent recovering unpopulated rows. Extra + // complexity probably not worth saving batch for snap. //--------------------------------------------------------------------- dropped(ec, ecdsa0, table_t::ecdsa0_table); dropped(ec, ecdsa1, table_t::ecdsa1_table); diff --git a/include/bitcoin/database/impl/unspent/unspent_reader.ipp b/include/bitcoin/database/impl/unspent/unspent_reader.ipp index 1ffa8e2c3..df2e34425 100644 --- a/include/bitcoin/database/impl/unspent/unspent_reader.ipp +++ b/include/bitcoin/database/impl/unspent/unspent_reader.ipp @@ -287,8 +287,8 @@ code CLASS::read_heights(std_vector& out, return error::success; } -// bitcoind retains duplicated coinbases at the overwriting heights (bip30 -// exceptions), the store at the originals. +// bitcoind retains duplicated coinbases at overwriting heights (bip30 +// exceptions), store at originals. TEMPLATE code CLASS::confirm(unspent_coins& out, size_t offset, const header_links& blocks, const std_vector& heights) const NOEXCEPT diff --git a/include/bitcoin/database/impl/unspent/unspent_scanner.ipp b/include/bitcoin/database/impl/unspent/unspent_scanner.ipp index 9af0d4168..58ab0de94 100644 --- a/include/bitcoin/database/impl/unspent/unspent_scanner.ipp +++ b/include/bitcoin/database/impl/unspent/unspent_scanner.ipp @@ -192,8 +192,8 @@ code CLASS::block(difference_set& set, uint64_t& unspendable, return toggle_spends(set, buffer.spends); } -// The duplicated coinbase outputs of the bip30 exception blocks overwrite -// (destroy) those of the original blocks. +// Duplicated coinbase outputs of bip30 exception blocks overwrite (destroy) +// those of original blocks. TEMPLATE code CLASS::overwritten(uint64_t& out, const table::transaction::get_puts& coinbase) const NOEXCEPT diff --git a/include/bitcoin/database/impl/unspent/unspent_serial.ipp b/include/bitcoin/database/impl/unspent/unspent_serial.ipp index 76b6489f1..a815ffb3d 100644 --- a/include/bitcoin/database/impl/unspent/unspent_serial.ipp +++ b/include/bitcoin/database/impl/unspent/unspent_serial.ipp @@ -38,8 +38,8 @@ CLASS::unspent_serial(const Store& store, const stopper& cancel, { } -// One folder thread for the run, each bucket handed off through 'ordered' -// (ready) and returned (done), so a fold overlaps the fill of the next bucket. +// One folder thread for run, each bucket handed off through 'ordered' (ready) +// and returned (done), so fold overlaps fill of next bucket. TEMPLATE code CLASS::hash(unspent_totals& out, hash_digest& digest, const difference_set& set) const NOEXCEPT diff --git a/include/bitcoin/database/locks/flush_lock.hpp b/include/bitcoin/database/locks/flush_lock.hpp index 724cb067b..9d3753f85 100644 --- a/include/bitcoin/database/locks/flush_lock.hpp +++ b/include/bitcoin/database/locks/flush_lock.hpp @@ -31,8 +31,8 @@ class BCD_API flush_lock : public file_lock { public: - /// Construction does not touch the file. - /// Destruction should not be used to delete the file (needs to remain). + /// Construction does not touch file. + /// Destruction should not be used to delete file (must remain). flush_lock(const std::filesystem::path& file) NOEXCEPT; /// False if file exists or fails to create. diff --git a/include/bitcoin/database/locks/interprocess_lock.hpp b/include/bitcoin/database/locks/interprocess_lock.hpp index 2131ea359..ccd8789c8 100644 --- a/include/bitcoin/database/locks/interprocess_lock.hpp +++ b/include/bitcoin/database/locks/interprocess_lock.hpp @@ -26,8 +26,8 @@ namespace libbitcoin { namespace database { -/// This class is not thread safe, and does not throw. -/// The lock is process-exclusive in linux/macOS, globally in win32. +/// Not thread safe, does not throw. +/// Lock is process-exclusive in linux/macOS, globally in win32. class BCD_API interprocess_lock : public file_lock { @@ -38,12 +38,12 @@ class BCD_API interprocess_lock /// Destruction calls try_unlock. ~interprocess_lock() NOEXCEPT override; - /// Creates the file and acquires exclusive access. - /// Returns false if failed to acquire lock or lock already held. + /// Creates file and acquires exclusive access. + /// False if failed to acquire lock or lock already held. bool try_lock() NOEXCEPT; - /// Releases access (if locked) and deletes the file. - /// Returns true if lock not held or succesfully unlocked and deleted. + /// Releases access (if locked) and deletes file. + /// True if lock not held or successfully unlocked and deleted. bool try_unlock() NOEXCEPT; private: diff --git a/include/bitcoin/database/memory/accessor.hpp b/include/bitcoin/database/memory/accessor.hpp index 8cfd7ef7e..5faf6a47d 100644 --- a/include/bitcoin/database/memory/accessor.hpp +++ b/include/bitcoin/database/memory/accessor.hpp @@ -55,11 +55,11 @@ class accessor final return !is_null(begin_); } - /// Set the buffer, where end is within allocated space. - /// Zero/negative size is allowed (automatically handled by bc streams). - /// End should be initialized to logical space though that may contract or - /// expand during accessor lifetime. The only guarantee offered by end is - /// that it remains within allocated space and is initially logical space. + /// Set buffer, where end is within allocated space. + /// Zero/negative size allowed (automatically handled by bc streams). + /// End should be initialized to logical space though it may contract or + /// expand during accessor lifetime. Only guarantee offered by end is that + /// it remains within allocated space and is initially logical space. inline void assign(uint8_t* begin, uint8_t* end) NOEXCEPT { begin_ = begin; diff --git a/include/bitcoin/database/memory/finalizer.hpp b/include/bitcoin/database/memory/finalizer.hpp index 937f64cab..e0bace982 100644 --- a/include/bitcoin/database/memory/finalizer.hpp +++ b/include/bitcoin/database/memory/finalizer.hpp @@ -47,8 +47,8 @@ class finalizer_ finalize_ = std::move(functor); } - // This is expected to have side effect on the stream buffer, specifically - // setting the "next" pointer into beginning of the address space. + // Expected to have side effect on stream buffer, specifically setting + // "next" pointer into beginning of address space. bool finalize() NOEXCEPT { if (!*this) return false; diff --git a/include/bitcoin/database/memory/interfaces/storage.hpp b/include/bitcoin/database/memory/interfaces/storage.hpp index 4e12f7769..459e7e72e 100644 --- a/include/bitcoin/database/memory/interfaces/storage.hpp +++ b/include/bitcoin/database/memory/interfaces/storage.hpp @@ -27,7 +27,7 @@ namespace libbitcoin { namespace database { /// Mapped memory interface. -/// A slab has a row width of 1, so "count" implies "bytes" for slabs below. +/// Slab has row width of 1, so "count" implies "bytes" for slabs below. class storage { public: @@ -108,8 +108,8 @@ class storage /// Increase logical by specified rows/bytes, return row of first (or eof). virtual size_t allocate(size_t count) NOEXCEPT = 0; - /// Allocate filled rows/bytes, avoiding memory residency of the fill - /// where the backend supports it (head creation path). + /// Allocate filled rows/bytes, avoiding memory residency of fill where + /// backend supports it (head creation path). virtual size_t allocate_filled(size_t count) NOEXCEPT = 0; /// Report element write completion of count rows/bytes at offset. diff --git a/include/bitcoin/database/memory/mmap.hpp b/include/bitcoin/database/memory/mmap.hpp index a246a090a..d598fbc37 100644 --- a/include/bitcoin/database/memory/mmap.hpp +++ b/include/bitcoin/database/memory/mmap.hpp @@ -36,9 +36,9 @@ namespace libbitcoin { namespace database { -/// Thread safe access to a memory-mapped file, or to a set of column files -/// sharing one allocation/remap guard set (SoA aggregate). -/// A slab has a row width of 1, so "count" implies "bytes" for slabs below. +/// Thread safe access to memory-mapped file, or to set of column files sharing +/// one allocation/remap guard set (SoA aggregate). +/// Slab has row width of 1, so "count" implies "bytes" for slabs below. template class mmap : public storage @@ -53,7 +53,7 @@ class mmap using sizes = std::array; /// Per-column record widths; transpose row<->byte by these (constexpr). - /// A zero width column is unbacked: its file is never grown or mapped. + /// Zero width column is unbacked: its file is never grown or mapped. static constexpr sizes widths{ Widths... }; /// Bytes per logical row across the aggregate (sum of column widths). @@ -64,14 +64,14 @@ class mmap /// ----------------------------------------------------------------------- /// Staged instances (append-only bodies) stage writes in anonymous memory - /// and convert flushed rows to a read-only file mapping, hard-faulting any + /// and convert flushed rows to read-only file mapping, hard-faulting any /// write into settled space. Unstaged instances (heads) hold all logical - /// content in anonymous memory for the life of the load. Both write the - /// file only by explicit transfer, so no dirty file-backed page ever - /// exists (no effect where the staging backend is not built). + /// content in anonymous memory for life of load. Both write file only by + /// explicit transfer, so no dirty file-backed page ever exists (no effect + /// where staging backend is not built). - /// Storage tuning is passed by settings (future tunables land there - /// without signature change); random and staged are structural. + /// Storage tuning passed by settings (future tunables land there without + /// signature change); random and staged are structural. /// Scalar construction (columns == 1). mmap(const path& filename, const storage_settings& settings={}, @@ -169,8 +169,8 @@ class mmap /// Increase logical by specified rows/bytes, return row of first (or eof). size_t allocate(size_t count) NOEXCEPT override; - /// Allocate filled rows/bytes; managed heads write the fill to the file - /// and map it released (no memory residency of the fill). + /// Allocate filled rows/bytes; managed heads write fill to file and map it + /// released (no memory residency of fill). size_t allocate_filled(size_t count) NOEXCEPT override; /// Report element write completion of count rows/bytes at offset. @@ -262,19 +262,18 @@ class mmap static constexpr size_t urgent_factor = 4; static constexpr size_t idle_seconds = 60; - // Settled-extent demotion ceiling (installed memory). Demotion trades - // body cache for head residency, which pays only while the head set - // contests memory. Above this ceiling nothing contests: demotion just - // converts warm cache into re-read faults (measured ~2x milestone and - // validation wall on a high-memory host), so ample hosts retain - // settled extents at normal priority. + // Settled-extent demotion ceiling (installed memory). Demotion trades body + // cache for head residency, which pays only while head set contests memory. + // Above this ceiling nothing contests: demotion converts warm cache into + // re-read faults (measured ~2x milestone and validation wall on high-memory + // host), so ample hosts retain settled extents at normal priority. static constexpr size_t demote_memory = system::power2(35u); - // Body eviction leads kernel reclaim: sweeping at the reclaim watermark - // concedes the choice of victim, and the kernel takes anonymous heads - // alongside the cold body cache (it balances the lists, it does not - // know that head residency is the store's priority). A higher floor - // keeps free memory above the watermark, so the sweep is the reclaim. + // Body eviction leads kernel reclaim: sweeping at reclaim watermark + // concedes choice of victim, and kernel takes anonymous heads alongside + // cold body cache (it balances lists, it does not know head residency is + // store's priority). Higher floor keeps free memory above watermark, so + // sweep is the reclaim. static constexpr size_t sweep_factor = 8; // Managed heads (touch, release, share). @@ -283,18 +282,18 @@ class mmap static constexpr size_t release_quiet = 128; // Release conversion granularity: chunked runs bound address space - // fragmentation (each conversion splits a mapping) to the measured flat - // zone of host memory management (heads / chunk fragments worst case). + // fragmentation (each conversion splits mapping) to measured flat zone of + // host memory management (heads / chunk fragments worst case). static constexpr size_t release_chunk = system::power2(20u); - // Writes per tick sustained for unshare_seconds reinstall a shared head - // (a block at the top is a burst of one tick, a catch-up is sustained). + // Writes per tick sustained for unshare_seconds reinstall shared head + // (block at top is burst of one tick, catch-up is sustained). static constexpr size_t unshare_writes = 1000; static constexpr size_t unshare_seconds = 10; #if defined(HAVE_APPLE) - // Anonymous overflow feeds the darwin compressor (10.8GB measured at - // 16GB), which mincore hides from the touch guard; release converts - // quiet heads to droppable file pages, removing them from its reach. + // Anonymous overflow feeds darwin compressor (10.8GB measured at 16GB), + // which mincore hides from touch guard; release converts quiet heads to + // droppable file pages, removing them from its reach. static constexpr bool head_release = true; #else static constexpr bool head_release = false; @@ -356,11 +355,11 @@ class mmap template bool finalize_() NOEXCEPT; - // Head working-set steering for the native (file-backed) mapping. The - // cache manager trims without knowing that head residency is the store's - // priority, and every head miss is a serial fault on the probe path, so - // the scan asserts residency (a read sets the access bit). Body placement - // is left to the cache manager, within the body memory bounds. + // Head working-set steering for native (file-backed) mapping. + // Cache manager trims without knowing head residency is store's + // priority, and every head miss is serial fault on probe path, + // so scan asserts residency (read sets access bit). Body + // placement left to cache manager, within body memory bounds. void scan_run_() NOEXCEPT; void reclaim_run_() NOEXCEPT; #endif @@ -416,8 +415,8 @@ class mmap void remark_(size_t offset, size_t size) NOEXCEPT; void head_run_() NOEXCEPT; - // head page release, synchronized with writers by the prepare/release - // bit protocol (see release_pages_). + // head page release, synchronized with writers + // by prepare/release bit protocol (see release_pages_). bool release_pages_() NOEXCEPT; void restore_(size_t offset, size_t size) NOEXCEPT; void declare_released_() NOEXCEPT; @@ -475,24 +474,20 @@ class mmap mutable std::mutex worker_mutex_{}; #if defined(MANAGE_STAGING) - // Page-dirty bitmap for unstaged (rewrite-in-place head) instances. - // Marks follow content writes; transfer clears before reading, so a - // racing mark is never lost (a torn disk page is unreachable state, as - // live heads are trusted only following a clean close). + // Page-dirty bitmap for unstaged (rewrite-in-place head) instances. Marks + // follow content writes; transfer clears before reading, so racing mark is + // never lost (torn disk page is unreachable state, as live heads are + // trusted only following clean close). using dirty_bitmaps = std::atomic[]; static constexpr size_t extents = 4096; - // Extent state packs a recycling generation with the outstanding count, - // so a lock-free claim (cas decrement) cannot land across a recycle: the - // generation changes before a slot is reused, failing the cas. This - // replaces the post-decrement start-recheck repair, which misfired when - // the decrement itself zeroed the extent and the slot recycled before - // the recheck (the repair then permanently inflated the successor, - // freezing the frontier). The count is atomic because the lock-free - // range search reads it against a concurrent recycle. The generation - // wraps at 16 bits; a stale claimer would need 65536 same-slot recycles - // (each a full ring lap) within one preempted claim to alias. + // Extent state packs recycling generation with outstanding count, so + // lock-free claim (cas decrement) cannot land across recycle: generation + // changes before slot is reused, failing cas. Count is atomic because + // lock-free range search reads it against concurrent recycle. Generation + // wraps at 16 bits; stale claimer would need 65536 same-slot recycles (each + // a full ring lap) within one preempted claim to alias. static constexpr size_t generation_shift = 48; static constexpr uint64_t generation_mask = sub1(system::power2(16u)); @@ -546,9 +541,9 @@ class mmap // Set across a settle transition (head writers back off, uncounted). std::atomic_bool transition_{}; - // Writers between prepare and mark (unaged, unlike intent bits), so a - // release pass cannot settle under a preempted in-flight write. Sharded - // by thread on separate lines: the write path touches one, drains sum. + // Writers between prepare and mark (unaged, unlike intent bits), so release + // pass cannot settle under preempted in-flight write. Sharded by thread on + // separate lines: write path touches one, drains sum. struct alignas(64) writer_shard { std::atomic count{}; }; static constexpr size_t writer_shards = 16; std::array writers_{}; @@ -560,8 +555,8 @@ class mmap mutable std::array restore_stripe_{}; // Serializes transfer passes (worker tick against flush), as concurrent - // passes split the claimed dirty set, allowing a flush to complete while - // claimed pages remain unwritten (a stale snapshot copy). + // passes split claimed dirty set, allowing flush to complete while claimed + // pages remain unwritten (stale snapshot copy). mutable std::mutex transfer_mutex_{}; // This is protected by extent_mutex_. diff --git a/include/bitcoin/database/memory/mmaps.hpp b/include/bitcoin/database/memory/mmaps.hpp index 9ad11aad3..afe147851 100644 --- a/include/bitcoin/database/memory/mmaps.hpp +++ b/include/bitcoin/database/memory/mmaps.hpp @@ -27,8 +27,8 @@ namespace libbitcoin { namespace database { /// SoA aggregate body or head: one substitutable multi-column map (Storage) -/// over N column files, one shared allocation guard. Storage is the map -/// family. A shared (unstaged) aggregate maps its files, as a head. +/// over N column files, one shared allocation guard. Storage is map family. +/// Shared (unstaged) aggregate maps its files, as head. template