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
// Copyright 2015 Pierre-Étienne Meunier and Florent Becker. See the
// COPYRIGHT file at the top-level directory of this distribution and
// at http://pijul.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::skiplist;
use crate::skiplist::{record_size, FIRST_BINDING_SIZE};
use crate::transaction::{Cow, Env, Exclusive};
use crate::{rc, Cursor, Db, Error, MutTxn, PageItem, PageT, Representable, PAGE_SIZE_U16};
use rand::Rng;
use std;
use std::borrow::Borrow;

impl<E: Borrow<Env<Exclusive>>, T> MutTxn<E, T> {
    /// Insert a binding to a database, returning `false` if and only
    /// if the exact same binding (key *and* value) was already in the database.
    pub fn put<R: Rng, K: Representable, V: Representable>(
        &mut self,
        rng: &mut R,
        db: &mut Db<K, V>,
        key: K,
        value: V,
    ) -> Result<bool, Error> {
        let mut cursor = Cursor::new();
        if cursor.set(self, db, Some((key, Some(value))))? {
            return Ok(false);
        }
        // Now insert in the leaf and split all pages that need to be split.

        let leaf_pointer = cursor.pointer;

        // Split all pages that need it.
        //
        // This loop uses unsafe slices, but the memory management is
        // simple: all pointers used in the loop are valid until we
        // explicitely call free, after the loop.
        let last_allocated = self.put_cascade(rng, &mut cursor, key, value)?;

        // Now, cursor_pointer is the reference to a page that doesn't
        // need to split anymore (possibly the new root).

        // Free all split pages.
        self.free_split_pages(rng, &mut cursor, leaf_pointer)?;

        // `put_cascade` above only returns after the insertion of a
        // (key, value) with right child `inserted_right_child`. For
        // `put_update_split_root` to update the reference properly in
        // the pages above the insertion, we need to update that child
        // here (it might be 0 if we're still at the leaf).

        // Has the root split?
        self.update_split_root(rng, &mut cursor, last_allocated, db)?;
        debug!("put done");
        Ok(true)
    }

    fn put_cascade<R: Rng, K: Representable, V: Representable>(
        &mut self,
        rng: &mut R,
        cursor: &mut Cursor,
        key: K,
        value: V,
    ) -> Result<u64, Error> {
        let mut last_allocated = 0;
        let mut inserted_right_child = 0;
        let mut inserted_key = key;
        let mut inserted_value = value;
        let mut inserted_left_child = 0u64;

        loop {
            let mut page = self.load_cow_page(cursor.current().page)?;

            debug!("page: {:?}", page);

            // If we're "CoWing" the first double-pointed page on the stack, decrease its RC.
            if cursor.pointer == cursor.first_rc_level {
                let page = cursor.current().page;
                let rc = rc(self, page)?;
                if rc >= 2 {
                    self.set_rc(rng, page, rc - 1)?;
                }
            }

            if skiplist::can_alloc(&page, inserted_key, inserted_value) != 0 {
                self.put_can_alloc(
                    rng,
                    page,
                    cursor,
                    &mut inserted_key,
                    &mut inserted_left_child,
                    &mut inserted_right_child,
                    &mut inserted_value,
                    &mut last_allocated,
                )?;
                break;
            } else {
                // We cannot allocate, we need to split this page

                debug!("cannot alloc");
                self.put_split(
                    rng,
                    &mut page,
                    cursor,
                    &mut inserted_key,
                    &mut inserted_left_child,
                    &mut inserted_right_child,
                    &mut inserted_value,
                )?;

                cursor.pointer -= 1;
                if cursor.pointer == 0 {
                    // We've just split the root! we need to
                    // allocate a page to collect the two sides of
                    // the split.
                    last_allocated = self.split_root(
                        rng,
                        cursor,
                        inserted_left_child,
                        inserted_right_child,
                        inserted_key,
                        inserted_value,
                    )?;
                    break;
                }
            }
        }
        Ok(last_allocated)
    }

    fn put_can_alloc<R: Rng, K: Representable, V: Representable>(
        &mut self,
        rng: &mut R,
        mut page: Cow,
        cursor: &mut Cursor,
        inserted_key: &mut K,
        inserted_left_child: &mut u64,
        inserted_right_child: &mut u64,
        inserted_value: &mut V,
        last_allocated: &mut u64,
    ) -> Result<(), Error> {
        debug!("can alloc");
        // We can allocate. Do we need to duplicate this
        // page (because of RC or first_free)?
        let needs_dup = skiplist::first_free(&page) + record_size(*inserted_key, *inserted_value)
            > PAGE_SIZE_U16;

        match page {
            Cow::MutPage(ref mut page) if cursor.pointer < cursor.first_rc_level && !needs_dup => {
                debug!("does not need dup");

                // No, there will be no other references to
                // this page after this method (`put`)
                // returns. Here, simply insert.

                // Update the right child from the previous split
                // (if any, `inserted_left_child` is 0 else).
                debug!("page right child: {:?}", cursor.current()[0]);
                self.set_right_child(page, cursor.current()[0], *inserted_left_child);
                self.skiplist_insert_after_cursor(
                    page,
                    rng,
                    &mut cursor.current_mut().cursor,
                    *inserted_key,
                    *inserted_value,
                    *inserted_right_child,
                );
                *last_allocated = page.page_offset();
            }
            _ => {
                debug!(
                    "needs dup {:?} {:?} {:?}",
                    cursor.pointer, cursor.first_rc_level, needs_dup
                );
                // Yes, we do need to duplicate this
                // page. Propagate RC to pages
                // below.
                let page = self.load_cow_page(cursor.current().page)?;

                // Iterate over the page, incorporating the new element.
                let it = Iter {
                    iter: skiplist::iter_all(&page).peekable(),
                    off: page.offset(cursor.current()[0] as isize),
                    next_is_extra: false,
                    extra_left: *inserted_left_child,
                    extra: (
                        Some((*inserted_key, *inserted_value)),
                        *inserted_right_child,
                    ),
                };

                // Increase the RC of everyone, but the left
                // side of the split (which was just
                // allocated now).
                let incr_rc = cursor.pointer >= cursor.first_rc_level;
                *last_allocated = self.spread_on_one_page(
                    rng,
                    it.map(|(b, c)| {
                        let fresh = c == *inserted_left_child || c == *inserted_right_child;
                        PageItem {
                            ptr: std::ptr::null(),
                            kv: b,
                            right: c,
                            incr_right_rc: incr_rc && !fresh,
                            incr_kv_rc: incr_rc,
                        }
                    }),
                )?;

                if cursor.pointer < cursor.first_rc_level {
                    unsafe {
                        // free of the current page.
                        self.free_page(cursor.current().page)
                    }
                }
            }
        }
        Ok(())
    }

    fn put_split<R: Rng, K: Representable, V: Representable>(
        &mut self,
        rng: &mut R,
        page: &mut Cow,
        cursor: &mut Cursor,
        inserted_key: &mut K,
        inserted_left_child: &mut u64,
        inserted_right_child: &mut u64,
        inserted_value: &mut V,
    ) -> Result<(), Error> {
        let it = Iter {
            iter: skiplist::iter_all(page).peekable(),
            off: page.offset(cursor.current()[0] as isize),
            next_is_extra: false,
            extra_left: *inserted_left_child,
            extra: (
                Some((*inserted_key, *inserted_value)),
                *inserted_right_child,
            ),
        };
        // We're going to add a page, hence
        // FIRST_BINDING_SIZE more bytes will be
        // needed.
        let total = skiplist::occupied(page)
            + record_size(*inserted_key, *inserted_value)
            + FIRST_BINDING_SIZE;
        let (left, right, sep_key, sep_value) = if cursor.pointer >= cursor.first_rc_level {
            let it = it.map(|(b, c)| {
                if c == *inserted_left_child || c == *inserted_right_child {
                    PageItem {
                        ptr: std::ptr::null(),
                        kv: b,
                        right: c,
                        incr_right_rc: false,
                        incr_kv_rc: true,
                    }
                } else {
                    PageItem {
                        ptr: std::ptr::null(),
                        kv: b,
                        right: c,
                        incr_right_rc: true,
                        incr_kv_rc: true,
                    }
                }
            });
            self.spread_on_two_pages(rng, it, total)?
        } else {
            let it = it.map(|(b, c)| PageItem {
                ptr: std::ptr::null(),
                kv: b,
                right: c,
                incr_right_rc: false,
                incr_kv_rc: false,
            });
            self.spread_on_two_pages(rng, it, total)?
        };
        // Extend the lifetime of "inserted_key".
        *inserted_key = sep_key;
        *inserted_left_child = left;
        *inserted_right_child = right;
        *inserted_value = sep_value;
        Ok(())
    }

    fn update_put<R: Rng, K: Representable, V: Representable>(
        &mut self,
        rng: &mut R,
        cursor: &mut Cursor,
    ) -> Result<(), Error> {
        let mut page = self.load_cow_page(cursor.current().page)?;
        match page {
            Cow::MutPage(ref mut p) if cursor.pointer < cursor.first_rc_level => {
                self.set_right_child(p, cursor.current()[0], cursor[cursor.pointer + 1].page);
                cursor.current_mut().page = p.offset;
            }
            Cow::MutPage(_) | Cow::Page(_) => {
                // Here, the page needs to be CoWed.
                let incr_rc = cursor.pointer >= cursor.first_rc_level;
                let current_ptr = page.offset(cursor.current()[0] as isize);
                let new_page = self.spread_on_one_page::<_, K, V, _>(
                    rng,
                    skiplist::iter_all(&page).map(|(off, b, c)| {
                        // Both pages will survive, increase reference count.
                        let mut item = PageItem {
                            ptr: std::ptr::null(),
                            kv: b,
                            right: c,
                            incr_kv_rc: incr_rc,
                            incr_right_rc: incr_rc,
                        };
                        if off == current_ptr {
                            item.right = cursor[cursor.pointer + 1].page;
                            item.incr_right_rc = false // fresh page.
                        }
                        item
                    }),
                )?;
                // If nothing points to the page anymore, free.
                if cursor.pointer < cursor.first_rc_level {
                    unsafe {
                        debug!("line {:?}, freeing {:?}", line!(), page.page_offset());
                        self.free_page(page.page_offset())
                    }
                }
                debug!("NEW_PAGE = {:?}", new_page);
                cursor.current_mut().page = new_page;
            }
        }
        Ok(())
    }

    fn free_split_pages<R: Rng>(
        &mut self,
        rng: &mut R,
        cursor: &mut Cursor,
        leaf_pointer: usize,
    ) -> Result<(), Error> {
        debug!(
            "freeing pages from {:?} to {:?} {:?} (inclusive)",
            cursor.pointer + 1,
            leaf_pointer,
            cursor.first_rc_level
        );
        let last_free = std::cmp::min(leaf_pointer + 1, cursor.first_rc_level);
        let first_free = std::cmp::min(cursor.pointer + 1, last_free);
        for page_cursor in &cursor.stack[first_free..last_free] {
            // free the page that was split.
            let rc = rc(self, page_cursor.page)?;
            if rc <= 1 {
                debug!("Freeing {:?}", page_cursor.page);
                self.remove_rc(rng, page_cursor.page)?;
                unsafe { self.free_page(page_cursor.page) }
            } else {
                debug!(
                    "Decrease RC for page {:?}, new rc: {:?}",
                    page_cursor.page,
                    rc - 1
                );
                self.set_rc(rng, page_cursor.page, rc - 1)?;
            }
        }
        debug!("freed");
        Ok(())
    }

    fn update_split_root<R: Rng, K: Representable, V: Representable>(
        &mut self,
        rng: &mut R,
        cursor: &mut Cursor,
        last_allocated: u64,
        db: &mut Db<K, V>,
    ) -> Result<(), Error> {
        if cursor.pointer > 0 {
            cursor.stack[cursor.pointer].page = last_allocated;
            cursor.pointer -= 1;
            // The root has not split, the splits stopped earlier. There are remaining pages.
            while cursor.pointer > 0 {
                if cursor.pointer == cursor.first_rc_level {
                    let page = cursor.current().page;
                    let rc = rc(self, page)?;
                    if rc >= 2 {
                        self.set_rc(rng, page, rc - 1)?;
                    }
                }
                self.update_put::<R, K, V>(rng, cursor)?;
                cursor.pointer -= 1;
            }

            db.0 = cursor[1].page
        } else {
            // The root has split, no need to do anything.
            debug!("the root has split");
            db.0 = last_allocated
        }
        Ok(())
    }
}

/// Iterator on a page, plus a middle element immediately after `off`,
/// with a fixed left and right child.
struct Iter<'a, P: PageT + Sized + 'a, K: Representable, V: Representable> {
    iter: std::iter::Peekable<skiplist::Iter<'a, P, K, V>>,
    off: *const u8,
    next_is_extra: bool,
    extra_left: u64,
    extra: (Option<(K, V)>, u64),
}

impl<'a, P: PageT + Sized + 'a, K: Representable, V: Representable> Iterator for Iter<'a, P, K, V> {
    type Item = (Option<(K, V)>, u64);

    fn next(&mut self) -> Option<Self::Item> {
        if self.next_is_extra {
            debug!("next_is_extra");
            self.next_is_extra = false;
            self.off = std::ptr::null();
            Some(self.extra)
        } else {
            debug!("not next_is_extra");

            if let Some((a, b, d)) = self.iter.next() {
                // if a == self.off, the extra element is to be
                // inserted immediately after this element.  Set
                // next_is_extra, and replace the current element's
                // right child with extra's left child.
                debug!("{:?}", a);
                if a == self.off {
                    self.next_is_extra = true;
                    Some((b, self.extra_left))
                } else {
                    Some((b, d))
                }
            } else {
                debug!("finished, extra = {:?}", self.off);
                None
            }
        }
    }
}