forked from malbrain/Btree-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jaluta2.c
2374 lines (1796 loc) · 57.2 KB
/
jaluta2.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
// jaluta's balanced B-Link tree algorithms
// 26 NOV 2013
// 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
// http://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>
#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 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_hashsize 512 // size of hash index for page cache
#define BT_hashprime 8191 // prime number for hashing
typedef enum{
BtLockShared = 1,
BtLockUpdate = 2,
BtLockXclusive = 3,
BtLockUpgrade = 4,
}BtLock;
// Define the length of the page and key pointers
#define BtId 6
// Page key slot definition.
// If BT_maxbits is 16 or less, you can save 4 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.
typedef struct {
uint off; // page offset for key start
uint tod; // time-stamp for 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 up to
// 255 value bytes.
typedef struct {
unsigned char len;
unsigned char key[255];
} *BtKey;
// The first part of an index page.
// It is immediately followed
// by the BtSlot array of keys.
typedef struct {
uint cnt; // count of keys in page
uint min; // next key offset
unsigned char lvl:3; // level of page
unsigned char bits:5; // page size in bits
unsigned char fence; // len of fence key at top of page
unsigned char right[BtId]; // page number to right
BtSlot slots[0]; // page slots
} *BtPage;
// The memory mapping hash table entry
typedef struct {
BtPage page; // mapped page pointer
uid page_no; // mapped page number
void *lruprev; // least recently used previous cache block
void *lrunext; // lru next cache block
void *hashprev; // previous cache block for the same hash idx
void *hashnext; // next cache block for the same hash idx
#ifndef unix
HANDLE hmap;
#endif
}BtHash;
// The object structure for Btree access
typedef struct {
uint page_size; // each page size
uint page_bits; // each page size in bits
uid parentpage; // current parent page number
uid cursorpage; // current cursor page number
uid childpage; // current child page number
int err;
uint mode; // read-write mode
uint mapped_io; // use memory mapping
BtPage temp; // temporary frame buffer (memory mapped/file IO)
BtPage alloc; // frame buffer for alloc page ( page 0 )
BtPage cursor; // cached frame for start/next (never mapped)
BtPage frame; // spare frame for the page split (never mapped)
BtPage parent; // current parent page
BtPage child; // current child page
BtPage sibling; // current sibling page
BtPage sibling2; // current sibling2 page
#ifdef unix
int idx;
#else
HANDLE idx;
#endif
unsigned char *mem; // frame, cursor, page memory buffer
int nodecnt; // highest page cache node in use
int nodemax; // highest page cache node allocated
int hashmask; // number of hash headers in cache - 1
BtHash *lrufirst; // lru list head
BtHash *lrulast; // lru list tail
ushort cache[BT_hashsize]; // hash index for cache
BtHash nodes[1]; // page cache follows
} BtDb;
typedef enum {
BTERR_ok = 0,
BTERR_struct,
BTERR_ovflw,
BTERR_lock,
BTERR_map,
BTERR_wrt,
BTERR_hash,
BTERR_restart
} 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, uid id, uint tod);
extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
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);
// Helper functions to return slot values
extern BtKey bt_key (BtDb *bt, uint slot);
extern uid bt_uid (BtDb *bt, uint slot);
extern uint bt_tod (BtDb *bt, uint slot);
// BTree page number constants
#define ALLOC_page 0
#define ROOT_page 1
// 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 overflowns.
// A key consists of a length byte, two bytes of
// index number (0 - 65535), 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 at each level are linked
// with next page to right to facilitate
// cursors and provide for concurrency.
// When to root page overflows, it is split in two and
// the tree height is raised by a new root at page
// one with two keys.
// Groups of pages from the btree are optionally
// cached with memory mapping. A hash table is used to keep
// track of the cached pages. 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.
// Empty nodes are chained together through the ALLOC page and reused.
// 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
#define slotptr(page, slot) ((page)->slots + 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;
}
// place requested latch on requested page_no.
// the Shared latch is a read lock over segment 0
// the Update latch is a write lock over segment 1
// the Xclusive latch is a write lock over segment 0 & 1
// the Upgrade latch upgrades Update to Xclusive
BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode)
{
off64_t off = page_no << bt->page_bits;
uint len = sizeof(*bt->parent);
uint type;
#ifdef unix
int flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
struct flock lock[1];
#else
uint flags = 0;
OVERLAPPED ovl[1];
#endif
switch( mode ) {
case BtLockShared: // lock segment 0 w/read lock
type = 0;
break;
case BtLockUpdate: // lock segment 1 w/write lock
off += sizeof(*bt->parent);
type = 1;
break;
case BtLockXclusive:// lock both segments w/write lock
len += sizeof(*bt->parent);
type = 1;
break;
case BtLockUpgrade: // lock segment 0 w/write lock
type = 1;
break;
}
#ifdef unix
memset (lock, 0, sizeof(lock));
lock->l_start = off;
lock->l_type = type ? F_WRLCK : F_RDLCK;
lock->l_len = len;
lock->l_whence = 0;
if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
return bt->err = BTERR_lock;
return 0;
#else
memset (ovl, 0, sizeof(ovl));
ovl->OffsetHigh = (uint)(off >> 32);
ovl->Offset = (uint)off;
// use large offsets to
// simulate advisory locking
ovl->OffsetHigh |= 0x80000000;
if( type = 1 )
flags |= LOCKFILE_EXCLUSIVE_LOCK;
if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
return bt->err = 0;
return bt->err = BTERR_lock;
#endif
}
// remove lock on requested page_no.
BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
{
off64_t off = page_no << bt->page_bits;
uint len = sizeof(*bt->parent);
#ifdef unix
struct flock lock[1];
#else
OVERLAPPED ovl[1];
#endif
switch( mode ) {
case BtLockShared: // unlock segment 0
break;
case BtLockUpdate: // unlock segment 1
off += sizeof(*bt->parent);
break;
case BtLockXclusive:// unlock both segments
len += sizeof(*bt->parent);
break;
case BtLockUpgrade: // unlock segment 0
break;
}
#ifdef unix
memset (lock, 0, sizeof(lock));
lock->l_start = off;
lock->l_type = F_UNLCK;
lock->l_len = len;
lock->l_whence = 0;
if( fcntl (bt->idx, F_SETLK, lock) < 0 )
return bt->err = BTERR_lock;
#else
memset (ovl, 0, sizeof(ovl));
ovl->OffsetHigh = (uint)(off >> 32);
ovl->Offset = (uint)off;
// use large offsets to
// simulate advisory locking
ovl->OffsetHigh |= 0x80000000;
if( !UnlockFileEx (bt->idx, 0, len, 0, ovl) )
return GetLastError(), bt->err = BTERR_lock;
#endif
return bt->err = 0;
}
// close and release memory
void bt_close (BtDb *bt)
{
BtHash *hash;
#ifdef unix
// release mapped pages
if( hash = bt->lrufirst )
do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
while(hash = hash->lrunext);
if ( bt->mem )
free (bt->mem);
close (bt->idx);
free (bt);
#else
if( hash = bt->lrufirst )
do
{
FlushViewOfFile(hash->page, 0);
UnmapViewOfFile(hash->page);
CloseHandle(hash->hmap);
} while(hash = hash->lrunext);
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 cache (e.g. 8192) or zero for no mapping.
BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax)
{
BtLock lockmode = BtLockXclusive;
uint lvl, attr, cacheblk;
BtPage alloc;
off64_t size;
uint amt[1];
BtKey key;
BtDb* bt;
#ifndef unix
SYSTEM_INFO sysinfo[1];
#endif
#ifdef unix
bt = malloc (sizeof(BtDb) + nodemax * sizeof(BtHash));
memset (bt, 0, sizeof(BtDb));
switch (mode & 0x7fff)
{
case BT_fl:
case BT_rw:
bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
break;
case BT_ro:
default:
bt->idx = open ((char*)name, O_RDONLY);
lockmode = BtLockShared;
break;
}
if( bt->idx == -1 )
return free(bt), NULL;
if( nodemax )
cacheblk = 4096; // page size for unix
else
cacheblk = 0;
#else
bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb) + nodemax * sizeof(BtHash));
attr = FILE_ATTRIBUTE_NORMAL;
switch (mode & 0x7fff)
{
case BT_fl:
attr |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
case BT_rw:
bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
break;
case BT_ro:
default:
bt->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
lockmode = BtLockShared;
break;
}
if( bt->idx == INVALID_HANDLE_VALUE )
return GlobalFree(bt), NULL;
// normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
GetSystemInfo(sysinfo);
if( nodemax )
cacheblk = sysinfo->dwAllocationGranularity;
else
cacheblk = 0;
#endif
// determine sanity of page size
if( bits > BT_maxbits )
bits = BT_maxbits;
else if( bits < BT_minbits )
bits = BT_minbits;
if ( bt_lockpage(bt, ALLOC_page, lockmode) )
return bt_close (bt), NULL;
#ifdef unix
*amt = 0;
// read minimum page size to get root info
if( size = lseek (bt->idx, 0L, 2) ) {
alloc = malloc (BT_minpage);
pread(bt->idx, alloc, BT_minpage, 0);
bits = alloc->bits;
free (alloc);
} else if( mode == BT_ro )
return bt_close (bt), NULL;
#else
size = GetFileSize(bt->idx, amt);
if( size || *amt ) {
alloc = VirtualAlloc(NULL, BT_minpage, MEM_COMMIT, PAGE_READWRITE);
if( !ReadFile(bt->idx, (char *)alloc, BT_minpage, amt, NULL) )
return bt_close (bt), NULL;
bits = alloc->bits;
VirtualFree (alloc, 0, MEM_RELEASE);
} else if( mode == BT_ro )
return bt_close (bt), NULL;
#endif
bt->page_size = 1 << bits;
bt->page_bits = bits;
bt->nodemax = nodemax;
bt->mode = mode;
// setup cache mapping
if( cacheblk ) {
if( cacheblk < bt->page_size )
cacheblk = bt->page_size;
bt->hashmask = (cacheblk >> bits) - 1;
bt->mapped_io = 1;
}
#ifdef unix
bt->mem = malloc (8 *bt->page_size);
#else
bt->mem = VirtualAlloc(NULL, 8 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
#endif
bt->frame = (BtPage)bt->mem;
bt->cursor = (BtPage)(bt->mem + bt->page_size);
bt->alloc = (BtPage)(bt->mem + 2 * bt->page_size);
bt->parent = (BtPage)(bt->mem + 3 * bt->page_size);
bt->child = (BtPage)(bt->mem + 4 * bt->page_size);
bt->temp = (BtPage)(bt->mem + 5 * bt->page_size);
bt->sibling = (BtPage)(bt->mem + 6 * bt->page_size);
bt->sibling2 = (BtPage)(bt->mem + 7 * bt->page_size);
if( size || *amt ) {
if ( bt_unlockpage(bt, ALLOC_page, lockmode) )
return bt_close (bt), NULL;
return bt;
}
// initialize an empty b-tree with alloc page & root page
memset (bt->alloc, 0, bt->page_size);
bt_putid(bt->alloc->right, ROOT_page + 1);
bt->alloc->bits = bt->page_bits;
#ifdef unix
if( write (bt->idx, bt->alloc, bt->page_size) < bt->page_size )
return bt_close (bt), NULL;
#else
if( !WriteFile (bt->idx, (char *)bt->alloc, bt->page_size, amt, NULL) )
return bt_close (bt), NULL;
if( *amt < bt->page_size )
return bt_close (bt), NULL;
#endif
// write root page
memset (bt->frame, 0, bt->page_size);
bt->frame->bits = bt->page_bits;
bt->frame->min = bt->page_size;
#ifdef unix
if( write (bt->idx, bt->frame, bt->page_size) < bt->page_size )
return bt_close (bt), NULL;
#else
if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
return bt_close (bt), NULL;
if( *amt < bt->page_size )
return bt_close (bt), NULL;
#endif
// create initial empty page area by writing last page of first
// cache area (other pages are zeroed by O/S)
if( bt->mapped_io && bt->hashmask > 2 ) {
memset(bt->frame, 0, bt->page_size);
#ifdef unix
pwrite(bt->idx, bt->frame, bt->page_size, bt->hashmask << bt->page_bits);
#else
SetFilePointer (bt->idx, bt->hashmask << bt->page_bits, NULL, FILE_BEGIN);
if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
return bt_close (bt), NULL;
if( *amt < bt->page_size )
return bt_close (bt), NULL;
#endif
}
if( bt_unlockpage(bt, ALLOC_page, lockmode) )
return bt_close (bt), NULL;
return bt;
}
// reset parent/child page pointers
void bt_resetpages (BtDb *bt)
{
if( bt->mapped_io )
return;
bt->frame = (BtPage)bt->mem;
bt->cursor = (BtPage)(bt->mem + bt->page_size);
bt->alloc = (BtPage)(bt->mem + 2 * bt->page_size);
bt->parent = (BtPage)(bt->mem + 3 * bt->page_size);
bt->child = (BtPage)(bt->mem + 4 * bt->page_size);
bt->temp = (BtPage)(bt->mem + 5 * bt->page_size);
bt->sibling = (BtPage)(bt->mem + 6 * bt->page_size);
bt->sibling2 = (BtPage)(bt->mem + 7 * bt->page_size);
}
// return pointer to high key
// or NULL if infinite value
BtKey bt_highkey (BtDb *bt, BtPage page)
{
if( page->lvl )
if( bt_getid (page->right) )
return keyptr(page, page->cnt);
else
return NULL;
if( bt_getid (page->right) )
return ((BtKey)((unsigned char*)(page) + bt->page_size - page->fence));
return NULL;
}
// return pointer to slot key in index page
// or NULL if infinite value
BtKey bt_slotkey (BtPage page, uint slot)
{
if( slot < page->cnt || bt_getid (page->right) )
return keyptr(page, slot);
else
return NULL;
}
// compare two keys, returning > 0, = 0, or < 0
// as the comparison value
int keycmp (BtKey key1, unsigned char *key2, uint len2)
{
uint len1 = key1->len;
int ans;
if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
return ans;
if( len1 > len2 )
return 1;
if( len1 < len2 )
return -1;
return 0;
}
// Update current page of btree by writing file contents
// or flushing mapped area to disk.
BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
{
off64_t off = page_no << bt->page_bits;
#ifdef unix
if ( !bt->mapped_io )
if ( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
return bt->err = BTERR_wrt;
#else
uint amt[1];
if ( !bt->mapped_io )
{
SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
return GetLastError(), bt->err = BTERR_wrt;
if( *amt < bt->page_size )
return GetLastError(), bt->err = BTERR_wrt;
}
else if ( bt->mode == BT_fl ) {
FlushViewOfFile(page, bt->page_size);
FlushFileBuffers(bt->idx);
}
#endif
return 0;
}
// find page in cache
BtHash *bt_findhash(BtDb *bt, uid page_no)
{
BtHash *hash;
uint idx;
// compute cache block first page and hash idx
page_no &= ~bt->hashmask;
idx = (uint)(page_no * BT_hashprime % BT_hashsize);
if( bt->cache[idx] )
hash = bt->nodes + bt->cache[idx];
else
return NULL;
do if( hash->page_no == page_no )
break;
while(hash = hash->hashnext );
return hash;
}
// add page cache entry to hash index
void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
{
uint idx = (uint)((page_no & ~bt->hashmask) * BT_hashprime % BT_hashsize);
BtHash *hash;
if( bt->cache[idx] ) {
node->hashnext = hash = bt->nodes + bt->cache[idx];
hash->hashprev = node;
}
node->hashprev = NULL;
bt->cache[idx] = (ushort)(node - bt->nodes);
}
// remove cache entry from hash table
void bt_unlinkhash(BtDb *bt, BtHash *node)
{
uint idx = (uint)((node->page_no & ~bt->hashmask) * BT_hashprime % BT_hashsize);
BtHash *hash;
// unlink node
if( hash = node->hashprev )
hash->hashnext = node->hashnext;
else if( hash = node->hashnext )
bt->cache[idx] = (ushort)(hash - bt->nodes);
else
bt->cache[idx] = 0;
if( hash = node->hashnext )
hash->hashprev = node->hashprev;
}
// add cache page to lru chain and map pages
BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
{
int flag;
off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
BtHash *node;
memset(hash, 0, sizeof(BtHash));
hash->page_no = (page_no & ~bt->hashmask);
bt_linkhash(bt, hash, page_no);
if( node = hash->lrunext = bt->lrufirst )
node->lruprev = hash;
else
bt->lrulast = hash;
bt->lrufirst = hash;
#ifdef unix
flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
if( (long long int)hash->page == -1LL )
return bt->err = BTERR_map, (BtPage)NULL;
#else
flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
hash->hmap = CreateFileMapping(bt->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
if( !hash->hmap )
return bt->err = BTERR_map, NULL;
flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
if( !hash->page )
return bt->err = BTERR_map, NULL;
#endif
return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
}
// find or place requested page in page-cache
// return memory address where page is located.
BtPage bt_hashpage(BtDb *bt, uid page_no)
{
BtHash *hash, *node, *next;
BtPage page;
// find page in cache and move to top of lru list
if( hash = bt_findhash(bt, page_no) ) {
page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
// swap node in lru list
if( node = hash->lruprev ) {
if( next = node->lrunext = hash->lrunext )
next->lruprev = node;
else
bt->lrulast = node;
if( next = hash->lrunext = bt->lrufirst )
next->lruprev = hash;
else
return bt->err = BTERR_hash, (BtPage)NULL;
hash->lruprev = NULL;
bt->lrufirst = hash;
}
return page;
}
// map pages and add to cache entry
if( bt->nodecnt < bt->nodemax ) {
hash = bt->nodes + ++bt->nodecnt;
return bt_linklru(bt, hash, page_no);
}
// hash table is already full, replace last lru entry from the cache
if( hash = bt->lrulast ) {
// unlink from lru list
if( node = bt->lrulast = hash->lruprev )
node->lrunext = NULL;
else
return bt->err = BTERR_hash, (BtPage)NULL;
#ifdef unix
munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
#else
FlushViewOfFile(hash->page, 0);
UnmapViewOfFile(hash->page);
CloseHandle(hash->hmap);
#endif
// unlink from hash table
bt_unlinkhash(bt, hash);
// map and add to cache
return bt_linklru(bt, hash, page_no);
}
return bt->err = BTERR_hash, (BtPage)NULL;
}
// map a btree page onto current page
BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
{
off64_t off = page_no << bt->page_bits;
#ifndef unix
int amt[1];
#endif
if( bt->mapped_io ) {
bt->err = 0;
*page = bt_hashpage(bt, page_no);
return bt->err;
}
#ifdef unix
if ( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
return bt->err = BTERR_map;
#else
SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
return bt->err = BTERR_map;
if( *amt < bt->page_size )
return bt->err = BTERR_map;
#endif
return 0;
}
// deallocate a deleted page
// place on free chain out of allocator page
// page must already be BtLockXclusive and mapped
BTERR bt_freepage (BtDb *bt, BtPage page, uid page_no)
{
// lock allocation page
if ( bt_lockpage(bt, ALLOC_page, BtLockUpdate) )
return bt->err;
if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
return bt->err;
// store chain in second right
bt_putid(page->right, bt_getid(bt->alloc[1].right));
bt_putid(bt->alloc[1].right, page_no);
if( bt_update(bt, bt->alloc, ALLOC_page) )
return bt->err;
if( bt_update(bt, page, page_no) )
return bt->err;
// unlock page zero
if( bt_unlockpage(bt, ALLOC_page, BtLockUpdate) )
return bt->err;
return 0;
}
// allocate a new page and write page into it
uid bt_newpage(BtDb *bt, BtPage page)
{
uid new_page;
char *pmap;
int reuse;
// lock page zero
if ( bt_lockpage(bt, ALLOC_page, BtLockUpdate) )
return 0;
if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
return 0;
// use empty chain first
// else allocate empty page
if( new_page = bt_getid(bt->alloc[1].right) ) {
if( bt_mappage (bt, &bt->temp, new_page) )
return 0; // don't unlock on error
bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
reuse = 1;
} else {
new_page = bt_getid(bt->alloc->right);
bt_putid(bt->alloc->right, new_page+1);
reuse = 0;
}
if( bt_update(bt, bt->alloc, ALLOC_page) )
return 0; // don't unlock on error
// unlock page zero
if ( bt_unlockpage(bt, ALLOC_page, BtLockUpdate) )
return 0;
if( !bt->mapped_io ) {
if( bt_update(bt, page, new_page) )
return 0; //don't unlock on error
// unlock page zero
if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
return 0;
return new_page;
}
#ifdef unix
if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
return bt->err = BTERR_wrt, 0;
// if writing first page of hash block, zero last page in the block
if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
{
// use temp buffer to write zeros
memset(bt->temp, 0, bt->page_size);