Skip to main content

blake3_servil/
lib.rs

1//! `blake3-servil` is a fast [BLAKE3] implementation for 64-bit Arm and
2//! x86-64. It produces the same digests as official BLAKE3, with a call
3//! for each way programs hash (the table below).
4//!
5//! It is two crates in one: [`blake3_servil_core`], which hashes on the
6//! calling thread (the assembly kernels, each proved against the
7//! specification, and every one-thread call), re-exported here whole; and
8//! this crate's own part, a pool of threads and the multithreaded form of
9//! each call. A program that wants no thread started depends on the core
10//! alone.
11//!
12//! # Examples
13//!
14//! ```
15//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
16//! // Once per process, before any other call (see Startup self-test).
17//! blake3_servil::initialize();
18//!
19//! // Hash an input all at once.
20//! let hash1 = blake3_servil::convenience::hash(b"foobarbaz");
21//!
22//! // Hash an input incrementally.
23//! let mut hasher = blake3_servil::convenience::Hasher::new(blake3_servil::Mode::Plain, None);
24//! hasher.update(b"foo");
25//! hasher.update(b"bar");
26//! hasher.update(b"baz");
27//! // finalize leaves the Hasher as it is: more updates may follow it.
28//! let hash2 = hasher.finalize();
29//! assert_eq!(hash1, hash2);
30//!
31//! // Extended output. OutputReader also implements Read and Seek.
32//! let mut output = [0; 1000];
33//! let mut hasher = blake3_servil::convenience::Hasher::new(blake3_servil::Mode::Plain, None);
34//! hasher.update(b"foobarbaz");
35//! let mut output_reader = hasher.finalize_xof();
36//! output_reader.fill(&mut output);
37//! assert_eq!(hash1, output[..32]);
38//!
39//! // Print a hash as hex.
40//! println!("{}", hash1);
41//!
42//! // Many short messages in one call: a Batch lays them out in Blocks.
43//! use blake3_servil::{throughput::{self, Batch}, Mode};
44//! let mut batch = Batch::new(64, 3);
45//! for i in 0..3 {
46//!     batch.set(i, &[i as u8; 64]);
47//! }
48//! let mut hashes = [[0u8; 32]; 3];
49//! throughput::hash_many(Mode::Plain, &batch, &mut hashes);
50//! assert_eq!(hashes[2], *blake3_servil::convenience::hash(&[2u8; 64]).as_bytes());
51//! # Ok(())
52//! # }
53//! ```
54//!
55//! # Two kinds of call
56//!
57//! - **[`convenience`]**: one call per hash, every feature of BLAKE3 (the
58//!   plain hash, the keyed hash, key derivation, extended output), any
59//!   slice, the result returned, and the [`Hasher`]
60//!   for a message fed in pieces. Tuned for a hash now and then, amid
61//!   other work: where it helps, a call fetches its code back into the
62//!   caches before it starts.
63//! - **[`throughput`]**, for power users: every way this crate makes
64//!   hashing fast (other cores, batches, collections), tuned for
65//!   call after call: an occasional call amid other work may run slower
66//!   than a convenience call would. The
67//!   program takes on more of the work: inputs come as
68//!   [`Block`](throughput::Block)s (64 bytes on a 64-byte boundary, so
69//!   alignment is the type's), digests go into the program's places, and
70//!   every call takes a [`Mode`].
71//!
72//! The [`Hasher`] runs on the calling thread; its
73//! first update is treated as a call now and then (its code fetched first
74//! where that helps), and its later updates as call after call. The
75//! throughput calls that take it, [`throughput::update_multithreaded`]
76//! and [`throughput::update_each`], are tuned as throughput calls.
77//!
78//! Start with the convenience calls; when a program needs more speed, it
79//! moves to the throughput ones.
80//!
81//! | Your data | Call |
82//! |---|---|
83//! | One message in memory (now and then) | [`convenience::hash`], or for large inputs across cores [`throughput::hash_multithreaded`] |
84//! | One message in memory, repeated call after call | [`throughput::hash_multithreaded`] (on aligned [`Block`](throughput::Block)s), or on one thread [`throughput::TreeHasher::hash`] directly on caller-owned `&[u8]` slices without copying into aligned blocks (use [`throughput::update_multithreaded`] for large unaligned slices across cores) |
85//! | One message arriving in pieces | [`convenience::Hasher`], or for speed [`throughput::update_multithreaded`] |
86//! | Many messages of one length, in one buffer | [`throughput::hash_many_multithreaded`] over a [`throughput::Batch`] |
87//! | Many 16-, 32-, or 48-byte messages (a Merkle layer's leaves or digests) | [`throughput::hash_many_multithreaded`] over [`throughput::Packed`] / `&[[u8; N]]` (compact storage; avoids refill copies in chains; full groups loaded directly on AVX2, AVX-512, NEON, and SME2; short tails and SSE4.1 expand on the stack) or an owned [`throughput::Batch::new`] (note [`Batch::from_blocks`](throughput::Batch::from_blocks) requires whole-block lengths) |
88//! | Many messages of different lengths, in memory | [`throughput::hash_each_multithreaded`] |
89//! | Many messages arriving at once (a server's uploads) | [`throughput::Pipeline`] (`owned` for zero-copy caller-owned buffers such as `Vec<u8>` or `bytes::Bytes`, `room`/`commit` for streaming); on one thread, or holding each message's running state, [`throughput::update_each`] |
90//! | Continuous stream of messages or batches (single or mixed [`Mode`]s) | [`throughput::Pipeline`] (`message` for the pipeline's default mode, `message_with` for a per-message [`Mode`]) |
91//!
92//! Each call returns once its hash is done, and uses other CPU cores
93//! where that is faster (the forms without `multithreaded` stay on the
94//! calling thread). As a current heuristic (not a frozen contract),
95//! [`throughput::hash_multithreaded`] and
96//! [`throughput::hash_many_multithreaded`] stay on the calling thread
97//! below 512 KiB of compression-block bytes — raw input length for single
98//! messages, and `count × max(64, round_up(message_len, 64))` for both
99//! [`throughput::Batch`] and [`throughput::Packed<N>`] (so 8,192 messages
100//! of 16, 32, or 64 bytes all equal 8,192 compressions and qualify) —
101//! and at or above 512 KiB are eligible to use available worker threads
102//! (batches also require at least two messages).
103//!
104//! Short messages hash fastest together: 1024 messages of 64 bytes in one
105//! [`throughput::hash_many`] call take about a fifth of the time of 1024
106//! [`convenience::hash`] calls.
107//!
108//! Select **keyed hashing or key derivation** with [`Mode`], supplied to
109//! throughput calls and the [`Hasher`] constructor. See [Key-dependent
110//! timing](#key-dependent-timing) for the key-independence contract.
111//!
112//! **Hashing now and then** (rather than nonstop) is slower per byte on
113//! every hash function, since its code and data must come back into the
114//! CPU's caches and a resting core runs slower at first: hashing 64 KiB
115//! after a pause takes about three times as long as nonstop on an Apple M4
116//! Max.
117//!
118//! **Apple M4 and later** have one matrix unit that this crate uses for
119//! inputs of 16 KiB and more; when several threads of a program hash such
120//! inputs at the same moment, one runs at full speed and the others at
121//! about two thirds of it. The multithreaded calls share the work among
122//! the cores themselves, so a program gets the most from one thread making
123//! them.
124//!
125//! # Key-dependent timing
126//!
127//! Hashing code treats secret key bytes, including derived keys, as data:
128//! they select neither branches, memory-access addresses, nor kernels.
129//! For a fixed public call shape, grouped calls do the same work whether
130//! their hashers' keys are equal or different. Key equality selects neither
131//! groups nor temporary storage sizes.
132//!
133//! Public call shape includes the mode kind (plain, keyed, or key derivation),
134//! message and output lengths, input layout, update boundaries, hasher indices,
135//! and size hints. Dispatch may also depend on CPU features and available
136//! processing resources. A batch supplied with one [`Mode`] shares a key by
137//! construction. Plain mode's fixed key is public.
138//!
139//! This is a software-level key-independence contract. Elapsed time varies
140//! with public call shape, scheduling, clock speed, and machine load. Caller
141//! callbacks and I/O have their own timing properties. Applications choose
142//! which lengths, modes, and operation patterns they expose to observers.
143//!
144//! # Memory
145//!
146//! - **A [`Hasher`] is 26 KiB**; box it where that matters.
147//! - **These single-threaded calls allocate nothing** (except on 512-bit SME2
148//!   CPUs, where the first flat-walk tree of 32 KiB or more on each thread
149//!   lazily allocates one reusable 64 KiB thread-local scratch block; during
150//!   thread-local teardown after that block is destroyed, it falls back to
151//!   stack scratch): [`convenience::hash`], [`throughput::hash`],
152//!   [`throughput::hash_many`], [`Hasher::update`](convenience::Hasher::update)
153//!   and [`Hasher::finalize`](convenience::Hasher::finalize), and
154//!   [`OutputReader`].
155//!   [`Hasher::update_reader`](convenience::Hasher::update_reader) uses a 64 KiB
156//!   stack buffer for the first read (even on immediate EOF), and promotes to a
157//!   1 MiB heap buffer once 65,536 bytes or more are read before EOF, freed when
158//!   it returns. [`throughput::hash_each`] keeps reusable per-thread `Vec`
159//!   storage for messages of 2 to 15 chunks (16 bytes per message and 32 bytes
160//!   per chunk of payload, plus `Vec` capacity): its first such collection and
161//!   a larger one grow that storage, and a repeated collection on a live
162//!   thread allocates nothing; during thread-local teardown after that storage
163//!   is destroyed, multi-chunk collections fall back to call-local `Vec`s.
164//! - **Grouped incremental calls** use bounded stack tables and tree buffers.
165//!   [`throughput::update_each`] allocates and frees nothing beyond the
166//!   one-time per-thread SME2 flat-walk scratch noted above if a fresh thread
167//!   hashes a whole 32 KiB+ piece on a 512-bit SME2 CPU.
168//! - **[`throughput::Pipeline`]** allocates its [`Limits`](throughput::Limits) rooms and message slots at construction, allocates nothing during steady-state message submission, hashing, and reaping on the calling thread or the workers, and frees its per-pipeline storage once the `Pipeline` and any surviving [`Room`](throughput::Room)s drop (returning only its worker-facing action ring, waker slot, and monotonic completion lines to the process free list).
169//! - **[`throughput::hash_multithreaded`]** allocates nothing below 512 KiB,
170//!   where it hashes on the calling thread. Above that length it keeps a list
171//!   of the pieces it hands out, 56 bytes for each piece (most are of up
172//!   to 128 KiB).
173//!   The list is the calling thread's and stays with it:
174//!   [`initialize_multithreaded`] makes 56 KiB of it ready on its own
175//!   thread (1,024 pieces), a call that needs more pieces grows it, and
176//!   the thread keeps it at that size (after 1 GiB on 16 CPUs without
177//!   SME2, 578 KiB).
178//!   A call that needs no more pieces than an earlier one on that thread
179//!   allocates nothing. The pieces follow the cut and not the length
180//!   alone: 1 GiB less one byte is cut into more pieces than 1 GiB.
181//! - **Once per process**: the core startup self-test (stack buffers only; see
182//!   `blake3-servil-core`'s memory section for the post-init per-thread 64 KiB
183//!   SME2 flat-walk scratch, which [`initialize_multithreaded`] also allocates
184//!   on the calling thread — even with `Some(1)` — and on the dedicated SME2
185//!   worker thread on a 512-bit SME2 CPU), and the pool threads started by
186//!   [`initialize_multithreaded`]: `threads - 1` ordinary workers (plus one
187//!   dedicated SME2 thread when `threads > 1` on a 512-bit SME2 CPU), where
188//!   `None` picks the [`std::thread::available_parallelism`] estimate capped by
189//!   permitted CPUs on the chosen node or process (see
190//!   [`initialize_multithreaded`] for the exact count and sandbox caveats),
191//!   each with the standard library's stack.
192//! - **Nothing is wiped**: this crate does not clear what it held from
193//!   memory, and offers no call that does. A key, the message bytes a
194//!   [`Hasher`] or a Pipeline holds and the chaining values made from
195//!   them stay in the value, in the copies the kernels leave on the
196//!   stacks, and in the pool's and the Pipelines' storage, until
197//!   something else overwrites them. Official BLAKE3 offers `Zeroize` for
198//!   its types.
199//!
200//! # Panics
201//!
202//! A broken precondition of a call panics on the calling thread, and
203//! unwinds as usual. This crate itself ends the whole process in the
204//! cases below, with a line on standard error where that takes one; a
205//! program cannot catch them. (Rust's own rules end a process too: a
206//! panic while another unwinds, as in an owner's destructor.)
207//!
208//! - Two breaches, since worker threads may be reading memory that the
209//!   unwinding would free: a [`Pipeline`](throughput::Pipeline) dropped
210//!   while its messages are still being hashed, and a
211//!   [`Lent`](throughput::Lent) guard dropped while its message's hashing
212//!   has not finished. A server keeps both from happening when a client
213//!   goes away: see "Giving up a message" on the Pipeline. In a child
214//!   forked while such work was in flight, either drop ends the child
215//!   ([`initialize_multithreaded`]).
216//! - A worker thread that the system refuses to start, and a panic on a
217//!   worker thread, which speaks through the panic hook first
218//!   ([`initialize_multithreaded`] tells both).
219//! - A [`Waker`](core::task::Waker) of the program's that panics when it
220//!   is woken, on whichever thread (the Pipeline's "Panics").
221//! - A startup self-test that fails, and an x86-64 CPU without SSE4.1
222//!   ([`initialize`]).
223//! - A panic out of this crate's own hashing on a calling thread while
224//!   workers hold that call's job: a fault of the crate's, which no
225//!   input is known to cause.
226//!
227//! # Startup self-test
228//!
229//! **Every program calls [`initialize`] (or [`initialize_multithreaded`])
230//! once before hashing**: any call that loads the detected platform before
231//! initialization completes panics, in every build, saying so (pure
232//! constructors such as `TreeHasher::new(Mode::Plain)` and `const` coordinate
233//! helpers do not load the platform). **A program that makes multithreaded
234//! calls calls [`initialize_multithreaded`]**: a multithreaded call
235//! before it panics (one load per call).
236//!
237//! `initialize` runs a minimal "outside-the-box" self-test before the process
238//! first hashes, well under a millisecond: one unified six-case chained pass
239//! (~5.5 KiB total input, shared across x86-64 and AArch64) exercises the
240//! scalar ALU, `.rodata` IV, active SIMD vector unit (NEON+SHA-3 / SSE4.1 /
241//! AVX2 / AVX-512), and on SME2 hosts the 512-bit streaming matrix unit plus
242//! live `rdsvl` check, comparing each folded result with reference values from
243//! official BLAKE3 1.8.7 (and checking compiled x86-64 `LZCNT`/`BMI1` features
244//! on the host CPU). Individual unrolled static assembly variants are proved by
245//! Z3 and verified by unit tests rather than exercised on every process start.
246//! A mismatch stops the process, which no caller can catch: it attempts a best-effort diagnostic
247//! directly to file descriptor 2 (bypassing Rust's stderr lock, arming a
248//! best-effort `alarm(1)` watchdog around `poll(0)` and `write`, skipping
249//! already-full or already-closed pipes, and disarming `alarm(0)` before
250//! aborting — taking over and clearing any pre-existing process real-time alarm
251//! even when the write to fd 2 is skipped) and calls `std::process::abort` when
252//! control returns. Other threads that call
253//! `initialize` meanwhile wait for it (parked via `std::sync::Once`).
254//!
255//! # Build requirements
256//!
257//! Both `blake3-servil` and `blake3-servil-core` require the standard library
258//! (neither defines a `std` Cargo feature or `no_std` mode; callers upgrading
259//! from `0.11.0` should drop `features = ["std"]`, and `default-features =
260//! false` does not opt out of `std`).
261//!
262//! All kernels are assembled directly by `rustc` via
263//! `core::arch::global_asm!` (no external C compiler or `cc` build dependency
264//! is required for the Rust libraries). This crate runs its assembly or not at
265//! all: for `no_std`, portable Rust, or other targets, use official BLAKE3.
266//!
267//! [BLAKE3]: https://blake3.io
268
269#![allow(clippy::too_many_arguments)]
270
271pub use blake3_servil_core::{
272    BLOCK_LEN, BUILD_VERSION, CHUNK_LEN, ContextKey, Hash, HexError, HexHash, KEY_LEN, Mode, OUT_LEN, OutputReader, convenience, initialize,
273};
274
275pub(crate) use blake3_servil_core::convenience::Hasher;
276pub(crate) use blake3_servil_core::thread_support::{Sme2Turn, assert_slots, has_sme2, prepare_collection_thread};
277#[cfg(test)]
278pub(crate) fn slot_len(len: usize) -> usize {
279    len.checked_next_multiple_of(BLOCK_LEN).expect("batch slot length overflow").max(BLOCK_LEN)
280}
281#[allow(unused_imports)]
282pub(crate) mod block {
283    pub use blake3_servil_core::throughput::{Batch, Block};
284}
285
286/// The primitives src/action_ring.rs runs on: the standard library's here, and
287/// Shuttle's in tests/shuttle_source_ring.rs, which compiles that file beside
288/// its own `action_ring_sync`.
289mod action_ring_sync {
290    pub use core::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, AtomicUsize, Ordering};
291}
292mod action_ring;
293/// The primitives src/finish.rs runs on: the standard library's here, and
294/// Shuttle's in tests/shuttle_finish.rs, which compiles that file beside its own
295/// `finish_sync`.
296mod finish_sync {
297    pub use std::sync::Mutex;
298    pub use std::sync::atomic::{AtomicUsize, Ordering};
299    pub use std::thread;
300}
301mod finish;
302/// The primitives src/park.rs runs on: the standard library's here, and
303/// Shuttle's in tests/shuttle_park.rs, which compiles that file beside its
304/// own `park_sync`.
305mod park_sync {
306    pub use std::sync::OnceLock;
307    pub use std::sync::atomic::{AtomicU64, Ordering, fence};
308    pub use std::thread;
309}
310mod waker_sync {
311    pub use core::cell::UnsafeCell;
312    pub use std::sync::atomic::{AtomicUsize, Ordering, fence};
313    #[inline(always)]
314    pub fn spin() {
315        core::hint::spin_loop();
316    }
317    #[inline(always)]
318    pub unsafe fn with_mut<T, R>(cell: &UnsafeCell<T>, f: impl FnOnce(&mut T) -> R) -> R {
319        // Sound: caller's safety contract guarantees exclusive access to `cell`.
320        f(unsafe { &mut *cell.get() })
321    }
322}
323/// The primitives src/pipeline.rs runs on: the standard library's here,
324/// and Shuttle's in tests/shuttle_pipeline.rs, which compiles that file
325/// beside its own `pipeline_sync`.
326mod pipeline_sync {
327    pub use core::cell::UnsafeCell;
328    pub use std::sync::Mutex;
329    pub use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
330    pub use std::thread;
331    pub use std::thread_local;
332    /// A static for the life of the process. (The model's is for one run.)
333    macro_rules! process_static {
334        ($(#[$attribute:meta])* static $name:ident: $kind:ty = $first:expr;) => {
335            $(#[$attribute])*
336            static $name: $kind = $first;
337        };
338    }
339    pub(crate) use process_static;
340    macro_rules! register_storage {
341        ($st:expr) => {};
342    }
343    pub(crate) use register_storage;
344    macro_rules! retire_storage {
345        ($st:expr) => {{
346            // Sound: caller released the final holder reference; free cleanly.
347            unsafe { drop(Box::from_raw($st)) };
348        }};
349    }
350    pub(crate) use retire_storage;
351
352    #[repr(transparent)]
353    pub(crate) struct SlotRef<T: 'static>(&'static T);
354    impl<T: 'static> SlotRef<T> {
355        #[inline(always)]
356        pub(crate) fn new(r: &'static T) -> Self {
357            Self(r)
358        }
359        #[inline(always)]
360        pub(crate) fn get(&self) -> &'static T {
361            self.0
362        }
363        #[inline(always)]
364        pub(crate) fn poison(&self) {}
365    }
366}
367mod lanes;
368mod park;
369mod pipeline;
370mod waker;
371
372#[cfg(test)]
373mod forms_test;
374/// The tests' helpers, the core's own file: this crate's tests use the
375/// same messages, fixed values and guard pages.
376#[cfg(test)]
377#[path = "../../src/test_support.rs"]
378#[allow(dead_code)] // Some serve the core's tests alone.
379pub(crate) mod test;
380
381/// A kind of path a call of this crate's ran, for its tests (the core
382/// has its own record).
383#[derive(Clone, Copy)]
384#[allow(dead_code)]
385pub(crate) enum Ran {
386    Pool = 1,
387    EqualMembers = 4,
388    MemberAlone = 8,
389}
390#[cfg(test)]
391std::thread_local! {
392    pub(crate) static RAN: core::cell::Cell<u32> = const { core::cell::Cell::new(0) };
393}
394#[inline(always)]
395#[allow(dead_code)]
396pub(crate) fn ran(kind: Ran) {
397    #[cfg(test)]
398    RAN.with(|r| r.set(r.get() | kind as u32));
399    let _ = kind;
400}
401
402/// [`initialize`], and start the threads that the multithreaded calls
403/// use: every program that makes such calls calls this once,
404/// before them, in place of `initialize`. It starts `threads - 1` workers,
405/// and each multithreaded call hashes on its calling thread and the
406/// workers (calls made at once share the workers), and on CPUs with SME2
407/// (Apple M4) the SME2 thread too. `None` uses the available logical CPUs,
408/// limited on Linux to the allowed CPUs of one memory node (below). With
409/// 1, calls hash on their calling
410/// thread alone: no workers start, nor the SME2 thread. Otherwise it
411/// starts the first worker and returns; the first worker starts the others
412/// (each 20-30 us on Linux x86-64), and calls run on the workers started
413/// so far. The
414/// threads wait asleep whenever no call has work for them (their memory:
415/// see [Memory](crate#memory)). Later calls return at once, and must ask
416/// for the same number: another `Some` panics. A panic on a worker thread
417/// (a bug in this crate, or a waker of the program's that panics when a
418/// worker wakes it) ends the process, once the process's panic hook has
419/// returned (the standard one prints the panic's message, and waits
420/// where standard error does not take it), rather than leaving the call
421/// that waits for that worker's piece waiting forever. A worker thread
422/// that the system refuses to start ends the process too, for the same
423/// reason, with one line on standard error: a limit on the process's
424/// threads (`RLIMIT_NPROC`, a container's `pids.max`) or a lack of
425/// memory can refuse one. The first worker is started by this call and
426/// the others by the first worker, so the end can come shortly after
427/// this call has returned, and the program cannot catch it: one that
428/// runs under such a limit passes a count of threads that fits.
429///
430/// `None` counts logical CPUs, so on a CPU with SMT (Hyper-Threading) both
431/// threads of each core, and that is the faster default. On an EPYC 9255,
432/// the 16-input kernels leave much of a core waiting on its loads, and a
433/// core's second thread fills that time: two threads hash 1.4-1.7 times
434/// what one does, as with official BLAKE3. The 32-input AVX-512 kernel
435/// (Linux) keeps a core busier on its own, so a second thread adds less
436/// (1.1-1.3 times); even so, on 1 GiB 24 threads, one a core, took 4-14%
437/// longer than 48. A thread slowed by the other thread on its core, by an
438/// efficiency core or by another program takes fewer of a call's pieces,
439/// and the pieces shrink toward the end of the input, so the slowest thread
440/// finishes holding a small one. To leave CPUs to other work, pass fewer
441/// threads. The count is also the one setting for energy against speed:
442/// every thread started may be woken by a call, and while a `Pipeline` is
443/// open one that finds no work looks for 5 us before it sleeps.
444///
445/// On Linux where the node topology is available and the system allows
446/// it, workers stay on one memory node: the node of the initializing
447/// thread's CPU or, where another node holds at least twice as many of
448/// the CPUs that thread is allowed, the node that holds the most of
449/// them. (The CPUs a
450/// process is allowed need not lie evenly over the nodes, and its first
451/// thread may start on a node that has one of them.)
452/// On a machine with more than one last-level cache, each worker is kept
453/// to a cache within that node.
454/// A call wakes workers under its own cache first where it has any there.
455/// Calling threads keep their own affinity and their buffer placement,
456/// the initializing thread too: it may run on another node than the
457/// workers.
458/// To do this, on a Linux machine with more than one memory node, the
459/// call reads the nodes' CPUs from `/sys/devices/system`, and the first
460/// worker binds itself to the chosen node's with `sched_setaffinity`
461/// before it starts the others, which inherit them (the SME2 thread
462/// binds itself too).
463/// All of this is for speed, and no call's result rests on it: what the
464/// system does not tell or allow is left undone, each part by itself,
465/// and the calls work as anywhere. Where the system shows no list of
466/// memory nodes, or keeps from the process that list, the node of the
467/// initializing CPU, that node's CPUs or the thread's own (a sandbox
468/// may), or shows parts that do not agree (a node that is not online,
469/// or does not hold its CPU), no node is chosen, and the workers start
470/// with the initializing thread's CPUs. Another node is taken in place
471/// of the initializing CPU's only where what the system shows of that
472/// node agrees in the same way. Where it refuses a thread's
473/// binding, to the node or later to a cache, that thread keeps the CPUs
474/// it has. (A pool of one thread asked for by number,
475/// `NonZeroUsize::new(1)`, has no workers: it reads no topology and
476/// binds nothing.)
477/// For each kind and size of call under 256 MiB, a caller with local
478/// workers learns whether they or all the workers finish sooner.
479///
480/// The count `None` takes is the standard library's estimate
481/// ([`std::thread::available_parallelism`], or 1 where it gives none)
482/// capped by the thread's allowed CPUs (reading `/proc/thread-self/status`
483/// on Linux when `sched_getaffinity` is refused) and, where a node is
484/// chosen, by the node's allowed CPUs. It is taken before any thread is
485/// bound, and a binding refused afterwards does not change it. Where the
486/// system hides both `sched_getaffinity` and `/proc/thread-self/status`,
487/// the estimate can still be as many as the machine has online: a program
488/// kept to fewer CPUs there does better to pass its number. A request for
489/// `n` threads starts `n - 1` workers whether or not the node, or the
490/// process, has `n` CPUs.
491///
492/// Several programs each with a full pool share the machine without
493/// trouble, and unevenly. On an i7-12700K (20 CPUs), N programs each
494/// streaming 64 KiB messages hashed 26 GB/s alone, 37-41 together at 2
495/// to 10, and 21-28 at 20 to 80 (400 to 1600 threads): the machine's
496/// total holds, and oversubscription costs it 31% at one program a core
497/// and 48% at four. What each program gets is the OS's choice among
498/// equal threads: at 20 programs the luckiest got 2.6 times the
499/// unluckiest, at 80, 8 times (bench-hashes #116, November 2026). A
500/// program that needs a predictable share beside others sizes its pool
501/// to its share of the machine.
502///
503/// The threads are this process's: fork before starting threads, or `exec` in
504/// the child and initialize in the new process (POSIX restricts a pre-`exec`
505/// child of a multithreaded process to async-signal-safe calls; this library's
506/// fork guard does not make Rust allocation, TLS, or unwinding async-signal-safe).
507/// As a diagnostic in a child forked after the pool started, every multithreaded
508/// call and every new [`Pipeline`](throughput::Pipeline) panics, saying so (the
509/// child has no pool workers). A Pipeline made before the fork is not to be used
510/// in the child: its calls panic the same way once one needs a worker, including
511/// while waiting for a free group or piece node when work was in flight at the
512/// fork. Nor is it to be dropped there with work in flight at the fork, which
513/// the child never sees finished: that drop, or the drop of a
514/// [`Lent`](throughput::Lent) guard for such work, stops the child (a child
515/// that leaves by `_exit` or `exec` drops neither).
516///
517/// Each thread that makes multithreaded calls keeps a little pool storage for
518/// them (its piece cut, its job record, and — for pooled tree calls — its
519/// chaining-value scratch; the two 1,024-piece vectors take 56 KiB together,
520/// plus the job record), grown on its first pooled call of that kind and on
521/// the first call that outgrows it, and otherwise untouched: a pooled call
522/// whose pieces fit in its thread's existing piece cut (and, for pooled tree
523/// calls including large items in [`hash_each_multithreaded`](throughput::hash_each_multithreaded),
524/// its existing chaining-value scratch) does not grow the pool's scratch.
525/// Batch jobs and the small-item pass of `hash_each_multithreaded` do not grow
526/// the pool's chaining-value vector (note that small-item / single-thread
527/// `hash_each_multithreaded` also uses `blake3-servil-core`'s own per-thread
528/// collection scratch, pre-sized to 144 middle messages / 288 chunk CVs). This
529/// call prepares the calling thread's pool storage for up to 1,024 pieces (and
530/// on a 512-bit SME2 CPU, allocates that thread's 64 KiB SME2 flat-walk
531/// scratch — even when called with `Some(1)` or on later calls from fresh
532/// threads); a call from an unprepared thread prepares its own on first use.
533///
534/// ```
535/// blake3_servil::initialize_multithreaded(None);
536/// let message = vec![blake3_servil::throughput::Block::ZERO; (1 << 20) / 64];
537/// let hash = blake3_servil::throughput::hash_multithreaded(blake3_servil::Mode::Plain, &message, 1 << 20);
538/// assert_eq!(hash, blake3_servil::convenience::hash(&[0u8; 1 << 20]));
539/// ```
540pub fn initialize_multithreaded(threads: Option<core::num::NonZeroUsize>) {
541    static STARTED: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
542    let started = *STARTED.get_or_init(|| {
543        initialize();
544        lanes::initialize(threads)
545    });
546    lanes::prepare_thread();
547    if let Some(threads) = threads {
548        assert_eq!(
549            started,
550            threads.get(),
551            "blake3-servil: the multithreaded calls were started with {started} threads; initialize_multithreaded cannot change that to {threads}"
552        );
553    }
554}
555
556/// Whether every worker of the multithreaded calls' pool is parked (false
557/// before [`initialize_multithreaded`]). Undocumented and unstable, for
558/// tests only: a test that needs the pool idle waits for this, not for a
559/// sleep that a loaded machine could outlast.
560#[doc(hidden)]
561pub fn __all_workers_parked() -> bool {
562    lanes::all_workers_parked()
563}
564
565/// Whether the process-wide `pthread_atfork` child handler has marked this
566/// process as a child forked after the pool started worker threads.
567/// Undocumented and unstable, for the async-signal-safe fork test only: a
568/// forked child reads this atomic flag and calls `_exit` without touching the
569/// allocator or unwinding machinery.
570#[doc(hidden)]
571pub fn __is_forked() -> bool {
572    lanes::is_forked()
573}
574
575/// The throughput API: the core's, and the calls that use other cores.
576pub mod throughput {
577    pub use crate::pipeline::{Event, Lent, Limits, Message, Pipeline, ROOM_LEN, Room, block_on};
578    use crate::{Hash, Hasher, Mode, OUT_LEN};
579    pub use blake3_servil_core::throughput::*;
580
581    /// [`Hasher::update`](crate::convenience::Hasher::update), eligible to use
582    /// other CPU cores above the split threshold (512 KiB per eligible aligned
583    /// subtree, an implementation heuristic): always the same digest as
584    /// single-threaded `update`. Shorter updates hash on the calling thread.
585    /// One `Hasher` may take both calls. The program calls
586    /// [`initialize_multithreaded`](crate::initialize_multithreaded) first.
587    ///
588    /// # Panics
589    ///
590    /// Panics if [`initialize_multithreaded`](crate::initialize_multithreaded)
591    /// has not been called, if the pool was invalidated by `fork()`, if the
592    /// cumulative input length exceeds `2^64 - 1` bytes, or if `hasher` was
593    /// poisoned by a prior unwinding [`Hasher::update_with`] call
594    /// ([after a panic](crate::convenience::Hasher#after-a-panic)).
595    ///
596    /// ```
597    /// # blake3_servil::initialize_multithreaded(None);
598    /// use blake3_servil::{Mode, convenience::Hasher, throughput};
599    /// let input = vec![7u8; 3 << 20];
600    /// let mut hasher = Hasher::new(Mode::Plain, Some(input.len() as u64));
601    /// for piece in input.chunks(64 * 1024) {
602    ///     throughput::update_multithreaded(&mut hasher, piece);
603    /// }
604    /// assert_eq!(hasher.finalize(), blake3_servil::convenience::hash(&input));
605    /// ```
606    pub fn update_multithreaded<'h>(hasher: &'h mut Hasher, input: &[u8]) -> &'h mut Hasher {
607        crate::lanes::require();
608        hasher.update_with(input, crate::lanes::MIN_SPLIT_LEN, &crate::lanes::subtree_halves)
609    }
610
611    /// [`hash_many`], eligible to use other CPU cores above the split
612    /// threshold: always the same digests as single-threaded `hash_many`.
613    ///
614    /// ```
615    /// # blake3_servil::initialize_multithreaded(None);
616    /// use blake3_servil::Mode;
617    /// let mut leaves = blake3_servil::throughput::Batch::new(256, 4096);
618    /// (0..4096).for_each(|i| leaves.set(i, &[7u8; 256]));
619    /// let mut hashes = vec![[0u8; 32]; 4096];
620    /// blake3_servil::throughput::hash_many_multithreaded(Mode::Plain, &leaves, &mut hashes);
621    /// assert!(hashes.iter().all(|h| h == blake3_servil::convenience::hash(&[7u8; 256]).as_bytes()));
622    /// ```
623    ///
624    /// **Speed**: below 512 KiB of compression-block bytes (`count × max(64,
625    /// round_up(message_len, 64))` for both [`Batch`] and [`Packed<N>`], so
626    /// 4,096 × 36 B stays serial while 8,192 × 16 B, 32 B, 36 B, or 64 B all
627    /// qualify; an implementation heuristic, not a frozen contract), or with
628    /// fewer than two messages, it runs on the calling thread at
629    /// [`hash_many`]'s speed. Larger batches are eligible to use available
630    /// worker threads (on an Apple M4 Max, 64-byte messages from about 10
631    /// down to 3 ns each). It shares the cores with other callers as
632    /// [`hash_multithreaded`] does.
633    // Inlined, so a constant mode folds to its constants (as
634    // convenience::hash is: no mode stored for the call to read).
635    #[inline(always)]
636    pub fn hash_many_multithreaded<P: Prepared + ?Sized>(mode: Mode, batch: &P, out: &mut [[u8; OUT_LEN]]) {
637        crate::lanes::require();
638        // The short path first and inline, so a small batch costs what
639        // hash_many costs (which checks its length against the digests);
640        // everything the pool needs is behind the call after. The admission
641        // gate counts at least one 64-byte compression per message so
642        // Packed<16>/Packed<32> enter the pool at 8,192 messages like Batch;
643        // once admitted, hash_many_over_pool keeps its storage-based piece cut.
644        if out.len() < 2 || out.len().saturating_mul(batch.slot().max(crate::BLOCK_LEN)) < crate::lanes::MIN_SPLIT_LEN {
645            return hash_many(mode, batch, out);
646        }
647        // Check the output count against the whole batch before taking
648        // `batch.part(0..out.len())`, which would otherwise silently hash a
649        // prefix when `out` is too short.
650        assert_eq!(Some(batch.bytes().len()), batch.slot().checked_mul(out.len()), "input holds one slot per output");
651        let (kind, key, context) = crate::lanes::parts(mode);
652        crate::lanes::hash_many_in(kind, key, context, batch.part(0..out.len()), out);
653    }
654
655    /// [`hash`], eligible to use other CPU cores above the split threshold:
656    /// always the same [`Hash`](struct@Hash) as single-threaded `hash`. For a
657    /// message whose bytes are not in blocks (a mapped file, say),
658    /// [`update_multithreaded`] into a [`Hasher`] takes any slice, at the same
659    /// speed on the i7-12700K from 512 KiB to 1 GiB (about 1% slower at 1 MiB).
660    ///
661    /// ```
662    /// # blake3_servil::initialize_multithreaded(None);
663    /// use blake3_servil::{Mode, throughput::{self, Block}};
664    /// let message = vec![Block::ZERO; 1 << 14];
665    /// let hash = throughput::hash_multithreaded(Mode::Plain, &message, 1 << 20);
666    /// assert_eq!(hash, blake3_servil::convenience::hash(&[0u8; 1 << 20]));
667    /// ```
668    ///
669    /// **Speed**, on an Apple M4 Max (16 cores): below 512 KiB (an
670    /// implementation heuristic, not a frozen contract) it hashes on the
671    /// calling thread, at [`hash`]'s speed; from 512 KiB it is eligible to
672    /// use available worker threads too: about 14 GB/s at 1 MiB, 21 GB/s
673    /// at 4 MiB, and 26 to 29 GB/s from 16 MiB, 2 to 5 times
674    /// [`hash`](crate::convenience::hash). Idle workers park between calls
675    /// and use no CPU once parked.
676    ///
677    /// **Several callers at once**: calls from several threads of one program
678    /// share the cores in turn, each getting a fair part; a call that finds the
679    /// cores all busy hashes on its own thread, at [`hash`](crate::convenience::hash)'s speed.
680    ///
681    /// **CPUs with performance and efficiency cores** (Intel's since Alder
682    /// Lake): a multithreaded call or stream uses every core, and afterwards
683    /// the OS sometimes leaves the calling thread on an efficiency core for a
684    /// while, where single-threaded hashing runs at about half speed (AVX2's
685    /// 256-bit operations run as two halves there). Measured on an i7-12700K
686    /// under Linux 7.0: beside nonstop multithreaded streams, 7% of 16 KiB
687    /// single-threaded hashes ran partly on an efficiency core, 2.2 times
688    /// slower, about 6% on their average. A program that alternates the two
689    /// and needs its single-threaded speed steady can keep that thread on the
690    /// performance cores (`sched_setaffinity` on Linux).
691    ///
692    /// The program calls [`initialize_multithreaded`](crate::initialize_multithreaded) first; a call before it
693    /// panics.
694    // Inlined, so a constant mode folds to its constants (as
695    // convenience::hash is: no mode stored for the call to read).
696    #[inline]
697    pub fn hash_multithreaded(mode: Mode, input: &[Block], len: usize) -> Hash {
698        crate::lanes::require();
699        // The short path first and inline, so a small input costs what
700        // hash costs; everything the pool needs is behind the call after.
701        if len < crate::lanes::MIN_SPLIT_LEN {
702            return hash(mode, input, len);
703        }
704        let (kind, key, context) = crate::lanes::parts(mode);
705        crate::lanes::hash_in(kind, key, context, &Block::bytes(input)[..len])
706    }
707
708    /// [`hash_each`], using other CPU cores for collections whose small items
709    /// total 512 KiB or more (and for individual items of 512 KiB or more, as
710    /// [`hash_multithreaded`] does), returning the same digests.
711    /// Requires `out.len() == items.len()`.
712    ///
713    /// ```
714    /// # blake3_servil::initialize_multithreaded(None);
715    /// use blake3_servil::{Mode, throughput::{self, Block}};
716    /// let blocks: Vec<Vec<Block>> = (0..100).map(|i| vec![Block([i as u8; 64]); (1000 * i as usize).div_ceil(64)]).collect();
717    /// let items: Vec<(&[Block], usize)> = blocks.iter().enumerate().map(|(i, b)| (&b[..], 1000 * i)).collect();
718    /// let (mut a, mut b) = (vec![[0u8; 32]; 100], vec![[0u8; 32]; 100]);
719    /// throughput::hash_each_multithreaded(Mode::Plain, &items, &mut a);
720    /// throughput::hash_each(Mode::Plain, &items, &mut b);
721    /// assert_eq!(a, b);
722    /// ```
723    pub fn hash_each_multithreaded(mode: Mode, items: &[(&[Block], usize)], out: &mut [[u8; OUT_LEN]]) {
724        crate::lanes::require();
725        assert_eq!(items.len(), out.len(), "one digest per item");
726        let tree = TreeHasher::new(mode);
727        let alone = |len: usize| len >= crate::lanes::MIN_SPLIT_LEN;
728        // The items that hash alone are set aside in the collection's
729        // call and hashed after, each over the whole pool. Validate every
730        // item's slice bound upfront and compute the exact small-item byte
731        // total once in u128 so `lanes::hash_each` / `cut_items` never
732        // re-traverse the collection just to sum weights.
733        let small_bytes: u128 = items
734            .iter()
735            .map(|i| {
736                let n = Block::bytes(i.0)[..i.1].len();
737                if alone(n) { 0 } else { n as u128 }
738            })
739            .sum();
740        if small_bytes < crate::lanes::MIN_SPLIT_LEN as u128 {
741            crate::lanes::hash_each_small(&tree, items, out);
742        } else {
743            crate::lanes::hash_each(&tree, items, small_bytes, out);
744        }
745        for (item, out) in items.iter().zip(out.iter_mut()) {
746            if alone(item.1) {
747                *out = *crate::lanes::hash_over_pool(&tree, &Block::bytes(item.0)[..item.1]).as_bytes();
748            }
749        }
750    }
751}