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
use std;
use std::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
use std::ptr::copy_nonoverlapping;
use std::collections::{HashSet, HashMap};
use fs2::FileExt;
use std::fs::{File, OpenOptions};
use std::path::Path;
use memmap;
use {Db, Representable, RC_ROOT};
#[doc(hidden)]
pub const CURRENT_VERSION: u64 = 0;
const OFF_MAP_LENGTH: isize = 1;
const OFF_CURRENT_FREE: isize = 2;
pub const PAGE_SIZE: usize = 4096;
pub const PAGE_SIZE_64: u64 = 4096;
pub const ZERO_HEADER: isize = 24; const DEFAULT_FLUSH_LIMIT: u64 = 4096;
#[derive(Debug)]
pub enum Error {
IO(std::io::Error),
NotEnoughSpace,
Poison,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Error::IO(ref err) => write!(f, "IO error: {}", err),
Error::NotEnoughSpace => {
write!(f,
"Not enough space. Try opening the environment with a larger size.")
}
Error::Poison => write!(f, "Lock poisoning error"),
}
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::IO(ref err) => err.description(),
Error::NotEnoughSpace => {
"Not enough space. Try opening the environment with a larger size."
}
Error::Poison => "Poison error",
}
}
fn cause(&self) -> Option<&std::error::Error> {
match *self {
Error::IO(ref err) => Some(err),
Error::NotEnoughSpace => None,
Error::Poison => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::IO(e)
}
}
impl<T> From<std::sync::PoisonError<T>> for Error {
fn from(_: std::sync::PoisonError<T>) -> Error {
Error::Poison
}
}
pub struct Env {
length: u64,
backing_file: File,
flush_limit: u64,
lock_file: Option<File>,
mmap: Option<memmap::MmapMut>,
map: *mut u8,
first_unused_page: Mutex<u64>,
lock: RwLock<()>,
mutable: Mutex<()>,
}
unsafe impl Send for Env {}
unsafe impl Sync for Env {}
impl Drop for Env {
fn drop(&mut self) {
if let Some(mmap) = self.mmap.take() {
drop(mmap);
if let Ok(f) = self.first_unused_page.lock() {
if *f > 0 {
self.backing_file.set_len(*f).unwrap_or(());
}
}
}
if let Some(ref mut lock_file) = self.lock_file {
lock_file.unlock().unwrap_or(());
}
}
}
pub struct Txn<'env> {
#[doc(hidden)]
env: &'env Env,
guard: RwLockReadGuard<'env, ()>,
}
pub struct MutTxn<'env, T> {
env: &'env Env,
mutable: Option<MutexGuard<'env, ()>>,
parent: T,
last_page: u64,
current_list_page: Page,
current_list_length: u64,
current_list_position: u64,
occupied_clean_pages: HashSet<u64>,
free_clean_pages: Vec<u64>,
free_pages: Vec<u64>,
roots: HashMap<usize, u64>,
mut_page_count: u64,
}
impl<'env> Drop for Txn<'env> {
fn drop(&mut self) {
*self.guard;
}
}
impl<'env, T> Drop for MutTxn<'env, T> {
fn drop(&mut self) {
debug!("dropping transaction");
if let Some(ref mut guard) = self.mutable {
debug!("dropping guard");
**guard
}
}
}
#[derive(Debug)]
#[doc(hidden)]
pub struct Statistics {
pub free_pages: HashSet<u64>,
pub bookkeeping_pages: Vec<u64>,
pub total_pages: usize,
pub reference_counts: HashMap<u64, u64>,
}
impl Env {
pub fn file_size<P: AsRef<Path>>(path: P) -> Result<u64, Error> {
let db_path = path.as_ref().join("db");
debug!("db_path = {:?}, len = {:?}", db_path, std::fs::metadata(&db_path)?.len());
Ok(std::fs::metadata(&db_path)?.len())
}
pub fn size(&self) -> u64 {
self.length
}
pub fn set_flush_limit(&mut self, flush: u64) {
self.flush_limit = flush
}
pub fn flush_limit(&self) -> u64 {
self.flush_limit
}
pub fn new<P: AsRef<Path>>(path: P, length: u64) -> Result<Env, Error> {
let lock_file = OpenOptions::new()
.read(true)
.write(true)
.truncate(false)
.create(true)
.open(path.as_ref()
.join("db")
.with_extension("lock"))?;
lock_file.lock_exclusive()?;
let mut env = unsafe { Self::new_nolock(path, length)? };
env.lock_file = Some(lock_file);
Ok(env)
}
pub unsafe fn new_nolock<P: AsRef<Path>>(path: P, length: u64) -> Result<Env, Error> {
debug!("length {:?}", length);
let db_path = path.as_ref().join("db");
let db_exists = std::fs::metadata(&db_path).is_ok();
let length = if let Ok(meta) = std::fs::metadata(&db_path) {
std::cmp::max(meta.len(), length)
} else {
length
};
let file = OpenOptions::new()
.read(true)
.write(true)
.truncate(false)
.create(true)
.open(&db_path)?;
debug!("allocate: {:?}", length);
file.set_len(length)?;
let mut mmap = memmap::MmapMut::map_mut(&file)?;
let map = mmap.as_mut_ptr();
debug!("mmap: {:?} {:?}", map, mmap.len());
if !db_exists {
std::ptr::write_bytes(map, 0, PAGE_SIZE);
*(map as *mut u64) = CURRENT_VERSION.to_le();
} else {
assert!(u64::from_le(*(map as *const u64)) == CURRENT_VERSION)
}
debug!("metadata.len() = {:?}", std::fs::metadata(&db_path).map(|x| x.len()));
let env = Env {
length: length,
mmap: Some(mmap),
map: map,
backing_file: file,
lock_file: None,
first_unused_page: Mutex::new(0),
lock: RwLock::new(()),
mutable: Mutex::new(()),
flush_limit: DEFAULT_FLUSH_LIMIT,
};
Ok(env)
}
pub fn txn_begin<'env>(&'env self) -> Result<Txn<'env>, Error> {
let read = try!(self.lock.read());
Ok(Txn {
env: self,
guard: read,
})
}
pub fn mut_txn_begin<'env>(&'env self) -> Result<MutTxn<'env, ()>, Error> {
unsafe {
let guard = try!(self.mutable.lock());
debug!("lock ok");
let last_page = u64::from_le(*((self.map as *const u64).offset(OFF_MAP_LENGTH)));
let current_list_page = u64::from_le(*((self.map as *const u64)
.offset(OFF_CURRENT_FREE)));
debug!("map header = {:?}, {:?}", last_page, current_list_page);
assert!(current_list_page < self.length);
let current_list_page = Page {
data: self.map.offset(current_list_page as isize),
offset: current_list_page,
};
let current_list_length = if current_list_page.offset == 0 {
0
} else {
u64::from_le(*((current_list_page.data as *const u64).offset(1)))
};
Ok(MutTxn {
env: self,
mutable: Some(guard),
parent: (),
last_page: if last_page == 0 {
PAGE_SIZE_64
} else {
last_page
},
current_list_page: current_list_page,
current_list_length: current_list_length,
current_list_position: current_list_length,
occupied_clean_pages: HashSet::new(),
free_clean_pages: Vec::new(),
free_pages: Vec::new(),
roots: HashMap::new(),
mut_page_count: 0
})
}
}
pub unsafe fn close(&mut self) {
if let Some(mmap) = self.mmap.take() {
drop(mmap);
if let Ok(f) = self.first_unused_page.lock() {
if *f > 0 {
self.backing_file.set_len(*f).unwrap_or(());
}
}
}
if let Some(ref mut lock_file) = self.lock_file {
lock_file.unlock().unwrap_or(());
}
}
}
impl<'a> Txn<'a> {
#[doc(hidden)]
pub fn statistics(&self) -> Statistics {
unsafe {
let total_pages = u64::from_le(*((self.env.map as *const u64)
.offset(OFF_MAP_LENGTH))) as usize;
let mut free_pages = HashSet::new();
let mut bookkeeping_pages = Vec::new();
let mut cur = u64::from_le(*((self.env.map as *const u64).offset(OFF_CURRENT_FREE)));
while cur != 0 {
bookkeeping_pages.push(cur);
let p = self.env.map.offset(cur as isize) as *const u64;
let prev = u64::from_le(*p);
let len = u64::from_le(*(p.offset(1))); debug!("bookkeeping page: {:?}, {} {}", cur, prev, len);
{
let mut p: *const u64 = (p).offset(2);
let mut i = 0;
while i < len {
let free_page = u64::from_le(*p);
if !free_pages.insert(free_page) {
panic!("free page counted twice: {:?}", free_page)
}
p = p.offset(1);
i += 1
}
}
cur = prev
}
let mut reference_counts = HashMap::new();
let rc_root = self.root_(RC_ROOT);
if rc_root != 0 {
use Transaction;
let db: Db<u64, u64> = Db(rc_root, std::marker::PhantomData);
reference_counts.extend(self.iter(&db, None))
}
Statistics {
total_pages: total_pages / PAGE_SIZE,
free_pages,
bookkeeping_pages,
reference_counts,
}
}
}
#[doc(hidden)]
pub fn references<K: Representable, V: Representable>(&self, h: &mut HashSet<u64>, root: Db<K, V>) {
self.references_::<K, V>(h, root.0)
}
fn references_<K: Representable, V: Representable>(&self, h: &mut HashSet<u64>, page: u64) {
if page != 0 {
if h.contains(&page) {
panic!("h.contains({:?})", page);
}
h.insert(page);
let page = Page {
data: unsafe { self.env.map.offset(page as isize) },
offset: page,
};
use skiplist::SkipListPage;
for (_, v, r) in page.iter_all::<K, V>() {
if let Some((k, v)) = v {
for offset in k.page_offsets() {
h.insert(offset);
}
for offset in v.page_offsets() {
h.insert(offset);
}
}
self.references_::<K, V>(h, r)
}
}
}
}
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct Page {
pub data: *const u8,
pub offset: u64,
}
#[doc(hidden)]
#[derive(Debug)]
pub struct MutPage {
pub data: *mut u8,
pub offset: u64,
}
impl MutPage {
pub fn as_page(&self) -> Page {
Page {
data: self.data,
offset: self.offset,
}
}
}
#[doc(hidden)]
pub trait LoadPage {
fn load_page(&self, off: u64) -> Page;
fn root_(&self, num: usize) -> u64;
}
impl<'env> LoadPage for Txn<'env> {
fn load_page(&self, off: u64) -> Page {
debug!("load_page: off={:?}, length = {:?}", off, self.env.length);
assert!(off < self.env.length);
unsafe {
Page {
data: self.env.map.offset(off as isize),
offset: off,
}
}
}
fn root_(&self, num: usize) -> u64 {
assert!(ZERO_HEADER as usize + ((num + 1) << 3) < PAGE_SIZE);
unsafe {
u64::from_le(*((self.env.map.offset(ZERO_HEADER) as *const u64).offset(num as isize)))
}
}
}
impl<'env, A> LoadPage for MutTxn<'env, A> {
fn load_page(&self, off: u64) -> Page {
if off >= self.env.length {
panic!("{:?} >= {:?}", off, self.env.length)
}
unsafe {
Page {
data: self.env.map.offset(off as isize),
offset: off,
}
}
}
fn root_(&self, num: usize) -> u64 {
if let Some(root) = self.roots.get(&num) {
*root
} else {
assert!(ZERO_HEADER + ((num as isize + 1) << 3) < (PAGE_SIZE as isize));
unsafe {
u64::from_le(*((self.env.map.offset(ZERO_HEADER) as *const u64)
.offset(num as isize)))
}
}
}
}
#[derive(Debug)]
#[doc(hidden)]
pub enum Cow {
Page(Page),
MutPage(MutPage),
}
impl Cow {
pub fn as_page(&self) -> Page {
match self {
&Cow::Page(ref p) => p.clone(),
&Cow::MutPage(ref p) => p.as_page(),
}
}
}
impl<'env, T> MutTxn<'env, T> {
pub fn mut_txn_begin<'txn>(&'txn mut self)
-> Result<MutTxn<'env, &'txn mut MutTxn<'env, T>>, Error> {
unsafe {
let mut txn = MutTxn {
env: self.env,
mutable: None,
parent: std::mem::uninitialized(),
last_page: self.last_page,
current_list_page: Page {
data: self.current_list_page.data,
offset: self.current_list_page.offset,
},
current_list_length: self.current_list_length,
current_list_position: self.current_list_position,
occupied_clean_pages: HashSet::new(),
free_clean_pages: Vec::new(),
free_pages: Vec::new(),
roots: self.roots.clone(), mut_page_count: 0,
};
txn.parent = self;
Ok(txn)
}
}
#[doc(hidden)]
pub fn set_root_(&mut self, num: usize, value: u64) {
self.roots.insert(num, value);
}
#[doc(hidden)]
pub fn load_cow_page(&mut self, off: u64) -> Cow {
trace!("transaction::load_mut_page: {:?} {:?}",
off,
self.occupied_clean_pages);
assert!(off < self.env.length);
if off != 0 && self.occupied_clean_pages.contains(&off) {
unsafe {
Cow::MutPage(MutPage {
data: self.env.map.offset(off as isize),
offset: off,
})
}
} else {
unsafe {
let d = self.env.map.offset(off as isize);
Cow::Page(Page {
data: d,
offset: off,
})
}
}
}
#[doc(hidden)]
pub unsafe fn free_page(&mut self, offset: u64) {
trace!("transaction::free page: {:?}", offset);
if self.occupied_clean_pages.remove(&offset) {
self.free_clean_pages.push(offset);
} else {
self.free_pages.push(offset)
}
}
fn free_pages_pop(&mut self) -> Option<u64> {
trace!("free_pages_pop, current_list_position:{}",
self.current_list_position);
if self.current_list_page.offset == 0 {
None
} else {
if self.current_list_position == 0 {
let previous_page =
unsafe { u64::from_le(*(self.current_list_page.data as *const u64)) };
trace!("free_pages_pop, previous page:{}", previous_page);
if previous_page == 0 {
None
} else {
self.free_pages.push(self.current_list_page.offset);
unsafe {
self.current_list_page = Page {
data: self.env.map.offset(previous_page as isize),
offset: previous_page,
};
self.current_list_length =
u64::from_le(*((self.current_list_page.data as *const u64).offset(1)))
}
self.current_list_position = self.current_list_length;
self.free_pages_pop()
}
} else {
let pos = self.current_list_position;
self.current_list_position -= 1;
trace!("free_pages_pop, new position:{}",
self.current_list_position);
unsafe {
Some(u64::from_le(*((self.current_list_page.data as *mut u64)
.offset(1 + pos as isize))))
}
}
}
}
pub fn alloc_page(&mut self) -> Result<MutPage, Error> {
trace!("alloc page");
self.mut_page_count += 1;
if self.mut_page_count >= self.env.flush_limit {
if let Some(ref map) = self.env.mmap {
map.flush()?;
}
self.mut_page_count = 0
}
if let Some(page) = self.free_clean_pages.pop() {
trace!("clean page reuse:{}", page);
self.occupied_clean_pages.insert(page);
Ok(MutPage {
data: unsafe { self.env.map.offset(page as isize) },
offset: page,
})
} else {
if let Some(page) = self.free_pages_pop() {
trace!("using an old free page: {}", page);
self.occupied_clean_pages.insert(page);
Ok(MutPage {
data: unsafe { self.env.map.offset(page as isize) },
offset: page,
})
} else {
let last = self.last_page;
trace!("eating the free space: {}", last);
if self.last_page + PAGE_SIZE_64 < self.env.length {
self.last_page += PAGE_SIZE_64;
self.occupied_clean_pages.insert(last);
Ok(MutPage {
data: unsafe { self.env.map.offset(last as isize) },
offset: last,
})
} else {
Err(Error::NotEnoughSpace)
}
}
}
}
}
pub trait Commit {
fn commit(self) -> Result<(), Error>;
}
impl<'a, 'env, T> Commit for MutTxn<'env, &'a mut MutTxn<'env, T>> {
fn commit(self) -> Result<(), Error> {
self.parent.last_page = self.last_page;
self.parent.current_list_page = Page {
offset: self.current_list_page.offset,
data: self.current_list_page.data,
};
self.parent.current_list_length = self.current_list_length;
self.parent.current_list_position = self.current_list_position;
self.parent.occupied_clean_pages.extend(self.occupied_clean_pages.iter());
self.parent.free_clean_pages.extend(self.free_clean_pages.iter());
self.parent.free_pages.extend(self.free_pages.iter());
for (u, v) in self.roots.iter() {
self.parent.roots.insert(*u, *v);
}
Ok(())
}
}
impl<'env> Commit for MutTxn<'env, ()> {
fn commit(mut self) -> Result<(), Error> {
unsafe {
let mut current_page = try!(self.alloc_page());
if self.current_list_page.offset != 0 {
debug!("commit: realloc BK, copy {:?}", self.current_list_position);
copy_nonoverlapping(self.current_list_page.data as *const u64,
current_page.data as *mut u64,
2 + self.current_list_position as usize);
*((current_page.data as *mut u64).offset(1)) = self.current_list_position.to_le();
debug!("freeing BK page {:?}", self.current_list_page.offset);
self.free_pages.push(self.current_list_page.offset);
} else {
*(current_page.data as *mut u64) = 0; *((current_page.data as *mut u64).offset(1)) = 0; }
while !(self.free_pages.is_empty() && self.free_clean_pages.is_empty()) {
debug!("commit: pushing");
let len = u64::from_le(*((current_page.data as *const u64).offset(1)));
debug!("len={:?}", len);
if 16 + len * 8 + 8 >= PAGE_SIZE_64 {
debug!("commit: current is full, len={}", len);
let p = self.free_pages
.pop()
.unwrap_or_else(|| self.free_clean_pages.pop().unwrap());
let new_page = MutPage {
data: self.env.map.offset(p as isize),
offset: p,
};
debug!("commit {} allocated {:?}", line!(), new_page.offset);
*(new_page.data as *mut u64) = current_page.offset.to_le();
*((new_page.data as *mut u64).offset(1)) = 0;
current_page = new_page;
} else {
let p = self.free_pages
.pop()
.unwrap_or_else(|| self.free_clean_pages.pop().unwrap());
debug!("commit: push {}", p);
*((current_page.data as *mut u64).offset(1)) = (len + 1).to_le();
*((current_page.data as *mut u64).offset(2 + len as isize)) = p.to_le();
}
}
{
debug!("commit: taking local lock");
*self.env.lock.write()?;
debug!("commit: lock ok");
for (u, v) in self.roots.iter() {
*((self.env.map.offset(ZERO_HEADER) as *mut u64).offset(*u as isize)) =
(*v).to_le();
}
debug!("env.length = {:?}", self.env.length);
if let Some(ref mmap) = self.env.mmap {
mmap.flush_range(2 * PAGE_SIZE, (self.env.length - 2 * PAGE_SIZE_64) as usize)?;
*((self.env.map as *mut u64).offset(OFF_MAP_LENGTH)) = self.last_page.to_le();
*((self.env.map as *mut u64).offset(OFF_CURRENT_FREE)) = current_page.offset
.to_le();
mmap.flush_range(0, 2 * PAGE_SIZE)?;
}
{
let mut last = self.env.first_unused_page.lock()?;
debug!("last_page = {:?}", self.last_page);
*last = self.last_page;
}
if let Some(guard) = self.mutable.take() {
debug!("dropping guard");
*guard
}
Ok(())
}
}
}
}