forked from malbrain/Btree-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadskv1.c
2717 lines (2141 loc) · 65.2 KB
/
threadskv1.c
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 threadskv1 sched_yield version
// with reworked bt_deletekey code
// and phase-fair reader writer lock
// 08 SEP 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
#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>
#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;
#ifndef unix
typedef unsigned long long off64_t;
typedef unsigned short ushort;
typedef unsigned int uint;
#endif
#define BT_latchtable 128 // number of latch manager slots
#define BT_ro 0x6f72 // ro
#define BT_rw 0x7772 // rw
#define BT_maxbits 24 // 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
/*
There are five lock types for each node in three 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.
*/
typedef enum{
BtLockAccess,
BtLockDelete,
BtLockRead,
BtLockWrite,
BtLockParent
} BtLock;
// definition for phase-fair reader/writer lock implementation
typedef struct {
ushort rin[1];
ushort rout[1];
ushort ticket[1];
ushort serving[1];
} RWLock;
#define PHID 0x1
#define PRES 0x2
#define MASK 0x3
#define RINC 0x4
// definition for spin latch implementation
// exclusive is set for write access
// share is count of read accessors
// grant write lock when share == 0
volatile typedef struct {
ushort exclusive:1;
ushort pending:1;
ushort share:14;
} BtSpinLatch;
#define XCL 1
#define PEND 2
#define BOTH 3
#define SHARE 4
// hash table entries
typedef struct {
BtSpinLatch latch[1];
volatile ushort slot; // Latch table entry at head of chain
} BtHashEntry;
// latch manager table structure
typedef struct {
RWLock readwr[1]; // read/write page lock
RWLock access[1]; // Access Intent/Page delete
RWLock parent[1]; // Posting of fence key in parent
BtSpinLatch busy[1]; // slot is being moved between chains
volatile ushort next; // next entry in hash table chain
volatile ushort prev; // prev entry in hash table chain
volatile ushort pin; // number of outstanding locks
volatile ushort hash; // hash slot entry is under
volatile uid page_no; // latch set page number
} BtLatchSet;
// Define the length of the page and key pointers
#define BtId 6
// Page key slot definition.
// If BT_maxbits is 15 or less, you can save 2 bytes
// for each key stored by making the two uints
// into ushorts.
// Keys are marked dead, but remain on the page until
// it cleanup is called. The fence key (highest key) for
// the page is always present, even after cleanup.
typedef struct {
uint off:BT_maxbits; // page offset for key start
uint dead:1; // set for deleted key
} 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;
unsigned char key[1];
} *BtKey;
// the value structure also occupies space at the upper
// end of the page.
typedef struct {
unsigned char len;
unsigned char value[1];
} *BtVal;
// 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 offset
unsigned char bits:7; // page size in bits
unsigned char free:1; // page is on free chain
unsigned char lvl:6; // level of page
unsigned char kill:1; // page is being deleted
unsigned char dirty:1; // page has deleted keys
unsigned char right[BtId]; // page number to right
} *BtPage;
// The memory mapping pool table buffer manager entry
typedef struct {
uid basepage; // mapped base page number
char *map; // mapped memory pointer
ushort slot; // slot index in this array
ushort pin; // mapped page pin counter
void *hashprev; // previous pool entry for the same hash idx
void *hashnext; // next pool entry for the same hash idx
#ifndef unix
HANDLE hmap; // Windows memory mapping handle
#endif
} BtPool;
#define CLOCK_bit 0x8000 // bit in pool->pin
// The loadpage interface object
typedef struct {
uid page_no; // current page number
BtPage page; // current page pointer
BtPool *pool; // current page pool
BtLatchSet *latch; // current page latch set
} BtPageSet;
// structure for latch manager on ALLOC_page
typedef struct {
struct BtPage_ alloc[1]; // next page_no in right ptr
unsigned char chain[BtId]; // head of free page_nos chain
BtSpinLatch lock[1]; // allocation area lite latch
ushort latchdeployed; // highest number of latch entries deployed
ushort nlatchpage; // number of latch pages at BT_latch
ushort latchtotal; // number of page latch entries
ushort latchhash; // number of latch hash table slots
ushort latchvictim; // next latch entry to examine
BtHashEntry table[0]; // the hash table
} BtLatchMgr;
// The object structure for Btree access
typedef struct {
uint page_size; // page size
uint page_bits; // page size in bits
uint seg_bits; // seg size in pages in bits
uint mode; // read-write mode
#ifdef unix
int idx;
#else
HANDLE idx;
#endif
ushort poolcnt; // highest page pool node in use
ushort poolmax; // highest page pool node allocated
ushort poolmask; // total number of pages in mmap segment - 1
ushort hashsize; // size of Hash Table for pool entries
volatile uint evicted; // last evicted hash table slot
ushort *hash; // pool index for hash entries
BtSpinLatch *latch; // latches for hash table slots
BtLatchMgr *latchmgr; // mapped latch page from allocation page
BtLatchSet *latchsets; // mapped latch set from latch pages
BtPool *pool; // memory pool page segments
#ifndef unix
HANDLE halloc; // allocation and latch table handle
#endif
} BtMgr;
typedef struct {
BtMgr *mgr; // buffer manager for thread
BtPage cursor; // cached frame for start/next (never mapped)
BtPage frame; // spare frame for the page split (never mapped)
uid cursor_page; // current cursor page number
unsigned char *mem; // frame, cursor, page memory buffer
int found; // last delete or insert was found
int err; // last error
} BtDb;
typedef enum {
BTERR_ok = 0,
BTERR_struct,
BTERR_ovflw,
BTERR_lock,
BTERR_map,
BTERR_wrt,
BTERR_hash
} BTERR;
// B-Tree functions
extern void bt_close (BtDb *bt);
extern BtDb *bt_open (BtMgr *mgr);
extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, void *value, uint vallen);
extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
extern int bt_findkey (BtDb *bt, unsigned char *key, uint keylen, unsigned char *value, uint vallen);
extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
extern uint bt_nextkey (BtDb *bt, uint slot);
// manager functions
extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
void bt_mgrclose (BtMgr *mgr);
// Helper functions to return slot values
// from the cursor page.
extern BtKey bt_key (BtDb *bt, uint slot);
extern BtVal bt_val (BtDb *bt, uint slot);
// BTree page number constants
#define ALLOC_page 0 // allocation & latch manager hash table
#define ROOT_page 1 // root of the btree
#define LEAF_page 2 // first page of leaves
#define LATCH_page 3 // pages for latch manager
// Number of levels to create in a new BTree
#define MIN_lvl 2
// 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 - 65534), and up to 253 bytes
// of key value. Duplicate keys are discarded.
// 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
// Groups of pages called segments from the btree are optionally
// cached with a memory mapped pool. A hash table is used to keep
// track of the cached segments. This behaviour is controlled
// by the cache block size parameter to bt_open.
// 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))
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;
}
// Phase-Fair reader/writer lock implementation
void WriteLock (RWLock *lock)
{
ushort w, r, tix;
#ifdef unix
tix = __sync_fetch_and_add (lock->ticket, 1);
#else
tix = _InterlockedExchangeAdd16 (lock->ticket, 1);
#endif
// wait for our ticket to come up
while( tix != lock->serving[0] )
#ifdef unix
sched_yield();
#else
SwitchToThread ();
#endif
w = PRES | (tix & PHID);
#ifdef unix
r = __sync_fetch_and_add (lock->rin, w);
#else
r = _InterlockedExchangeAdd16 (lock->rin, w);
#endif
while( r != *lock->rout )
#ifdef unix
sched_yield();
#else
SwitchToThread();
#endif
}
void WriteRelease (RWLock *lock)
{
#ifdef unix
__sync_fetch_and_and (lock->rin, ~MASK);
#else
_InterlockedAnd16 (lock->rin, ~MASK);
#endif
lock->serving[0]++;
}
void ReadLock (RWLock *lock)
{
ushort w;
#ifdef unix
w = __sync_fetch_and_add (lock->rin, RINC) & MASK;
#else
w = _InterlockedExchangeAdd16 (lock->rin, RINC) & MASK;
#endif
if( w )
while( w == (*lock->rin & MASK) )
#ifdef unix
sched_yield ();
#else
SwitchToThread ();
#endif
}
void ReadRelease (RWLock *lock)
{
#ifdef unix
__sync_fetch_and_add (lock->rout, RINC);
#else
_InterlockedExchangeAdd16 (lock->rout, RINC);
#endif
}
// Spin Latch Manager
// wait until write lock mode is clear
// and add 1 to the share count
void bt_spinreadlock(BtSpinLatch *latch)
{
ushort prev;
do {
#ifdef unix
prev = __sync_fetch_and_add ((ushort *)latch, SHARE);
#else
prev = _InterlockedExchangeAdd16((ushort *)latch, SHARE);
#endif
// see if exclusive request is granted or pending
if( !(prev & BOTH) )
return;
#ifdef unix
prev = __sync_fetch_and_add ((ushort *)latch, -SHARE);
#else
prev = _InterlockedExchangeAdd16((ushort *)latch, -SHARE);
#endif
#ifdef unix
} while( sched_yield(), 1 );
#else
} while( SwitchToThread(), 1 );
#endif
}
// wait for other read and write latches to relinquish
void bt_spinwritelock(BtSpinLatch *latch)
{
ushort prev;
do {
#ifdef unix
prev = __sync_fetch_and_or((ushort *)latch, PEND | XCL);
#else
prev = _InterlockedOr16((ushort *)latch, PEND | XCL);
#endif
if( !(prev & XCL) )
if( !(prev & ~BOTH) )
return;
else
#ifdef unix
__sync_fetch_and_and ((ushort *)latch, ~XCL);
#else
_InterlockedAnd16((ushort *)latch, ~XCL);
#endif
#ifdef unix
} while( sched_yield(), 1 );
#else
} while( SwitchToThread(), 1 );
#endif
}
// try to obtain write lock
// return 1 if obtained,
// 0 otherwise
int bt_spinwritetry(BtSpinLatch *latch)
{
ushort prev;
#ifdef unix
prev = __sync_fetch_and_or((ushort *)latch, XCL);
#else
prev = _InterlockedOr16((ushort *)latch, XCL);
#endif
// take write access if all bits are clear
if( !(prev & XCL) )
if( !(prev & ~BOTH) )
return 1;
else
#ifdef unix
__sync_fetch_and_and ((ushort *)latch, ~XCL);
#else
_InterlockedAnd16((ushort *)latch, ~XCL);
#endif
return 0;
}
// clear write mode
void bt_spinreleasewrite(BtSpinLatch *latch)
{
#ifdef unix
__sync_fetch_and_and((ushort *)latch, ~BOTH);
#else
_InterlockedAnd16((ushort *)latch, ~BOTH);
#endif
}
// decrement reader count
void bt_spinreleaseread(BtSpinLatch *latch)
{
#ifdef unix
__sync_fetch_and_add((ushort *)latch, -SHARE);
#else
_InterlockedExchangeAdd16((ushort *)latch, -SHARE);
#endif
}
// link latch table entry into latch hash table
void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
{
BtLatchSet *set = bt->mgr->latchsets + victim;
if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
bt->mgr->latchsets[set->next].prev = victim;
bt->mgr->latchmgr->table[hashidx].slot = victim;
set->page_no = page_no;
set->hash = hashidx;
set->prev = 0;
}
// release latch pin
void bt_unpinlatch (BtLatchSet *set)
{
#ifdef unix
__sync_fetch_and_add(&set->pin, -1);
#else
_InterlockedDecrement16 (&set->pin);
#endif
}
// find existing latchset or inspire new one
// return with latchset pinned
BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
{
ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
ushort slot, avail = 0, victim, idx;
BtLatchSet *set;
// obtain read lock on hash table entry
bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
{
set = bt->mgr->latchsets + slot;
if( page_no == set->page_no )
break;
} while( slot = set->next );
if( slot ) {
#ifdef unix
__sync_fetch_and_add(&set->pin, 1);
#else
_InterlockedIncrement16 (&set->pin);
#endif
}
bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
if( slot )
return set;
// try again, this time with write lock
bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
{
set = bt->mgr->latchsets + slot;
if( page_no == set->page_no )
break;
if( !set->pin && !avail )
avail = slot;
} while( slot = set->next );
// found our entry, or take over an unpinned one
if( slot || (slot = avail) ) {
set = bt->mgr->latchsets + slot;
#ifdef unix
__sync_fetch_and_add(&set->pin, 1);
#else
_InterlockedIncrement16 (&set->pin);
#endif
set->page_no = page_no;
bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
return set;
}
// see if there are any unused entries
#ifdef unix
victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
#else
victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
#endif
if( victim < bt->mgr->latchmgr->latchtotal ) {
set = bt->mgr->latchsets + victim;
#ifdef unix
__sync_fetch_and_add(&set->pin, 1);
#else
_InterlockedIncrement16 (&set->pin);
#endif
bt_latchlink (bt, hashidx, victim, page_no);
bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
return set;
}
#ifdef unix
victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
#else
victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
#endif
// find and reuse previous lock entry
while( 1 ) {
#ifdef unix
victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
#else
victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
#endif
// we don't use slot zero
if( victim %= bt->mgr->latchmgr->latchtotal )
set = bt->mgr->latchsets + victim;
else
continue;
// take control of our slot
// from other threads
if( set->pin || !bt_spinwritetry (set->busy) )
continue;
idx = set->hash;
// try to get write lock on hash chain
// skip entry if not obtained
// or has outstanding locks
if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
bt_spinreleasewrite (set->busy);
continue;
}
if( set->pin ) {
bt_spinreleasewrite (set->busy);
bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
continue;
}
// unlink our available victim from its hash chain
if( set->prev )
bt->mgr->latchsets[set->prev].next = set->next;
else
bt->mgr->latchmgr->table[idx].slot = set->next;
if( set->next )
bt->mgr->latchsets[set->next].prev = set->prev;
bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
#ifdef unix
__sync_fetch_and_add(&set->pin, 1);
#else
_InterlockedIncrement16 (&set->pin);
#endif
bt_latchlink (bt, hashidx, victim, page_no);
bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
bt_spinreleasewrite (set->busy);
return set;
}
}
void bt_mgrclose (BtMgr *mgr)
{
BtPool *pool;
uint slot;
// release mapped pages
// note that slot zero is never used
for( slot = 1; slot < mgr->poolmax; slot++ ) {
pool = mgr->pool + slot;
if( pool->slot )
#ifdef unix
munmap (pool->map, (uid)(mgr->poolmask+1) << mgr->page_bits);
#else
{
FlushViewOfFile(pool->map, 0);
UnmapViewOfFile(pool->map);
CloseHandle(pool->hmap);
}
#endif
}
#ifdef unix
munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
munmap (mgr->latchmgr, 2 * mgr->page_size);
#else
FlushViewOfFile(mgr->latchmgr, 0);
UnmapViewOfFile(mgr->latchmgr);
CloseHandle(mgr->halloc);
#endif
#ifdef unix
close (mgr->idx);
free (mgr->pool);
free (mgr->hash);
free ((void *)mgr->latch);
free (mgr);
#else
FlushFileBuffers(mgr->idx);
CloseHandle(mgr->idx);
GlobalFree (mgr->pool);
GlobalFree (mgr->hash);
GlobalFree ((void *)mgr->latch);
GlobalFree (mgr);
#endif
}
// close and release memory
void bt_close (BtDb *bt)
{
#ifdef unix
if( bt->mem )
free (bt->mem);
#else
if( bt->mem)
VirtualFree (bt->mem, 0, MEM_RELEASE);
#endif
free (bt);
}
// open/create new btree buffer manager
// call with file_name, BT_openmode, bits in page size (e.g. 16),
// size of mapped page pool (e.g. 8192)
BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
{
uint lvl, attr, cacheblk, last, slot, idx;
uint nlatchpage, latchhash;
unsigned char value[BtId];
BtLatchMgr *latchmgr;
off64_t size;
uint amt[1];
BtMgr* mgr;
BtKey key;
BtVal val;
int flag;
#ifndef unix
SYSTEM_INFO sysinfo[1];
#endif
// determine sanity of page size and buffer pool
if( bits > BT_maxbits )
bits = BT_maxbits;
else if( bits < BT_minbits )
bits = BT_minbits;
if( !poolmax )
return NULL; // must have buffer pool
#ifdef unix
mgr = calloc (1, sizeof(BtMgr));
mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
if( mgr->idx == -1 )
return free(mgr), NULL;
cacheblk = 4096; // minimum mmap segment size for unix
#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 )
return GlobalFree(mgr), NULL;
// normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
GetSystemInfo(sysinfo);
cacheblk = sysinfo->dwAllocationGranularity;
#endif
#ifdef unix
latchmgr = malloc (BT_maxpage);
*amt = 0;
// read minimum page size to get root info
if( size = lseek (mgr->idx, 0L, 2) ) {
if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
bits = latchmgr->alloc->bits;
else
return free(mgr), free(latchmgr), NULL;
} else if( mode == BT_ro )
return free(latchmgr), bt_mgrclose (mgr), NULL;
#else
latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
size = GetFileSize(mgr->idx, amt);
if( size || *amt ) {
if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
return bt_mgrclose (mgr), NULL;
bits = latchmgr->alloc->bits;
} else if( mode == BT_ro )
return bt_mgrclose (mgr), NULL;
#endif
mgr->page_size = 1 << bits;
mgr->page_bits = bits;
mgr->poolmax = poolmax;
mgr->mode = mode;
if( cacheblk < mgr->page_size )
cacheblk = mgr->page_size;
// mask for partial memmaps
mgr->poolmask = (cacheblk >> bits) - 1;
// see if requested size of pages per memmap is greater
if( (1 << segsize) > mgr->poolmask )
mgr->poolmask = (1 << segsize) - 1;
mgr->seg_bits = 0;
while( (1 << mgr->seg_bits) <= mgr->poolmask )
mgr->seg_bits++;
mgr->hashsize = hashsize;
#ifdef unix
mgr->pool = calloc (poolmax, sizeof(BtPool));
mgr->hash = calloc (hashsize, sizeof(ushort));
mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
#else
mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
#endif
if( size || *amt )
goto mgrlatch;
// initialize an empty b-tree with latch page, root page, page of leaves
// and page(s) of latches
memset (latchmgr, 0, 1 << bits);
nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
latchmgr->alloc->bits = mgr->page_bits;
latchmgr->nlatchpage = nlatchpage;
latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
// initialize latch manager
latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
// size of hash table = total number of latchsets
if( latchhash > latchmgr->latchtotal )
latchhash = latchmgr->latchtotal;
latchmgr->latchhash = latchhash;
#ifdef unix
if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
return bt_mgrclose (mgr), NULL;
#else
if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
return bt_mgrclose (mgr), NULL;
if( *amt < mgr->page_size )
return bt_mgrclose (mgr), NULL;
#endif
memset (latchmgr, 0, 1 << bits);
latchmgr->alloc->bits = mgr->page_bits;
for( lvl=MIN_lvl; lvl--; ) {
slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3 - (lvl ? BtId + 1: 1);
key = keyptr(latchmgr->alloc, 1);
key->len = 2; // create stopper key
key->key[0] = 0xff;
key->key[1] = 0xff;
bt_putid(value, MIN_lvl - lvl + 1);
val = valptr(latchmgr->alloc, 1);
val->len = lvl ? BtId : 0;
memcpy (val->value, value, val->len);
latchmgr->alloc->min = slotptr(latchmgr->alloc, 1)->off;
latchmgr->alloc->lvl = lvl;
latchmgr->alloc->cnt = 1;
latchmgr->alloc->act = 1;
#ifdef unix
if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
return bt_mgrclose (mgr), NULL;
#else
if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
return bt_mgrclose (mgr), NULL;
if( *amt < mgr->page_size )
return bt_mgrclose (mgr), NULL;
#endif
}
// clear out latch manager locks
// and rest of pages to round out segment
memset(latchmgr, 0, mgr->page_size);
last = MIN_lvl + 1;
while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
#ifdef unix
pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
#else
SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
return bt_mgrclose (mgr), NULL;
if( *amt < mgr->page_size )
return bt_mgrclose (mgr), NULL;
#endif
last++;
}
mgrlatch:
#ifdef unix
// mlock the root page and the latchmgr page
flag = PROT_READ | PROT_WRITE;
mgr->latchmgr = mmap (0, 2 * mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
if( mgr->latchmgr == MAP_FAILED )