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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! The [`crate::Submitter`]'s op table (D-098, D-099): one row per operation
//! in flight, holding everything its completion needs, and the integrity
//! bookkeeping run when the completion is collected. A durable write keeps
//! its row (and its region's pass) after its I/O completes, until a flush
//! covering it succeeds; a barrier holds a row and no I/O.
use std::collections::VecDeque;
use std::sync::Arc;
use store_io_core::error::{Error, ErrorContext, NotWrittenCause};
use store_io_platform::{IoBuf, Platform, RawResult};
use crate::completion::{Completion, Done, Written};
use crate::exec::LaneMark;
use crate::flusher::Flushed;
use crate::frontier::Reservation;
use crate::gate::OwnedPass;
use crate::io::not_written;
use crate::receipt::{DurableReceipt, WriteTicket};
use crate::settle::{Wrote, durable_receipt, in_range, settle_read, settle_write};
use crate::store::{LiveRegion, Store};
/// What an operation in flight is, in region bytes.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Kind {
/// An append and its reserved range.
Append(Reservation),
/// A page write of `[start, end)`.
Page { start: u64, end: u64 },
/// A read of `[start, end)`.
Read { start: u64, end: u64 },
/// A barrier for one ticket: the receipt to complete (its `need` set
/// by the flush).
Sync(DurableReceipt),
/// A barrier for the whole store.
All,
/// A blocking layer's operation on a lane (A1): no region bookkeeping in
/// the row; its caller settles it ([`crate::settle`]) or discards it.
Raw,
}
/// A `Submitter` operation across runs (format 2, spec ยง11): one device
/// operation per run, one in flight at a time, under the operation's row.
/// After each piece the caller's buffer is rotated so the next piece starts
/// at its front; after the last the rotations add up to a whole turn, so
/// the bytes are back in order (and so, rotated back, after a piece that
/// failed or came back short).
///
/// The row's age (the busy mark, `Store::oldest_outstanding`) is the first
/// piece's: it covers the whole operation.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Split {
/// The operation's length.
pub(crate) total: usize,
/// Bytes done before the piece in flight.
pub(crate) done: usize,
}
/// What an I/O completion came to.
pub(crate) enum Finish {
/// Handed back (or matched nothing).
Done,
/// A durable write that completed in full, waiting for this flush:
/// `(qtag, need)`.
Flush(u64, u64),
/// A piece of an operation across runs completed in full: the next one,
/// to submit under the same tag.
Next {
qtag: u64,
offset: u64,
buf: IoBuf,
write: bool,
},
}
/// An operation in flight: everything its completion needs.
struct Live {
tag: u64,
seq: u64,
kind: Kind,
/// Keeps the region's generation open until the completion is handed
/// back (`None` for barriers, which do no I/O on a region).
pass: Option<OwnedPass<LiveRegion>>,
/// A write to hand back only once durable ([`crate::WriteMode::Durable`]).
durable: bool,
/// A durable write that completed in full, waiting for its flush: its
/// buffer, its ticket, and for an append whose region was complete up
/// to its end, how far (the receipt is then a prefix receipt).
held: Option<(Option<IoBuf>, WriteTicket, Option<u64>)>,
/// An operation across runs: where it stands.
split: Option<Split>,
}
/// One row. `generation` changes each time the row is freed, so a queue tag
/// names one use of one row.
struct Row {
generation: u32,
live: Option<Live>,
}
/// The op table and the completions handed back but not yet taken.
pub(crate) struct Table {
rows: Box<[Row]>,
free: Vec<u32>,
pub(crate) ready: VecDeque<Completion>,
/// `(row, seq)` in submission order; entries whose row has finished (or
/// was reused) are stale and skipped. Compacted in place when it reaches
/// twice the depth, so it never grows: the oldest operation in flight is
/// found in amortised O(1).
order: VecDeque<(u32, u64)>,
/// Operations submitted and not yet processed.
pub(crate) live: usize,
/// Rows waiting for a flush outcome (durable writes and barriers).
pub(crate) flushing: usize,
/// Of those, requests the flush thread accepted and has not answered
/// (or whose answer is not taken yet): the ones worth waiting for.
pub(crate) asked: usize,
/// Flushes wanted by the completions of one pass, `(qtag, need)`, asked
/// for once the whole pass is finished (one row each, so never more
/// than the depth: no allocation after creation).
pub(crate) asks: Vec<(u64, u64)>,
next_seq: u64,
/// Busy mark for `Store::oldest_outstanding`: `2 * oldest + 1` while
/// anything is in flight, even otherwise (D-095's lane-mark rules).
mark: Arc<LaneMark>,
}
impl Table {
pub(crate) fn new(depth: usize, mark: Arc<LaneMark>) -> Self {
Self {
rows: (0..depth)
.map(|_| Row {
generation: 0,
live: None,
})
.collect(),
free: (0..depth as u32).rev().collect(),
ready: VecDeque::with_capacity(depth),
order: VecDeque::with_capacity(2 * depth),
live: 0,
flushing: 0,
asked: 0,
asks: Vec::with_capacity(depth),
next_seq: 0,
mark,
}
}
pub(crate) fn depth(&self) -> usize {
self.rows.len()
}
/// No room: operations in flight plus completions not yet taken fill
/// the table (so the ready queue never grows past the depth).
pub(crate) fn full(&self) -> bool {
self.live + self.ready.len() >= self.rows.len()
}
/// A free row and the queue tag naming this use of it.
pub(crate) fn claim(&mut self) -> Option<(u32, u64)> {
let index = self.free.pop()?;
let generation = self.rows[index as usize].generation;
Some((index, u64::from(index) | (u64::from(generation) << 32)))
}
/// Frees the row a lane operation's completion names (`Kind::Raw`,
/// never settled here) and returns the caller's tag; `None` if the
/// completion names no row in use (a backend breaking its contract).
pub(crate) fn take(&mut self, qtag: u64) -> Option<u64> {
let index = (qtag & 0xFFFF_FFFF) as usize;
let row = self.row(qtag)?;
let live = row.live.take()?;
row.generation = row.generation.wrapping_add(1);
debug_assert!(
matches!(live.kind, Kind::Raw),
"a settled row freed unsettled"
);
self.free.push(index as u32);
self.live -= 1;
while let Some(&(i, s)) = self.order.front() {
if is_live(&self.rows, i, s) {
break;
}
let _stale = self.order.pop_front();
}
self.publish();
Some(live.tag)
}
/// Frees every row in use without settling it: a lane whose queue
/// holds nothing in flight can never see their completions.
pub(crate) fn forget(&mut self) {
for (i, row) in self.rows.iter_mut().enumerate() {
if row.live.take().is_some() {
row.generation = row.generation.wrapping_add(1);
self.free.push(i as u32);
self.live -= 1;
}
}
self.order.clear();
self.publish();
}
/// Undoes [`Self::start`] for an operation the queue refused: the row is
/// free again (same generation: no completion can name it) and the busy
/// mark is republished. Its pass, if any, is released.
pub(crate) fn abort(&mut self, index: u32) {
let Some(row) = self.rows.get_mut(index as usize) else {
return;
};
let Some(live) = row.live.take() else { return };
if matches!(live.kind, Kind::Sync(_) | Kind::All) {
self.flushing -= 1;
}
drop(live);
self.free.push(index);
self.live -= 1;
while let Some(&(i, s)) = self.order.front() {
if is_live(&self.rows, i, s) {
break;
}
let _stale = self.order.pop_front();
}
self.publish();
}
/// Records an operation in its claimed row and publishes the busy mark,
/// **before** the operation is submitted: a queue that performs the
/// operation inside `submit` (the synchronous tier) must already show
/// it as outstanding, so a hung device is visible to
/// `Store::oldest_outstanding`. A refused submission is undone with
/// [`Self::abort`]. A barrier waits for a flush from the start.
pub(crate) fn start(
&mut self,
index: u32,
tag: u64,
kind: Kind,
pass: Option<OwnedPass<LiveRegion>>,
durable: bool,
) {
let seq = self.next_seq;
self.next_seq += 1;
if self.order.len() >= 2 * self.rows.len() {
let rows = &self.rows;
self.order.retain(|&(i, s)| is_live(rows, i, s));
}
self.order.push_back((index, seq));
if matches!(kind, Kind::Sync(_) | Kind::All) {
self.flushing += 1;
}
self.rows[index as usize].live = Some(Live {
tag,
seq,
kind,
pass,
durable,
held: None,
split: None,
});
self.live += 1;
self.publish();
}
/// Marks the operation just started in row `index` as one across runs,
/// its first piece the one submitted.
pub(crate) fn set_split(&mut self, index: u32, split: Split) {
if let Some(live) = self.rows[index as usize].live.as_mut() {
live.split = Some(split);
}
}
/// Publishes the busy mark of an operation performed at once, with no
/// row (`Lane::perform`): outstanding until [`Self::publish`].
pub(crate) fn busy(&mut self) {
let seq = self.next_seq;
self.next_seq += 1;
self.mark.set(2 * seq + 1);
}
/// Publishes the busy mark (only the owner writes it).
pub(crate) fn publish(&self) {
self.mark.set(match self.order.front() {
Some(&(_, seq)) if self.live > 0 => 2 * seq + 1,
_ => 2 * self.next_seq,
});
}
/// Whether a write's I/O is in flight (not a durable write whose I/O
/// completed, nor a barrier).
pub(crate) fn writes_live(&self) -> bool {
self.rows.iter().any(|r| {
r.live.as_ref().is_some_and(|l| {
l.held.is_none() && matches!(l.kind, Kind::Append(_) | Kind::Page { .. })
})
})
}
/// Whether `live` counts exactly the rows in use (false only if a panic
/// interrupted the processing of a completion).
pub(crate) fn consistent(&self) -> bool {
self.rows.iter().filter(|r| r.live.is_some()).count() == self.live
}
/// The row a tag names, if it is in use by that tag's operation.
fn row(&mut self, qtag: u64) -> Option<&mut Row> {
let index = (qtag & 0xFFFF_FFFF) as usize;
let generation = (qtag >> 32) as u32;
self.rows
.get_mut(index)
.filter(|r| r.generation == generation && r.live.is_some())
}
/// Processes one I/O completion. A piece of an operation across runs
/// that completed in full, not its last, returns the next piece
/// ([`Finish::Next`]); the operation is settled only once (ticket,
/// reservation or poison), after its last piece or one that failed or
/// came back short. A durable write that completed in full on a
/// flush-required store keeps its row and returns the flush it needs;
/// anything else is handed back now, after which its row and pass are
/// released.
pub(crate) fn finish<P: Platform>(
&mut self,
store: &Store<P>,
qtag: u64,
mut buf: Option<IoBuf>,
mut result: RawResult<usize>,
) -> Finish
where
P::Queue: Send,
{
let row = self.row(qtag);
// The queue is this submitter's alone and every tag names one use of
// one row: an unmatched completion cannot happen. Its buffer, if
// any, is the device's no longer, so dropping it is safe.
debug_assert!(row.is_some(), "a completion matched no operation");
let Some(live) = row.and_then(|r| r.live.as_mut()) else {
return Finish::Done;
};
if let Some(split) = live.split {
let piece = buf.as_ref().map_or(0, IoBuf::len);
let whole = buf.is_some() && matches!(result, Ok(n) if n == piece);
let left = split.total - split.done - piece.min(split.total - split.done);
if let (true, true, Some(state), Some(b)) =
(whole, left > 0, region(live), buf.as_mut())
{
let pos = start_of(live.kind) + (split.done + piece) as u64;
let next = (state.map.run_left(pos) as usize).min(left);
// The rest to the front: the next piece starts at the start.
let fits = b.set_len(split.total);
debug_assert!(fits, "a split buffer shorter than its operation");
b.as_mut_slice().rotate_left(piece);
let _fits = b.set_len(next);
let offset = state.map.locate(pos, next as u64);
let write = !matches!(live.kind, Kind::Read { .. });
let next_split = Split {
total: split.total,
done: split.done + piece,
};
// Every piece moves the operation on (one that did not would
// be re-issued for ever): checked in release builds too.
assert!(
next_split.done > split.done && next_split.done < split.total,
"a split operation that does not move on"
);
live.split = Some(next_split);
if let Some(buf) = buf.take() {
return Finish::Next {
qtag,
offset,
buf,
write,
};
}
}
// The last piece, or one that failed or came back short: the
// bytes back in order, the result over the whole operation.
if let Some(b) = buf.as_mut() {
let fits = b.set_len(split.total);
debug_assert!(fits, "a split buffer shorter than its operation");
b.as_mut_slice().rotate_left(split.total - split.done);
}
result = result.map(|n| split.done + n);
live.split = None;
}
self.conclude(store, qtag, buf, result)
}
/// The next piece of an operation across runs was refused before it
/// reached the device: the operation ends there, settled over the bytes
/// done (the buffer, rotated back, in order).
pub(crate) fn refused_next<P: Platform>(
&mut self,
store: &Store<P>,
qtag: u64,
mut buf: Option<IoBuf>,
raw: Option<store_io_core::error::OsError>,
) -> Finish
where
P::Queue: Send,
{
let Some(live) = self.row(qtag).and_then(|r| r.live.as_mut()) else {
return Finish::Done;
};
let Some(split) = live.split.take() else {
return Finish::Done;
};
if let Some(b) = buf.as_mut() {
let fits = b.set_len(split.total);
debug_assert!(fits, "a split buffer shorter than its operation");
b.as_mut_slice().rotate_left(split.total - split.done);
}
// A read refused without a code (a full queue: not expected, a slot
// was just freed) is an error, never a short read of what was done.
if raw.is_none() {
if let Kind::Read { start, end } = live.kind {
let c = region(live).map_or_else(ErrorContext::default, |r| {
crate::io::ctx_range(r, start, end)
});
self.release(qtag, buf, Err(not_written(NotWrittenCause::QueueFull, c)));
return Finish::Done;
}
}
self.conclude(store, qtag, buf, raw.map_or(Ok(split.done), Err))
}
/// Settles an operation whose I/O is over (see [`Self::finish`]).
fn conclude<P: Platform>(
&mut self,
store: &Store<P>,
qtag: u64,
mut buf: Option<IoBuf>,
result: RawResult<usize>,
) -> Finish
where
P::Queue: Send,
{
let Some(live) = self.row(qtag).and_then(|r| r.live.as_mut()) else {
return Finish::Done;
};
let mut prefix = None;
let mut outcome = settle(store, live, buf.as_ref(), result, &mut prefix);
// A flush-required store, or a region forcing data sync (D-102):
// read only for a durable write.
let flushes =
|| store.inner.policy.flush || live.pass.as_ref().is_some_and(|p| p.get().forced());
if live.durable && flushes() {
if let Ok(Done::Written(w)) = outcome {
// The ticket's need was taken when the write's completion
// had been observed: a flush that far covers it (D-047).
let need = w.ticket.need;
live.held = Some((buf, w.ticket, prefix));
self.flushing += 1;
return Finish::Flush(qtag, need);
}
} else if live.durable {
if let Ok(Done::Written(w)) = &mut outcome {
match store.inner.domain.poisoned() {
// As a blocking durable write: no receipt once poisoned.
Some(first) => outcome = Err(Error::Poisoned { first }),
// Power-safe: the write itself was durable at completion.
None => {
w.receipt = Some(durable_receipt(
store,
region(live),
&w.ticket,
prefix,
u64::MAX,
));
}
}
}
}
// A short read: the buffer holds only the bytes read, never what
// its previous user left after them.
if let (Ok(Done::Read { len }), Some(b)) = (&outcome, buf.as_mut()) {
let _shorter = b.set_len(*len);
}
self.release(qtag, buf, outcome);
Finish::Done
}
/// Processes a flush outcome for a row waiting for one: the durable
/// write's receipt (or the flush's failure), or the barrier's.
pub(crate) fn flushed<P: Platform>(&mut self, store: &Store<P>, qtag: u64, outcome: Flushed)
where
P::Queue: Send,
{
let live = self.row(qtag).and_then(|r| r.live.as_mut());
debug_assert!(live.is_some(), "a flush outcome matched no operation");
let Some(live) = live else { return };
let (buf, done) = match (live.held.take(), live.kind) {
(Some((buf, ticket, prefix)), _) => {
let done = match outcome {
Ok(need) => {
let receipt = durable_receipt(store, region(live), &ticket, prefix, need);
Ok(Done::Written(Written {
ticket,
receipt: Some(receipt),
}))
}
Err(e) => Err(in_range(e, &ticket)),
};
(buf, done)
}
(None, Kind::Sync(mut receipt)) => {
let done = outcome.map(|need| {
receipt.need = need;
receipt.synced = need != u64::MAX;
Done::Synced(receipt)
});
(None, done)
}
(None, _) => (None, outcome.map(|_| Done::Flushed)),
};
self.flushing -= 1;
self.release(qtag, buf, done);
}
/// Hands an operation back and frees its row: its pass is released only
/// now, after its reservation was completed (or the store poisoned) and
/// any flush it waited for.
fn release(&mut self, qtag: u64, buf: Option<IoBuf>, outcome: Result<Done, Error>) {
let index = (qtag & 0xFFFF_FFFF) as usize;
let Some(row) = self.row(qtag) else { return };
let Some(live) = row.live.take() else { return };
row.generation = row.generation.wrapping_add(1);
let Live { tag, pass, .. } = live;
drop(pass);
self.free.push(index as u32);
self.live -= 1;
while let Some(&(i, s)) = self.order.front() {
if is_live(&self.rows, i, s) {
break;
}
let _stale = self.order.pop_front();
}
self.publish();
self.ready.push_back(Completion { tag, buf, outcome });
}
}
fn is_live(rows: &[Row], index: u32, seq: u64) -> bool {
rows[index as usize]
.live
.as_ref()
.is_some_and(|l| l.seq == seq)
}
/// The verdict on one row's I/O completion, through the shared verdicts
/// ([`crate::settle`]): a write is full when it transferred its whole
/// buffer; `prefix` as [`settle_write`].
fn settle<P: Platform>(
store: &Store<P>,
live: &Live,
buf: Option<&IoBuf>,
result: RawResult<usize>,
prefix: &mut Option<u64>,
) -> Result<Done, Error>
where
P::Queue: Send,
{
let Some(state) = region(live) else {
// Barriers have no I/O completion.
return Err(not_written(
NotWrittenCause::Interrupted,
ErrorContext::default(),
));
};
let full = matches!((result, buf), (Ok(n), Some(b)) if n == b.len());
let wrote = match live.kind {
Kind::Append(r) => Wrote::Append(r),
Kind::Page { start, end } => Wrote::Page { start, end },
Kind::Read { start, end } => {
return settle_read(store, state, start, end, buf, result)
.map(|len| Done::Read { len });
}
Kind::Sync(_) | Kind::All | Kind::Raw => {
return Err(not_written(
NotWrittenCause::Interrupted,
ErrorContext::default(),
));
}
};
settle_write(store, state, wrote, full, result.err(), prefix).map(|ticket| {
Done::Written(Written {
ticket,
receipt: None,
})
})
}
/// Where an I/O operation starts, in region bytes.
fn start_of(kind: Kind) -> u64 {
match kind {
Kind::Append(r) => r.start,
Kind::Page { start, .. } | Kind::Read { start, .. } => start,
Kind::Sync(_) | Kind::All | Kind::Raw => 0,
}
}
/// The region a row's pass was admitted to (`None` for barriers).
fn region(live: &Live) -> Option<&LiveRegion> {
live.pass.as_ref().map(|p| &**p.get())
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{Kind, Table};
use crate::exec::LaneMark;
fn raw(t: &mut Table, tag: u64) -> u64 {
let (index, qtag) = t.claim().unwrap_or_else(|| panic!("a free row"));
t.start(index, tag, Kind::Raw, None, false);
qtag
}
/// The busy mark names the oldest operation in flight (A1 C6, D-095):
/// the oldest completing while a newer one is in flight moves it (the age
/// restarts: progress), a newer one completing first does not (the
/// oldest keeps aging), and the last one leaves it even.
#[test]
fn test_the_busy_mark_follows_the_oldest_operation() {
let mark = Arc::new(LaneMark::new());
let mut t = Table::new(4, Arc::clone(&mark));
assert_eq!(mark.get() % 2, 0);
let (a, b) = (raw(&mut t, 1), raw(&mut t, 2));
assert_eq!(mark.get(), 1, "operation 0 is the oldest");
assert_eq!(t.take(a), Some(1));
assert_eq!(mark.get(), 3, "operation 1 is the oldest now");
assert_eq!(t.take(b), Some(2));
assert_eq!(mark.get() % 2, 0, "nothing in flight");
let (c, d) = (raw(&mut t, 3), raw(&mut t, 4));
let oldest = mark.get();
assert_eq!(t.take(d), Some(4));
assert_eq!(
mark.get(),
oldest,
"a newer completion moved the oldest's mark"
);
assert_eq!(t.take(c), Some(3));
assert_eq!(mark.get() % 2, 0);
}
}