forked from malbrain/Btree-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadskv7.c
3054 lines (2375 loc) · 72.5 KB
/
threadskv7.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 threadskv7 sched_yield version
// with reworked bt_deletekey code,
// phase-fair reader writer lock,
// librarian page split code,
// duplicate key management
// bi-directional cursors
// traditional buffer pool manager
// and atomic non-consistent key insert
// 17 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_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
// BTree page number constants
#define ALLOC_page 0 // allocation page
#define ROOT_page 1 // root of the btree
#define LEAF_page 2 // first page of leaves
// Number of levels to create in a new BTree
#define MIN_lvl 2
// maximum number of keys to insert atomically in one call
#define MAX_atomic 256
#define BT_maxkey 255 // maximum number of bytes in a key
#define BT_keyarray (BT_maxkey + sizeof(BtKey))
/*
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 {
uint exclusive:1;
uint pending:1;
uint share:30;
} BtSpinLatch;
#define XCL 1
#define PEND 2
#define BOTH 3
#define SHARE 4
// 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;
// hash table entries
typedef struct {
uint slot; // Latch table entry at head of chain
BtSpinLatch latch[1];
} BtHashEntry;
// latch manager table structure
typedef struct {
uid page_no; // latch set page number
RWLock readwr[1]; // read/write page lock
RWLock access[1]; // Access Intent/Page delete
RWLock parent[1]; // Posting of fence key in parent
uint slot; // entry slot in latch table
uint next; // next entry in hash table chain
uint prev; // prev entry in hash table chain
volatile ushort pin; // number of outstanding threads
ushort dirty:1; // page in cache is dirty
} BtLatchSet;
// lock manager table structure
typedef struct {
RWLock readwr[1]; // read/write key lock
uint next;
uint prev;
uint pin; // count of readers waiting
uint hashidx; // hash idx for entry
unsigned char key[BT_keyarray];
} BtLockSet;
// 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,
Librarian,
Duplicate
} 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 first part of an index page.
// It is immediately followed
// by the BtSlot array of keys.
// note that this structure size
// must be a multiple of 8 bytes
// in order to place dups correctly.
typedef struct BtPage_ {
uint cnt; // count of keys in page
uint act; // count of active keys
uint min; // next key offset
uint garbage; // page garbage in bytes
unsigned char bits:7; // page size in bits
unsigned char free:1; // page is on free chain
unsigned char lvl:7; // level of page
unsigned char kill:1; // page is being deleted
unsigned char left[BtId]; // page number to left
unsigned char filler[2]; // padding to multiple of 8
unsigned char right[BtId]; // page number to right
} *BtPage;
// The loadpage interface object
typedef struct {
uid page_no; // current page number
BtPage page; // current page pointer
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 long long dups[1]; // global duplicate key uniqueifier
unsigned char chain[BtId]; // head of free page_nos chain
} BtPageZero;
// The object structure for Btree access
typedef struct {
uint page_size; // page size
uint page_bits; // page size in bits
#ifdef unix
int idx;
#else
HANDLE idx;
#endif
BtPageZero *pagezero; // mapped allocation page
BtSpinLatch alloclatch[1]; // allocation area lite latch
uint latchdeployed; // highest number of pool entries deployed
uint nlatchpage; // number of latch & lock & pool pages
uint latchtotal; // number of page latch entries
uint latchhash; // number of latch hash table slots
uint latchvictim; // next latch entry to examine
BtHashEntry *hashtable; // the anonymous mapping buffer pool
BtLatchSet *latchsets; // mapped latch set from latch pages
unsigned char *pagepool; // mapped to the buffer pool pages
uint lockhash; // number of lock hash table slots
uint lockfree; // next available lock table entry
BtSpinLatch locklatch[1]; // lock manager free chain latch
BtHashEntry *hashlock; // the lock manager hash table
BtLockSet *locktable; // the lock manager key table
#ifndef unix
HANDLE halloc; // allocation handle
HANDLE hpool; // buffer pool 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
unsigned char key[BT_keyarray]; // last found complete key
int found; // last delete or insert was found
int err; // last error
int reads, writes; // number of reads and writes from the btree
} BtDb;
typedef enum {
BTERR_ok = 0,
BTERR_struct,
BTERR_ovflw,
BTERR_lock,
BTERR_map,
BTERR_read,
BTERR_wrt,
BTERR_hash
} BTERR;
#define CLOCK_bit 0x8000
// 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, int unique);
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 valmax);
extern BtKey *bt_foundkey (BtDb *bt);
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 bits, uint poolsize, uint locksize);
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);
// 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))
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;
}
uid bt_newdup (BtDb *bt)
{
#ifdef unix
return __sync_fetch_and_add (bt->mgr->pagezero->dups, 1) + 1;
#else
return _InterlockedIncrement64(bt->mgr->pagezero->dups, 1);
#endif
}
// 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)
{
uint prev;
do {
#ifdef unix
prev = __sync_fetch_and_add ((uint *)latch, SHARE);
#else
prev = _InterlockedExchangeAdd((uint *)latch, SHARE);
#endif
// see if exclusive request is granted or pending
if( !(prev & BOTH) )
return;
#ifdef unix
prev = __sync_fetch_and_add ((uint *)latch, -SHARE);
#else
prev = _InterlockedExchangeAdd((uint *)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)
{
uint prev;
do {
#ifdef unix
prev = __sync_fetch_and_or((uint *)latch, PEND | XCL);
#else
prev = _InterlockedOr((uint *)latch, PEND | XCL);
#endif
if( !(prev & XCL) )
if( !(prev & ~BOTH) )
return;
else
#ifdef unix
__sync_fetch_and_and ((uint *)latch, ~XCL);
#else
_InterlockedAnd((uint *)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)
{
uint prev;
#ifdef unix
prev = __sync_fetch_and_or((uint *)latch, XCL);
#else
prev = _InterlockedOr((uint *)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 ((uint *)latch, ~XCL);
#else
_InterlockedAnd((uint *)latch, ~XCL);
#endif
return 0;
}
// clear write mode
void bt_spinreleasewrite(BtSpinLatch *latch)
{
#ifdef unix
__sync_fetch_and_and((uint *)latch, ~BOTH);
#else
_InterlockedAnd((uint *)latch, ~BOTH);
#endif
}
// decrement reader count
void bt_spinreleaseread(BtSpinLatch *latch)
{
#ifdef unix
__sync_fetch_and_add((uint *)latch, -SHARE);
#else
_InterlockedExchangeAdd((uint *)latch, -SHARE);
#endif
}
// read page from permanent location in Btree file
BTERR bt_readpage (BtMgr *mgr, BtPage page, uid page_no)
{
off64_t off = page_no << mgr->page_bits;
#ifdef unix
if( pread (mgr->idx, page, mgr->page_size, page_no << mgr->page_bits) < mgr->page_size ) {
fprintf (stderr, "Unable to read page %.8x errno = %d\n", page_no, errno);
return BTERR_read;
}
#else
OVERLAPPED ovl[1];
uint amt[1];
memset (ovl, 0, sizeof(OVERLAPPED));
ovl->Offset = off;
ovl->OffsetHigh = off >> 32;
if( !ReadFile(mgr->idx, page, mgr->page_size, amt, ovl)) {
fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
return BTERR_read;
}
if( *amt < mgr->page_size ) {
fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
return BTERR_read;
}
#endif
return 0;
}
// write page to permanent location in Btree file
// clear the dirty bit
BTERR bt_writepage (BtMgr *mgr, BtPage page, uid page_no)
{
off64_t off = page_no << mgr->page_bits;
#ifdef unix
if( pwrite(mgr->idx, page, mgr->page_size, off) < mgr->page_size )
return BTERR_wrt;
#else
OVERLAPPED ovl[1];
uint amt[1];
memset (ovl, 0, sizeof(OVERLAPPED));
ovl->Offset = off;
ovl->OffsetHigh = off >> 32;
if( !WriteFile(mgr->idx, page, mgr->page_size, amt, ovl) )
return BTERR_wrt;
if( *amt < mgr->page_size )
return 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, uint loadit)
{
BtPage page = (BtPage)(((uid)slot << bt->mgr->page_bits) + bt->mgr->pagepool);
BtLatchSet *latch = bt->mgr->latchsets + slot;
if( latch->next = bt->mgr->hashtable[hashidx].slot )
bt->mgr->latchsets[latch->next].prev = slot;
bt->mgr->hashtable[hashidx].slot = slot;
latch->page_no = page_no;
latch->slot = slot;
latch->prev = 0;
latch->pin = 1;
if( loadit )
if( bt->err = bt_readpage (bt->mgr, page, page_no) )
return bt->err;
else
bt->reads++;
return bt->err = 0;
}
// set CLOCK bit in latch
// decrement pin count
void bt_unpinlatch (BtLatchSet *latch)
{
#ifdef unix
if( ~latch->pin & CLOCK_bit )
__sync_fetch_and_or(&latch->pin, CLOCK_bit);
__sync_fetch_and_add(&latch->pin, -1);
#else
if( ~latch->pin & CLOCK_bit )
_InterlockedOr16 (&latch->pin, CLOCK_bit);
_InterlockedDecrement16 (&latch->pin);
#endif
}
// return the btree cached page address
BtPage bt_mappage (BtDb *bt, BtLatchSet *latch)
{
BtPage page = (BtPage)(((uid)latch->slot << bt->mgr->page_bits) + bt->mgr->pagepool);
return page;
}
// find existing latchset or inspire new one
// return with latchset pinned
BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no, uint loadit)
{
uint hashidx = page_no % bt->mgr->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->mgr->hashtable[hashidx].latch);
if( slot = bt->mgr->hashtable[hashidx].slot ) do
{
latch = bt->mgr->latchsets + slot;
if( page_no == latch->page_no )
break;
} while( slot = latch->next );
// found our entry
// increment clock
if( slot ) {
latch = bt->mgr->latchsets + slot;
#ifdef unix
__sync_fetch_and_add(&latch->pin, 1);
#else
_InterlockedIncrement16 (&latch->pin);
#endif
bt_spinreleasewrite(bt->mgr->hashtable[hashidx].latch);
return latch;
}
// see if there are any unused pool entries
#ifdef unix
slot = __sync_fetch_and_add (&bt->mgr->latchdeployed, 1) + 1;
#else
slot = _InterlockedIncrement (&bt->mgr->latchdeployed);
#endif
if( slot < bt->mgr->latchtotal ) {
latch = bt->mgr->latchsets + slot;
if( bt_latchlink (bt, hashidx, slot, page_no, loadit) )
return NULL;
bt_spinreleasewrite (bt->mgr->hashtable[hashidx].latch);
return latch;
}
#ifdef unix
__sync_fetch_and_add (&bt->mgr->latchdeployed, -1);
#else
_InterlockedDecrement (&bt->mgr->latchdeployed);
#endif
// find and reuse previous entry on victim
while( 1 ) {
#ifdef unix
slot = __sync_fetch_and_add(&bt->mgr->latchvictim, 1);
#else
slot = _InterlockedIncrement (&bt->mgr->latchvictim) - 1;
#endif
// try to get write lock on hash chain
// skip entry if not obtained
// or has outstanding pins
slot %= bt->mgr->latchtotal;
if( !slot )
continue;
latch = bt->mgr->latchsets + slot;
idx = latch->page_no % bt->mgr->latchhash;
// see we are on same chain as hashidx
if( idx == hashidx )
continue;
if( !bt_spinwritetry (bt->mgr->hashtable[idx].latch) )
continue;
// skip this slot if it is pinned
// or the CLOCK bit is set
if( latch->pin ) {
if( latch->pin & CLOCK_bit ) {
#ifdef unix
__sync_fetch_and_and(&latch->pin, ~CLOCK_bit);
#else
_InterlockedAnd16 (&latch->pin, ~CLOCK_bit);
#endif
}
bt_spinreleasewrite (bt->mgr->hashtable[idx].latch);
continue;
}
// update permanent page area in btree from buffer pool
page = (BtPage)(((uid)slot << bt->mgr->page_bits) + bt->mgr->pagepool);
if( latch->dirty )
if( bt->err = bt_writepage (bt->mgr, page, latch->page_no) )
return NULL;
else
latch->dirty = 0, bt->writes++;
// unlink our available slot from its hash chain
if( latch->prev )
bt->mgr->latchsets[latch->prev].next = latch->next;
else
bt->mgr->hashtable[idx].slot = latch->next;
if( latch->next )
bt->mgr->latchsets[latch->next].prev = latch->prev;
bt_spinreleasewrite (bt->mgr->hashtable[idx].latch);
if( bt_latchlink (bt, hashidx, slot, page_no, loadit) )
return NULL;
bt_spinreleasewrite (bt->mgr->hashtable[hashidx].latch);
return latch;
}
}
void bt_mgrclose (BtMgr *mgr)
{
BtLatchSet *latch;
uint num = 0;
BtPage page;
uint slot;
// flush dirty pool pages to the btree
for( slot = 1; slot <= mgr->latchdeployed; slot++ ) {
page = (BtPage)(((uid)slot << mgr->page_bits) + mgr->pagepool);
latch = mgr->latchsets + slot;
if( latch->dirty ) {
bt_writepage(mgr, page, latch->page_no);
latch->dirty = 0, num++;
}
// madvise (page, mgr->page_size, MADV_DONTNEED);
}
fprintf(stderr, "%d buffer pool pages flushed\n", num);
#ifdef unix
munmap (mgr->hashtable, (uid)mgr->nlatchpage << mgr->page_bits);
munmap (mgr->pagezero, mgr->page_size);
#else
FlushViewOfFile(mgr->pagezero, 0);
UnmapViewOfFile(mgr->pagezero);
UnmapViewOfFile(mgr->hashtable);
CloseHandle(mgr->halloc);
CloseHandle(mgr->hpool);
#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)
{
#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 page pool (e.g. 262144) and number of lock table entries.
BtMgr *bt_mgr (char *name, uint bits, uint nodemax, uint lockmax)
{
uint lvl, attr, last, slot, idx;
unsigned char value[BtId];
int flag, initit = 0;
BtPageZero *pagezero;
off64_t size;
uint amt[1];
BtMgr* mgr;
BtKey* key;
BtVal *val;
// determine sanity of page size and buffer pool
if( bits > BT_maxbits )
bits = BT_maxbits;
else if( bits < BT_minbits )
bits = BT_minbits;
if( nodemax < 16 ) {
fprintf(stderr, "Buffer pool too small: %d\n", nodemax);
return NULL;
}
#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 open btree file\n");
return free(mgr), NULL;
}
#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;
#endif
#ifdef unix
pagezero = valloc (BT_maxpage);
*amt = 0;
// read minimum page size to get root info
// to support raw disk partition files
// check if bits == 0 on the disk.
if( size = lseek (mgr->idx, 0L, 2) )
if( pread(mgr->idx, pagezero, BT_minpage, 0) == BT_minpage )
if( pagezero->alloc->bits )
bits = pagezero->alloc->bits;
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;
bits = pagezero->alloc->bits;
} else
initit = 1;
#endif
mgr->page_size = 1 << bits;
mgr->page_bits = bits;
// calculate number of latch hash table entries
mgr->nlatchpage = (nodemax/16 * sizeof(BtHashEntry) + mgr->page_size - 1) / mgr->page_size;
mgr->latchhash = ((uid)mgr->nlatchpage << mgr->page_bits) / sizeof(BtHashEntry);
// add on the number of pages in buffer pool
// along with the corresponding latch table
mgr->nlatchpage += nodemax; // size of the buffer pool in pages
mgr->nlatchpage += (sizeof(BtLatchSet) * nodemax + mgr->page_size - 1)/mgr->page_size;
mgr->latchtotal = nodemax;
// add on the sizeof the lock manager hash table and the lock table
mgr->nlatchpage += (lockmax / 16 * sizeof(BtHashEntry) + mgr->page_size - 1) / mgr->page_size;
mgr->nlatchpage += (lockmax * sizeof(BtLockSet) + mgr->page_size - 1) / mgr->page_size;
if( !initit )
goto mgrlatch;
// initialize an empty b-tree with latch page, root page, page of leaves
// and page(s) of latches and page pool cache
memset (pagezero, 0, 1 << bits);
pagezero->alloc->bits = mgr->page_bits;
bt_putid(pagezero->alloc->right, MIN_lvl+1);
// initialize left-most LEAF page in