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