-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathextent_inner_raw.rs
2345 lines (2119 loc) · 81 KB
/
extent_inner_raw.rs
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Oxide Computer Company
use crate::{
cdt,
extent::{
check_input, extent_path, DownstairsBlockContext, ExtentInner,
EXTENT_META_RAW,
},
extent_inner_raw_common::{
pread_all, pwrite_all, OnDiskMeta, BLOCK_META_SIZE_BYTES,
},
integrity_hash, mkdir_for_file,
region::JobOrReconciliationId,
Block, BlockContext, CrucibleError, ExtentReadRequest, ExtentReadResponse,
ExtentWrite, JobId, RegionDefinition,
};
use crucible_common::ExtentId;
use crucible_protocol::ReadBlockContext;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use slog::{error, Logger};
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Read};
use std::os::fd::{AsFd, AsRawFd};
use std::path::Path;
/// Equivalent to `DownstairsBlockContext`, but without one's own block number
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct OnDiskDownstairsBlockContext {
block_context: BlockContext,
on_disk_hash: u64,
}
/// Size of backup data
///
/// This must be large enough to fit an `Option<OnDiskDownstairsBlockContext>`
/// serialized using `bincode`.
const BLOCK_CONTEXT_SLOT_SIZE_BYTES: u64 = 48;
/// Number of extra syscalls per read / write that triggers defragmentation
const DEFRAGMENT_THRESHOLD: u64 = 3;
/// `RawInner` is a wrapper around a [`std::fs::File`] representing an extent
///
/// The file is structured as follows:
/// - Block data, structured as `block_size` × `extent_size`
/// - Block contexts (for encryption). There are two arrays of context slots,
/// each containing `extent_size` elements (i.e. one slot for each block).
/// Each slot is [`BLOCK_CONTEXT_SLOT_SIZE_BYTES`] in size, so this section of
/// the file is `BLOCK_CONTEXT_SLOT_SIZE_BYTES * extent_size * 2` bytes in
/// total. The slots contain an `Option<OnDiskDownstairsBlockContext>`,
/// serialized using `bincode`.
/// - Active context slots, stored as a bit-packed array (where 0 is
/// [`ContextSlot::A`] and 1 is [`ContextSlot::B`]). This array contains
/// `(extent_size + 7) / 8` bytes. It is only valid when the `dirty` bit is
/// cleared. This is an optimization that speeds up opening a clean extent
/// file; otherwise, we would have to rehash every block to find the active
/// context slot.
/// - [`BLOCK_META_SIZE_BYTES`], which contains an [`OnDiskMeta`] serialized
/// using `bincode`. The first byte of this range is `dirty`, serialized as a
/// `u8` (where `1` is dirty and `0` is clean).
///
/// There are a few considerations that led to this particular ordering:
/// - Active context slots and metadata must be contiguous, because we want to
/// write them atomically when clearing the `dirty` flag
/// - The metadata contains an extent version (currently [`EXTENT_META_RAW`]).
/// We will eventually have multiple raw file formats, so it's convenient to
/// always place the metadata at the end; this lets us deserialize it without
/// knowing anything else about the file, then dispatch based on extent
/// version.
#[derive(Debug)]
pub struct RawInner {
file: File,
/// Our extent number
extent_number: ExtentId,
/// Extent size, in blocks
extent_size: Block,
/// Helper `struct` controlling layout within the file
layout: RawLayout,
/// Is the `A` or `B` context slot active, on a per-block basis?
active_context: Vec<ContextSlot>,
/// Local cache for the `dirty` value
///
/// This allows us to only write the flag when the value changes
dirty: bool,
/// Marks whether the given context slot is dirty
///
/// A dirty context slot has not yet been saved to disk, and must be
/// synched before being overwritten.
///
/// Context slots are stored as a 2-bit field, with bit 0 marking
/// `ContextSlot::A` and bit 1 marking `ContextSlot::B`.
context_slot_dirty: Vec<u8>,
/// Total number of extra syscalls due to context slot fragmentation
extra_syscall_count: u64,
/// Denominator corresponding to `extra_syscall_count`
extra_syscall_denominator: u64,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ContextSlot {
A,
B,
}
impl std::ops::Not for ContextSlot {
type Output = Self;
fn not(self) -> Self {
match self {
ContextSlot::A => ContextSlot::B,
ContextSlot::B => ContextSlot::A,
}
}
}
impl ExtentInner for RawInner {
fn flush_number(&self) -> Result<u64, CrucibleError> {
self.get_metadata().map(|v| v.flush_number)
}
fn gen_number(&self) -> Result<u64, CrucibleError> {
self.get_metadata().map(|v| v.gen_number)
}
fn dirty(&self) -> Result<bool, CrucibleError> {
Ok(self.dirty)
}
/// Performs a single write within this extent
fn write(
&mut self,
job_id: JobId,
write: &ExtentWrite,
only_write_unwritten: bool,
_iov_max: usize,
) -> Result<(), CrucibleError> {
check_input(self.extent_size, write.offset, write.data.len())?;
/*
* In order to be crash consistent, perform the following steps in
* order:
*
* 1) set the dirty bit
* 2) for each write:
* a) write out encryption context and hashes first
* b) write out extent data second
*
* If encryption context is written after the extent data, a crash or
* interruption before extent data is written would potentially leave
* data on the disk that cannot be decrypted.
*
* If hash is written after extent data, same thing - a crash or
* interruption would leave data on disk that would fail the
* integrity hash check.
*
* Note that writing extent data here does not assume that it is
* durably on disk - the only guarantee of that is returning
* ok from fsync. The data is only potentially on disk and
* this depends on operating system implementation.
*
* To minimize the performance hit of sending many transactions to the
* filesystem, as much as possible is written at the same time. This
* means multiple loops are required. The steps now look like:
*
* 1) set the dirty bit
* 2) gather and write all encryption contexts + hashes
* 3) write all extent data
*
* If "only_write_unwritten" is true, then we only issue a write for
* a block if that block has not been written to yet. Note
* that we can have a write that is "sparse" if the range of
* blocks it contains has a mix of written an unwritten
* blocks.
*
* We define a block being written to or not has if that block has
* `Some(...)` with a matching checksum serialized into a context slot
* or not. So it is required that a written block has a checksum.
*/
let num_blocks = write.block_contexts.len() as u64;
let block_size = self.extent_size.block_size_in_bytes() as u64;
// If `only_write_written`, we need to skip writing to blocks that
// already contain data. We'll first query the metadata to see which
// blocks have hashes
let mut writes_to_skip = HashSet::new();
if only_write_unwritten {
cdt::extent__write__get__hashes__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// Query hashes for the write range.
let block_contexts =
self.get_block_contexts(write.offset.0, num_blocks)?;
for (i, block_contexts) in block_contexts.iter().enumerate() {
if block_contexts.is_some() {
writes_to_skip.insert(i);
}
}
cdt::extent__write__get__hashes__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
if writes_to_skip.len() == write.block_contexts.len() {
// Nothing to do
return Ok(());
}
}
self.set_dirty()?;
// Write all the context data to the raw file
//
// TODO right now we're including the integrity_hash() time in the
// measured time. Is it small enough to be ignored?
cdt::extent__write__raw__context__insert__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// Compute block contexts, then write them to disk
let block_ctx: Vec<_> = write
.block_contexts
.iter()
.enumerate()
.filter(|(i, _ctx)| !writes_to_skip.contains(i))
.map(|(i, ctx)| {
// TODO it would be nice if we could profile what % of time we're
// spending on hashes locally vs writing to disk
let chunk = &write.data[i * block_size as usize..]
[..block_size as usize];
let on_disk_hash = integrity_hash(&[chunk]);
DownstairsBlockContext {
block_context: *ctx,
block: write.offset.0 + i as u64,
on_disk_hash,
}
})
.collect();
self.set_block_contexts(&block_ctx)?;
cdt::extent__write__raw__context__insert__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// PERFORMANCE TODO:
//
// Something worth considering for small writes is that, based on
// my memory of conversations we had with propolis folks about what
// OSes expect out of an NVMe driver, I believe our contract with the
// upstairs doesn't require us to have the writes inside the file
// until after a flush() returns. If that is indeed true, we could
// buffer a certain amount of writes, only actually writing that
// buffer when either a flush is issued or the buffer exceeds some
// set size (based on our memory constraints). This would have
// benefits on any workload that frequently writes to the same block
// between flushes, would have benefits for small contiguous writes
// issued over multiple write commands by letting us batch them into
// a larger write, and (speculation) may benefit non-contiguous writes
// by cutting down the number of metadata writes. But, it introduces
// complexity. The time spent implementing that would probably better be
// spent switching to aio or something like that.
cdt::extent__write__file__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
let r = self.write_inner(write, &writes_to_skip);
if r.is_err() {
for i in 0..write.block_contexts.len() {
if !writes_to_skip.contains(&i) {
// Try to recompute the context slot from the file. If this
// fails, then we _really_ can't recover, so bail out
// unceremoniously.
let block = write.offset.0 + i as u64;
self.recompute_slot_from_file(block).unwrap();
}
}
} else {
// Now that writes have gone through, update active context slots
for i in 0..write.block_contexts.len() {
if !writes_to_skip.contains(&i) {
// We always write to the inactive slot, so just swap it
let block = write.offset.0 as usize + i;
self.active_context[block] = !self.active_context[block];
}
}
}
cdt::extent__write__file__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
Ok(())
}
fn read(
&mut self,
job_id: JobId,
req: ExtentReadRequest,
_iov_max: usize, // unused by raw backend
) -> Result<ExtentReadResponse, CrucibleError> {
let mut buf = req.data;
let block_size = self.extent_size.block_size_in_bytes() as u64;
let num_blocks = buf.capacity() as u64 / block_size;
check_input(self.extent_size, req.offset, buf.capacity())?;
// Query the block metadata
cdt::extent__read__get__contexts__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
let blocks = self.get_block_contexts_inner(
req.offset.0,
num_blocks,
|ctx, _block| match ctx {
None => ReadBlockContext::Empty,
Some(c) => match c.block_context.encryption_context {
Some(ctx) => ReadBlockContext::Encrypted { ctx },
None => ReadBlockContext::Unencrypted {
hash: c.block_context.hash,
},
},
},
)?;
cdt::extent__read__get__contexts__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// To avoid a `memset`, we're reading directly into uninitialized
// memory in the buffer. This is fine; we sized the buffer
// appropriately in advance (and will panic here if we messed up).
assert!(buf.is_empty());
// Finally we get to read the actual data. That's why we're here
cdt::extent__read__file__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// SAFETY: the buffer has sufficient capacity, and this is a valid
// file descriptor.
let expected_bytes = buf.capacity();
let r = unsafe {
libc::pread(
self.file.as_raw_fd(),
buf.spare_capacity_mut().as_mut_ptr() as *mut libc::c_void,
expected_bytes as libc::size_t,
req.offset.0 as i64 * block_size as i64,
)
};
// Check against the expected number of bytes. We could do more
// robust error handling here (e.g. retrying in a loop), but for
// now, simply bailing out seems wise.
let r = nix::errno::Errno::result(r).map(|r| r as usize);
let num_bytes = r.map_err(|e| {
CrucibleError::IoError(format!(
"extent {}: read failed: {e}",
self.extent_number
))
})?;
if num_bytes != expected_bytes {
return Err(CrucibleError::IoError(format!(
"extent {}: incomplete read \
(expected {expected_bytes}, got {num_bytes})",
self.extent_number
)));
}
// SAFETY: we just initialized this chunk of the buffer
unsafe {
buf.set_len(expected_bytes);
}
cdt::extent__read__file__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
Ok(ExtentReadResponse { data: buf, blocks })
}
fn flush(
&mut self,
new_flush: u64,
new_gen: u64,
job_id: JobOrReconciliationId,
) -> Result<(), CrucibleError> {
if !self.dirty()? {
/*
* If we have made no writes to this extent since the last flush,
* we do not need to update the extent on disk
*/
return Ok(());
}
cdt::extent__flush__start!(|| {
(job_id.get(), self.extent_number.0, 0)
});
// We put all of our metadata updates into a single write to make this
// operation atomic.
self.set_flush_number(new_flush, new_gen)?;
// Now, we fsync to ensure data is flushed to disk. It's okay to crash
// before this point, because setting the flush number is atomic.
cdt::extent__flush__file__start!(|| {
(job_id.get(), self.extent_number.0, 0)
});
if let Err(e) = self.file.sync_all() {
/*
* XXX Retry? Mark extent as broken?
*/
return Err(CrucibleError::IoError(format!(
"extent {}: fsync 1 failure: {e:?}",
self.extent_number,
)));
}
self.context_slot_dirty.fill(0);
cdt::extent__flush__file__done!(|| {
(job_id.get(), self.extent_number.0, 0)
});
// Check for fragmentation in the context slots leading to worse
// performance, and defragment if that's the case.
let extra_syscalls_per_rw = self
.extra_syscall_count
.checked_div(self.extra_syscall_denominator)
.unwrap_or(0);
self.extra_syscall_count = 0;
self.extra_syscall_denominator = 0;
let r = if extra_syscalls_per_rw > DEFRAGMENT_THRESHOLD {
self.defragment()
} else {
Ok(())
};
cdt::extent__flush__done!(|| {
(job_id.get(), self.extent_number.0, 0)
});
r
}
#[cfg(test)]
fn set_dirty_and_block_context(
&mut self,
block_context: &DownstairsBlockContext,
) -> Result<(), CrucibleError> {
self.set_dirty()?;
self.set_block_contexts(&[*block_context])?;
self.active_context[block_context.block as usize] =
!self.active_context[block_context.block as usize];
Ok(())
}
#[cfg(test)]
fn get_block_contexts(
&mut self,
block: u64,
count: u64,
) -> Result<Vec<Option<DownstairsBlockContext>>, CrucibleError> {
RawInner::get_block_contexts(self, block, count)
}
}
impl RawInner {
/// Imports context and metadata
///
/// Returns a buffer that must be appended to raw block data to form the
/// full raw extent file.
pub fn import(
file: &mut File,
def: &RegionDefinition,
ctxs: Vec<Option<DownstairsBlockContext>>,
dirty: bool,
flush_number: u64,
gen_number: u64,
) -> Result<(), CrucibleError> {
let layout = RawLayout::new(def.extent_size());
let block_count = layout.block_count() as usize;
assert_eq!(block_count, def.extent_size().value as usize);
assert_eq!(block_count, ctxs.len());
file.set_len(layout.file_size())?;
layout.write_context_slots_contiguous(
file,
0,
ctxs.iter().map(Option::as_ref),
ContextSlot::A,
)?;
layout.write_context_slots_contiguous(
file,
0,
std::iter::repeat(None).take(block_count),
ContextSlot::B,
)?;
layout.write_active_context_and_metadata(
file,
vec![ContextSlot::A; block_count].as_slice(),
dirty,
flush_number,
gen_number,
)?;
Ok(())
}
pub fn create(
dir: &Path,
def: &RegionDefinition,
extent_number: ExtentId,
) -> Result<Self, CrucibleError> {
let path = extent_path(dir, extent_number);
let extent_size = def.extent_size();
let layout = RawLayout::new(extent_size);
let size = layout.file_size();
mkdir_for_file(&path)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)?;
// All 0s are fine for everything except extent version in the metadata
file.set_len(size)?;
let mut out = Self {
file,
dirty: false,
extent_size,
layout,
extent_number,
active_context: vec![
ContextSlot::A; // both slots are empty, so this is fine
def.extent_size().value as usize
],
context_slot_dirty: vec![0; def.extent_size().value as usize],
extra_syscall_count: 0,
extra_syscall_denominator: 0,
};
// Setting the flush number also writes the extent version, since
// they're serialized together in the same block.
out.set_flush_number(0, 0)?;
// Sync the file to disk, to avoid any questions
if let Err(e) = out.file.sync_all() {
return Err(CrucibleError::IoError(format!(
"extent {}: fsync 1 failure during initial sync: {e}",
out.extent_number,
)));
}
Ok(out)
}
/// Constructs a new `Inner` object from files that already exist on disk
pub fn open(
dir: &Path,
def: &RegionDefinition,
extent_number: ExtentId,
read_only: bool,
log: &Logger,
) -> Result<Self, CrucibleError> {
let path = extent_path(dir, extent_number);
let extent_size = def.extent_size();
let layout = RawLayout::new(extent_size);
let size = layout.file_size();
/*
* Open the extent file and verify the size is as we expect.
*/
let file =
match OpenOptions::new().read(true).write(!read_only).open(&path) {
Err(e) => {
error!(
log,
"Open of {path:?} for extent#{extent_number} \
returned: {e}",
);
return Err(CrucibleError::IoError(format!(
"extent {extent_number}: open of {path:?} failed: {e}",
)));
}
Ok(f) => {
let cur_size = f.metadata().unwrap().len();
if size != cur_size {
return Err(CrucibleError::IoError(format!(
"extent {extent_number}: file size {cur_size:?} \
does not match expected {size:?}",
)));
}
f
}
};
// Just in case, let's be very sure that the file on disk is what it
// should be
if !read_only {
if let Err(e) = file.sync_all() {
return Err(CrucibleError::IoError(format!(
"extent {extent_number}: \
fsync 1 failure during initial rehash: {e}",
)));
}
}
let layout = RawLayout::new(def.extent_size());
let meta = layout.get_metadata(&file)?;
// If the file is dirty, then we have to recompute which context slot is
// active for every block. This is slow, but can't be avoided; we
// closed the file without a flush so we can't be confident about the
// data that was on disk.
let active_context = if !meta.dirty {
// Easy case first: if it's **not** dirty, then just assign active
// slots based on the bitpacked active context buffer from the file.
layout.get_active_contexts(&file)?
} else {
// Otherwise, read block-size chunks and check hashes against
// both context slots, looking for a match.
let ctx_a = layout.read_context_slots_contiguous(
&file,
0,
layout.block_count(),
ContextSlot::A,
)?;
let ctx_b = layout.read_context_slots_contiguous(
&file,
0,
layout.block_count(),
ContextSlot::B,
)?;
// Now that we've read the context slot arrays, read file data and
// figure out which context slot is active.
let mut file_buffered = BufReader::with_capacity(64 * 1024, &file);
let mut active_context = vec![];
let mut buf = vec![0; extent_size.block_size_in_bytes() as usize];
let mut last_seek_block = 0;
for (block, (context_a, context_b)) in
ctx_a.into_iter().zip(ctx_b).enumerate()
{
let slot = if context_a.is_none() && context_b.is_none() {
// Small optimization: if both context slots are empty, the
// block must also be empty (and we don't need to read +
// hash it, saving a little time)
//
// Note that if `context_a == context_b` but they are both
// `Some(..)`, we still want to read + hash the block to
// make sure that it matches. Otherwise, someone has managed
// to corrupt our extent file on disk, which is Bad News.
ContextSlot::A
} else {
// Otherwise, we have to compute hashes from the file.
if block != last_seek_block {
file_buffered.seek_relative(
(block - last_seek_block) as i64
* extent_size.block_size_in_bytes() as i64,
)?;
}
file_buffered.read_exact(&mut buf)?;
last_seek_block = block + 1; // since we just read a block
let hash = integrity_hash(&[&buf]);
let mut matching_slot = None;
let mut empty_slot = None;
for slot in [ContextSlot::A, ContextSlot::B] {
let context = [context_a, context_b][slot as usize];
if let Some(context) = context {
if context.on_disk_hash == hash {
matching_slot = Some(slot);
}
} else if empty_slot.is_none() {
empty_slot = Some(slot);
}
}
matching_slot.or(empty_slot).ok_or(
CrucibleError::MissingContextSlot(block as u64),
)?
};
active_context.push(slot);
}
active_context
};
Ok(Self {
file,
active_context,
dirty: meta.dirty,
extent_number,
extent_size: def.extent_size(),
layout: RawLayout::new(def.extent_size()),
context_slot_dirty: vec![0; def.extent_size().value as usize],
extra_syscall_count: 0,
extra_syscall_denominator: 0,
})
}
fn set_dirty(&mut self) -> Result<(), CrucibleError> {
if !self.dirty {
self.layout.set_dirty(&self.file)?;
self.dirty = true;
}
Ok(())
}
/// Updates `self.active_context[block]` based on data read from the file
///
/// This returns an error if neither context slot matches the block data,
/// which should never happen (even during error conditions or after a
/// crash).
///
/// We expect to call this function rarely, so it does not attempt to
/// minimize the number of syscalls it executes.
fn recompute_slot_from_file(
&mut self,
block: u64,
) -> Result<(), CrucibleError> {
// Read the block data itself:
let block_size = self.extent_size.block_size_in_bytes();
let mut buf = vec![0; block_size as usize];
pread_all(
self.file.as_fd(),
&mut buf,
(block_size as u64 * block) as i64,
)
.map_err(|e| {
CrucibleError::IoError(format!(
"extent {}: reading block {block} data failed: {e}",
self.extent_number
))
})?;
let hash = integrity_hash(&[&buf]);
// Then, read the slot data and decide if either slot
// (1) is present and
// (2) has a matching hash
let mut matching_slot = None;
let mut empty_slot = None;
for slot in [ContextSlot::A, ContextSlot::B] {
// Read a single context slot, which is by definition contiguous
let mut context = self
.layout
.read_context_slots_contiguous(&self.file, block, 1, slot)?;
assert_eq!(context.len(), 1);
let context = context.pop().unwrap();
if let Some(context) = context {
if context.on_disk_hash == hash {
matching_slot = Some(slot);
}
} else if empty_slot.is_none() {
empty_slot = Some(slot);
}
}
let value = matching_slot
.or(empty_slot)
.ok_or(CrucibleError::MissingContextSlot(block))?;
self.active_context[block as usize] = value;
Ok(())
}
fn set_block_contexts(
&mut self,
block_contexts: &[DownstairsBlockContext],
) -> Result<(), CrucibleError> {
// If any of these block contexts will be overwriting an unsynched
// context slot, then we insert a sync here.
let needs_sync = block_contexts.iter().any(|block_context| {
let block = block_context.block as usize;
// We'll be writing to the inactive slot
let slot = !self.active_context[block];
(self.context_slot_dirty[block] & (1 << slot as usize)) != 0
});
if needs_sync {
self.file.sync_all().map_err(|e| {
CrucibleError::IoError(format!(
"extent {}: fsync 1 failure: {e}",
self.extent_number,
))
})?;
self.context_slot_dirty.fill(0);
}
// Mark the to-be-written slots as unsynched on disk
//
// It's harmless if we bail out before writing the actual context slot
// here, because all it will do is force a sync next time this is called
// (that sync is right above here!)
for block_context in block_contexts {
let block = block_context.block as usize;
let slot = !self.active_context[block];
self.context_slot_dirty[block] |= 1 << (slot as usize);
}
let mut start = 0;
let mut write_count = 0;
for i in 0..block_contexts.len() {
if i + 1 == block_contexts.len()
|| block_contexts[i].block + 1 != block_contexts[i + 1].block
{
write_count += self.set_block_contexts_contiguous(
&block_contexts[start..=i],
)?;
start = i + 1;
}
}
cdt::extent__set__block__contexts__write__count!(|| (
self.extent_number.0,
write_count,
));
Ok(())
}
/// Efficiently sets block contexts in bulk
///
/// Returns the number of writes, for profiling
///
/// # Panics
/// `block_contexts` must represent a contiguous set of blocks
fn set_block_contexts_contiguous(
&mut self,
block_contexts: &[DownstairsBlockContext],
) -> Result<u64, CrucibleError> {
for (a, b) in block_contexts.iter().zip(block_contexts.iter().skip(1)) {
assert_eq!(a.block + 1, b.block, "blocks must be contiguous");
}
let mut writes = 0u64;
for (slot, group) in block_contexts
.iter()
.group_by(|block_context| {
// We'll be writing to the inactive slot
!self.active_context[block_context.block as usize]
})
.into_iter()
{
let mut group = group.peekable();
let start = group.peek().unwrap().block;
self.layout.write_context_slots_contiguous(
&self.file,
start,
group.map(Option::Some),
slot,
)?;
writes += 1;
}
if let Some(writes) = writes.checked_sub(1) {
self.extra_syscall_count += writes;
self.extra_syscall_denominator += 1;
}
Ok(writes)
}
fn get_metadata(&self) -> Result<OnDiskMeta, CrucibleError> {
self.layout.get_metadata(&self.file)
}
/// Update the flush number, generation number, and clear the dirty bit
fn set_flush_number(
&mut self,
new_flush: u64,
new_gen: u64,
) -> Result<(), CrucibleError> {
self.layout.write_active_context_and_metadata(
&self.file,
&self.active_context,
false, // dirty
new_flush,
new_gen,
)?;
self.dirty = false;
Ok(())
}
/// Returns the valid block contexts (or `None`) for the given block range
fn get_block_contexts(
&mut self,
block: u64,
count: u64,
) -> Result<Vec<Option<DownstairsBlockContext>>, CrucibleError> {
self.get_block_contexts_inner(block, count, |ctx, block| {
ctx.map(|c| DownstairsBlockContext {
block,
block_context: c.block_context,
on_disk_hash: c.on_disk_hash,
})
})
}
/// Maps a function across block contexts, return a `Vec<T>`
fn get_block_contexts_inner<F, T>(
&mut self,
block: u64,
count: u64,
f: F,
) -> Result<Vec<T>, CrucibleError>
where
F: Fn(Option<OnDiskDownstairsBlockContext>, u64) -> T,
{
let mut out = Vec::with_capacity(count as usize);
let mut reads = 0u64;
for (slot, group) in (block..block + count)
.group_by(|block| self.active_context[*block as usize])
.into_iter()
{
let mut group = group.peekable();
let start = *group.peek().unwrap();
let count = group.count();
self.layout.read_context_slots_contiguous_inner(
&self.file,
start,
count as u64,
slot,
&f,
&mut out,
)?;
reads += 1;
}
if let Some(reads) = reads.checked_sub(1) {
self.extra_syscall_count += reads;
self.extra_syscall_denominator += 1;
}
Ok(out)
}
fn write_inner(
&self,
write: &ExtentWrite,
writes_to_skip: &HashSet<usize>,
) -> Result<(), CrucibleError> {
// Perform writes, which may be broken up by skipped blocks
let block_size = self.extent_size.block_size_in_bytes() as u64;
for (skip, mut group) in (0..write.block_contexts.len())
.group_by(|i| writes_to_skip.contains(i))
.into_iter()
{
if skip {
continue;
}
let start = group.next().unwrap();
let count = group.count() + 1;
let data = &write.data[start * block_size as usize..]
[..count * block_size as usize];
let start_block = write.offset.0 + start as u64;
pwrite_all(
self.file.as_fd(),
data,
(start_block * block_size) as i64,
)
.map_err(|e| CrucibleError::IoError(e.to_string()))?;
}
Ok(())
}
/// Helper function to get a single block context
///
/// This is inefficient and should only be used in unit tests
#[cfg(test)]
fn get_block_context(
&mut self,
block: u64,
) -> Result<Option<DownstairsBlockContext>, CrucibleError> {
let mut out = self.get_block_contexts(block, 1)?;
assert_eq!(out.len(), 1);
Ok(out.pop().unwrap())
}
/// Consolidates context slots into either the A or B array
///
/// This must only be run directly after the file is synced to disk
fn defragment(&mut self) -> Result<(), CrucibleError> {
// At this point, the active context slots (on a per-block basis)
// may be scattered across the two arrays:
//
// block | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | ... |
// context | A | A | | | | | A | A | A | ... | [A array]
// | | | B | B | B | B | | | | ... | [B array]
//
// This can be inefficient, because it means that a write would have to
// be split into updating multiple regions (instead of a single
// contiguous write). As such, if the context slots disagree, we
// "defragment" them:
//
// - Figure out whether A or B is more popular
// - Copy context data from the less-popular slot to the more-popular
//