forked from malbrain/Btree-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadskv10h.c
More file actions
3700 lines (2861 loc) · 88.6 KB
/
Copy paththreadskv10h.c
File metadata and controls
3700 lines (2861 loc) · 88.6 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
// btree version threadskv10h futex version
// with reworked bt_deletekey code,
// phase-fair re-entrant reader writer lock,
// librarian page split code,
// duplicate key management
// bi-directional cursors
// ACID batched key-value updates
// LSM B-trees for write optimization
// larger sized leaf pages than non-leaf
// and LSM B-tree find & count operations
// 15 DEC 2014
// author: karl malbrain, malbrain@cal.berkeley.edu
/*
This work, including the source code, documentation
and related data, is placed into the public domain.
The orginal author is Karl Malbrain.
THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
RESULTING FROM THE USE, MODIFICATION, OR
REDISTRIBUTION OF THIS SOFTWARE.
*/
// Please see the project home page for documentation
// code.google.com/p/high-concurrency-btree
#define _FILE_OFFSET_BITS 64
#define _LARGEFILE64_SOURCE
#ifdef linux
#define _GNU_SOURCE
#include <xmmintrin.h>
#include <linux/futex.h>
#include <sys/syscall.h>
#endif
#ifdef unix
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <errno.h>
#include <pthread.h>
#include <limits.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <process.h>
#include <intrin.h>
#endif
#include <memory.h>
#include <string.h>
#include <stddef.h>
typedef unsigned long long uid;
typedef unsigned long long logseqno;
#ifndef unix
typedef unsigned long long off64_t;
typedef unsigned short ushort;
typedef unsigned int uint;
#endif
#define BT_ro 0x6f72 // ro
#define BT_rw 0x7772 // rw
#define BT_maxbits 26 // maximum page size in bits
#define BT_minbits 9 // minimum page size in bits
#define BT_minpage (1 << BT_minbits) // minimum page size
#define BT_maxpage (1 << BT_maxbits) // maximum page size
// BTree page number constants
#define ALLOC_page 0 // allocation page
#define ROOT_page 1 // root of the btree
#define LATCH_page 2 // first page of latches
#define SEG_bits 16 // number of leaf pages in a segment in bits
#define MIN_seg 32 // initial number of mapping segments
// Number of levels to create in a new BTree
#define MIN_lvl 2
/*
There are six lock types for each node in four independent sets:
1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
6. (set 4) LinkModification: Exclusive. Update of a node's left link is underway. Incompatible with another LinkModification.
*/
typedef enum{
BtLockAccess = 1,
BtLockDelete = 2,
BtLockRead = 4,
BtLockWrite = 8,
BtLockParent = 16,
BtLockLink = 32
} BtLock;
typedef struct {
union {
struct {
volatile unsigned char xcl[1];
volatile unsigned char filler;
volatile ushort waiters[1];
} bits[1];
uint value[1];
};
} MutexLatch;
// definition for reader/writer reentrant lock implementation
typedef struct {
MutexLatch xcl[1];
MutexLatch wrt[1];
ushort readers; // number of readers holding lock
#ifdef DEBUG
ushort line; // owner source line number
#endif
ushort dup; // re-entrant lock count
pid_t tid; // owner pid
} RWLock;
// hash table entries
typedef struct {
MutexLatch latch[1];
uint entry; // Latch table entry at head of chain
} BtHashEntry;
// latch manager table structure
typedef struct {
uid page_no; // latch set page number
MutexLatch modify[1]; // modify entry lite latch
RWLock readwr[1]; // read/write page lock
RWLock access[1]; // Access Intent/Page delete
RWLock parent[1]; // Posting of fence key in parent
RWLock link[1]; // left link update in progress
uint split; // right split page atomic insert
uint next; // next entry in hash table chain
uint prev; // prev entry in hash table chain
uint pin; // number of accessing threads
} BtLatchSet;
// Define the length of the page record numbers
#define BtId 6
// Page key slot definition.
// Keys are marked dead, but remain on the page until
// it cleanup is called. The fence key (highest key) for
// a leaf page is always present, even after cleanup.
// Slot types
// In addition to the Unique keys that occupy slots
// there are Librarian and Duplicate key
// slots occupying the key slot array.
// The Librarian slots are dead keys that
// serve as filler, available to add new Unique
// or Dup slots that are inserted into the B-tree.
// The Duplicate slots have had their key bytes extended
// by 6 bytes to contain a binary duplicate key uniqueifier.
typedef enum {
Unique,
Update,
Librarian,
Duplicate,
Delete
} BtSlotType;
typedef struct {
uint off:BT_maxbits; // page offset for key start
uint type:3; // type of slot
uint dead:1; // set for deleted slot
} BtSlot;
// The key structure occupies space at the upper end of
// each page. It's a length byte followed by the key
// bytes.
typedef struct {
unsigned char len; // this can be changed to a ushort or uint
unsigned char key[0];
} BtKey;
// the value structure also occupies space at the upper
// end of the page. Each key is immediately followed by a value.
typedef struct {
unsigned char len; // this can be changed to a ushort or uint
unsigned char value[0];
} BtVal;
#define BT_maxkey 255 // maximum number of bytes in a key
#define BT_keyarray (BT_maxkey + sizeof(BtKey))
// The first part of an index page.
// It is immediately followed
// by the BtSlot array of keys.
typedef struct BtPage_ {
uint cnt; // count of keys in page
uint act; // count of active keys
uint min; // next key/value offset
uint fence; // page fence key offset
uint garbage; // page garbage in bytes
unsigned char lvl; // level of page, zero = leaf
unsigned char free; // page is on the free chain
unsigned char kill; // page is being deleted
unsigned char nopromote; // page is being constructed
uid right, left; // page numbers to right and left
} *BtPage;
// The loadpage interface object
typedef struct {
BtPage page; // current page pointer
BtLatchSet *latch; // current page latch set
} BtPageSet;
// structure for latch manager on shared ALLOC_page
typedef struct {
uid allocpage; // page number of first available page
uid freechain; // head of free page_nos chain
uid leafchain; // head of leaf page_nos chain
uid leaf_page; // page number of leftmost leaf
uid rightleaf; // page number of rightmost leaf
uid leafpromote; // next leaf page to try promotion
unsigned long long leafpages; // number of active leaf pages
unsigned long long upperpages; // number of active upper pages
unsigned char leaf_xtra; // leaf page size in xtra bits
unsigned char page_bits; // base page size in bits
uint nlatchpage; // size of buffer pool & latchsets
uint latchtotal; // number of page latch entries
uint latchvictim; // next latch entry to test for pin
uint latchhash; // number of latch hash table slots
MutexLatch lock[1]; // allocation area lite latch
MutexLatch promote[1]; // promotion lite latch
} BtPageZero;
// The object structure for Btree access
typedef struct {
uint page_size; // base page size
uint page_bits; // base page size in bits
uint leaf_xtra; // leaf xtra bits
#ifdef unix
int idx;
#else
HANDLE idx;
#endif
BtPageZero *pagezero; // mapped allocation page
BtHashEntry *hashtable; // the buffer pool hash table entries
BtLatchSet *latchsets; // mapped latch set from buffer pool
uint maxleaves; // leaf page count to begin promote
int err; // last error
int line; // last error line no
int found; // number of keys found by delete
int type; // type of LSM tree 0=cache, 1=main
uint maxseg; // max number of memory mapped segments
uint segments; // number of memory mapped segments in use
MutexLatch maps[1]; // segment table mutex
unsigned char **pages; // memory mapped segments of b-tree
} BtMgr;
typedef struct {
BtMgr *mgr; // buffer manager for entire process
BtMgr *main; // buffer manager for main btree
pid_t tid; // thread-id of thread
BtPageSet cacheset[1]; // cached page frame for cache btree
BtPageSet mainset[1]; // cached page frame for main btree
uint cacheslot; // slot number in cacheset
uint mainslot; // slot number in mainset
ushort phase; // 1 = main btree 0 = cache btree 2 = both
BtSlot *cachenode;
BtSlot *mainnode;
BtKey *cachekey;
BtKey *mainkey;
BtVal *cacheval;
BtVal *mainval;
} BtDb;
typedef struct {
uint entry:31; // latch table entry number
uint reuse:1; // reused previous page
uint slot; // slot on page
uint src; // source slot
} AtomicTxn;
// Catastrophic errors
typedef enum {
BTERR_ok = 0,
BTERR_struct,
BTERR_ovflw,
BTERR_lock,
BTERR_map,
BTERR_read,
BTERR_wrt,
BTERR_atomic
} BTERR;
// B-Tree functions
extern void bt_close (BtDb *bt);
extern BtDb *bt_open (BtMgr *mgr, BtMgr *main);
extern BTERR bt_writepage (BtMgr *mgr, BtPage page, uid page_no, uint leaf);
extern void bt_lockpage(BtLock mode, BtLatchSet *latch, pid_t tid, uint line);
extern void bt_unlockpage(BtLock mode, BtLatchSet *latch, uint line);
extern BTERR bt_insertkey (BtMgr *mgr, unsigned char *key, uint len, uint lvl, void *value, uint vallen, BtSlotType type);
extern BTERR bt_deletekey (BtMgr *mgr, unsigned char *key, uint len, uint lvl);
extern int bt_findkey (BtDb *db, unsigned char *key, uint keylen, unsigned char *value, uint valmax);
extern BTERR bt_startkey (BtDb *db, unsigned char *key, uint len);
extern BTERR bt_nextkey (BtDb *bt);
extern uint bt_lastkey (BtDb *bt);
extern uint bt_prevkey (BtDb *bt);
// manager functions
extern BtMgr *bt_mgr (char *name, uint bits, uint leaf_xtra, uint poolsize);
extern void bt_mgrclose (BtMgr *mgr);
// atomic transaction functions
BTERR bt_atomicexec(BtMgr *mgr, BtPage source, uint count, pid_t tid);
BTERR bt_promote (BtDb *bt);
// The page is allocated from low and hi ends.
// The key slots are allocated from the bottom,
// while the text and value of the key
// are allocated from the top. When the two
// areas meet, the page is split into two.
// A key consists of a length byte, two bytes of
// index number (0 - 65535), and up to 253 bytes
// of key value.
// Associated with each key is a value byte string
// containing any value desired.
// The b-tree root is always located at page 1.
// The first leaf page of level zero is always
// located on page 2.
// The b-tree pages are linked with next
// pointers to facilitate enumerators,
// and provide for concurrency.
// When to root page fills, it is split in two and
// the tree height is raised by a new root at page
// one with two keys.
// Deleted keys are marked with a dead bit until
// page cleanup. The fence key for a leaf node is
// always present
// To achieve maximum concurrency one page is locked at a time
// as the tree is traversed to find leaf key in question. The right
// page numbers are used in cases where the page is being split,
// or consolidated.
// Page 0 is dedicated to lock for new page extensions,
// and chains empty pages together for reuse. It also
// contains the latch manager hash table.
// The ParentModification lock on a node is obtained to serialize posting
// or changing the fence key for a node.
// Empty pages are chained together through the ALLOC page and reused.
// Access macros to address slot and key values from the page
// Page slots use 1 based indexing.
#define slotptr(page, slot) (((BtSlot *)(page+1)) + ((slot)-1))
#define keyptr(page, slot) ((BtKey*)((unsigned char*)(page) + slotptr(page, slot)->off))
#define valptr(page, slot) ((BtVal*)(keyptr(page,slot)->key + keyptr(page,slot)->len))
#define fenceptr(page) ((BtKey*)((unsigned char*)(page) + page->fence))
void bt_putid(unsigned char *dest, uid id)
{
int i = BtId;
while( i-- )
dest[i] = (unsigned char)id, id >>= 8;
}
uid bt_getid(unsigned char *src)
{
uid id = 0;
int i;
for( i = 0; i < BtId; i++ )
id <<= 8, id |= *src++;
return id;
}
// lite weight spin lock Latch Manager
pid_t sys_gettid ()
{
return syscall(SYS_gettid);
}
int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
{
return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
}
void bt_mutexlock(MutexLatch *latch)
{
uint idx, waited = 0;
MutexLatch prev[1];
while( 1 ) {
for( idx = 0; idx < 100; idx++ ) {
*prev->value = __sync_fetch_and_or (latch->value, 1);
if( !*prev->bits->xcl ) {
if( waited )
__sync_fetch_and_sub (latch->bits->waiters, 1);
return;
}
}
if( !waited ) {
__sync_fetch_and_add (latch->bits->waiters, 1);
*prev->bits->waiters += 1;
waited++;
}
sys_futex (latch->value, FUTEX_WAIT, *prev->value, NULL, NULL, 0);
}
}
int bt_mutextry(MutexLatch *latch)
{
return !__sync_lock_test_and_set (latch->bits->xcl, 1);
}
void bt_releasemutex(MutexLatch *latch)
{
MutexLatch prev[1];
*prev->value = __sync_fetch_and_and (latch->value, 0xffff0000);
if( *prev->bits->waiters )
sys_futex( latch->value, FUTEX_WAKE, 1, NULL, NULL, 0 );
}
// reader/writer lock implementation
void WriteLock (RWLock *lock, pid_t tid, uint line)
{
if( tid && lock->tid == tid ) {
lock->dup++;
return;
}
bt_mutexlock (lock->xcl);
bt_mutexlock (lock->wrt);
bt_releasemutex (lock->xcl);
lock->tid = tid;
#ifdef DEBUG
lock->line = line;
#endif
}
void WriteRelease (RWLock *lock)
{
if( lock->dup ) {
lock->dup--;
return;
}
lock->tid = 0;
bt_releasemutex (lock->wrt);
}
void ReadLock (RWLock *lock)
{
bt_mutexlock (lock->xcl);
if( !__sync_fetch_and_add (&lock->readers, 1) )
bt_mutexlock (lock->wrt);
bt_releasemutex (lock->xcl);
}
void ReadRelease (RWLock *lock)
{
if( __sync_fetch_and_sub (&lock->readers, 1) == 1 )
bt_releasemutex (lock->wrt);
}
// read page into buffer pool from permanent location in Btree file
BTERR bt_readpage (BtMgr *mgr, BtPage page, uid page_no, uint leaf)
{
uint page_size = mgr->page_size;
if( leaf )
page_size <<= mgr->leaf_xtra;
if( pread(mgr->idx, page, page_size, page_no << mgr->page_bits) < page_size )
return mgr->err = BTERR_read;
return 0;
}
// write page to location in Btree file
BTERR bt_writepage (BtMgr *mgr, BtPage page, uid page_no, uint leaf)
{
uint page_size = mgr->page_size;
if( leaf )
page_size <<= mgr->leaf_xtra;
if( pwrite(mgr->idx, page, page_size, page_no << mgr->page_bits) < page_size )
return mgr->err = BTERR_wrt;
return 0;
}
// decrement pin count
void bt_unpinlatch (BtLatchSet *latch)
{
bt_mutexlock(latch->modify);
latch->pin--;
bt_releasemutex(latch->modify);
}
// return the btree cached page address
BtPage bt_mappage (BtMgr *mgr, BtLatchSet *latch)
{
uint segment = latch->page_no >> SEG_bits;
int flag = PROT_READ | PROT_WRITE;
uid mask = (uid)1 << SEG_bits;
BtPage page;
bt_mutexlock (mgr->maps);
mask--;
while( 1 ) {
if( segment < mgr->segments ) {
page = (BtPage)(mgr->pages[segment] + ((latch->page_no & mask) << mgr->page_bits));
bt_releasemutex (mgr->maps);
return page;
}
if( mgr->segments < mgr->maxseg ) {
mgr->pages[mgr->segments] = mmap (0, (uid)mgr->page_size << SEG_bits, flag, MAP_SHARED, mgr->idx, (uid)mgr->segments << mgr->page_bits << SEG_bits);
mgr->segments++;
continue;
}
mgr->maxseg <<= 1;
mgr->pages = realloc (mgr->pages, mgr->maxseg * sizeof(void *));
}
}
// return next available latch entry
// and with latch entry locked
uint bt_availnext (BtMgr *mgr)
{
BtLatchSet *latch;
uint entry;
while( 1 ) {
#ifdef unix
entry = __sync_fetch_and_add (&mgr->pagezero->latchvictim, 1) + 1;
#else
entry = _InterlockedIncrement (&mgr->pagezero->latchvictim);
#endif
entry %= mgr->pagezero->latchtotal;
if( !entry )
continue;
latch = mgr->latchsets + entry;
if( !bt_mutextry(latch->modify) )
continue;
// return this entry if it is not pinned
if( !latch->pin )
return entry;
bt_releasemutex(latch->modify);
}
}
// pin latch in latch pool
BtLatchSet *bt_pinlatch (BtMgr *mgr, uid page_no)
{
uint hashidx = page_no % mgr->pagezero->latchhash;
uint entry, oldidx;
BtLatchSet *latch;
BtPage page;
// try to find our entry
bt_mutexlock(mgr->hashtable[hashidx].latch);
if( entry = mgr->hashtable[hashidx].entry ) do
{
latch = mgr->latchsets + entry;
if( page_no == latch->page_no )
break;
} while( entry = latch->next );
// found our entry: increment pin
if( entry ) {
latch = mgr->latchsets + entry;
bt_mutexlock(latch->modify);
latch->pin++;
bt_releasemutex(latch->modify);
bt_releasemutex(mgr->hashtable[hashidx].latch);
return latch;
}
// find and reuse unpinned entry
trynext:
entry = bt_availnext (mgr);
latch = mgr->latchsets + entry;
oldidx = latch->page_no % mgr->pagezero->latchhash;
// skip over this entry if latch not available
if( latch->page_no )
if( oldidx != hashidx )
if( !bt_mutextry (mgr->hashtable[oldidx].latch) ) {
bt_releasemutex(latch->modify);
goto trynext;
}
// if latch is on a different hash chain
// unlink from the old page_no chain
if( latch->page_no )
if( oldidx != hashidx ) {
if( latch->prev )
mgr->latchsets[latch->prev].next = latch->next;
else
mgr->hashtable[oldidx].entry = latch->next;
if( latch->next )
mgr->latchsets[latch->next].prev = latch->prev;
bt_releasemutex (mgr->hashtable[oldidx].latch);
}
// link page as head of hash table chain
// if this is a never before used entry,
// or it was previously on a different
// hash table chain. Otherwise, just
// leave it in its current hash table
// chain position.
if( !latch->page_no || hashidx != oldidx ) {
if( latch->next = mgr->hashtable[hashidx].entry )
mgr->latchsets[latch->next].prev = entry;
mgr->hashtable[hashidx].entry = entry;
latch->prev = 0;
}
// fill in latch structure
latch->page_no = page_no;
latch->pin = 1;
bt_releasemutex (latch->modify);
bt_releasemutex (mgr->hashtable[hashidx].latch);
return latch;
}
void bt_mgrclose (BtMgr *mgr)
{
char *name = mgr->type ? "Main" : "Cache";
BtLatchSet *latch;
uint num = 0;
BtPage page;
uint entry;
// flush previously written dirty pages
// and write recovery buffer to disk
fdatasync (mgr->idx);
#ifdef unix
while( mgr->segments )
munmap (mgr->pages[--mgr->segments], (uid)mgr->page_size << SEG_bits);
#else
while( mgr->segments ) {
FlushViewOfFile(mgr->pages[--mgr->segments], 0);
UnmapViewOfFile(mgr->pages[mgr->Segments]);
}
#endif
#ifdef unix
close (mgr->idx);
free (mgr);
#else
FlushFileBuffers(mgr->idx);
CloseHandle(mgr->idx);
GlobalFree (mgr);
#endif
}
// close and release memory
void bt_close (BtDb *bt)
{
free (bt);
}
void bt_initpage (BtMgr *mgr, BtPage page, uid leaf_page_no, uint lvl)
{
BtSlot *node = slotptr(page, 1);
unsigned char value[BtId];
uid page_no;
BtKey* key;
BtVal *val;
page_no = lvl ? ROOT_page : leaf_page_no;
node->off = mgr->page_size;
if( !lvl )
node->off <<= mgr->leaf_xtra;
node->off -= 3 + (lvl ? BtId + sizeof(BtVal): sizeof(BtVal));
node->type = Librarian;
node++->dead = 1;
node->off = node[-1].off;
key = keyptr(page, 2);
key = keyptr(page, 1);
key->len = 2; // create stopper key
key->key[0] = 0xff;
key->key[1] = 0xff;
bt_putid(value, leaf_page_no);
val = valptr(page, 1);
val->len = lvl ? BtId : 0;
memcpy (val->value, value, val->len);
page->fence = node->off;
page->min = node->off;
page->lvl = lvl;
page->cnt = 2;
page->act = 1;
if( bt_writepage (mgr, page, page_no, !lvl) ) {
fprintf (stderr, "Unable to create btree page %d\n", page_no);
exit(0);
}
}
// open/create new btree buffer manager
// call with file_name, BT_openmode, bits in page size (e.g. 16),
// extra bits for leaves (e.g. 4) size of latch pool (e.g. 500)
BtMgr *bt_mgr (char *name, uint pagebits, uint leafxtra, uint nodemax)
{
uint lvl, attr, last, slot, idx, blk;
int flag, initit = 0;
BtPageZero *pagezero;
struct flock lock[1];
BtLatchSet *latch;
uid leaf_page;
off64_t size;
BtPage page;
uint amt[1];
BtMgr* mgr;
// determine sanity of page size and buffer pool
if( leafxtra | pagebits )
if( leafxtra + pagebits > BT_maxbits )
fprintf (stderr, "pagebits + leafxtra > maxbits\n"), exit(1);
if( pagebits )
if( pagebits < BT_minbits )
fprintf (stderr, "pagebits < minbits\n"), exit(1);
#ifdef unix
mgr = calloc (1, sizeof(BtMgr));
mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
if( mgr->idx == -1 ) {
fprintf (stderr, "Unable to create/open btree file %s\n", name);
return free(mgr), NULL;
}
memset (lock, 0, sizeof(lock));
lock->l_len = sizeof(struct BtPage_);
lock->l_type = F_WRLCK;
if( fcntl (mgr->idx, F_SETLKW, lock) < 0 ) {
fprintf(stderr, "unable to lock record zero %s\n", name);
exit(1);
}
#else
mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
attr = FILE_ATTRIBUTE_NORMAL;
mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
if( mgr->idx == INVALID_HANDLE_VALUE ) {
fprintf (stderr, "Unable to create/open btree file %s\n", name);
return GlobalFree(mgr), NULL;
}
#endif
#ifdef unix
pagezero = valloc (BT_maxpage);
page = (BtPage)pagezero;
*amt = 0;
// read minimum page size to get root info
// to support raw disk partition files
// check if page_bits == 0 on the disk.
if( size = lseek (mgr->idx, 0L, 2) )
if( pread(mgr->idx, pagezero, BT_minpage, 0) == BT_minpage )
if( pagezero->page_bits ) {
pagebits = pagezero->page_bits;
leafxtra = pagezero->leaf_xtra;
} else
initit = 1;
else
return free(mgr), free(pagezero), NULL;
else
initit = 1;
#else
pagezero = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
size = GetFileSize(mgr->idx, amt);
if( size || *amt ) {
if( !ReadFile(mgr->idx, (char *)pagezero, BT_minpage, amt, NULL) )
return bt_mgrclose (mgr), NULL;
pagebits = pagezero->page_bits;
leafxtra = pagezero->leaf_xtra;
} else
initit = 1;
#endif
mgr->page_size = 1 << pagebits;
mgr->page_bits = pagebits;
mgr->leaf_xtra = leafxtra;
if( !initit )
goto mgrlatch;
// calculate number of latch table & hash entries
memset (pagezero, 0, 1 << pagebits);
pagezero->nlatchpage = nodemax/16 * sizeof(BtHashEntry);
pagezero->nlatchpage += sizeof(BtLatchSet) * nodemax + mgr->page_size - 1;
pagezero->nlatchpage >>= mgr->page_bits;
pagezero->latchtotal = nodemax;
pagezero->latchhash = (((uid)pagezero->nlatchpage<< mgr->page_bits) - nodemax * sizeof(BtLatchSet)) / sizeof(BtHashEntry);
// initialize an empty b-tree with alloc page, root page, leaf page
// and page(s) of latches and page pool cache
pagezero->page_bits = mgr->page_bits;
pagezero->leaf_xtra = leafxtra;
pagezero->upperpages = 1;
pagezero->leafpages = 1;
leaf_page = pagezero->leaf_page = pagezero->nlatchpage + LATCH_page;
// round first leafpage up to leafxtra boundary
if( pagezero->leaf_page & ((1 << leafxtra) - 1)) {
blk = pagezero->leaf_page;
pagezero->leaf_page |= (1 << leafxtra) - 1;
pagezero->freechain = pagezero->leaf_page++;
leaf_page = pagezero->leaf_page;
} else
blk = 0;
pagezero->rightleaf = pagezero->leaf_page;
pagezero->allocpage = pagezero->leaf_page + (1 << leafxtra);
if( pwrite (mgr->idx, pagezero, 1 << pagebits, 0) < 1 << pagebits) {
fprintf (stderr, "Unable to create btree page zero\n");
return bt_mgrclose (mgr), NULL;
}
// initialize root level 1 page
memset (page, 0, 1 << pagebits);
bt_initpage (mgr, page, leaf_page, 1);
// chain unused pages as first freelist
memset (page, 0, 1 << pagebits);
while( blk & ((1 << leafxtra) - 1) ) {
if( bt_writepage (mgr, page, blk, 0) ) {
fprintf(stderr, "unable to write initial free blk %d\r\n", blk);
exit(1);
}
page->right = blk++;
}
// initialize first page of leaves
memset (page, 0, 1 << pagebits);
bt_initpage (mgr, page, leaf_page, 0);
mgrlatch:
#ifdef unix
free (pagezero);
#else
VirtualFree (pagezero, 0, MEM_RELEASE);
#endif
lock->l_type = F_UNLCK;
if( fcntl (mgr->idx, F_SETLK, lock) < 0 ) {
fprintf (stderr, "Unable to unlock page zero\n");
exit(1);
}
// map first segment
mgr->segments = 1;
mgr->maxseg = MIN_seg;
mgr->pages = calloc (MIN_seg, sizeof(unsigned char *));
flag = PROT_READ | PROT_WRITE;
mgr->pages[0] = mmap (0, (uid)mgr->page_size << SEG_bits, flag, MAP_SHARED, mgr->idx, 0);
if( mgr->pages[0] == MAP_FAILED ) {
fprintf (stderr, "Unable to mmap pagezero btree segment, error = %d\n", errno);
return bt_mgrclose (mgr), NULL;
}
mgr->pagezero = (BtPageZero *)mgr->pages[0];
// mlock (mgr->pagezero, mgr->page_size);
// allocate latch pool
mgr->latchsets = (BtLatchSet *)(mgr->pages[0] + ((uid)LATCH_page << mgr->page_bits));
mgr->hashtable = (BtHashEntry *)(mgr->latchsets + mgr->pagezero->latchtotal);
return mgr;
}
// open BTree access method
// based on buffer manager
BtDb *bt_open (BtMgr *mgr, BtMgr *main)
{
BtDb *bt = malloc (sizeof(*bt));
memset (bt, 0, sizeof(*bt));
bt->tid = sys_gettid();
bt->main = main;
bt->mgr = mgr;
return bt;
}
// compare two keys, return > 0, = 0, or < 0