store-io-engine 0.5.1

The store-io engine: volumes, regions, barriers with flush sharing, receipts, provisioning and A/B slot objects over any store-io platform.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Provisioning regions: placement, fill, flush, verification, header and
//! the region-table flip that commits it.

use std::sync::{Arc, Mutex, PoisonError};

use store_io_core::error::{
    Error, ErrorContext, FirstCause, Named, NotWrittenCause, Op, ReserveTag,
};
use store_io_core::id::{Generation, RegionId};
use store_io_format::fill::fill_keyed_v1;
use store_io_format::meta::{
    FillPattern, REGION_META_LEN, RegionKind, RegionMeta, RegionName, RegionState, TableEntry,
    encode_table,
};
use store_io_platform::{IoOp, Platform};

use crate::exec::{Ran, run};
use crate::frontier::AppendFrontier;
use crate::gate::Gate;
use crate::slots::{PairRead, plan_next};
use crate::space::{Reservation, lock_acct, no_space};
use crate::store::*;

/// What a fill writes past its zeros: `content(index, dst)` fills `dst`
/// with the bytes of region offsets `index..` (the pattern, or a copy's
/// source bytes, D-137).
pub(crate) type Content<'a> = dyn FnMut(u64, &mut [u8]) -> Result<(), Error> + 'a;

impl<P: Platform> Store<P>
where
    P::Queue: Send,
{
    /// Provisions a region of `data_size` bytes (rounded up to the block size)
    /// and returns its state, taking the space from `from` when given (else
    /// under tag 0, growing the container past every outstanding
    /// reservation).
    pub(crate) fn provision(
        &self,
        name: &str,
        kind: RegionKind,
        opts: crate::RegionOptions,
        from: Option<&mut Reservation<P>>,
    ) -> Result<Arc<LiveRegion>, Error> {
        let data_size = opts.size_bytes();
        let _timed = self
            .inner
            .observer
            .span(store_io_core::observe::Stage::Provision);
        let inner = &self.inner;
        let tag = from.as_ref().map_or(0, |r| r.tag());
        if inner.read_only {
            return Err(Error::NotWritten {
                cause: NotWrittenCause::ReadOnly,
                ctx: ErrorContext::default(),
            });
        }
        if let Some(first) = inner.domain.poisoned() {
            return Err(Error::Poisoned { first });
        }
        // Before any I/O: options that contradict each other, and a cap
        // format 1 cannot record.
        opts.validate()?;
        if inner.layout.format == store_io_format::slot::FORMAT_2 {
            return self.provision2(name, kind, opts, from, None, None);
        }
        if opts.max_size_bytes().is_some() {
            return Err(Error::Unsupported {
                what: store_io_core::error::Capability::FormatVersion,
            });
        }
        let rname = RegionName::new(name).map_err(|_| Error::NotWritten {
            cause: NotWrittenCause::InvalidName,
            ctx: ErrorContext::default(),
        })?;
        let block = inner.layout.block();
        let data_size =
            store_io_core::align::align_up(data_size, block).ok_or(Error::NotWritten {
                cause: NotWrittenCause::TooLarge,
                ctx: ErrorContext::default(),
            })?;
        if data_size / block >= u64::from(u32::MAX) {
            return Err(Error::NotWritten {
                cause: NotWrittenCause::TooLarge,
                ctx: ErrorContext::default(),
            });
        }
        let mut meta = lock_meta(&inner.meta);
        // Names are unique among the table's ready entries, including any
        // region this open could not load (its header failed to verify):
        // reusing such a name would make the table undecodable.
        if meta
            .entries
            .iter()
            .any(|e| e.state == RegionState::Ready && e.name == rname)
        {
            return Err(Error::AlreadyExists {
                what: Named::Region,
            });
        }
        let extent = inner.layout.extent(data_size).ok_or(Error::NotWritten {
            cause: NotWrittenCause::TooLarge,
            ctx: ErrorContext::default(),
        })?;
        // Space: a reservation must hold the extent; otherwise the tag's cap
        // must allow it.
        {
            let mut acct = lock_acct(&inner.acct);
            match &from {
                Some(r) if extent > r.remaining() => return Err(no_space(tag)),
                None if !acct.fits(tag, extent) => return Err(no_space(tag)),
                _ => {}
            }
        }
        // Placement. A large region's data area is aligned (see
        // `Layout::place`). A reservation pays only for the extent: the
        // alignment gap comes from growing the container past every
        // reservation, and when that growth finds no space the region is
        // placed unaligned instead, which needs no growth at all (the
        // container already holds the reservation), so a reservation's
        // guarantee always holds.
        let too_large = || Error::NotWritten {
            cause: NotWrittenCause::TooLarge,
            ctx: ErrorContext::default(),
        };
        let reserved_after = {
            let acct = lock_acct(&inner.acct);
            match &from {
                Some(_) => acct.reserved().saturating_sub(extent),
                None => acct.reserved(),
            }
        };
        let mut align = true;
        let (offset, reuse) = loop {
            let (offset, reuse, _grow) = inner
                .layout
                .place(&meta.entries, meta.container_len, extent, align)
                .ok_or_else(too_large)?;
            let end = offset.checked_add(extent).ok_or_else(too_large)?;
            // The new table must fit its slot. Released entries stay in the
            // table until their space is reused, so they count; a reused
            // entry is replaced in place. Checked before any I/O.
            if meta.entries.len() + usize::from(reuse.is_none()) > inner.layout.table_capacity() {
                return Err(Error::NoSpace {
                    tag: ReserveTag::Table,
                    ctx: ErrorContext::default(),
                });
            }
            let target = self
                .tail(&meta)
                .max(end)
                .checked_add(reserved_after)
                .ok_or_else(too_large)?;
            match self.grow_to(&mut meta, target, tag) {
                Ok(()) => break (offset, reuse),
                Err(Error::NoSpace { .. }) if align && from.is_some() => align = false,
                Err(e) => return Err(e),
            }
        };
        let id = meta.next_region_id;
        let next_id = id.checked_add(1).ok_or(Error::NoSpace {
            tag: ReserveTag::Table,
            ctx: ErrorContext::default(),
        })?;
        let fill = if inner.opts.keyed_fill {
            FillPattern::KeyedV1
        } else {
            FillPattern::Zeros
        };
        let fill_key = if fill == FillPattern::KeyedV1 {
            random_uuid()
        } else {
            [0; 16]
        };
        // 1. Fill the header blocks and the data area with direct writes,
        //    blanking any old header pair at this location.
        self.fill(offset, extent, block, fill, &fill_key)?;
        // 2. Make the fill and the size durable.
        self.flush_all_accounted()?;
        // 3. Verify the extent is really written and out of the page cache.
        self.verify_ready(offset, extent)?;
        // 4. Region header slot A, generation 1, Ready.
        let rmeta = RegionMeta {
            region_id: id,
            kind,
            state: RegionState::Ready,
            fill,
            data_offset: offset + 2 * block,
            data_size,
            fill_key,
        };
        let mut rbuf = [0u8; REGION_META_LEN];
        let _len = rmeta.encode(&mut rbuf).map_err(|_| meta_err())?;
        let entry = TableEntry {
            region_id: id,
            kind,
            state: RegionState::Ready,
            name: rname,
            offset,
            data_size,
            fill,
            tag,
        };
        let at = pair_region(inner.volume, &inner.layout, &entry);
        let blank = PairRead::blank();
        let next = plan_next(&blank, &rbuf, inner.owner_generation)?;
        let header = {
            // `durable_slot` poisons exactly when durability became unknown;
            // an error before submission leaves the store usable.
            let mut q = inner.queues.get(id as usize);
            durable_slot::<P>(
                &mut q,
                &inner.file,
                &inner.pool,
                &at,
                &blank,
                &next,
                &inner.policy,
                &inner.domain,
            )
            .inspect_err(|_| self.wake_frontiers())?
        };
        // 5. Table flip adding the entry (replacing a reused released entry).
        let mut entries = meta.entries.clone();
        match reuse {
            Some(i) => entries[i] = entry,
            None => entries.push(entry),
        }
        self.flip_table(&mut meta, next_id, &entries)?;
        meta.entries = entries;
        meta.next_region_id = next_id;
        if let Some(r) = from {
            // Checked above against `remaining`, under the same `meta` lock.
            r.consume(extent)?;
        }
        lock_acct(&inner.acct).add(&entry, block);
        let state = Arc::new(LiveRegion {
            id: RegionId::from_raw(u64::from(id)),
            name: rname,
            kind,
            generation: Generation::FIRST,
            map: crate::regionmap::RegionMap::single(offset + 2 * block, data_size),
            header_at: [offset, offset + block],
            header: Mutex::new(header),
            frontier: (kind == RegionKind::Append).then(|| {
                AppendFrontier::new(
                    0,
                    data_size,
                    u32::from(inner.layout.log2_block),
                    crate::frontier::ring_for(
                        inner.opts.append_window,
                        data_size,
                        u32::from(inner.layout.log2_block),
                    ),
                )
            }),
            positioned: std::sync::atomic::AtomicBool::new(true),
            force_sync: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            read_only: std::sync::atomic::AtomicBool::new(false),
            superseded: false,
            foreign: false,
            gate: Gate::new(),
        });
        inner
            .regions
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(Arc::clone(&state));
        Ok(state)
    }

    pub(crate) fn fill(
        &self,
        offset: u64,
        extent: u64,
        block: u64,
        fill: FillPattern,
        key: &[u8; 16],
    ) -> Result<(), Error> {
        // The two header blocks are always zero so no old header survives;
        // the data area gets the pattern from its first byte.
        self.fill_range(offset, extent, 2 * block, fill, key, 0)
    }

    /// Whether space a region holds but has no data in yet (a capped
    /// region's slack, the rest of a growth's extent) is written with the
    /// region's pattern rather than allocated unwritten: on Windows, where a
    /// write past a file's valid data makes NTFS zero every byte below it
    /// first (slack left unwritten would cost a later write that zeroing),
    /// and on macOS, which cannot allocate inside a file.
    pub(crate) fn writes_slack(&self) -> bool {
        matches!(
            self.inner.report.evidence.platform,
            store_io_core::evidence::PlatformKind::Windows
                | store_io_core::evidence::PlatformKind::MacOs
        )
    }

    /// Writes `[offset, offset + extent)` of the container: its first `zeros`
    /// bytes zero, the rest `fill`, whose keyed index starts at region
    /// offset `key_at` (a growth's fill of a run: no zeros, its region
    /// offset). Failures as [`Self::fill`] (a write failed after submission
    /// poisons; running out of space does not).
    pub(crate) fn fill_range(
        &self,
        offset: u64,
        extent: u64,
        zeros: u64,
        fill: FillPattern,
        key: &[u8; 16],
        key_at: u64,
    ) -> Result<(), Error> {
        self.write_range(offset, extent, zeros, key_at, &mut |index, dst| {
            match fill {
                FillPattern::KeyedV1 => fill_keyed_v1(key, index, dst),
                FillPattern::Zeros => dst.fill(0),
            }
            Ok(())
        })
    }

    /// Writes `[offset, offset + extent)` of the container: its first
    /// `zeros` bytes zero, every later byte from `content(index, dst)`, which
    /// fills `dst` with the bytes of region offsets `index..` (`key_at` for
    /// the first byte past the zeros). One write in flight at a time. A
    /// write that failed after submission poisons (`DurabilityUnknown`);
    /// running out of space is `NoSpace`, unpoisoned; an error from
    /// `content` stops the fill before that piece is written, unpoisoned
    /// (the region never became Ready).
    pub(crate) fn write_range(
        &self,
        offset: u64,
        extent: u64,
        zeros: u64,
        key_at: u64,
        content: &mut Content<'_>,
    ) -> Result<(), Error> {
        let inner = &self.inner;
        let block = inner.layout.block();
        let chunk = (self.chunk() as u64).min(1 << 20).max(block);
        let mut q = inner.queues.get(0);
        let mut at = 0u64;
        while at < extent {
            let len = chunk.min(extent - at);
            let mut buf = self.take(len as usize, ErrorContext::default())?;
            // The content from the first byte past the zeros, even inside a
            // chunk that also covers some of them.
            let dst = buf.as_mut_slice();
            let z = zeros.saturating_sub(at).min(len) as usize;
            dst[..z].fill(0);
            let index = key_at + (at + z as u64).saturating_sub(zeros);
            content(index, &mut dst[z..])?;
            let ran = run(
                &mut q,
                IoOp::Write {
                    file: &inner.file,
                    offset: offset + at,
                    buf,
                    dsync: false,
                },
            )
            .map_err(|(_, raw)| {
                raw.map_or(
                    Error::NotWritten {
                        cause: NotWrittenCause::QueueFull,
                        ctx: ErrorContext::default(),
                    },
                    |r| space_err(Op::Write, r, 0),
                )
            })?;
            // A fill write that failed after submission stops the store
            // (fail-stop, D-071); only running out of space is reported as
            // `NoSpace` without poisoning: the region never became Ready.
            // An abandoned write (its wait failed) is never "out of space":
            // its fate is unknown, so it poisons like any other failure.
            let (result, abandoned) = match ran {
                Ran::Done { result, .. } => (result, false),
                Ran::Abandoned(raw) => (Err(raw), true),
            };
            match result {
                Ok(n) if n as u64 == len => {}
                Err(raw) if !abandoned && store_io_core::errno::is_no_space(raw) => {
                    return Err(space_err(Op::Write, raw, 0));
                }
                result => {
                    let raw = result.err();
                    inner.domain.poison(FirstCause {
                        op: Some(Op::Write),
                        raw,
                    });
                    self.wake_frontiers();
                    return Err(Error::DurabilityUnknown {
                        op: Op::Write,
                        raw,
                        ctx: ErrorContext::default(),
                    });
                }
            }
            at += len;
        }
        Ok(())
    }

    pub(crate) fn flush_all_accounted(&self) -> Result<(), Error> {
        let inner = &self.inner;
        // Holding slot 0, so no data flush runs on the main handle at the
        // same time (each flush's failure report stays its own, D-124).
        // A failure poisons before slot 0 is given back: the next flush on
        // the main handle (another fill, now that fills run outside the
        // metadata lock) could otherwise succeed past the error this one
        // consumed, and its caller go on before the poison.
        let flushed = inner.domain.exclusive_main(|| {
            let r = inner.platform.flush_all(&inner.file);
            if let Err(raw) = r {
                inner.domain.poison(FirstCause {
                    op: Some(Op::FlushAll),
                    raw: Some(raw),
                });
            }
            r
        });
        flushed.map_err(|raw| Error::DurabilityUnknown {
            op: Op::FlushAll,
            raw: Some(raw),
            ctx: ErrorContext::default(),
        })
    }

    pub(crate) fn verify_ready(&self, offset: u64, extent: u64) -> Result<(), Error> {
        let inner = &self.inner;
        let st = inner
            .platform
            .range_state(&inner.file, offset, extent)
            .map_err(|e| io(Op::Probe, e))?;
        use store_io_core::evidence::Tri;
        let bad = st.unwritten == Tri::Yes
            || st.shared == Tri::Yes
            || st.cached_pages.is_some_and(|n| n > 0)
            || st.valid_data == Tri::No;
        if bad {
            return Err(Error::NotWritten {
                cause: NotWrittenCause::NotReady,
                ctx: ErrorContext::default(),
            });
        }
        Ok(())
    }

    pub(crate) fn flip_table(
        &self,
        meta: &mut Meta,
        next_id: u32,
        entries: &[TableEntry],
    ) -> Result<(), Error> {
        let inner = &self.inner;
        // The payload room of the table slot: the slot less its header.
        let mut tbuf = vec![0u8; inner.layout.table() as usize - store_io_format::slot::HEADER_LEN];
        let len = encode_table(&mut tbuf, next_id, entries).map_err(|_| Error::NoSpace {
            tag: ReserveTag::Table,
            ctx: ErrorContext::default(),
        })?;
        let tat = pair_table(inner.volume, &inner.layout);
        let next = plan_next(&meta.table_pair, &tbuf[..len], inner.owner_generation)?;
        let mut q = inner.queues.get(1);
        // `durable_slot` poisons exactly when durability became unknown.
        meta.table_pair = durable_slot::<P>(
            &mut q,
            &inner.file,
            &inner.pool,
            &tat,
            &meta.table_pair,
            &next,
            &inner.policy,
            &inner.domain,
        )
        .inspect_err(|_| self.wake_frontiers())?;
        Ok(())
    }
}