]> pd.if.org Git - btree/blob - btree2s.c
fix original problem with bt_deletekey, obviating need for btree2t.c
[btree] / btree2s.c
1 // btree version 2s
2 // 13 FEB 2014
3
4 // author: karl malbrain, malbrain@cal.berkeley.edu
5
6 /*
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
9
10 The orginal author is Karl Malbrain.
11
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
18 */
19
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
22
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
25
26 #ifdef linux
27 #define _GNU_SOURCE
28 #endif
29
30 #ifdef unix
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <time.h>
35 #include <fcntl.h>
36 #include <sys/mman.h>
37 #include <errno.h>
38 #else
39 #define WIN32_LEAN_AND_MEAN
40 #include <windows.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <time.h>
44 #include <fcntl.h>
45 #endif
46
47 #include <memory.h>
48 #include <string.h>
49
50 typedef unsigned long long      uid;
51
52 #ifndef unix
53 typedef unsigned long long      off64_t;
54 typedef unsigned short          ushort;
55 typedef unsigned int            uint;
56 #endif
57
58 #define BT_ro 0x6f72    // ro
59 #define BT_rw 0x7772    // rw
60 #define BT_fl 0x6c66    // fl
61
62 #define BT_maxbits              24                                      // maximum page size in bits
63 #define BT_minbits              9                                       // minimum page size in bits
64 #define BT_minpage              (1 << BT_minbits)       // minimum page size
65
66 /*
67 There are five lock types for each node in three independent sets: 
68 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete. 
69 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent. 
70 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock. 
71 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks. 
72 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification. 
73 */
74
75 typedef enum{
76         BtLockAccess,
77         BtLockDelete,
78         BtLockRead,
79         BtLockWrite,
80         BtLockParent
81 }BtLock;
82
83 //      Define the length of the page and key pointers
84
85 #define BtId 6
86
87 //      Page key slot definition.
88
89 //      If BT_maxbits is 15 or less, you can save 2 bytes
90 //      for each key stored by making the first two uints
91 //      into ushorts.  You can also save 4 bytes by removing
92 //      the tod field from the key.
93
94 //      Keys are marked dead, but remain on the page until
95 //      cleanup is called. The fence key (highest key) for
96 //      the page is always present, even if dead.
97
98 typedef struct {
99         uint off:BT_maxbits;            // page offset for key start
100         uint dead:1;                            // set for deleted key
101         uint tod;                                       // time-stamp for key
102         unsigned char id[BtId];         // id associated with key
103 } BtSlot;
104
105 //      The key structure occupies space at the upper end of
106 //      each page.  It's a length byte followed by the value
107 //      bytes.
108
109 typedef struct {
110         unsigned char len;
111         unsigned char key[0];
112 } *BtKey;
113
114 //      The first part of an index page.
115 //      It is immediately followed
116 //      by the BtSlot array of keys.
117
118 typedef struct {
119         uint cnt;                                       // count of keys in page
120         uint act;                                       // count of active keys
121         uint min;                                       // next key offset
122         unsigned char bits:7;           // page size in bits
123         unsigned char free:1;           // page is on free list
124         unsigned char lvl:5;            // level of page
125         unsigned char kill:1;           // page is being deleted
126         unsigned char dirty:1;          // page is dirty
127         unsigned char posted:1;         // page is posted in parent
128         unsigned char right[BtId];      // page number to right
129 } *BtPage;
130
131 //      The memory mapping hash table entry
132
133 typedef struct {
134         BtPage page;            // mapped page pointer
135         uid  page_no;           // mapped page number
136         void *lruprev;          // least recently used previous cache block
137         void *lrunext;          // lru next cache block
138         void *hashprev;         // previous cache block for the same hash idx
139         void *hashnext;         // next cache block for the same hash idx
140 #ifndef unix
141         HANDLE hmap;
142 #endif
143 }BtHash;
144
145 //      The object structure for Btree access
146
147 typedef struct _BtDb {
148         uint page_size;         // each page size       
149         uint page_bits;         // each page size in bits       
150         uint seg_bits;          // segment size in pages in bits
151         uid page_no;            // current page number  
152         uid cursor_page;        // current cursor page number   
153         int  err;
154         uint mode;                      // read-write mode
155         uint mapped_io;         // use memory mapping
156         BtPage temp;            // temporary frame buffer (memory mapped/file IO)
157         BtPage alloc;           // frame buffer for alloc page ( page 0 )
158         BtPage cursor;          // cached frame for start/next (never mapped)
159         BtPage frame;           // spare frame for the page split (never mapped)
160         BtPage zero;            // zeroes frame buffer (never mapped)
161         BtPage page;            // current page
162 #ifdef unix
163         int idx;
164 #else
165         HANDLE idx;
166 #endif
167         unsigned char *mem;     // frame, cursor, page memory buffer
168         int nodecnt;            // highest page cache segment in use
169         int nodemax;            // highest page cache segment allocated
170         int hashmask;           // number of pages in segments - 1
171         int hashsize;           // size of hash table
172         int found;                      // last deletekey found key
173         BtHash *lrufirst;       // lru list head
174         BtHash *lrulast;        // lru list tail
175         ushort *cache;          // hash table for cached segments
176         BtHash nodes[1];        // segment cache follows
177 } BtDb;
178
179 typedef enum {
180 BTERR_ok = 0,
181 BTERR_struct,
182 BTERR_ovflw,
183 BTERR_lock,
184 BTERR_map,
185 BTERR_wrt,
186 BTERR_hash
187 } BTERR;
188
189 // B-Tree functions
190 extern void bt_close (BtDb *bt);
191 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk, uint pgblk);
192 extern BTERR  bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
193 extern BTERR  bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
194 extern uid bt_findkey    (BtDb *bt, unsigned char *key, uint len);
195 extern uint bt_startkey  (BtDb *bt, unsigned char *key, uint len);
196 extern uint bt_nextkey   (BtDb *bt, uint slot);
197
198 //  Helper functions to return slot values
199
200 extern BtKey bt_key (BtDb *bt, uint slot);
201 extern uid bt_uid (BtDb *bt, uint slot);
202 extern uint bt_tod (BtDb *bt, uint slot);
203
204 //  BTree page number constants
205 #define ALLOC_page              0
206 #define ROOT_page               1
207 #define LEAF_page               2
208
209 //      Number of levels to create in a new BTree
210
211 #define MIN_lvl                 2
212
213 //  The page is allocated from low and hi ends.
214 //  The key offsets and row-id's are allocated
215 //  from the bottom, while the text of the key
216 //  is allocated from the top.  When the two
217 //  areas meet, the page is split into two.
218
219 //  A key consists of a length byte, two bytes of
220 //  index number (0 - 65534), and up to 253 bytes
221 //  of key value.  Duplicate keys are discarded.
222 //  Associated with each key is a 48 bit row-id.
223
224 //  The b-tree root is always located at page 1.
225 //      The first leaf page of level zero is always
226 //      located on page 2.
227
228 //      The b-tree pages are linked with right
229 //      pointers to facilitate enumerators,
230 //      and provide for concurrency.
231
232 //      When to root page fills, it is split in two and
233 //      the tree height is raised by a new root at page
234 //      one with two keys.
235
236 //      Deleted keys are marked with a dead bit until
237 //      page cleanup The fence key for a node is always
238 //      present, even after deletion and cleanup.
239
240 //  Deleted leaf pages are reclaimed  on a free list.
241 //      The upper levels of the btree are fixed on creation.
242
243 //  Groups of pages from the btree are optionally
244 //  cached with memory mapping. A hash table is used to keep
245 //  track of the cached pages.  This behaviour is controlled
246 //  by the number of cache blocks parameter and pages per block
247 //      given to bt_open.
248
249 //  To achieve maximum concurrency one page is locked at a time
250 //  as the tree is traversed to find leaf key in question. The right
251 //  page numbers are used in cases where the page is being split,
252 //      or consolidated.
253
254 //  Page 0 (ALLOC page) is dedicated to lock for new page extensions,
255 //      and chains empty leaf pages together for reuse.
256
257 //      Parent locks are obtained to prevent resplitting or deleting a node
258 //      before its fence is posted into its upper level.
259
260 //      A special open mode of BT_fl is provided to safely access files on
261 //      WIN32 networks. WIN32 network operations should not use memory mapping.
262 //      This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
263 //      to prevent local caching of network file contents.
264
265 //      Access macros to address slot and key values from the page.
266 //      Page slots use 1 based indexing.
267
268 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
269 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
270
271 void bt_putid(unsigned char *dest, uid id)
272 {
273 int i = BtId;
274
275         while( i-- )
276                 dest[i] = (unsigned char)id, id >>= 8;
277 }
278
279 uid bt_getid(unsigned char *src)
280 {
281 uid id = 0;
282 int i;
283
284         for( i = 0; i < BtId; i++ )
285                 id <<= 8, id |= *src++; 
286
287         return id;
288 }
289
290 // place write, read, or parent lock on requested page_no.
291
292 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode)
293 {
294 off64_t off = page_no << bt->page_bits;
295 #ifdef unix
296 int flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
297 struct flock lock[1];
298 #else
299 uint flags = 0, len;
300 OVERLAPPED ovl[1];
301 #endif
302
303         if( mode == BtLockRead || mode == BtLockWrite )
304                 off +=  sizeof(*bt->page);      // use second segment
305
306         if( mode == BtLockParent )
307                 off +=  2 * sizeof(*bt->page);  // use third segment
308
309 #ifdef unix
310         memset (lock, 0, sizeof(lock));
311
312         lock->l_start = off;
313         lock->l_type = (mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent) ? F_WRLCK : F_RDLCK;
314         lock->l_len = sizeof(*bt->page);
315         lock->l_whence = 0;
316
317         if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
318                 return bt->err = BTERR_lock;
319
320         return 0;
321 #else
322         memset (ovl, 0, sizeof(ovl));
323         ovl->OffsetHigh = (uint)(off >> 32);
324         ovl->Offset = (uint)off;
325         len = sizeof(*bt->page);
326
327         //      use large offsets to
328         //      simulate advisory locking
329
330         ovl->OffsetHigh |= 0x80000000;
331
332         if( mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent )
333                 flags |= LOCKFILE_EXCLUSIVE_LOCK;
334
335         if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
336                 return bt->err = 0;
337
338         return bt->err = BTERR_lock;
339 #endif 
340 }
341
342 // remove write, read, or parent lock on requested page_no.
343
344 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
345 {
346 off64_t off = page_no << bt->page_bits;
347 #ifdef unix
348 struct flock lock[1];
349 #else
350 OVERLAPPED ovl[1];
351 uint len;
352 #endif
353
354         if( mode == BtLockRead || mode == BtLockWrite )
355                 off +=  sizeof(*bt->page);      // use second segment
356
357         if( mode == BtLockParent )
358                 off +=  2 * sizeof(*bt->page);  // use third segment
359
360 #ifdef unix
361         memset (lock, 0, sizeof(lock));
362
363         lock->l_start = off;
364         lock->l_type = F_UNLCK;
365         lock->l_len = sizeof(*bt->page);
366         lock->l_whence = 0;
367
368         if( fcntl (bt->idx, F_SETLK, lock) < 0 )
369                 return bt->err = BTERR_lock;
370 #else
371         memset (ovl, 0, sizeof(ovl));
372         ovl->OffsetHigh = (uint)(off >> 32);
373         ovl->Offset = (uint)off;
374         len = sizeof(*bt->page);
375
376         //      use large offsets to
377         //      simulate advisory locking
378
379         ovl->OffsetHigh |= 0x80000000;
380
381         if( !UnlockFileEx (bt->idx, 0, len, 0, ovl) )
382                 return GetLastError(), bt->err = BTERR_lock;
383 #endif
384
385         return bt->err = 0;
386 }
387
388 //      close and release memory
389
390 void bt_close (BtDb *bt)
391 {
392 BtHash *hash;
393 #ifdef unix
394         // release mapped pages
395
396         if( hash = bt->lrufirst )
397                 do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
398                 while(hash = hash->lrunext);
399
400         if ( bt->mem )
401                 free (bt->mem);
402         close (bt->idx);
403         free (bt->cache);
404         free (bt);
405 #else
406         if( hash = bt->lrufirst )
407           do
408           {
409                 FlushViewOfFile(hash->page, 0);
410                 UnmapViewOfFile(hash->page);
411                 CloseHandle(hash->hmap);
412           } while(hash = hash->lrunext);
413
414         if ( bt->mem)
415                 VirtualFree (bt->mem, 0, MEM_RELEASE);
416         FlushFileBuffers(bt->idx);
417         CloseHandle(bt->idx);
418         GlobalFree (bt->cache);
419         GlobalFree (bt);
420 #endif
421 }
422
423 //  open/create new btree
424 //      call with file_name, BT_openmode, bits in page size (e.g. 16),
425 //              size of mapped page cache (e.g. 8192) or zero for no mapping.
426
427 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax, uint pgblk)
428 {
429 uint lvl, attr, cacheblk, last;
430 BtLock lockmode = BtLockWrite;
431 BtPage alloc;
432 off64_t size;
433 uint amt[1];
434 BtKey key;
435 BtDb* bt;
436
437 #ifndef unix
438 SYSTEM_INFO sysinfo[1];
439 #endif
440
441 #ifdef unix
442         bt = malloc (sizeof(BtDb) + nodemax * sizeof(BtHash));
443         memset (bt, 0, sizeof(BtDb));
444
445         switch (mode & 0x7fff)
446         {
447         case BT_fl:
448         case BT_rw:
449                 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
450                 break;
451
452         case BT_ro:
453         default:
454                 bt->idx = open ((char*)name, O_RDONLY);
455                 lockmode = BtLockRead;
456                 break;
457         }
458         if( bt->idx == -1 )
459                 return free(bt), NULL;
460         
461         if( nodemax )
462                 cacheblk = 4096;        // page size for unix
463         else
464                 cacheblk = 0;
465
466 #else
467         bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb) + nodemax * sizeof(BtHash));
468         attr = FILE_ATTRIBUTE_NORMAL;
469         switch (mode & 0x7fff)
470         {
471         case BT_fl:
472                 attr |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
473
474         case BT_rw:
475                 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
476                 break;
477
478         case BT_ro:
479         default:
480                 bt->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
481                 lockmode = BtLockRead;
482                 break;
483         }
484         if( bt->idx == INVALID_HANDLE_VALUE )
485                 return GlobalFree(bt), NULL;
486
487         // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
488         GetSystemInfo(sysinfo);
489
490         if( nodemax )
491                 cacheblk = sysinfo->dwAllocationGranularity;
492         else
493                 cacheblk = 0;
494 #endif
495
496         // determine sanity of page size
497
498         if( bits > BT_maxbits )
499                 bits = BT_maxbits;
500         else if( bits < BT_minbits )
501                 bits = BT_minbits;
502
503         if ( bt_lockpage(bt, ALLOC_page, lockmode) )
504                 return bt_close (bt), NULL;
505
506 #ifdef unix
507         *amt = 0;
508
509         // read minimum page size to get root info
510
511         if( size = lseek (bt->idx, 0L, 2) ) {
512                 alloc = malloc (BT_minpage);
513                 pread(bt->idx, alloc, BT_minpage, 0);
514                 bits = alloc->bits;
515                 free (alloc);
516         } else if( mode == BT_ro )
517                 return bt_close (bt), NULL;
518 #else
519         size = GetFileSize(bt->idx, amt);
520
521         if( size || *amt ) {
522                 alloc = VirtualAlloc(NULL, BT_minpage, MEM_COMMIT, PAGE_READWRITE);
523                 if( !ReadFile(bt->idx, (char *)alloc, BT_minpage, amt, NULL) )
524                         return bt_close (bt), NULL;
525                 bits = alloc->bits;
526                 VirtualFree (alloc, 0, MEM_RELEASE);
527         } else if( mode == BT_ro )
528                 return bt_close (bt), NULL;
529 #endif
530
531         bt->page_size = 1 << bits;
532         bt->page_bits = bits;
533
534         bt->nodemax = nodemax;
535         bt->mode = mode;
536
537         // setup cache mapping
538
539         if( cacheblk ) {
540                 if( cacheblk < bt->page_size )
541                         cacheblk = bt->page_size;
542
543                 bt->hashsize = nodemax / 8;
544                 bt->hashmask = (cacheblk >> bits) - 1;
545                 bt->mapped_io = 1;
546         }
547
548         //      requested number of pages per memmap segment
549
550         if( cacheblk )
551           if( (1 << pgblk) > bt->hashmask )
552                 bt->hashmask = (1 << pgblk) - 1;
553
554         bt->seg_bits = 0;
555
556         while( (1 << bt->seg_bits) <= bt->hashmask )
557                 bt->seg_bits++;
558
559 #ifdef unix
560         bt->mem = malloc (6 *bt->page_size);
561         bt->cache = calloc (bt->hashsize, sizeof(ushort));
562 #else
563         bt->mem = VirtualAlloc(NULL, 6 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
564         bt->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, bt->hashsize * sizeof(ushort));
565 #endif
566         bt->frame = (BtPage)bt->mem;
567         bt->cursor = (BtPage)(bt->mem + bt->page_size);
568         bt->page = (BtPage)(bt->mem + 2 * bt->page_size);
569         bt->alloc = (BtPage)(bt->mem + 3 * bt->page_size);
570         bt->temp = (BtPage)(bt->mem + 4 * bt->page_size);
571         bt->zero = (BtPage)(bt->mem + 5 * bt->page_size);
572
573         if( size || *amt ) {
574                 if ( bt_unlockpage(bt, ALLOC_page, lockmode) )
575                         return bt_close (bt), NULL;
576
577                 return bt;
578         }
579
580         // initializes an empty b-tree with root page and page of leaves
581
582         memset (bt->alloc, 0, bt->page_size);
583         bt_putid(bt->alloc->right, MIN_lvl+1);
584         bt->alloc->bits = bt->page_bits;
585
586 #ifdef unix
587         if( write (bt->idx, bt->alloc, bt->page_size) < bt->page_size )
588                 return bt_close (bt), NULL;
589 #else
590         if( !WriteFile (bt->idx, (char *)bt->alloc, bt->page_size, amt, NULL) )
591                 return bt_close (bt), NULL;
592
593         if( *amt < bt->page_size )
594                 return bt_close (bt), NULL;
595 #endif
596
597         memset (bt->frame, 0, bt->page_size);
598         bt->frame->bits = bt->page_bits;
599
600         for( lvl=MIN_lvl; lvl--; ) {
601                 slotptr(bt->frame, 1)->off = bt->page_size - 3;
602                 bt_putid(slotptr(bt->frame, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0);               // next(lower) page number
603                 key = keyptr(bt->frame, 1);
604                 key->len = 2;                   // create stopper key
605                 key->key[0] = 0xff;
606                 key->key[1] = 0xff;
607                 bt->frame->min = bt->page_size - 3;
608                 bt->frame->lvl = lvl;
609                 bt->frame->cnt = 1;
610                 bt->frame->act = 1;
611 #ifdef unix
612                 if( write (bt->idx, bt->frame, bt->page_size) < bt->page_size )
613                         return bt_close (bt), NULL;
614 #else
615                 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
616                         return bt_close (bt), NULL;
617
618                 if( *amt < bt->page_size )
619                         return bt_close (bt), NULL;
620 #endif
621         }
622
623         // create empty page area by writing last page of first
624         // cache area (other pages are zeroed by O/S)
625
626         if( bt->mapped_io && bt->hashmask ) {
627                 memset(bt->frame, 0, bt->page_size);
628                 last = bt->hashmask;
629
630                 while( last < MIN_lvl + 1 )
631                         last += bt->hashmask + 1;
632 #ifdef unix
633                 pwrite(bt->idx, bt->frame, bt->page_size, last << bt->page_bits);
634 #else
635                 SetFilePointer (bt->idx, last << bt->page_bits, NULL, FILE_BEGIN);
636                 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
637                         return bt_close (bt), NULL;
638                 if( *amt < bt->page_size )
639                         return bt_close (bt), NULL;
640 #endif
641         }
642
643         if( bt_unlockpage(bt, ALLOC_page, lockmode) )
644                 return bt_close (bt), NULL;
645
646         return bt;
647 }
648
649 //  compare two keys, returning > 0, = 0, or < 0
650 //  as the comparison value
651
652 int keycmp (BtKey key1, unsigned char *key2, uint len2)
653 {
654 uint len1 = key1->len;
655 int ans;
656
657         if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
658                 return ans;
659
660         if( len1 > len2 )
661                 return 1;
662         if( len1 < len2 )
663                 return -1;
664
665         return 0;
666 }
667
668 //  Update current page of btree by writing file contents
669 //      or flushing mapped area to disk.
670
671 BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
672 {
673 off64_t off = page_no << bt->page_bits;
674
675 #ifdef unix
676     if ( !bt->mapped_io )
677          if ( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
678                  return bt->err = BTERR_wrt;
679 #else
680 uint amt[1];
681         if ( !bt->mapped_io )
682         {
683                 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
684                 if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
685                         return GetLastError(), bt->err = BTERR_wrt;
686
687                 if( *amt < bt->page_size )
688                         return GetLastError(), bt->err = BTERR_wrt;
689         } 
690         else if ( bt->mode == BT_fl ) {
691                         FlushViewOfFile(page, bt->page_size);
692                         FlushFileBuffers(bt->idx);
693         }
694 #endif
695         return 0;
696 }
697
698 // find page in cache 
699
700 BtHash *bt_findhash(BtDb *bt, uid page_no)
701 {
702 BtHash *hash;
703 uint idx;
704
705         // compute cache block first page and hash idx 
706
707         page_no &= ~bt->hashmask;
708         idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
709
710         if( bt->cache[idx] ) 
711                 hash = bt->nodes + bt->cache[idx];
712         else
713                 return NULL;
714
715         do if( hash->page_no == page_no )
716                  break;
717         while(hash = hash->hashnext );
718
719         return hash;
720 }
721
722 // add page cache entry to hash index
723
724 void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
725 {
726 uint idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
727 BtHash *hash;
728
729         if( bt->cache[idx] ) {
730                 node->hashnext = hash = bt->nodes + bt->cache[idx];
731                 hash->hashprev = node;
732         }
733
734         node->hashprev = NULL;
735         bt->cache[idx] = (ushort)(node - bt->nodes);
736 }
737
738 // remove cache entry from hash table
739
740 void bt_unlinkhash(BtDb *bt, BtHash *node)
741 {
742 uint idx = (uint)(node->page_no >> bt->seg_bits) % bt->hashsize;
743 BtHash *hash;
744
745         // unlink node
746         if( hash = node->hashprev )
747                 hash->hashnext = node->hashnext;
748         else if( hash = node->hashnext )
749                 bt->cache[idx] = (ushort)(hash - bt->nodes);
750         else
751                 bt->cache[idx] = 0;
752
753         if( hash = node->hashnext )
754                 hash->hashprev = node->hashprev;
755 }
756
757 // add cache page to lru chain and map pages
758
759 BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
760 {
761 int flag;
762 off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
763 off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
764 BtHash *node;
765
766         memset(hash, 0, sizeof(BtHash));
767         hash->page_no = (page_no & ~bt->hashmask);
768         bt_linkhash(bt, hash, page_no);
769
770         if( node = hash->lrunext = bt->lrufirst )
771                 node->lruprev = hash;
772         else
773                 bt->lrulast = hash;
774
775         bt->lrufirst = hash;
776
777 #ifdef unix
778         flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
779         hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
780         if( hash->page == MAP_FAILED )
781                 return bt->err = BTERR_map, (BtPage)NULL;
782
783 #else
784         flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
785         hash->hmap = CreateFileMapping(bt->idx, NULL, flag,     (DWORD)(limit >> 32), (DWORD)limit, NULL);
786         if( !hash->hmap )
787                 return bt->err = BTERR_map, NULL;
788
789         flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
790         hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
791         if( !hash->page )
792                 return bt->err = BTERR_map, NULL;
793 #endif
794
795         return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
796 }
797
798 //      find or place requested page in page-cache
799 //      return memory address where page is located.
800
801 BtPage bt_hashpage(BtDb *bt, uid page_no)
802 {
803 BtHash *hash, *node, *next;
804 BtPage page;
805
806         // find page in cache and move to top of lru list  
807
808         if( hash = bt_findhash(bt, page_no) ) {
809                 page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
810                 // swap node in lru list
811                 if( node = hash->lruprev ) {
812                         if( next = node->lrunext = hash->lrunext )
813                                 next->lruprev = node;
814                         else
815                                 bt->lrulast = node;
816
817                         if( next = hash->lrunext = bt->lrufirst )
818                                 next->lruprev = hash;
819                         else
820                                 return bt->err = BTERR_hash, (BtPage)NULL;
821
822                         hash->lruprev = NULL;
823                         bt->lrufirst = hash;
824                 }
825                 return page;
826         }
827
828         // map pages and add to cache entry
829
830         if( bt->nodecnt < bt->nodemax ) {
831                 hash = bt->nodes + ++bt->nodecnt;
832                 return bt_linklru(bt, hash, page_no);
833         }
834
835         // hash table is already full, replace last lru entry from the cache
836
837         if( hash = bt->lrulast ) {
838                 // unlink from lru list
839                 if( node = bt->lrulast = hash->lruprev )
840                         node->lrunext = NULL;
841                 else
842                         return bt->err = BTERR_hash, (BtPage)NULL;
843
844 #ifdef unix
845                 munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
846 #else
847                 FlushViewOfFile(hash->page, 0);
848                 UnmapViewOfFile(hash->page);
849                 CloseHandle(hash->hmap);
850 #endif
851                 // unlink from hash table
852
853                 bt_unlinkhash(bt, hash);
854
855                 // map and add to cache
856
857                 return bt_linklru(bt, hash, page_no);
858         }
859
860         return bt->err = BTERR_hash, (BtPage)NULL;
861 }
862
863 //  map a btree page onto current page
864
865 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
866 {
867 off64_t off = page_no << bt->page_bits;
868 #ifndef unix
869 int amt[1];
870 #endif
871         
872         if( bt->mapped_io ) {
873                 bt->err = 0;
874                 *page = bt_hashpage(bt, page_no);
875                 return bt->err;
876         }
877 #ifdef unix
878         if ( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
879                 return bt->err = BTERR_map;
880 #else
881         SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
882
883         if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
884                 return bt->err = BTERR_map;
885
886         if( *amt <  bt->page_size )
887                 return bt->err = BTERR_map;
888 #endif
889         return 0;
890 }
891
892 //      deallocate a deleted page 
893 //      place on free chain out of allocator page
894
895 BTERR bt_freepage(BtDb *bt, uid page_no)
896 {
897         if( bt_mappage (bt, &bt->temp, page_no) )
898                 return bt->err;
899
900         //      lock allocation page
901
902         if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
903                 return bt->err;
904
905         if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
906                 return bt->err;
907
908         //      store chain in second right
909         bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
910         bt_putid(bt->alloc[1].right, page_no);
911         bt->temp->free = 1;
912
913         if( bt_update(bt, bt->alloc, ALLOC_page) )
914                 return bt->err;
915         if( bt_update(bt, bt->temp, page_no) )
916                 return bt->err;
917
918         // unlock page zero 
919
920         if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
921                 return bt->err;
922
923         //  remove write lock on deleted node
924
925         if( bt_unlockpage(bt, page_no, BtLockWrite) )
926                 return bt->err;
927
928         //  remove delete lock on deleted node
929
930         if( bt_unlockpage(bt, page_no, BtLockDelete) )
931                 return bt->err;
932
933         return 0;
934 }
935
936 //      allocate a new page and write page into it
937
938 uid bt_newpage(BtDb *bt, BtPage page)
939 {
940 uid new_page;
941 char *pmap;
942 int reuse;
943
944         // lock page zero
945
946         if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
947                 return 0;
948
949         if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
950                 return 0;
951
952         // use empty chain first
953         // else allocate empty page
954
955         if( new_page = bt_getid(bt->alloc[1].right) ) {
956                 if( bt_mappage (bt, &bt->temp, new_page) )
957                         return 0;       // don't unlock on error
958                 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
959                 reuse = 1;
960         } else {
961                 new_page = bt_getid(bt->alloc->right);
962                 bt_putid(bt->alloc->right, new_page+1);
963                 reuse = 0;
964         }
965
966         if( bt_update(bt, bt->alloc, ALLOC_page) )
967                 return 0;       // don't unlock on error
968
969         if( !bt->mapped_io ) {
970                 if( bt_update(bt, page, new_page) )
971                         return 0;       //don't unlock on error
972
973                 // unlock page zero 
974
975                 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
976                         return 0;
977
978                 return new_page;
979         }
980
981 #ifdef unix
982         if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
983                 return bt->err = BTERR_wrt, 0;
984
985         // if writing first page of hash block, zero last page in the block
986
987         if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
988         {
989                 // use temp buffer to write zeros
990                 memset(bt->zero, 0, bt->page_size);
991                 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
992                         return bt->err = BTERR_wrt, 0;
993         }
994 #else
995         //      bring new page into page-cache and copy page.
996         //      this will extend the file into the new pages.
997
998         if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
999                 return 0;
1000
1001         memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
1002 #endif
1003
1004         // unlock page zero 
1005
1006         if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1007                 return 0;
1008
1009         return new_page;
1010 }
1011
1012 //  find slot in page for given key at a given level
1013
1014 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1015 {
1016 uint diff, higher = bt->page->cnt, low = 1, slot;
1017 uint good = 0;
1018
1019         //      make stopper key an infinite fence value
1020
1021         if( bt_getid (bt->page->right) )
1022                 higher++;
1023         else
1024                 good++;
1025
1026         //      low is the next candidate, higher is already
1027         //      tested as .ge. the given key, loop ends when they meet
1028
1029         while( diff = higher - low ) {
1030                 slot = low + ( diff >> 1 );
1031                 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1032                         low = slot + 1;
1033                 else
1034                         higher = slot, good++;
1035         }
1036
1037         //      return zero if key is on right link page
1038
1039         return good ? higher : 0;
1040 }
1041
1042 //  find and load page at given level for given key
1043 //      leave page rd or wr locked as requested
1044
1045 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1046 {
1047 uid page_no = ROOT_page, prevpage = 0;
1048 uint drill = 0xff, slot;
1049 uint mode, prevmode;
1050
1051   //  start at root of btree and drill down
1052
1053   do {
1054         // determine lock mode of drill level
1055         mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead; 
1056
1057         bt->page_no = page_no;
1058
1059         // obtain access lock using lock chaining
1060
1061         if( page_no > ROOT_page )
1062           if( bt_lockpage(bt, bt->page_no, BtLockAccess) )
1063                 return 0;                                                                       
1064
1065         if( prevpage )
1066           if( bt_unlockpage(bt, prevpage, prevmode) )
1067                 return 0;
1068
1069         // obtain read lock using lock chaining
1070
1071         if( bt_lockpage(bt, bt->page_no, mode) )
1072                 return 0;                                                                       
1073
1074         if( page_no > ROOT_page )
1075           if( bt_unlockpage(bt, bt->page_no, BtLockAccess) )
1076                 return 0;                                                                       
1077
1078         //      map/obtain page contents
1079
1080         if( bt_mappage (bt, &bt->page, page_no) )
1081                 return 0;
1082
1083         // re-read and re-lock root after determining actual level of root
1084
1085         if( bt->page->lvl != drill) {
1086                 if ( bt->page_no != ROOT_page )
1087                         return bt->err = BTERR_struct, 0;
1088                         
1089                 drill = bt->page->lvl;
1090
1091                 if( lock == BtLockWrite && drill == lvl )
1092                   if( bt_unlockpage(bt, page_no, mode) )
1093                         return 0;
1094                   else
1095                         continue;
1096         }
1097
1098         prevpage = bt->page_no;
1099         prevmode = mode;
1100
1101         //  find key on page at this level
1102         //  and descend to requested level
1103
1104         if( !bt->page->kill )
1105          if( slot = bt_findslot (bt, key, len) ) {
1106           if( drill == lvl )
1107                 return slot;
1108
1109           while( slotptr(bt->page, slot)->dead )
1110                 if( slot++ < bt->page->cnt )
1111                         continue;
1112                 else
1113                         break;
1114
1115           //  if the page has no active slots,
1116           //  move right otherwise drill down
1117
1118           if( slot <= bt->page->cnt ) {
1119                 page_no = bt_getid(slotptr(bt->page, slot)->id);
1120                 drill--;
1121                 continue;
1122           }
1123          }
1124
1125         //  or slide right into next page
1126
1127         page_no = bt_getid(bt->page->right);
1128
1129   } while( page_no );
1130
1131   // return error on end of right chain
1132
1133   bt->err = BTERR_struct;
1134   return 0;     // return error
1135 }
1136
1137 //      a fence key was deleted from a page
1138 //      push new fence value up to the root
1139
1140 BTERR bt_fixfence (BtDb *bt, uid page_no, uint lvl)
1141 {
1142 unsigned char leftkey[256], rightkey[256];
1143 BtKey ptr;
1144 uid left;
1145
1146         // remove deleted key, the old fence value
1147
1148         ptr = keyptr(bt->page, bt->page->cnt--);
1149         memcpy(rightkey, ptr, ptr->len + 1);
1150
1151         left = bt_getid (slotptr(bt->page, bt->page->cnt)->id);
1152         ptr = keyptr(bt->page, bt->page->cnt);
1153         memcpy(leftkey, ptr, ptr->len + 1);
1154
1155         if( bt_update (bt, bt->page, page_no) )
1156                 return bt->err;
1157
1158         if( bt_unlockpage (bt, page_no, BtLockWrite) )
1159                 return bt->err;
1160
1161         if( bt_lockpage (bt, left, BtLockParent) )
1162                 return bt->err;
1163
1164         //  insert new (now smaller) fence key
1165
1166         if( bt_insertkey (bt, leftkey+1, *leftkey, lvl + 1, page_no, time(NULL)) )
1167                 return bt->err;
1168
1169         if( bt_unlockpage (bt, left, BtLockParent) )
1170                 return bt->err;
1171
1172         //  remove old (larger) fence key
1173
1174         return bt_deletekey (bt, rightkey+1, *rightkey, lvl + 1);
1175 }
1176
1177 //      root has a single child
1178 //      collapse a level from the btree
1179 //      call with root locked in bt->page
1180
1181 BTERR bt_collapseroot (BtDb *bt, BtPage root)
1182 {
1183 uid child;
1184 uint idx;
1185
1186         // find the child entry
1187         //      and promote to new root
1188
1189   do {
1190         for( idx = 0; idx++ < root->cnt; )
1191           if( !slotptr(root, idx)->dead )
1192                 break;
1193
1194         child = bt_getid (slotptr(root, idx)->id);
1195
1196         if( bt_lockpage (bt, child, BtLockDelete) )
1197                 return bt->err;
1198
1199         if( bt_lockpage (bt, child, BtLockWrite) )
1200                 return bt->err;
1201
1202         if( bt_mappage (bt, &bt->temp, child) )
1203                 return bt->err;
1204
1205         memcpy (root, bt->temp, bt->page_size);
1206
1207         if( bt_update (bt, root, ROOT_page) )
1208                 return bt->err;
1209
1210         if( bt_freepage (bt, child) )
1211                 return bt->err;
1212
1213   } while( root->lvl > 1 && root->act == 1 );
1214
1215   return bt_unlockpage (bt, ROOT_page, BtLockWrite);
1216 }
1217
1218 //  find and delete key on page by marking delete flag bit
1219 //  when page becomes empty, delete it
1220
1221 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1222 {
1223 unsigned char lowerkey[256], higherkey[256];
1224 uint slot, dirty = 0, idx, fence;
1225 uid page_no, right;
1226 BtKey ptr;
1227
1228 retry:
1229         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1230                 ptr = keyptr(bt->page, slot);
1231         else
1232                 return bt->err;
1233
1234         // are we deleting a fence slot?
1235
1236         fence = slot == bt->page->cnt;
1237
1238         // if key is found delete it, otherwise ignore request
1239
1240         if( !keycmp (ptr, key, len) )
1241           if( slotptr(bt->page, slot)->dead == 0 ) {
1242                 dirty = slotptr(bt->page,slot)->dead = 1;
1243                 if( slot < bt->page->cnt )
1244                         bt->page->dirty = 1;
1245                 bt->page->act--;
1246
1247                 // collapse empty slots
1248
1249                 while( idx = bt->page->cnt - 1 )
1250                   if( slotptr(bt->page, idx)->dead ) {
1251                         *slotptr(bt->page, idx) = *slotptr(bt->page, idx + 1);
1252                         memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1253                   } else
1254                         break;
1255           }
1256
1257         right = bt_getid(bt->page->right);
1258         page_no = bt->page_no;
1259
1260         //      did we delete our fence key in an upper level?
1261
1262         if( dirty && lvl && bt->page->act && fence )
1263           return bt_fixfence (bt, page_no, lvl);
1264
1265         //      is this a collapsed root?
1266
1267         if( lvl > 1 && page_no == ROOT_page && bt->page->act == 1 )
1268           return bt_collapseroot (bt, bt->page);
1269
1270         // return if page is not empty
1271
1272         if( bt->page->act )
1273           if ( dirty && bt_update(bt, bt->page, page_no) )
1274                 return bt->err;
1275           else
1276                 return bt_unlockpage(bt, page_no, BtLockWrite);
1277
1278         // mark page being deleted
1279
1280         bt->page->kill = 1;
1281
1282         // cache copy of fence key
1283         //      in order to find parent
1284
1285         ptr = keyptr(bt->page, bt->page->cnt);
1286         memcpy(lowerkey, ptr, ptr->len + 1);
1287
1288         if( bt_update(bt, bt->page, page_no) )
1289                 return bt->err;
1290
1291         if( bt_unlockpage(bt, page_no, BtLockWrite) )
1292                 return bt->err;
1293
1294         // obtain Parent lock
1295
1296         if( bt_lockpage(bt, page_no, BtLockParent) )
1297                 return bt->err;
1298
1299         // lock and map right page
1300
1301         if ( bt_lockpage(bt, right, BtLockWrite) )
1302                 return bt->err;
1303
1304         if( bt_mappage (bt, &bt->temp, right) )
1305                 return bt->err;
1306
1307         //      is our right sibling being deleted?
1308
1309         if( bt->temp->kill ) {
1310           if ( bt_unlockpage(bt, right, BtLockWrite) )
1311                 return bt->err;
1312
1313           if( bt_unlockpage(bt, page_no, BtLockParent) )
1314                 return bt->err;
1315 #ifdef linux
1316           sched_yield ();
1317 #else
1318           SwitchToThread();
1319 #endif
1320           goto retry;
1321         }
1322
1323         if( bt_lockpage(bt, page_no, BtLockWrite) )
1324                 return bt->err;
1325
1326         if( bt_mappage (bt, &bt->page, page_no) )
1327                 return bt->err;
1328
1329         // pull contents of next page into current empty page 
1330
1331         memcpy (bt->page, bt->temp, bt->page_size);
1332
1333         //      cache copy of key to update
1334
1335         ptr = keyptr(bt->temp, bt->temp->cnt);
1336         memcpy(higherkey, ptr, ptr->len + 1);
1337
1338         //  Mark right page as deleted and point it to left page
1339         //      until we can post updates at higher level.
1340
1341         bt_putid(bt->temp->right, page_no);
1342         bt->temp->kill = 1;
1343
1344         if( bt_update(bt, bt->page, page_no) )
1345                 return bt->err;
1346
1347         if( bt_update(bt, bt->temp, right) )
1348                 return bt->err;
1349
1350         if( bt_unlockpage(bt, right, BtLockWrite) )
1351                 return bt->err;
1352
1353         if( bt_unlockpage(bt, page_no, BtLockWrite) )
1354                 return bt->err;
1355
1356         //  redirect higher key directly to consolidated node
1357
1358         if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, time(NULL)) )
1359                 return bt->err;
1360
1361         //  delete old lower key to consolidated node
1362
1363         if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1364                 return bt->err;
1365
1366         //  obtain delete lock on deleted node
1367         //      add right block to free chain
1368
1369         if( bt_lockpage(bt, right, BtLockDelete) )
1370                 return bt->err;
1371
1372         //  obtain write lock on deleted node
1373
1374         if( bt_lockpage(bt, right, BtLockWrite) )
1375                 return bt->err;
1376
1377         if( bt_freepage (bt, right) )
1378                 return bt->err;
1379
1380         //      remove ParentModify lock
1381
1382         return bt_unlockpage(bt, page_no, BtLockParent);
1383 }
1384
1385 //      find key in leaf level and return row-id
1386
1387 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1388 {
1389 uint  slot;
1390 BtKey ptr;
1391 uid id;
1392
1393         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1394                 ptr = keyptr(bt->page, slot);
1395         else
1396                 return 0;
1397
1398         // if key exists, return row-id
1399         //      otherwise return 0
1400
1401         if( ptr->len == len && !memcmp (ptr->key, key, len) )
1402                 id = bt_getid(slotptr(bt->page,slot)->id);
1403         else
1404                 id = 0;
1405
1406         if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1407                 return 0;
1408
1409         return id;
1410 }
1411
1412 //      check page for space available,
1413 //      clean if necessary and return
1414 //      0 - page needs splitting
1415 //      >0 - go ahead with new slot
1416  
1417 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1418 {
1419 uint nxt = bt->page_size;
1420 BtPage page = bt->page;
1421 uint cnt = 0, idx = 0;
1422 uint max = page->cnt;
1423 uint newslot = slot;
1424 BtKey key;
1425 int ret;
1426
1427         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1428                 return slot;
1429
1430         //      skip cleanup if nothing to reclaim
1431
1432         if( !page->dirty )
1433                 return 0;
1434
1435         memcpy (bt->frame, page, bt->page_size);
1436
1437         // skip page info and set rest of page to zero
1438
1439         memset (page+1, 0, bt->page_size - sizeof(*page));
1440         page->act = 0;
1441
1442         while( cnt++ < max ) {
1443                 if( cnt == slot )
1444                         newslot = idx + 1;
1445                 // always leave fence key in list
1446                 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1447                         continue;
1448
1449                 // copy key
1450                 key = keyptr(bt->frame, cnt);
1451                 nxt -= key->len + 1;
1452                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1453
1454                 // copy slot
1455                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1456                 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1457                         page->act++;
1458                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1459                 slotptr(page, idx)->off = nxt;
1460         }
1461
1462         page->min = nxt;
1463         page->cnt = idx;
1464
1465         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1466                 return newslot;
1467
1468         return 0;
1469 }
1470
1471 // split the root and raise the height of the btree
1472
1473 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
1474 {
1475 uint nxt = bt->page_size;
1476 BtPage root = bt->page;
1477 uid right;
1478
1479         //  Obtain an empty page to use, and copy the current
1480         //  root contents into it
1481
1482         if( !(right = bt_newpage(bt, root)) )
1483                 return bt->err;
1484
1485         // preserve the page info at the bottom
1486         // and set rest to zero
1487
1488         memset(root+1, 0, bt->page_size - sizeof(*root));
1489
1490         // insert first key on newroot page
1491
1492         nxt -= *leftkey + 1;
1493         memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
1494         bt_putid(slotptr(root, 1)->id, right);
1495         slotptr(root, 1)->off = nxt;
1496         
1497         // insert second key on newroot page
1498         // and increase the root height
1499
1500         nxt -= 3;
1501         ((unsigned char *)root)[nxt] = 2;
1502         ((unsigned char *)root)[nxt+1] = 0xff;
1503         ((unsigned char *)root)[nxt+2] = 0xff;
1504         bt_putid(slotptr(root, 2)->id, page_no2);
1505         slotptr(root, 2)->off = nxt;
1506
1507         bt_putid(root->right, 0);
1508         root->min = nxt;                // reset lowest used offset and key count
1509         root->cnt = 2;
1510         root->act = 2;
1511         root->lvl++;
1512
1513         // update and release root (bt->page)
1514
1515         if( bt_update(bt, root, bt->page_no) )
1516                 return bt->err;
1517
1518         return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1519 }
1520
1521 //  split already locked full node
1522 //      return unlocked.
1523
1524 BTERR bt_splitpage (BtDb *bt)
1525 {
1526 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1527 uid page_no = bt->page_no, right;
1528 unsigned char fencekey[256];
1529 BtPage page = bt->page;
1530 uint lvl = page->lvl;
1531 BtKey key;
1532
1533         //  split higher half of keys to bt->frame
1534         //      the last key (fence key) might be dead
1535
1536         memset (bt->frame, 0, bt->page_size);
1537         max = (int)page->cnt;
1538         cnt = max / 2;
1539         idx = 0;
1540
1541         while( cnt++ < max ) {
1542                 key = keyptr(page, cnt);
1543                 nxt -= key->len + 1;
1544                 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1545                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1546                 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1547                         bt->frame->act++;
1548                 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1549                 slotptr(bt->frame, idx)->off = nxt;
1550         }
1551
1552         bt->frame->bits = bt->page_bits;
1553         bt->frame->min = nxt;
1554         bt->frame->cnt = idx;
1555         bt->frame->lvl = lvl;
1556
1557         // link right node
1558
1559         if( page_no > ROOT_page )
1560                 memcpy (bt->frame->right, page->right, BtId);
1561
1562         //      get new free page and write frame to it.
1563
1564         if( !(right = bt_newpage(bt, bt->frame)) )
1565                 return bt->err;
1566
1567         //      update lower keys to continue in old page
1568
1569         memcpy (bt->frame, page, bt->page_size);
1570         memset (page+1, 0, bt->page_size - sizeof(*page));
1571         nxt = bt->page_size;
1572         page->posted = 0;
1573         page->dirty = 0;
1574         page->act = 0;
1575         cnt = 0;
1576         idx = 0;
1577
1578         //  assemble page of smaller keys
1579         //      (they're all active keys)
1580
1581         while( cnt++ < max / 2 ) {
1582                 key = keyptr(bt->frame, cnt);
1583                 nxt -= key->len + 1;
1584                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1585                 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1586                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1587                 slotptr(page, idx)->off = nxt;
1588                 page->act++;
1589         }
1590
1591         // remember fence key for old page
1592
1593         memcpy (fencekey, key, key->len + 1);
1594         bt_putid(page->right, right);
1595         page->min = nxt;
1596         page->cnt = idx;
1597
1598         // if current page is the root page, split it
1599
1600         if( page_no == ROOT_page )
1601                 return bt_splitroot (bt, fencekey, right);
1602
1603         // update left (containing) node
1604
1605         if( bt_update(bt, page, page_no) )
1606                 return bt->err;
1607
1608         if( bt_unlockpage (bt, page_no, BtLockWrite) )
1609                 return bt->err;
1610
1611         //  insert new fences in parent pages
1612
1613         do {
1614           if( bt_lockpage (bt, page_no, BtLockParent) )
1615                 return bt->err;
1616
1617           if( bt_lockpage (bt, page_no, BtLockWrite) )
1618                 return bt->err;
1619
1620           if( bt_mappage (bt, &bt->page, page_no) )
1621                 return bt->err;
1622
1623           key = keyptr(bt->page, bt->page->cnt);
1624           memcpy (fencekey, key, key->len + 1);
1625
1626           if( bt->page->posted ) {
1627                 if( bt_unlockpage (bt, page_no, BtLockParent) )
1628                   return bt->err;
1629                 return bt_unlockpage (bt, page_no, BtLockWrite);
1630           }
1631
1632           right = bt_getid (bt->page->right);
1633           bt->page->posted = 1;
1634
1635           if( bt_update (bt, bt->page, page_no) )
1636                 return bt->err;
1637
1638           if( bt_unlockpage (bt, page_no, BtLockWrite) )
1639                 return bt->err;
1640
1641           // insert new fence for reformulated left block
1642
1643           if( bt_insertkey (bt, fencekey+1, *fencekey, lvl + 1, page_no, time(NULL)) )
1644                 return bt->err;
1645
1646           if( bt_unlockpage (bt, page_no, BtLockParent) )
1647                 return bt->err;
1648         } while( page_no = right );
1649
1650         return 0;
1651 }
1652
1653 //  Insert new key into the btree at requested level.
1654 //  Level zero pages are leaf pages and are unlocked at exit.
1655 //      Interior nodes remain locked.
1656
1657 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1658 {
1659 uint slot, idx;
1660 BtPage page;
1661 BtKey ptr;
1662
1663   while( 1 ) {
1664         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1665                 ptr = keyptr(bt->page, slot);
1666         else
1667         {
1668                 if ( !bt->err )
1669                         bt->err = BTERR_ovflw;
1670                 return bt->err;
1671         }
1672
1673         // if key already exists, update id and return
1674
1675         page = bt->page;
1676
1677         if( !keycmp (ptr, key, len) ) {
1678                 slotptr(page, slot)->dead = 0;
1679                 slotptr(page, slot)->tod = tod;
1680                 bt_putid(slotptr(page,slot)->id, id);
1681                 if ( bt_update(bt, bt->page, bt->page_no) )
1682                         return bt->err;
1683                 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1684         }
1685
1686         // check if page has enough space
1687
1688         if( slot = bt_cleanpage (bt, len, slot) )
1689                 break;
1690
1691         if( bt_splitpage (bt) )
1692                 return bt->err;
1693   }
1694
1695   // calculate next available slot and copy key into page
1696
1697   page->min -= len + 1; // reset lowest used offset
1698   ((unsigned char *)page)[page->min] = len;
1699   memcpy ((unsigned char *)page + page->min +1, key, len );
1700
1701   for( idx = slot; idx < page->cnt; idx++ )
1702         if( slotptr(page, idx)->dead )
1703                 break;
1704
1705   // now insert key into array before slot
1706   // preserving the fence slot
1707
1708   if( idx == page->cnt )
1709         idx++, page->cnt++;
1710
1711   page->act++;
1712
1713   while( idx > slot )
1714         *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1715
1716   bt_putid(slotptr(page,slot)->id, id);
1717   slotptr(page, slot)->off = page->min;
1718   slotptr(page, slot)->tod = tod;
1719   slotptr(page, slot)->dead = 0;
1720
1721   if ( bt_update(bt, bt->page, bt->page_no) )
1722           return bt->err;
1723
1724   return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1725 }
1726
1727 //  cache page of keys into cursor and return starting slot for given key
1728
1729 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1730 {
1731 uint slot;
1732
1733         // cache page for retrieval
1734         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1735                 memcpy (bt->cursor, bt->page, bt->page_size);
1736         bt->cursor_page = bt->page_no;
1737         if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1738                 return 0;
1739
1740         return slot;
1741 }
1742
1743 //  return next slot for cursor page
1744 //  or slide cursor right into next page
1745
1746 uint bt_nextkey (BtDb *bt, uint slot)
1747 {
1748 off64_t right;
1749
1750   do {
1751         right = bt_getid(bt->cursor->right);
1752         while( slot++ < bt->cursor->cnt )
1753           if( slotptr(bt->cursor,slot)->dead )
1754                 continue;
1755           else if( right || (slot < bt->cursor->cnt))
1756                 return slot;
1757           else
1758                 break;
1759
1760         if( !right )
1761                 break;
1762
1763         bt->cursor_page = right;
1764
1765     if( bt_lockpage(bt, right,BtLockRead) )
1766                 return 0;
1767
1768         if( bt_mappage (bt, &bt->page, right) )
1769                 break;
1770
1771         memcpy (bt->cursor, bt->page, bt->page_size);
1772         if ( bt_unlockpage(bt, right, BtLockRead) )
1773                 return 0;
1774
1775         slot = 0;
1776   } while( 1 );
1777
1778   return bt->err = 0;
1779 }
1780
1781 BtKey bt_key(BtDb *bt, uint slot)
1782 {
1783         return keyptr(bt->cursor, slot);
1784 }
1785
1786 uid bt_uid(BtDb *bt, uint slot)
1787 {
1788         return bt_getid(slotptr(bt->cursor,slot)->id);
1789 }
1790
1791 uint bt_tod(BtDb *bt, uint slot)
1792 {
1793         return slotptr(bt->cursor,slot)->tod;
1794 }
1795
1796
1797 #ifdef STANDALONE
1798 //  standalone program to index file of keys
1799 //  then list them onto std-out
1800
1801 int main (int argc, char **argv)
1802 {
1803 uint slot, line = 0, off = 0, found = 0;
1804 int dead, ch, cnt = 0, bits = 12;
1805 unsigned char key[256];
1806 clock_t done, start;
1807 uint pgblk = 0;
1808 time_t tod[1];
1809 uint scan = 0;
1810 uint len = 0;
1811 uint map = 0;
1812 BtKey ptr;
1813 BtDb *bt;
1814 FILE *in;
1815
1816         if( argc < 4 ) {
1817                 fprintf (stderr, "Usage: %s idx_file src_file Read/Write/Scan/Delete/Find [page_bits mapped_pool_segments pages_per_segment start_line_number]\n", argv[0]);
1818                 fprintf (stderr, "  page_bits: size of btree page in bits\n");
1819                 fprintf (stderr, "  mapped_pool_segments: size of buffer pool in segments\n");
1820                 fprintf (stderr, "  pages_per_segment: size of buffer pool segment in pages in bits\n");
1821                 exit(0);
1822         }
1823
1824         start = clock();
1825         time(tod);
1826
1827         if( argc > 4 )
1828                 bits = atoi(argv[4]);
1829
1830         if( argc > 5 )
1831                 map = atoi(argv[5]);
1832
1833         if( map > 65536 )
1834                 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
1835
1836         if( map && map < 8 )
1837                 fprintf (stderr, "Buffer_pool too small\n");
1838
1839         if( argc > 6 )
1840                 pgblk = atoi(argv[6]);
1841
1842         if( bits + pgblk > 30 )
1843                 fprintf (stderr, "Warning: very large buffer pool segment size\n");
1844
1845         if( argc > 7 )
1846                 off = atoi(argv[7]);
1847
1848         bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
1849
1850         if( !bt ) {
1851                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
1852                 exit (1);
1853         }
1854
1855         switch(argv[3][0]| 0x20)
1856         {
1857         case 'w':
1858                 fprintf(stderr, "started indexing for %s\n", argv[2]);
1859                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1860                   while( ch = getc(in), ch != EOF )
1861                         if( ch == '\n' )
1862                         {
1863                           if( off )
1864                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1865
1866                           if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
1867                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1868                           len = 0;
1869                         }
1870                         else if( len < 245 )
1871                                 key[len++] = ch;
1872                 fprintf(stderr, "finished adding keys, %d \n", line);
1873                 break;
1874
1875         case 'd':
1876                 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
1877                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1878                   while( ch = getc(in), ch != EOF )
1879                         if( ch == '\n' )
1880                         {
1881                           if( off )
1882                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1883                           line++;
1884                           if( bt_deletekey (bt, key, len, 0) )
1885                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1886                           len = 0;
1887                         }
1888                         else if( len < 245 )
1889                                 key[len++] = ch;
1890                 fprintf(stderr, "finished deleting keys, %d \n", line);
1891                 break;
1892
1893         case 'f':
1894                 fprintf(stderr, "started finding keys for %s\n", argv[2]);
1895                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1896                   while( ch = getc(in), ch != EOF )
1897                         if( ch == '\n' )
1898                         {
1899                           if( off )
1900                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1901                           line++;
1902                           if( bt_findkey (bt, key, len) )
1903                                 found++;
1904                           else if( bt->err )
1905                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1906                           len = 0;
1907                         }
1908                         else if( len < 245 )
1909                                 key[len++] = ch;
1910                 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
1911                 break;
1912
1913         case 's':
1914                 scan++;
1915                 break;
1916
1917         }
1918
1919         done = clock();
1920         fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
1921
1922         dead = cnt = 0;
1923         len = key[0] = 0;
1924
1925         fprintf(stderr, "started reading\n");
1926
1927         if( slot = bt_startkey (bt, key, len) )
1928           slot--;
1929         else
1930           fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1931
1932         while( slot = bt_nextkey (bt, slot) )
1933           if( cnt++, scan ) {
1934                         ptr = bt_key(bt, slot);
1935                         fwrite (ptr->key, ptr->len, 1, stdout);
1936                         fputc ('\n', stdout);
1937           }
1938
1939         fprintf(stderr, " Total keys read %d\n", cnt);
1940         return 0;
1941 }
1942
1943 #endif  //STANDALONE