forked from malbrain/Btree-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btree2u.c
2322 lines (1854 loc) · 54.5 KB
/
btree2u.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 2u sched_yield locks
// with combined latch & pool manager
// and phase-fair reader writer lock
// 12 MAR 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 <time.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <io.h>
#endif
#include <memory.h>
#include <string.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_ro 0x6f72 // ro
#define BT_rw 0x7772 // rw
#define BT_fl 0x6c66 // fl
#define BT_maxbits 15 // maximum page size in bits
#define BT_minbits 12 // 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
#define ROOT_page 1
#define LEAF_page 2
#define LATCH_page 3
// Number of levels to create in a new BTree
#define MIN_lvl 2
#define MAX_lvl 15
/*
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 latch implementation
volatile typedef struct {
ushort lock[1];
} BtSpinLatch;
#define XCL 1
#define PEND 2
#define BOTH 3
#define SHARE 4
volatile typedef struct {
ushort rin[1]; // readers in count
ushort rout[1]; // readers out count
ushort serving[1]; // writers out count
ushort ticket[1]; // writers in count
} RWLock;
// define bits at bottom of rin
#define PHID 0x1 // writer phase (0/1)
#define PRES 0x2 // writer present
#define MASK 0x3 // both write bits
#define RINC 0x4 // reader increment
// 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 first two uints
// into ushorts. You can also save 4 bytes by removing
// the tod field from the key.
// Keys are marked dead, but remain on the page until
// cleanup is called. The fence key (highest key) for
// the page is always present, even if dead.
typedef struct {
#ifdef USETOD
uint tod; // time-stamp for key
#endif
ushort off:BT_maxbits; // page offset for key start
ushort dead:1; // set for deleted key
unsigned char id[BtId]; // id associated with key
} BtSlot;
// The key structure occupies space at the upper end of
// each page. It's a length byte followed by the value
// bytes.
typedef struct {
unsigned char len;
unsigned char key[0];
} *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 offset
unsigned char bits:6; // page size in bits
unsigned char free:1; // page is on free list
unsigned char dirty:1; // page is dirty in cache
unsigned char lvl:6; // level of page
unsigned char kill:1; // page is being deleted
unsigned char clean:1; // page needs cleaning
unsigned char right[BtId]; // page number to right
} *BtPage;
typedef struct {
struct BtPage_ alloc[2]; // next & free page_nos in right ptr
BtSpinLatch lock[1]; // allocation area lite latch
volatile uint latchdeployed;// highest number of latch entries deployed
volatile uint nlatchpage; // number of latch pages at BT_latch
volatile uint latchtotal; // number of page latch entries
volatile uint latchhash; // number of latch hash table slots
volatile uint latchvictim; // next latch hash entry to examine
volatile uint safelevel; // safe page level in cache
volatile uint cache[MAX_lvl];// cache census counts by btree level
} BtLatchMgr;
// latch hash table entries
typedef struct {
volatile uint slot; // Latch table entry at head of collision chain
BtSpinLatch latch[1]; // lock for the collision chain
} BtHashEntry;
// latch manager table structure
typedef struct {
volatile uid page_no; // latch set page number on disk
RWLock readwr[1]; // read/write page lock
RWLock access[1]; // Access Intent/Page delete
RWLock parent[1]; // Posting of fence key in parent
volatile ushort pin; // number of pins/level/clock bits
volatile uint next; // next entry in hash table chain
volatile uint prev; // prev entry in hash table chain
} BtLatchSet;
#define CLOCK_mask 0xe000
#define CLOCK_unit 0x2000
#define PIN_mask 0x07ff
#define LVL_mask 0x1800
#define LVL_shift 11
// The object structure for Btree access
typedef struct _BtDb {
uint page_size; // each page size
uint page_bits; // each page size in bits
uid page_no; // current page number
uid cursor_page; // current cursor page number
int err;
uint mode; // read-write mode
BtPage cursor; // cached frame for start/next (never mapped)
BtPage frame; // spare frame for the page split (never mapped)
BtPage page; // current mapped page in buffer pool
BtLatchSet *latch; // current page latch
BtLatchMgr *latchmgr; // mapped latch page from allocation page
BtLatchSet *latchsets; // mapped latch set from latch pages
unsigned char *pagepool; // cached page pool set
BtHashEntry *table; // the hash table
#ifdef unix
int idx;
#else
HANDLE idx;
HANDLE halloc; // allocation and latch table handle
#endif
unsigned char *mem; // frame, cursor, memory buffers
uint found; // last deletekey found key
} BtDb;
typedef enum {
BTERR_ok = 0,
BTERR_notfound,
BTERR_struct,
BTERR_ovflw,
BTERR_read,
BTERR_lock,
BTERR_hash,
BTERR_kill,
BTERR_map,
BTERR_wrt,
BTERR_eof
} BTERR;
// B-Tree functions
extern void bt_close (BtDb *bt);
extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk);
extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
extern uint bt_nextkey (BtDb *bt, uint slot);
// internal functions
void bt_update (BtDb *bt, BtPage page);
BtPage bt_mappage (BtDb *bt, BtLatchSet *latch);
// Helper functions to return slot values
extern BtKey bt_key (BtDb *bt, uint slot);
extern uid bt_uid (BtDb *bt, uint slot);
#ifdef USETOD
extern uint bt_tod (BtDb *bt, uint slot);
#endif
// The page is allocated from low and hi ends.
// The key offsets and row-id's are allocated
// from the bottom, while the text of the key
// is 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 48 bit row-id.
// 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 right
// 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 node is always
// present, even after deletion and cleanup.
// Deleted leaf pages are reclaimed on a free list.
// The upper levels of the btree are fixed on creation.
// 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 (ALLOC page) is dedicated to lock for new page extensions,
// and chains empty leaf pages together for reuse.
// Parent locks are obtained to prevent resplitting or deleting a node
// before its fence is posted into its upper level.
// A special open mode of BT_fl is provided to safely access files on
// WIN32 networks. WIN32 network operations should not use memory mapping.
// This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
// to prevent local caching of network file contents.
// 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))
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;
}
BTERR bt_abort (BtDb *bt, BtPage page, uid page_no, BTERR err)
{
BtKey ptr;
fprintf(stderr, "\n Btree2 abort, error %d on page %.8x\n", err, page_no);
fprintf(stderr, "level=%d kill=%d free=%d cnt=%x act=%x\n", page->lvl, page->kill, page->free, page->cnt, page->act);
ptr = keyptr(page, page->cnt);
fprintf(stderr, "fence='%.*s'\n", ptr->len, ptr->key);
fprintf(stderr, "right=%.8x\n", bt_getid(page->right));
return bt->err = err;
}
// 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 (latch->lock, SHARE);
#else
prev = _InterlockedExchangeAdd16(latch->lock, SHARE);
#endif
// see if exclusive request is granted or pending
if( !(prev & BOTH) )
return;
#ifdef unix
prev = __sync_fetch_and_add (latch->lock, -SHARE);
#else
prev = _InterlockedExchangeAdd16(latch->lock, -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(latch->lock, PEND | XCL);
#else
prev = _InterlockedOr16(latch->lock, PEND | XCL);
#endif
if( !(prev & XCL) )
if( !(prev & ~BOTH) )
return;
else
#ifdef unix
__sync_fetch_and_and (latch->lock, ~XCL);
#else
_InterlockedAnd16(latch->lock, ~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(latch->lock, XCL);
#else
prev = _InterlockedOr16(latch->lock, 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 (latch->lock, ~XCL);
#else
_InterlockedAnd16(latch->lock, ~XCL);
#endif
return 0;
}
// clear write mode
void bt_spinreleasewrite(BtSpinLatch *latch)
{
#ifdef unix
__sync_fetch_and_and(latch->lock, ~BOTH);
#else
_InterlockedAnd16(latch->lock, ~BOTH);
#endif
}
// decrement reader count
void bt_spinreleaseread(BtSpinLatch *latch)
{
#ifdef unix
__sync_fetch_and_add(latch->lock, -SHARE);
#else
_InterlockedExchangeAdd16(latch->lock, -SHARE);
#endif
}
// read page from permanent location in Btree file
BTERR bt_readpage (BtDb *bt, BtPage page, uid page_no)
{
off64_t off = page_no << bt->page_bits;
#ifdef unix
if( pread (bt->idx, page, bt->page_size, page_no << bt->page_bits) < bt->page_size ) {
fprintf (stderr, "Unable to read page %.8x errno = %d\n", page_no, errno);
return bt->err = BTERR_read;
}
#else
OVERLAPPED ovl[1];
uint amt[1];
memset (ovl, 0, sizeof(OVERLAPPED));
ovl->Offset = off;
ovl->OffsetHigh = off >> 32;
if( !ReadFile(bt->idx, page, bt->page_size, amt, ovl)) {
fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
return bt->err = BTERR_read;
}
if( *amt < bt->page_size ) {
fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
return bt->err = BTERR_read;
}
#endif
return 0;
}
// write page to permanent location in Btree file
// clear the dirty bit
BTERR bt_writepage (BtDb *bt, BtPage page, uid page_no)
{
off64_t off = page_no << bt->page_bits;
#ifdef unix
page->dirty = 0;
if( pwrite(bt->idx, page, bt->page_size, off) < bt->page_size )
return bt->err = BTERR_wrt;
#else
OVERLAPPED ovl[1];
uint amt[1];
memset (ovl, 0, sizeof(OVERLAPPED));
ovl->Offset = off;
ovl->OffsetHigh = off >> 32;
page->dirty = 0;
if( !WriteFile(bt->idx, page, bt->page_size, amt, ovl) )
return bt->err = BTERR_wrt;
if( *amt < bt->page_size )
return bt->err = BTERR_wrt;
#endif
return 0;
}
// link latch table entry into head of latch hash table
BTERR bt_latchlink (BtDb *bt, uint hashidx, uint slot, uid page_no)
{
BtPage page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
BtLatchSet *latch = bt->latchsets + slot;
int lvl;
if( latch->next = bt->table[hashidx].slot )
bt->latchsets[latch->next].prev = slot;
bt->table[hashidx].slot = slot;
latch->page_no = page_no;
latch->prev = 0;
latch->pin = 1;
if( bt_readpage (bt, page, page_no) )
return bt->err;
lvl = page->lvl << LVL_shift;
if( lvl > LVL_mask )
lvl = LVL_mask;
latch->pin |= lvl; // store lvl
latch->pin |= lvl << 3; // initialize clock
#ifdef unix
__sync_fetch_and_add (&bt->latchmgr->cache[page->lvl], 1);
#else
_InterlockedExchangeAdd(&bt->latchmgr->cache[page->lvl], 1);
#endif
return bt->err = 0;
}
// release latch pin
void bt_unpinlatch (BtLatchSet *latch)
{
#ifdef unix
__sync_fetch_and_add(&latch->pin, -1);
#else
_InterlockedDecrement16 (&latch->pin);
#endif
}
// find existing latchset or inspire new one
// return with latchset pinned
BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
{
uint hashidx = page_no % bt->latchmgr->latchhash;
BtLatchSet *latch;
uint slot, idx;
uint lvl, cnt;
off64_t off;
uint amt[1];
BtPage page;
// try to find our entry
bt_spinwritelock(bt->table[hashidx].latch);
if( slot = bt->table[hashidx].slot ) do
{
latch = bt->latchsets + slot;
if( page_no == latch->page_no )
break;
} while( slot = latch->next );
// found our entry
// increment clock
if( slot ) {
latch = bt->latchsets + slot;
lvl = (latch->pin & LVL_mask) >> LVL_shift;
lvl *= CLOCK_unit * 2;
lvl |= CLOCK_unit;
#ifdef unix
__sync_fetch_and_add(&latch->pin, 1);
__sync_fetch_and_or(&latch->pin, lvl);
#else
_InterlockedIncrement16 (&latch->pin);
_InterlockedOr16 (&latch->pin, lvl);
#endif
bt_spinreleasewrite(bt->table[hashidx].latch);
return latch;
}
// see if there are any unused pool entries
#ifdef unix
slot = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, 1) + 1;
#else
slot = _InterlockedIncrement (&bt->latchmgr->latchdeployed);
#endif
if( slot < bt->latchmgr->latchtotal ) {
latch = bt->latchsets + slot;
if( bt_latchlink (bt, hashidx, slot, page_no) )
return NULL;
bt_spinreleasewrite (bt->table[hashidx].latch);
return latch;
}
#ifdef unix
__sync_fetch_and_add (&bt->latchmgr->latchdeployed, -1);
#else
_InterlockedDecrement (&bt->latchmgr->latchdeployed);
#endif
// find and reuse previous entry on victim
while( 1 ) {
#ifdef unix
slot = __sync_fetch_and_add(&bt->latchmgr->latchvictim, 1);
#else
slot = _InterlockedIncrement (&bt->latchmgr->latchvictim) - 1;
#endif
// try to get write lock on hash chain
// skip entry if not obtained
// or has outstanding pins
slot %= bt->latchmgr->latchtotal;
// on slot wraparound, check census
// count and increment safe level
cnt = bt->latchmgr->cache[bt->latchmgr->safelevel];
if( !slot ) {
if( cnt < bt->latchmgr->latchtotal / 10 )
#ifdef unix
__sync_fetch_and_add(&bt->latchmgr->safelevel, 1);
#else
_InterlockedIncrement (&bt->latchmgr->safelevel);
#endif
continue;
}
latch = bt->latchsets + slot;
idx = latch->page_no % bt->latchmgr->latchhash;
lvl = (latch->pin & LVL_mask) >> LVL_shift;
// see if we are evicting this level yet
// or if we are on same chain as hashidx
if( idx == hashidx || lvl > bt->latchmgr->safelevel )
continue;
if( !bt_spinwritetry (bt->table[idx].latch) )
continue;
if( latch->pin & ~LVL_mask ) {
if( latch->pin & CLOCK_mask )
#ifdef unix
__sync_fetch_and_add(&latch->pin, -CLOCK_unit);
#else
_InterlockedExchangeAdd16 (&latch->pin, -CLOCK_unit);
#endif
bt_spinreleasewrite (bt->table[idx].latch);
continue;
}
// update permanent page area in btree
page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
#ifdef unix
posix_fadvise (bt->idx, page_no << bt->page_bits, bt->page_size, POSIX_FADV_WILLNEED);
__sync_fetch_and_add (&bt->latchmgr->cache[page->lvl], -1);
#else
_InterlockedExchangeAdd(&bt->latchmgr->cache[page->lvl], -1);
#endif
if( page->dirty )
if( bt_writepage (bt, page, latch->page_no) )
return NULL;
// unlink our available slot from its hash chain
if( latch->prev )
bt->latchsets[latch->prev].next = latch->next;
else
bt->table[idx].slot = latch->next;
if( latch->next )
bt->latchsets[latch->next].prev = latch->prev;
bt_spinreleasewrite (bt->table[idx].latch);
if( bt_latchlink (bt, hashidx, slot, page_no) )
return NULL;
bt_spinreleasewrite (bt->table[hashidx].latch);
return latch;
}
}
// close and release memory
void bt_close (BtDb *bt)
{
#ifdef unix
munmap (bt->table, bt->latchmgr->nlatchpage * bt->page_size);
munmap (bt->latchmgr, bt->page_size);
#else
FlushViewOfFile(bt->latchmgr, 0);
UnmapViewOfFile(bt->latchmgr);
CloseHandle(bt->halloc);
#endif
#ifdef unix
if( bt->mem )
free (bt->mem);
close (bt->idx);
free (bt);
#else
if( bt->mem)
VirtualFree (bt->mem, 0, MEM_RELEASE);
FlushFileBuffers(bt->idx);
CloseHandle(bt->idx);
GlobalFree (bt);
#endif
}
// open/create new btree
// call with file_name, BT_openmode, bits in page size (e.g. 16),
// size of mapped page pool (e.g. 8192)
BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax)
{
uint lvl, attr, last, slot, idx;
uint nlatchpage, latchhash;
BtLatchMgr *latchmgr;
off64_t size, off;
uint amt[1];
BtKey key;
BtDb* bt;
int flag;
#ifndef unix
OVERLAPPED ovl[1];
#else
struct flock lock[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( mode == BT_ro ) {
fprintf(stderr, "ReadOnly mode not supported: %s\n", name);
return NULL;
}
#ifdef unix
bt = calloc (1, sizeof(BtDb));
bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
posix_fadvise( bt->idx, 0, 0, POSIX_FADV_RANDOM);
if( bt->idx == -1 ) {
fprintf(stderr, "unable to open %s\n", name);
return free(bt), NULL;
}
#else
bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb));
attr = FILE_ATTRIBUTE_NORMAL;
bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
if( bt->idx == INVALID_HANDLE_VALUE ) {
fprintf(stderr, "unable to open %s\n", name);
return GlobalFree(bt), NULL;
}
#endif
#ifdef unix
memset (lock, 0, sizeof(lock));
lock->l_len = sizeof(struct BtPage_);
lock->l_type = F_WRLCK;
if( fcntl (bt->idx, F_SETLKW, lock) < 0 ) {
fprintf(stderr, "unable to lock record zero %s\n", name);
return bt_close (bt), NULL;
}
#else
memset (ovl, 0, sizeof(ovl));
// use large offsets to
// simulate advisory locking
ovl->OffsetHigh |= 0x80000000;
if( !LockFileEx (bt->idx, LOCKFILE_EXCLUSIVE_LOCK, 0, sizeof(struct BtPage_), 0L, ovl) ) {
fprintf(stderr, "unable to lock record zero %s, GetLastError = %d\n", name, GetLastError());
return bt_close (bt), NULL;
}
#endif
#ifdef unix
latchmgr = valloc (BT_maxpage);
*amt = 0;
// read minimum page size to get root info
if( size = lseek (bt->idx, 0L, 2) ) {
if( pread(bt->idx, latchmgr, BT_minpage, 0) == BT_minpage )
bits = latchmgr->alloc->bits;
else {
fprintf(stderr, "Unable to read page zero\n");
return free(bt), free(latchmgr), NULL;
}
}
#else
latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
size = GetFileSize(bt->idx, amt);
if( size || *amt ) {
if( !ReadFile(bt->idx, (char *)latchmgr, BT_minpage, amt, NULL) ) {
fprintf(stderr, "Unable to read page zero\n");
return bt_close (bt), NULL;
} else
bits = latchmgr->alloc->bits;
}
#endif
bt->page_size = 1 << bits;
bt->page_bits = bits;
bt->mode = mode;
if( size || *amt ) {
nlatchpage = latchmgr->nlatchpage;
goto btlatch;
}
if( nodemax < 16 ) {
fprintf(stderr, "Buffer pool too small: %d\n", nodemax);
return bt_close(bt), NULL;
}
// initialize an empty b-tree with latch page, root page, page of leaves
// and page(s) of latches and page pool cache
memset (latchmgr, 0, 1 << bits);
latchmgr->alloc->bits = bt->page_bits;
// calculate number of latch hash table entries
nlatchpage = (nodemax/16 * sizeof(BtHashEntry) + bt->page_size - 1) / bt->page_size;
latchhash = nlatchpage * bt->page_size / sizeof(BtHashEntry);
nlatchpage += nodemax; // size of the buffer pool in pages
nlatchpage += (sizeof(BtLatchSet) * nodemax + bt->page_size - 1)/bt->page_size;
bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
latchmgr->nlatchpage = nlatchpage;
latchmgr->latchtotal = nodemax;
latchmgr->latchhash = latchhash;
if( bt_writepage (bt, latchmgr->alloc, 0) ) {
fprintf (stderr, "Unable to create btree page zero\n");
return bt_close (bt), NULL;
}
memset (latchmgr, 0, 1 << bits);
latchmgr->alloc->bits = bt->page_bits;
for( lvl=MIN_lvl; lvl--; ) {
last = MIN_lvl - lvl; // page number
slotptr(latchmgr->alloc, 1)->off = bt->page_size - 3;
bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? last + 1 : 0);
key = keyptr(latchmgr->alloc, 1);
key->len = 2; // create stopper key
key->key[0] = 0xff;
key->key[1] = 0xff;
latchmgr->alloc->min = bt->page_size - 3;
latchmgr->alloc->lvl = lvl;
latchmgr->alloc->cnt = 1;
latchmgr->alloc->act = 1;
if( bt_writepage (bt, latchmgr->alloc, last) ) {
fprintf (stderr, "Unable to create btree page %.8x\n", last);
return bt_close (bt), NULL;
}
}
// clear out buffer pool pages
memset(latchmgr, 0, bt->page_size);
last = MIN_lvl + nlatchpage;
if( bt_writepage (bt, latchmgr->alloc, last) ) {
fprintf (stderr, "Unable to write buffer pool page %.8x\n", last);
return bt_close (bt), NULL;
}
#ifdef unix
free (latchmgr);
#else
VirtualFree (latchmgr, 0, MEM_RELEASE);
#endif
btlatch:
#ifdef unix
lock->l_type = F_UNLCK;
if( fcntl (bt->idx, F_SETLK, lock) < 0 ) {
fprintf (stderr, "Unable to unlock page zero\n");
return bt_close (bt), NULL;
}
#else