-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathpage.rs
More file actions
2584 lines (2248 loc) · 106 KB
/
Copy pathpage.rs
File metadata and controls
2584 lines (2248 loc) · 106 KB
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
//! Provides a [`Page`] abstraction that stores rows
//! and an associated header necessary for the page to work.
//! Consult the documentation of this type for a list of operations
//! and a description of how page work.
//!
//! A page can provide a split mutable view of its fixed section and its variable section.
//! This is provided through [`Page::split_fixed_var_mut`] with view operations
//! defined on [`FixedView`] and [`VarView`].
//!
//! [ralfj_safe_valid]: https://www.ralfj.de/blog/2018/08/22/two-kinds-of-invariants.html
//!
//! Technical terms:
//!
//! - `valid` refers to, when referring to a type, granule, or row,
//! depending on the context, a memory location that holds a *safe* object.
//! When "valid for writes" is used, the location must be properly aligned
//! and none of its bytes may be uninit,
//! but the value need not be valid at the type in question.
//! "Valid for writes" is equivalent to valid-unconstrained.
//!
//! - `valid-unconstrained`, when referring to a memory location with a given type,
//! that the location stores a byte pattern which Rust/LLVM's memory model recognizes as valid,
//! and therefore must not contain any uninit,
//! but the value is not required to be logically meaningful,
//! and no code may depend on the data within it to uphold any invariants.
//! E.g. an unallocated [`VarLenGranule`] within a page stores valid-unconstrained bytes,
//! because the bytes are either 0 from the initial [`alloc_zeroed`] of the page,
//! or contain stale data from a previously freed [`VarLenGranule`].
//!
//! - `unused` means that it is safe to overwrite a block of memory without cleaning up its previous value.
//!
//! See the post [Two Kinds of Invariants: Safety and Validity][ralf_safe_valid]
//! for a discussion on safety and validity invariants.
use super::{
blob_store::{BlobHash, BlobStore},
fixed_bit_set::FixedBitSet,
fixed_bit_set::IterSet,
indexes::{max_rows_in_page, Byte, Bytes, PageOffset, PAGE_HEADER_SIZE, PAGE_SIZE},
static_assert_size,
table::BlobNumBytes,
var_len::{is_granule_offset_aligned, VarLenGranule, VarLenGranuleHeader, VarLenMembers, VarLenRef},
};
use core::{mem, ops::ControlFlow};
use spacetimedb_sats::layout::{Size, MIN_ROW_SIZE};
use spacetimedb_sats::memory_usage::MemoryUsage;
use spacetimedb_sats::{de::Deserialize, ser::Serialize};
use thiserror::Error;
#[derive(Error, Debug, PartialEq, Eq)]
pub enum Error {
#[error("Want to allocate a var-len object of {need} granules, but have only {have} granules available")]
InsufficientVarLenSpace { need: u16, have: u16 },
#[error("Want to allocate a fixed-len row of {} bytes, but the page is full", need.len())]
InsufficientFixedLenSpace { need: Size },
}
/// A cons-cell in a freelist either
/// for an unused fixed-len cell or a variable-length granule.
#[repr(C)] // Required for a stable ABI.
#[derive(Clone, Copy, Debug, PartialEq, Eq, bytemuck::NoUninit, Serialize, Deserialize)]
struct FreeCellRef {
/// The address of the next free cell in a freelist.
///
/// The `PageOffset::PAGE_END` is used as a sentinel to signal "`None`".
next: PageOffset,
}
impl MemoryUsage for FreeCellRef {
fn heap_usage(&self) -> usize {
let Self { next } = self;
next.heap_usage()
}
}
impl FreeCellRef {
/// The sentinel for NULL cell references.
const NIL: Self = Self {
next: PageOffset::PAGE_END,
};
/// Replaces the cell reference with `offset`, returning the existing one.
#[inline]
fn replace(&mut self, offset: PageOffset) -> FreeCellRef {
let next = mem::replace(&mut self.next, offset);
Self { next }
}
/// Returns whether the cell reference is non-empty.
#[inline]
const fn has(&self) -> bool {
!self.next.is_at_end()
}
/// Take the first free cell in the freelist starting with `self`, if any,
/// and promote the second free cell as the freelist head.
///
/// # Safety
///
/// When `self.has()`, it must point to a valid `FreeCellRef`.
#[inline]
unsafe fn take_freelist_head(
self: &mut FreeCellRef,
row_data: &Bytes,
adjust_free: impl FnOnce(PageOffset) -> PageOffset,
) -> Option<PageOffset> {
self.has().then(|| {
let head = adjust_free(self.next);
// SAFETY: `self.next` so `head` points to a valid `FreeCellRef`.
let next = unsafe { get_ref(row_data, head) };
self.replace(*next).next
})
}
/// Prepend `new_head` to the freelist starting with `self`.
///
/// SAFETY: `new_head`, after adjustment, must be in bounds of `row_data`.
/// Moreover, it must be valid for writing a `FreeCellRef` to it,
/// which includes being properly aligned with respect to `row_data` for a `FreeCellRef`.
/// Additionally, `self` must contain a valid `FreeCellRef`.
#[inline]
unsafe fn prepend_freelist(
self: &mut FreeCellRef,
row_data: &mut Bytes,
new_head: PageOffset,
adjust_free: impl FnOnce(PageOffset) -> PageOffset,
) {
let next = self.replace(new_head);
let new_head = adjust_free(new_head);
// SAFETY: Per caller contract, `new_head` is in bounds of `row_data`.
// Moreover, `new_head` points to an unused `FreeCellRef`, so we can write to it.
let next_slot: &mut FreeCellRef = unsafe { get_mut(row_data, new_head) };
*next_slot = next;
}
}
/// All the fixed size header information.
#[repr(C)] // Required for a stable ABI.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] // So we can dump and restore pages during snapshotting.
struct FixedHeader {
/// A pointer to the head of the freelist which stores
/// all the unused (freed) fixed row cells.
/// These cells can be reused when inserting a new row.
next_free: FreeCellRef,
/// High water mark (HWM) for fixed-length rows.
/// Points one past the last-allocated (highest-indexed) fixed-length row,
/// so to allocate a fixed-length row from the gap,
/// post-increment this index.
// TODO(perf,future-work): determine how to lower the high water mark when freeing the topmost row.
last: PageOffset,
/// The number of rows currently in the page.
///
/// N.B. this is not the same as `self.present_rows.len()`
/// as that counts both zero and one bits.
num_rows: u16,
// TODO(stable-module-abi): should this be inlined into the page?
/// For each fixed-length row slot, true if a row is stored there,
/// false if the slot is unallocated.
///
/// Unallocated row slots store valid-unconstrained bytes, i.e. are never uninit.
present_rows: FixedBitSet,
}
impl MemoryUsage for FixedHeader {
fn heap_usage(&self) -> usize {
let Self {
next_free,
last,
num_rows,
present_rows,
} = self;
next_free.heap_usage() + last.heap_usage() + num_rows.heap_usage() + present_rows.heap_usage()
}
}
static_assert_size!(FixedHeader, 16);
impl FixedHeader {
/// Returns a new `FixedHeader`
/// using the provided `max_rows_in_page` to decide how many rows `present_rows` can represent.
#[inline]
fn new(max_rows_in_page: usize) -> Self {
Self {
next_free: FreeCellRef::NIL,
// Points one after the last allocated fixed-length row, or `NULL` for an empty page.
last: PageOffset::VAR_LEN_NULL,
num_rows: 0,
present_rows: FixedBitSet::new(max_rows_in_page),
}
}
/// Set the (fixed) row starting at `offset`
/// and lasting `fixed_row_size` as `present`.
#[inline]
fn set_row_present(&mut self, offset: PageOffset, fixed_row_size: Size) {
self.set_row_presence(offset, fixed_row_size, true);
self.num_rows += 1;
}
/// Sets whether the (fixed) row starting at `offset`
/// and lasting `fixed_row_size` is `present` or not.
#[inline]
fn set_row_presence(&mut self, offset: PageOffset, fixed_row_size: Size, present: bool) {
self.present_rows.set(offset / fixed_row_size, present);
}
/// Returns whether the (fixed) row starting at `offset`
/// and lasting `fixed_row_size` is present or not.
#[inline]
fn is_row_present(&self, offset: PageOffset, fixed_row_size: Size) -> bool {
self.present_rows.get(offset / fixed_row_size)
}
/// Resets the header information to its state
/// when it was first created in [`FixedHeader::new`]
/// but with `max_rows_in_page` instead of the value passed on creation.
fn reset_for(&mut self, max_rows_in_page: usize) {
self.next_free = FreeCellRef::NIL;
self.last = PageOffset::VAR_LEN_NULL;
self.num_rows = 0;
self.present_rows.reset_for(max_rows_in_page);
}
/// Resets the header information to its state
/// when it was first created in [`FixedHeader::new`].
///
/// The header is only good for the original row size.
#[inline]
fn clear(&mut self) {
self.next_free = FreeCellRef::NIL;
self.last = PageOffset::VAR_LEN_NULL;
self.num_rows = 0;
self.present_rows.clear();
}
}
/// All the var-len header information.
#[repr(C)] // Required for a stable ABI.
#[derive(bytemuck::NoUninit, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct VarHeader {
/// A pointer to the head of the freelist which stores
/// all the unused (freed) var-len granules.
/// These cells can be reused when inserting a new row.
next_free: FreeCellRef,
/// The length of the freelist with its head referred to by `next_free`.
/// Stored in units of var-len nodes.
///
/// This field is redundant,
/// as it can be recovered by traversing `next_free`.
/// However, traversing this linked-list is not cache friendly,
/// so we memoize the computation here.
freelist_len: u16,
/// High water mark (HWM) for var-len granules.
/// Points to the last-allocated (lowest-indexed) var-len granule,
/// so to allocate a var-len granule from the gap,
/// pre-decrement this index.
// TODO(perf,future-work): determine how to "lower" the high water mark when freeing the "top"-most granule.
first: PageOffset,
/// The number of granules currently used by rows within this page.
///
/// [`Page::bytes_used_by_rows`] needs this information.
/// Stored here because otherwise counting it would require traversing all the present rows.
num_granules: u16,
}
impl MemoryUsage for VarHeader {
fn heap_usage(&self) -> usize {
let Self {
next_free,
freelist_len,
first,
num_granules,
} = self;
next_free.heap_usage() + freelist_len.heap_usage() + first.heap_usage() + num_granules.heap_usage()
}
}
static_assert_size!(VarHeader, 8);
impl Default for VarHeader {
fn default() -> Self {
Self {
next_free: FreeCellRef::NIL,
freelist_len: 0,
first: PageOffset::PAGE_END,
num_granules: 0,
}
}
}
impl VarHeader {
/// Resets the header information to its state
/// when it was first created in [`VarHeader::default`].
fn clear(&mut self) {
*self = Self::default();
}
}
/// The metadata / header of a page that is necessary
/// for modifying and interpreting the `row_data`.
///
/// This header info is split into a header for the fixed part
/// and one for the variable part.
/// The header is stored in the same heap allocation as the `row_data`
/// as the whole [`Page`] is `Box`ed.
#[repr(C)] // Required for a stable ABI.
#[repr(align(64))] // Alignment must be same as `VarLenGranule::SIZE`.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] // So we can dump and restore pages during snapshotting.
pub(super) struct PageHeader {
/// The header data relating to the fixed component of a row.
fixed: FixedHeader,
/// The header data relating to the var-len component of a row.
var: VarHeader,
/// The content-addressed hash of the page on disk,
/// if unmodified since the last snapshot,
/// and `None` otherwise.
///
/// This means that modifications to the page always sets this field to `None`.
unmodified_hash: Option<blake3::Hash>,
}
impl MemoryUsage for PageHeader {
fn heap_usage(&self) -> usize {
let Self {
fixed,
var,
// MEMUSE: no allocation, ok to ignore
unmodified_hash: _,
} = self;
fixed.heap_usage() + var.heap_usage()
}
}
static_assert_size!(PageHeader, PAGE_HEADER_SIZE);
impl PageHeader {
/// Returns a new `PageHeader` proper a [`Page`] for holding at most `max_rows_in_page` rows.
fn new(max_rows_in_page: usize) -> Self {
Self {
fixed: FixedHeader::new(max_rows_in_page),
var: VarHeader::default(),
unmodified_hash: None,
}
}
/// Resets the header information to its state
/// when it was first created in [`PageHeader::new`]
/// but with `max_rows_in_page` instead of the value passed on creation.
fn reset_for(&mut self, max_rows_in_page: usize) {
self.fixed.reset_for(max_rows_in_page);
self.var.clear();
self.unmodified_hash = None;
}
/// Resets the header information to its state
/// when it was first created in [`PageHeader::new`].
///
/// The header is only good for the original row size.
fn clear(&mut self) {
self.fixed.clear();
self.var.clear();
self.unmodified_hash = None;
}
/// Returns the maximum number of rows the page can hold.
///
/// Note that this number can be bigger
/// than the value provided in [`Self::new`] due to rounding up.
pub(super) fn max_rows_in_page(&self) -> usize {
self.fixed.present_rows.bits()
}
/// Returns a pointer to the `present_rows` bitset.
/// This is exposed for testing only.
#[cfg(test)]
pub(super) fn present_rows_storage_ptr_for_test(&self) -> *const () {
self.fixed.present_rows.storage().as_ptr().cast()
}
/// Returns the number of var-len granules available for allocation,
/// including those in the "gap" between the fixed-len and var-len part of the page.
fn available_var_len_granules(&self) -> usize {
self.var.freelist_len as usize
+ VarLenGranule::space_to_granules(gap_remaining_size(self.var.first, self.fixed.last))
}
}
/// Fixed-length row portions must be at least large enough to store a `FreeCellRef`.
const _MIN_ROW_SIZE_CAN_STORE_FCR: () = assert!(MIN_ROW_SIZE.len() >= mem::size_of::<FreeCellRef>());
/// [`VarLenGranule`]s must be at least large enough to store a [`FreeCellRef`].
const _VLG_CAN_STORE_FCR: () = assert!(VarLenGranule::SIZE.len() >= MIN_ROW_SIZE.len());
/// Pointers properly aligned for a [`VarLenGranule`] must be properly aligned for [`FreeCellRef`].
/// This is the case as the former's alignment is a multiple of the latter's alignment.
const _VLG_ALIGN_MULTIPLE_OF_FCR: () =
assert!(mem::align_of::<VarLenGranule>().is_multiple_of(mem::align_of::<FreeCellRef>()));
/// The actual row data of a [`Page`].
type RowData = [Byte; PageOffset::PAGE_END.idx()];
/// A page of row data with an associated `header` and the raw `row_data` itself.
///
/// As a rough summary, the strategy employed by this page is:
///
/// - The fixed-len parts of rows grows left-to-right
/// and starts from the beginning of the `row_data`
/// until its high water mark (fixed HWM), i.e., `self.header.fixed.last`.
///
/// - The var-len parts of rows grows right-to-left
/// and starts from the end of the `row_data`
/// until its high water mark (variable HWM), i.e., `self.header.var.first`.
///
/// Each var-len object is stored in terms of a linked-list of chunks.
/// Each chunk in this case is a [`VarLenGranule`] taking up 64 bytes where:
/// - 6 bits = length, 10 bits = next-cell-pointer
/// - 62 bytes = the bytes of the object
///
/// - As new rows are added, the HWMs move appropriately.
/// When the fixed and variable HWMs meet, the page is full.
///
/// - When rows are freed, a freelist strategy is used both for
/// the fixed parts and each `VarLenGranule`.
/// These freelists are then used first before using space from the gap.
/// The head of these freelists are stored in `next_free`
/// in the fixed and variable headers respectively.
///
/// - As the fixed parts of rows may store pointers into the var-length section,
/// to ensure that these pointers aren't dangling,
/// the page uses pointer fixups when adding to, deleting from, and copying the page.
/// These fixups are handled by having callers provide `VarLenMembers`
/// to find the var-len reference slots in the fixed parts.
#[repr(C)]
// ^-- Required for a stable ABI.
#[repr(align(64))]
// ^-- Must have align at least that of `VarLenGranule`,
// so that `row_data[PageOffset::PAGE_END - VarLenGranule::SIZE]` is an aligned pointer to `VarLenGranule`.
// TODO(bikeshedding): consider raising the alignment. We may want this to be OS page (4096) aligned.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] // So we can dump and restore pages during snapshotting.
pub struct Page {
/// The header containing metadata on how to interpret and modify the `row_data`.
header: PageHeader,
/// The actual bytes stored in the page.
/// This contains row data, fixed and variable, and freelists.
row_data: RowData,
}
impl MemoryUsage for Page {
fn heap_usage(&self) -> usize {
self.header.heap_usage()
}
}
static_assert_size!(Page, PAGE_SIZE);
/// A mutable view of the fixed-len section of a [`Page`].
pub struct FixedView<'page> {
/// A mutable view of the fixed-len bytes.
fixed_row_data: &'page mut Bytes,
/// A mutable view of the fixed header.
header: &'page mut FixedHeader,
}
impl FixedView<'_> {
/// Returns a mutable view of the row from `start` lasting `fixed_row_size` number of bytes.
///
/// This method is safe, but callers should take care that `start` and `fixed_row_size`
/// are correct for this page, and that `start` is aligned.
/// Callers should further ensure that mutations to the row leave the row bytes
/// in an expected state, i.e. initialized where required by the row type,
/// and with `VarLenRef`s that point to valid granules and with correct lengths.
pub fn get_row_mut(&mut self, start: PageOffset, fixed_row_size: Size) -> &mut Bytes {
&mut self.fixed_row_data[start.range(fixed_row_size)]
}
/// Returns a shared view of the row from `start` lasting `fixed_row_size` number of bytes.
fn get_row(&mut self, start: PageOffset, fixed_row_size: Size) -> &Bytes {
&self.fixed_row_data[start.range(fixed_row_size)]
}
/// Frees the row starting at `row_offset` and lasting `fixed_row_size` bytes.
///
/// # Safety
///
/// `range_move(0..fixed_row_size, row_offset)` must be in bounds of `row_data`.
/// Moreover, it must be valid for writing a `FreeCellRef` to it,
/// which includes being properly aligned with respect to `row_data` for a `FreeCellRef`.
pub unsafe fn free(&mut self, row_offset: PageOffset, fixed_row_size: Size) {
// TODO(perf,future-work): if `row` is at the HWM, return it to the gap.
// SAFETY: Per caller contract, `row_offset` must be in bounds of `row_data`.
// Moreover, it must be valid for writing a `FreeCellRef` to it,
// which includes being properly aligned with respect to `row_data` for a `FreeCellRef`.
// We also know that `self.header.next_free` contains a valid `FreeCellRef`.
unsafe {
self.header
.next_free
.prepend_freelist(self.fixed_row_data, row_offset, |x| x)
};
self.header.num_rows -= 1;
self.header.set_row_presence(row_offset, fixed_row_size, false);
}
}
/// A mutable view of the var-len section of a [`Page`].
pub struct VarView<'page> {
/// A mutable view of the var-len bytes.
var_row_data: &'page mut Bytes,
/// A mutable view of the var-len header.
header: &'page mut VarHeader,
/// One past the end of the fixed-len section of the page.
last_fixed: PageOffset,
}
impl<'page> VarView<'page> {
/// Returns the number of granules required to store the data,
/// whether the page has enough space,
/// and whether the object needs to go in the blob store.
///
/// If the third value is `true`, i.e., the object will go in the blob store,
/// the first value will always be `1`.
fn has_enough_space_for(&self, len_in_bytes: usize) -> (usize, bool, bool) {
let (num_granules_req, in_blob) = VarLenGranule::bytes_to_granules(len_in_bytes);
let enough_space = num_granules_req <= self.num_granules_available();
(num_granules_req, enough_space, in_blob)
}
/// Returns the number of granules available for allocation.
fn num_granules_available(&self) -> usize {
self.header.freelist_len as usize
+ VarLenGranule::space_to_granules(gap_remaining_size(self.header.first, self.last_fixed))
}
/// Provides an adjuster of offset in terms of `Page::row_data`
/// to work in terms of `VarView::var_row_data`.
///
/// This has to be done due to `page.row_data.split_at_mut(last_fixed)`.
#[inline(always)]
fn adjuster(&self) -> impl FnOnce(PageOffset) -> PageOffset + use<> {
let lf = self.last_fixed;
move |offset| offset - lf
}
/// Allocates a linked-list of granules, in the var-len storage of the page,
/// for a var-len object of `obj_len` bytes.
///
/// Returns a [`VarLenRef`] pointing to the head of that list,
/// and a boolean `in_blob` for whether the allocation is a `BlobHash`
/// and the object must be inserted into the large-blob store.
///
/// The length of each granule is set, but no data is written to any granule.
/// Thus, the caller must proceed to write data to each granule for the claimed lengths.
///
/// # Safety post-requirements
///
/// The following are the safety *post-requirements* of calling this method.
/// That is, this method is safe to call,
/// but may leave the page in an inconsistent state
/// which must be rectified before other **unsafe methods** may be called.
///
/// 1. When the returned `in_blob` holds, caller must ensure that,
/// before the granule's data is read from / assumed to be initialized,
/// the granule pointed to by the returned `vlr.first_granule`
/// has an initialized header and a data section initialized to at least
/// as many bytes as claimed by the header.
///
/// 2. The caller must initialize each granule with data for the claimed length
/// of the granule's data.
pub fn alloc_for_len(&mut self, obj_len: usize) -> Result<(VarLenRef, bool), Error> {
// Safety post-requirements of `alloc_for_obj_common`:
// 1. caller promised they will be satisfied.
// 2a. already satisfied as the closure below returns all the summands of `obj_len`.
// 2b. caller promised in 2. that they will satisfy this.
self.alloc_for_obj_common(obj_len, |req_granules| {
let rem = obj_len % VarLenGranule::DATA_SIZE;
(0..req_granules).map(move |rev_idx| {
let len = if rev_idx == 0 && rem != 0 {
// The first allocated granule will be the last in the list.
// Thus, `rev_idx == 0` is the last element and might not take up a full granule.
rem
} else {
VarLenGranule::DATA_SIZE
};
// Caller will initialize the granule's data for `len` bytes.
(<&[u8]>::default(), len)
})
})
}
/// Returns an iterator over all offsets of the `VarLenGranule`s of the var-len object
/// that has its first granule at offset `first_granule`.
/// An empty iterator will be returned when `first_granule` is `NULL`.
///
/// # Safety
///
/// `first_granule` must be an offset to a granule or `NULL`.
/// The data of the granule need not be initialized.
pub unsafe fn granule_offset_iter(&mut self, first_granule: PageOffset) -> GranuleOffsetIter<'_, 'page> {
GranuleOffsetIter {
next_granule: first_granule,
var_view: self,
}
}
/// Allocates and stores `slice` as a linked-list of granules
/// in the var-len storage of the page.
///
/// Returns a [`VarLenRef`] pointing to the head of that list,
/// and a boolean `in_blob` for whether the allocation is a `BlobHash`
/// and the `slice` must be inserted into the large-blob store.
///
/// # Safety post-requirements
///
/// The following are the safety *post-requirements* of calling this method.
/// That is, this method is safe to call,
/// but may leave the page in an inconsistent state
/// which must be rectified before other **unsafe methods** may be called.
///
/// 1. When the returned `in_blob` holds, caller must ensure that,
/// before the granule's data is read from / assumed to be initialized,
/// the granule pointed to by the returned `vlr.first_granule`
/// has an initialized header and a data section initialized to at least
/// as many bytes as claimed by the header.
pub fn alloc_for_slice(&mut self, slice: &[u8]) -> Result<(VarLenRef, bool), Error> {
let obj_len = slice.len();
// Safety post-requirement 2. of `alloc_for_obj_common` is already satisfied
// as `chunks(slice)` will return sub-slices where the sum is `obj_len`.
// Moreover, we initialize each granule already with the right data and length.
// The requirement 1. is forwarded to the caller.
let chunks = |_| VarLenGranule::chunks(slice).rev().map(|c| (c, c.len()));
self.alloc_for_obj_common(obj_len, chunks)
}
/// Allocates for `obj_len` bytes as a linked-list of granules
/// in the var-len storage of the page.
///
/// For every granule in the aforementioned linked-list,
/// the caller must provide an element in the *reversed* iterator `chunks`,
/// and of pairs `(chunk, len)`.
/// To each granule `chunk` will be written and the granule will be of length `len`.
/// The caller can opt to provide `chunk` that is not of `len`.
///
/// Returns a [`VarLenRef`] pointing to the head of that list,
/// and a boolean `in_blob` for whether the allocation is a `BlobHash`
/// and the `slice` must be inserted into the large-blob store.
///
/// # Safety post-requirements
///
/// The following are the safety *post-requirements* of calling this method.
/// That is, this method is safe to call,
/// but may leave the page in an inconsistent state
/// which must be rectified before other **unsafe methods** may be called.
///
/// 1. When the returned `in_blob` holds, caller must ensure that,
/// before the granule's data is read from / assumed to be initialized,
/// the granule pointed to by the returned `vlr.first_granule`
/// has an initialized header and a data section initialized to at least
/// as many bytes as claimed by the header.
///
/// 2. Otherwise, when `in_blob` doesn't hold the safety post-requirements are:
///
/// a. Let `cs = chunks(req_granules)` for the `req_granules` derived from `obj_len`.
/// Then, `obj_len == cs.map(|(_, len)| len).sum()`.
///
/// b. For each `(_, len) ∈ cs`, caller must ensure that
/// the relevant granule is initialized with data for at least `len`
/// before the granule's data is read from / assumed to be initialized.
#[expect(clippy::doc_overindented_list_items)]
fn alloc_for_obj_common<'chunk, Cs: Iterator<Item = (&'chunk [u8], usize)>>(
&mut self,
obj_len: usize,
chunks: impl Copy + FnOnce(usize) -> Cs,
) -> Result<(VarLenRef, bool), Error> {
// Check that we have sufficient space to allocate `obj_len` bytes in var-len data.
let (req_granules, enough_space, in_blob) = self.has_enough_space_for(obj_len);
if !enough_space {
return Err(Error::InsufficientVarLenSpace {
need: req_granules.try_into().unwrap_or(u16::MAX),
have: self.num_granules_available().try_into().unwrap_or(u16::MAX),
});
}
// For large blob objects, only reserve a granule.
// The caller promised that they will initialize it with a blob hash.
if in_blob {
let vlr = self.alloc_blob_hash()?;
return Ok((vlr, true));
};
// Write each `chunk` to var-len storage.
// To do this, we allocate granules for and store the chunks in reverse,
// starting with the end first.
// The offset to the previous granule in the iteration is kept to
// link it in as the next pointer in the current iteration.
let mut next = PageOffset::VAR_LEN_NULL;
debug_assert_eq!(obj_len, chunks(req_granules).map(|(_, len)| len).sum::<usize>());
for (chunk, len) in chunks(req_granules) {
// This should never error, since we already checked for available space.
let granule = self.alloc_granule()?;
// SAFETY:
// 1. `granule` is properly aligned as it came from `alloc_granule`
// and so is `next` as it's either NULL or was the previous `granule`.
// This also ensures that both are in bounds
// of the page for `granule + granule + VarLenGranule::SIZE`.
//
// 2. `next` is either NULL or was initialized in the previous loop iteration.
//
// 3. `granule` points to an unused slot as the space was just allocated.
unsafe { self.write_chunk_to_granule(chunk, len, granule, next) };
next = granule;
}
Ok((
VarLenRef {
first_granule: next,
length_in_bytes: obj_len as u16,
},
false,
))
}
/// Allocates a granule for a large blob object
/// and returns a [`VarLenRef`] pointing to that granule.
///
/// The granule is not initialized by this method, and contains valid-unconstrained bytes.
/// It is the caller's responsibility to initialize it with a [`BlobHash`](super::blob_hash::BlobHash).
#[cold]
fn alloc_blob_hash(&mut self) -> Result<VarLenRef, Error> {
// Var-len hashes are 32 bytes, which fits within a single granule.
self.alloc_granule().map(VarLenRef::large_blob)
}
/// Inserts `var_len_obj` into `blob_store`
/// and stores the blob hash in the granule pointed to by `vlr.first_granule`.
///
/// This insertion will never fail.
///
/// # Safety
///
/// `vlr.first_granule` must point to an unused `VarLenGranule` in bounds of this page,
/// which must be valid for writes.
pub unsafe fn write_large_blob_hash_to_granule(
&mut self,
blob_store: &mut dyn BlobStore,
var_len_obj: &impl AsRef<[u8]>,
vlr: VarLenRef,
) -> BlobNumBytes {
let hash = blob_store.insert_blob(var_len_obj.as_ref());
let granule = vlr.first_granule;
// SAFETY:
// 1. `granule` is properly aligned for `VarLenGranule` and is in bounds of the page.
// 2. The null granule is trivially initialized.
// 3. The caller promised that `granule` is safe to overwrite.
unsafe { self.write_chunk_to_granule(&hash.data, hash.data.len(), granule, PageOffset::VAR_LEN_NULL) };
var_len_obj.as_ref().len().into()
}
/// Write the `chunk` (data) to the [`VarLenGranule`] pointed to by `granule`,
/// set the granule's length to be `len`,
/// and set the next granule in the list to `next`.
///
/// SAFETY:
///
/// 1. Both `granule` and `next` must be properly aligned pointers to [`VarLenGranule`]s
/// and they must be in bounds of the page. However, neither need to point to init data.
///
/// 2. The caller must initialize the granule pointed to by `next`
/// before the granule-list is read from (e.g., iterated on).
/// The null granule is considered trivially initialized.
///
/// 3. The space pointed to by `granule` must be unused and valid for writes,
/// and will be overwritten here.
unsafe fn write_chunk_to_granule(&mut self, chunk: &[u8], len: usize, granule: PageOffset, next: PageOffset) {
let granule = self.adjuster()(granule);
// SAFETY: A `PageOffset` is always in bounds of the page.
let ptr: *mut VarLenGranule = unsafe { offset_to_ptr_mut(self.var_row_data, granule).cast() };
// TODO(centril,bikeshedding): check if creating the `VarLenGranule` first on stack
// and then writing to `ptr` would have any impact on perf.
// This would be nicer as it requires less `unsafe`.
// We need to initialize `Page::header`
// without materializing a `&mut` as that is instant UB.
// SAFETY: `ptr` isn't NULL as `&mut self.row_data` itself is a non-null pointer.
let header = unsafe { &raw mut (*ptr).header };
// SAFETY: `header` is valid for writes as only we have exclusive access.
// (1) The `ptr` was also promised as aligned
// and `granule + (granule + 64 bytes)` is in bounds of the page per caller contract.
// (2) Moreover, `next` will be an initialized granule per caller contract,
// so we can link it into the list without causing UB elsewhere.
// (3) It's also OK to write to `granule` as it's unused.
unsafe {
header.write(VarLenGranuleHeader::new(len as u8, next));
}
// SAFETY: We can treat any part of `row_data` as `.data`. Also (1) and (2).
let data = unsafe { &mut (*ptr).data };
// Copy the data into the granule.
data[0..chunk.len()].copy_from_slice(chunk);
}
/// Allocate a [`VarLenGranule`] at the returned [`PageOffset`].
///
/// The allocated storage is not initialized by this method,
/// and will be valid-unconstrained at [`VarLenGranule`].
///
/// This offset will be properly aligned for `VarLenGranule` when converted to a pointer.
///
/// Returns an error when there are neither free granules nor space in the gap left.
fn alloc_granule(&mut self) -> Result<PageOffset, Error> {
let granule = self
.alloc_from_freelist()
.or_else(|| self.alloc_from_gap())
.ok_or(Error::InsufficientVarLenSpace { need: 1, have: 0 })?;
debug_assert!(
is_granule_offset_aligned(granule),
"Allocated an unaligned var-len granule: {granule:x}",
);
self.header.num_granules += 1;
Ok(granule)
}
/// Allocate a [`VarLenGranule`] at the returned [`PageOffset`]
/// taken from the freelist, if any.
#[inline]
fn alloc_from_freelist(&mut self) -> Option<PageOffset> {
// SAFETY: `header.next_free` points to a `c: FreeCellRef` when the former `.has()`.
let free = unsafe {
self.header
.next_free
.take_freelist_head(self.var_row_data, |o| o - self.last_fixed)
}?;
self.header.freelist_len -= 1;
Some(free)
}
/// Allocate a [`VarLenGranule`] at the returned [`PageOffset`]
/// taken from the gap, if there is space left, or `None` if there is insufficient space.
#[inline]
fn alloc_from_gap(&mut self) -> Option<PageOffset> {
if gap_enough_size_for_row(self.header.first, self.last_fixed, VarLenGranule::SIZE) {
// `var.first` points *at* the lowest-indexed var-len granule,
// *not* before it, so pre-decrement.
self.header.first -= VarLenGranule::SIZE;
Some(self.header.first)
} else {
None
}
}
/// Free a single var-len granule pointed to at by `offset`.
///
/// SAFETY: `offset` must point to a valid [`VarLenGranule`].
#[inline]
unsafe fn free_granule(&mut self, offset: PageOffset) {
// TODO(perf,future-work): if `chunk` is at the HWM, return it to the gap.
// Returning a single chunk to the gap is easy,
// but we want to return a whole "run" of sequential freed chunks,
// which requires some bookkeeping (or an O(> n) linked list traversal).
self.header.freelist_len += 1;
self.header.num_granules -= 1;
let adjuster = self.adjuster();
// SAFETY: Per caller contract, `offset` is a valid `VarLenGranule`,
// and is therefore in bounds of the page row data.
// By `_VLG_CAN_STORE_FCR`, and as we won't be reading from the granule anymore,
// we know that this makes it valid for writing a `FreeCellRef` to it.
// Moreover, by `_VLG_ALIGN_MULTIPLE_OF_FCR`,
// the derived pointer is properly aligned (64) for a granule
// and as `64 % 2 == 0` the alignment of a granule works for a `FreeCellRef`.
// Finally, `self.header.next_free` contains a valid `FreeCellRef`.
unsafe {
self.header
.next_free
.prepend_freelist(self.var_row_data, offset, adjuster)
};
}
/// Returns a reference to the granule at `offset`.
///
/// SAFETY: `offset` must point to a valid [`VarLenGranule`].
unsafe fn get_granule_ref(&self, offset: PageOffset) -> &VarLenGranule {
unsafe { get_ref(self.var_row_data, self.adjuster()(offset)) }
}
/// Frees the blob pointed to by the [`BlobHash`] stored in the granule at `offset`.
///
/// Panics when `offset` is NULL.
///
/// SAFETY: `offset` must point to a valid [`VarLenGranule`] or be NULL.
#[cold]
#[inline(never)]
unsafe fn free_blob(&self, offset: PageOffset, blob_store: &mut dyn BlobStore) -> BlobNumBytes {
assert!(!offset.is_var_len_null());
// SAFETY: Per caller contract + the assertion above,
// we know `offset` refers to a valid `VarLenGranule`.
let granule = unsafe { self.get_granule_ref(offset) };
// Actually free the blob.
let hash = granule.blob_hash();
// The size of `deleted_bytes` is calculated here instead of requesting it from `blob_store`.
// This is because the actual number of bytes deleted depends on the `blob_store`'s logic.
// We prefer to measure it from the datastore's point of view.
let blob_store_deleted_bytes = blob_store
.retrieve_blob(&hash)
.expect("failed to free var-len blob")
.len()
.into();
// Actually free the blob.
blob_store.free_blob(&hash).expect("failed to free var-len blob");
blob_store_deleted_bytes
}
/// Frees an entire var-len linked-list object.
///
/// If the `var_len_obj` is a large blob,
/// the `VarLenGranule` which stores its blob hash will be freed from the page,
/// but the blob itself will not be freed from the blob store.
/// If used incorrectly, this may leak large blobs.
///
/// This behavior is used to roll-back on failure in `[crate::bflatn::ser::write_av_to_page]`,
/// where inserting large blobs is deferred until all allocations succeed.
/// Freeing a fully-inserted object should instead use [`Self::free_object`].
///
/// # Safety
///
/// `var_len_obj.first_granule` must point to a valid [`VarLenGranule`] or be NULL.
pub unsafe fn free_object_ignore_blob(&mut self, var_len_obj: VarLenRef) {
let mut next_granule = var_len_obj.first_granule;
while !next_granule.is_var_len_null() {
// SAFETY: Per caller contract, `first_granule` points to a valid granule or is NULL.
// We know however at this point that it isn't NULL so it is valid.
// Thus the successor is too a valid granule or NULL.
// However, again, at this point we know that the successor isn't NULL.
// It follows then by induction that any `next_granule` at this point is valid.
// Thus we have fulfilled the requirement that `next_granule` points to a valid granule.
let header = unsafe { self.get_granule_ref(next_granule) }.header;
// SAFETY: `next_granule` still points to a valid granule per above.
unsafe {
self.free_granule(next_granule);
}
next_granule = header.next();
}
}
/// Frees an entire var-len linked-list object.
///
/// SAFETY: `var_len_obj.first_granule` must point to a valid [`VarLenGranule`] or be NULL.
unsafe fn free_object(&mut self, var_len_obj: VarLenRef, blob_store: &mut dyn BlobStore) -> BlobNumBytes {
let mut blob_store_deleted_bytes = BlobNumBytes::default();
// For large blob objects, extract the hash and tell `blob_store` to discard it.
if var_len_obj.is_large_blob() {
// SAFETY: `var_len_obj.first_granule` was promised to
// point to a valid [`VarLenGranule`] or be NULL, as required.
unsafe {
blob_store_deleted_bytes = self.free_blob(var_len_obj.first_granule, blob_store);
}
}
// SAFETY: `free_object_ignore_blob` has the same safety contract as this method.
unsafe {
self.free_object_ignore_blob(var_len_obj);
}
blob_store_deleted_bytes
}
}
/// An iterator yielding the offsets to the granules of a var-len object.
pub struct GranuleOffsetIter<'vv, 'page> {
/// Our mutable view of the page.
var_view: &'vv mut VarView<'page>,
/// The offset, that will be yielded next, pointing to next granule.
next_granule: PageOffset,
}
impl GranuleOffsetIter<'_, '_> {
/// Returns a mutable view of, for the `granule` at `offset`, `granule.data[start..]`.
///
/// # Safety
///
/// - `offset` must point to a valid granule
/// - `start < VarLenGranule::DATA_SIZE`