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
use std::{
    cmp::min,
    collections::hash_map::DefaultHasher,
    hash::Hasher,
    mem::{size_of, MaybeUninit},
    sync::Arc,
};

use tickv::{success_codes::SuccessCode, ErrorCode, FlashController};
use twizzler_object::ObjID;

use crate::nvme::NvmeController;

pub struct Storage {
    nvme: Arc<NvmeController>,
}

impl Storage {
    pub fn new(nvme: Arc<NvmeController>) -> Self {
        Self { nvme }
    }
}

pub const BLOCK_SIZE: usize = 4096;
// TODO: don't hardcode this
pub const SECTORS_TO_BLOCK: usize = 8;

impl FlashController<BLOCK_SIZE> for Storage {
    fn read_region(
        &self,
        region_number: usize,
        offset: usize,
        buf: &mut [u8; BLOCK_SIZE],
    ) -> Result<(), tickv::ErrorCode> {
        twizzler_async::block_on(self.nvme.read_page(region_number as u64 * 8, buf, offset))
            .map_err(|_| tickv::ErrorCode::ReadFail)
    }

    fn write(&self, mut address: usize, mut buf: &[u8]) -> Result<(), tickv::ErrorCode> {
        while !buf.is_empty() {
            let offset = address % BLOCK_SIZE;
            let start = (address / BLOCK_SIZE) * SECTORS_TO_BLOCK;
            let thislen = min(BLOCK_SIZE - offset, buf.len());

            twizzler_async::block_on(self.nvme.write_page(start as u64, &buf[0..thislen], offset))
                .map_err(|_| tickv::ErrorCode::WriteFail)?;

            buf = &buf[thislen..buf.len()];
            address += thislen;
        }
        Ok(())
    }

    fn erase_region(&self, region_number: usize) -> Result<(), tickv::ErrorCode> {
        twizzler_async::block_on(self.nvme.write_page(
            (region_number * SECTORS_TO_BLOCK) as u64,
            &[0xffu8; BLOCK_SIZE],
            0,
        ))
        .map_err(|_| tickv::ErrorCode::WriteFail)
    }
}

pub struct KeyValueStore<'a> {
    pub internal: tickv::tickv::TicKV<'a, Storage, BLOCK_SIZE>,
}

pub fn hasher<T: std::hash::Hash>(t: &T) -> u64 {
    let mut h = DefaultHasher::new();
    t.hash(&mut h);
    let x = h.finish();
    // Don't ever hash to 0, 1, MAX, or MAX-1. Makes the open addressing easier, and 0 and MAX-1 are required for tickv.
    match x {
        0 => 2,
        u64::MAX => u64::MAX - 2,
        m => m,
    }
}

#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Ord, Eq, Debug)]
#[repr(C)]
pub struct Key {
    pub id: ObjID,
    pub info: u32,
    pub kind: KeyKind,
}

impl Key {
    pub fn new(id: ObjID, info: u32, kind: KeyKind) -> Self {
        Self { id, info, kind }
    }
}

#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Ord, Eq, Debug)]
#[repr(u32)]
pub enum KeyKind {
    ObjectInfo = 10,
    Tombstone = 42,
}

impl<'a> KeyValueStore<'a> {
    pub fn new(
        storage: Storage,
        read_buffer: &'a mut [u8; BLOCK_SIZE],
        size: usize,
    ) -> Result<Self, ErrorCode> {
        let this = Self {
            internal: tickv::tickv::TicKV::new(storage, read_buffer, size),
        };
        this.internal.initialise(hasher(tickv::tickv::MAIN_KEY))?;
        Ok(this)
    }

    pub fn do_get(&self, hash: u64, buf_size: usize) -> Result<(SuccessCode, Vec<u8>), ErrorCode> {
        let mut buf = Vec::new();
        buf.resize(buf_size, 0u8);
        match self.internal.get_key(hash, &mut buf) {
            Ok(s) => Ok((s, buf)),
            Err(ErrorCode::BufferTooSmall(l)) => self.do_get(hash, l),
            Err(e) => Err(e),
        }
    }

    fn convert<T: Copy>(buf: &[u8]) -> T {
        let mut mu = MaybeUninit::uninit();
        let num_bytes = std::mem::size_of::<T>();
        unsafe {
            let buffer = std::slice::from_raw_parts_mut(
                &mut mu as *mut MaybeUninit<T> as *mut u8,
                num_bytes,
            );
            buffer.copy_from_slice(&buf[0..num_bytes]);
            drop(buffer);
            mu.assume_init()
        }
    }

    pub fn get<V: Copy>(&self, key: Key) -> Result<V, ErrorCode> {
        let mut hash = hasher(&key);
        let prev = hash.wrapping_sub(1);
        let size = size_of::<Key>() + size_of::<V>();
        while hash != prev {
            if hash == 0 || hash == u64::MAX {
                hash = hash.wrapping_add(1);
                continue;
            }
            let data = self.do_get(hash, size)?;
            let thiskey: Key = Self::convert(&data.1);
            if key == thiskey {
                return Ok(Self::convert(&data.1[size_of::<Key>()..]));
            }
            hash = hash.wrapping_add(1);
        }
        Err(ErrorCode::KeyNotFound)
    }

    pub fn put<V: Copy>(&mut self, key: Key, value: V) -> Result<SuccessCode, ErrorCode> {
        let mut hash = hasher(&key);
        let prev = hash.wrapping_sub(1);
        let size = size_of::<Key>() + size_of::<V>();
        let mut raw_value = Vec::new();
        let key_slice = unsafe {
            std::slice::from_raw_parts(&key as *const Key as *const u8, size_of::<Key>())
        };
        let val_slice =
            unsafe { std::slice::from_raw_parts(&value as *const V as *const u8, size_of::<V>()) };
        raw_value.extend_from_slice(key_slice);
        raw_value.extend_from_slice(val_slice);
        while hash != prev {
            if hash == 0 || hash == u64::MAX {
                hash = hash.wrapping_add(1);
                continue;
            }
            let data = self.do_get(hash, size);
            if let Ok(data) = data {
                let thiskey: Key = Self::convert(&data.1);
                if key == thiskey {
                    return Err(ErrorCode::KeyAlreadyExists);
                }
            } else {
                return self.internal.append_key(hash, &raw_value);
            }

            hash = hash.wrapping_add(1);
        }
        Err(ErrorCode::KeyNotFound)
    }

    pub fn del(&mut self, key: Key) -> Result<SuccessCode, ErrorCode> {
        let mut hash = hasher(&key);
        let prev = hash.wrapping_sub(1);
        let size = size_of::<Key>();
        while hash != prev {
            if hash == 0 || hash == u64::MAX {
                hash = hash.wrapping_add(1);
                continue;
            }
            let data = self.do_get(hash, size)?;
            let thiskey: Key = Self::convert(&data.1);
            if key == thiskey {
                return self.do_del(hash);
            }
            hash = hash.wrapping_add(1);
        }
        Err(ErrorCode::KeyNotFound)
    }

    pub fn do_del(&self, hash: u64) -> Result<SuccessCode, ErrorCode> {
        let next = hash.wrapping_add(1);
        let res = self.internal.get_key(next, &mut []);
        if let Err(ErrorCode::BufferTooSmall(_)) = res {
            // leave a tombstone
            let t = Key::new(0.into(), 0, KeyKind::Tombstone);
            let t_slice = unsafe {
                std::slice::from_raw_parts(&t as *const Key as *const u8, size_of::<Key>())
            };
            self.internal.invalidate_key(hash).unwrap();
            self.internal.append_key(hash, t_slice)
        } else {
            self.internal.invalidate_key(hash)
        }
    }
}