]> pd.if.org Git - btree/blob - btree2s.c
fixes for file I/O version that only deletes leaf pages
[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:7;           // page size in bits
123         unsigned char free:1;           // page is on free list
124         unsigned char lvl:7;            // level of page
125         unsigned char dirty:1;          // page is dirty
126         unsigned char right[BtId];      // page number to right
127 } *BtPage;
128
129 //      The memory mapping hash table entry
130
131 typedef struct {
132         BtPage page;            // mapped page pointer
133         uid  page_no;           // mapped page number
134         void *lruprev;          // least recently used previous cache block
135         void *lrunext;          // lru next cache block
136         void *hashprev;         // previous cache block for the same hash idx
137         void *hashnext;         // next cache block for the same hash idx
138 #ifndef unix
139         HANDLE hmap;
140 #endif
141 }BtHash;
142
143 //      The object structure for Btree access
144
145 typedef struct _BtDb {
146         uint page_size;         // each page size       
147         uint page_bits;         // each page size in bits       
148         uint seg_bits;          // segment size in pages in bits
149         uid page_no;            // current page number  
150         uid cursor_page;        // current cursor page number   
151         int  err;
152         uint mode;                      // read-write mode
153         uint mapped_io;         // use memory mapping
154         BtPage temp;            // temporary frame buffer (memory mapped/file IO)
155         BtPage alloc;           // frame buffer for alloc page ( page 0 )
156         BtPage cursor;          // cached frame for start/next (never mapped)
157         BtPage frame;           // spare frame for the page split (never mapped)
158         BtPage zero;            // zeroes frame buffer (never mapped)
159         BtPage page;            // current page
160 #ifdef unix
161         int idx;
162 #else
163         HANDLE idx;
164 #endif
165         unsigned char *mem;     // frame, cursor, page memory buffer
166         int nodecnt;            // highest page cache segment in use
167         int nodemax;            // highest page cache segment allocated
168         int hashmask;           // number of pages in segments - 1
169         int hashsize;           // size of hash table
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         bt->temp->free = 1;
921
922         if( bt_update(bt, bt->alloc, ALLOC_page) )
923                 return bt->err;
924         if( bt_update(bt, bt->temp, page_no) )
925                 return bt->err;
926
927         // unlock page zero 
928
929         if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
930                 return bt->err;
931
932         //  remove write lock on deleted node
933
934         if( bt_unlockpage(bt, page_no, BtLockWrite) )
935                 return bt->err;
936
937         //  remove delete lock on deleted node
938
939         if( bt_unlockpage(bt, page_no, BtLockDelete) )
940                 return bt->err;
941
942         return 0;
943 }
944
945 //      allocate a new page and write page into it
946
947 uid bt_newpage(BtDb *bt, BtPage page)
948 {
949 uid new_page;
950 char *pmap;
951 int reuse;
952
953         // lock page zero
954
955         if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
956                 return 0;
957
958         if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
959                 return 0;
960
961         // use empty chain first
962         // else allocate empty page
963
964         if( new_page = bt_getid(bt->alloc[1].right) ) {
965                 if( bt_mappage (bt, &bt->temp, new_page) )
966                         return 0;       // don't unlock on error
967                 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
968                 reuse = 1;
969         } else {
970                 new_page = bt_getid(bt->alloc->right);
971                 bt_putid(bt->alloc->right, new_page+1);
972                 reuse = 0;
973         }
974
975         if( bt_update(bt, bt->alloc, ALLOC_page) )
976                 return 0;       // don't unlock on error
977
978         if( !bt->mapped_io ) {
979                 if( bt_update(bt, page, new_page) )
980                         return 0;       //don't unlock on error
981
982                 // unlock page zero 
983
984                 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
985                         return 0;
986
987                 return new_page;
988         }
989
990 #ifdef unix
991         if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
992                 return bt->err = BTERR_wrt, 0;
993
994         // if writing first page of hash block, zero last page in the block
995
996         if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
997         {
998                 // use temp buffer to write zeros
999                 memset(bt->zero, 0, bt->page_size);
1000                 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
1001                         return bt->err = BTERR_wrt, 0;
1002         }
1003 #else
1004         //      bring new page into page-cache and copy page.
1005         //      this will extend the file into the new pages.
1006
1007         if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
1008                 return 0;
1009
1010         memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
1011 #endif
1012
1013         // unlock page zero 
1014
1015         if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1016                 return 0;
1017
1018         return new_page;
1019 }
1020
1021 //  find slot in page for given key at a given level
1022
1023 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1024 {
1025 uint diff, higher = bt->page->cnt, low = 1, slot;
1026 uint good = 0;
1027
1028         //      make stopper key an infinite fence value
1029
1030         if( bt_getid (bt->page->right) )
1031                 higher++;
1032         else
1033                 good++;
1034
1035         //      low is the next candidate, higher is already
1036         //      tested as .ge. the given key, loop ends when they meet
1037
1038         while( diff = higher - low ) {
1039                 slot = low + ( diff >> 1 );
1040                 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1041                         low = slot + 1;
1042                 else
1043                         higher = slot, good++;
1044         }
1045
1046         //      return zero if key is on right link page
1047
1048         return good ? higher : 0;
1049 }
1050
1051 //  find and load page at given level for given key
1052 //      leave page rd or wr locked as requested
1053
1054 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1055 {
1056 uid page_no = ROOT_page, prevpage = 0;
1057 uint drill = 0xff, slot;
1058 uint mode, prevmode;
1059
1060   //  start at root of btree and drill down
1061
1062   do {
1063         // determine lock mode of drill level
1064         mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead; 
1065
1066         bt->page_no = page_no;
1067
1068         // obtain access lock using lock chaining
1069
1070         if( page_no > ROOT_page )
1071           if( bt_lockpage(bt, bt->page_no, BtLockAccess) )
1072                 return 0;                                                                       
1073
1074         if( prevpage )
1075           if( bt_unlockpage(bt, prevpage, prevmode) )
1076                 return 0;
1077
1078         // obtain read lock using lock chaining
1079
1080         if( bt_lockpage(bt, bt->page_no, mode) )
1081                 return 0;                                                                       
1082
1083         if( page_no > ROOT_page )
1084           if( bt_unlockpage(bt, bt->page_no, BtLockAccess) )
1085                 return 0;                                                                       
1086
1087         //      map/obtain page contents
1088
1089         if( bt_mappage (bt, &bt->page, page_no) )
1090                 return 0;
1091
1092         // re-read and re-lock root after determining actual level of root
1093
1094         if( bt->page->lvl != drill) {
1095                 if ( bt->page_no != ROOT_page )
1096                         return bt->err = BTERR_struct, 0;
1097                         
1098                 drill = bt->page->lvl;
1099
1100                 if( lock == BtLockWrite && drill == lvl )
1101                   if( bt_unlockpage(bt, page_no, mode) )
1102                         return 0;
1103                   else
1104                         continue;
1105         }
1106
1107         prevpage = bt->page_no;
1108         prevmode = mode;
1109
1110         //  find key on page at this level
1111         //  and descend to requested level
1112
1113         if( slot = bt_findslot (bt, key, len) ) {
1114           if( drill == lvl )
1115                 return slot;
1116
1117           while( slotptr(bt->page, slot)->dead )
1118                 if( slot++ < bt->page->cnt )
1119                         continue;
1120                 else
1121                         break;
1122
1123           //  if the page has no active slots,
1124           //  move right otherwise drill down
1125
1126           if( slot <= bt->page->cnt ) {
1127                 page_no = bt_getid(slotptr(bt->page, slot)->id);
1128                 bt->fence = slot == bt->page->cnt;
1129                 drill--;
1130                 continue;
1131           }
1132         }
1133
1134         //  or slide right into next page
1135
1136         page_no = bt_getid(bt->page->right);
1137
1138   } while( page_no );
1139
1140   // return error on end of right chain
1141
1142   bt->err = BTERR_struct;
1143   return 0;     // return error
1144 }
1145
1146 //  find and delete key on page by marking delete flag bit
1147 //  when page becomes empty, delete it
1148
1149 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1150 {
1151 unsigned char lowerkey[256], higherkey[256];
1152 uint slot, tod, dirty = 0;
1153 uid page_no, right;
1154 BtKey ptr;
1155
1156         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1157                 ptr = keyptr(bt->page, slot);
1158         else
1159                 return bt->err;
1160
1161         // if key is found delete it, otherwise ignore request
1162
1163         if( !keycmp (ptr, key, len) )
1164                 if( slotptr(bt->page, slot)->dead == 0 ) {
1165                         dirty = slotptr(bt->page,slot)->dead = 1;
1166                         if( slot < bt->page->cnt )
1167                                 bt->page->dirty = 1;
1168                         bt->page->act--;
1169                 }
1170
1171         // return if page is not empty, or
1172         //      if non-leaf level or fence key
1173
1174         right = bt_getid(bt->page->right);
1175         page_no = bt->page_no;
1176
1177         if( lvl || bt->page->act || bt->fence )
1178           if ( dirty && bt_update(bt, bt->page, page_no) )
1179                 return bt->err;
1180           else
1181                 return bt_unlockpage(bt, page_no, BtLockWrite);
1182
1183         // obtain Parent lock over write lock
1184
1185         if( bt_lockpage(bt, page_no, BtLockParent) )
1186                 return bt->err;
1187
1188         // cache copy of fence key
1189         //      in order to find parent
1190
1191         ptr = keyptr(bt->page, bt->page->cnt);
1192         memcpy(lowerkey, ptr, ptr->len + 1);
1193
1194         // lock and map right page
1195
1196         if ( bt_lockpage(bt, right, BtLockWrite) )
1197                 return bt->err;
1198
1199         if( bt_mappage (bt, &bt->temp, right) )
1200                 return bt->err;
1201
1202         // pull contents of next page into current empty page 
1203
1204         memcpy (bt->page, bt->temp, bt->page_size);
1205
1206         //      cache copy of key to update
1207
1208         ptr = keyptr(bt->temp, bt->temp->cnt);
1209         memcpy(higherkey, ptr, ptr->len + 1);
1210
1211         //  Mark right page as deleted and point it to left page
1212         //      until we can post updates at higher level.
1213
1214         bt_putid(bt->temp->right, page_no);
1215         bt->temp->cnt = 0;
1216
1217         if( bt_update(bt, bt->page, page_no) )
1218                 return bt->err;
1219
1220         if( bt_update(bt, bt->temp, right) )
1221                 return bt->err;
1222
1223         if( bt_unlockpage(bt, right, BtLockWrite) )
1224                 return bt->err;
1225
1226         if( bt_unlockpage(bt, page_no, BtLockWrite) )
1227                 return bt->err;
1228
1229         //  delete old lower key to consolidated node
1230
1231         if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1232                 return bt->err;
1233
1234         //  redirect higher key directly to consolidated node
1235
1236         tod = (uint)time(NULL);
1237
1238         if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1239                 return bt->err;
1240
1241         //      obtain write lock and
1242         //      add right block to free chain
1243
1244         if( bt_freepage (bt, right) )
1245                 return bt->err;
1246
1247         //      remove ParentModify lock
1248
1249         if( bt_unlockpage(bt, page_no, BtLockParent) )
1250                 return bt->err;
1251         
1252         return 0;
1253 }
1254
1255 //      find key in leaf level and return row-id
1256
1257 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1258 {
1259 uint  slot;
1260 BtKey ptr;
1261 uid id;
1262
1263         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1264                 ptr = keyptr(bt->page, slot);
1265         else
1266                 return 0;
1267
1268         // if key exists, return row-id
1269         //      otherwise return 0
1270
1271         if( ptr->len == len && !memcmp (ptr->key, key, len) )
1272                 id = bt_getid(slotptr(bt->page,slot)->id);
1273         else
1274                 id = 0;
1275
1276         if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1277                 return 0;
1278
1279         return id;
1280 }
1281
1282 //      check page for space available,
1283 //      clean if necessary and return
1284 //      0 - page needs splitting
1285 //      >0 - go ahead with new slot
1286  
1287 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1288 {
1289 uint nxt = bt->page_size;
1290 BtPage page = bt->page;
1291 uint cnt = 0, idx = 0;
1292 uint max = page->cnt;
1293 uint newslot = slot;
1294 BtKey key;
1295 int ret;
1296
1297         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1298                 return slot;
1299
1300         //      skip cleanup if nothing to reclaim
1301
1302         if( !page->dirty )
1303                 return 0;
1304
1305         memcpy (bt->frame, page, bt->page_size);
1306
1307         // skip page info and set rest of page to zero
1308
1309         memset (page+1, 0, bt->page_size - sizeof(*page));
1310         page->act = 0;
1311
1312         while( cnt++ < max ) {
1313                 if( cnt == slot )
1314                         newslot = idx + 1;
1315                 // always leave fence key in list
1316                 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1317                         continue;
1318
1319                 // copy key
1320                 key = keyptr(bt->frame, cnt);
1321                 nxt -= key->len + 1;
1322                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1323
1324                 // copy slot
1325                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1326                 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1327                         page->act++;
1328                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1329                 slotptr(page, idx)->off = nxt;
1330         }
1331
1332         page->min = nxt;
1333         page->cnt = idx;
1334
1335         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1336                 return newslot;
1337
1338         return 0;
1339 }
1340
1341 // split the root and raise the height of the btree
1342
1343 BTERR bt_splitroot(BtDb *bt,  unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1344 {
1345 uint nxt = bt->page_size;
1346 BtPage root = bt->page;
1347 uid new_page;
1348
1349         //  Obtain an empty page to use, and copy the current
1350         //  root contents into it
1351
1352         if( !(new_page = bt_newpage(bt, root)) )
1353                 return bt->err;
1354
1355         // preserve the page info at the bottom
1356         // and set rest to zero
1357
1358         memset(root+1, 0, bt->page_size - sizeof(*root));
1359
1360         // insert first key on newroot page
1361
1362         nxt -= *newkey + 1;
1363         memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1364         bt_putid(slotptr(root, 1)->id, new_page);
1365         slotptr(root, 1)->off = nxt;
1366         
1367         // insert second key on newroot page
1368         // and increase the root height
1369
1370         nxt -= *oldkey + 1;
1371         memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1372         bt_putid(slotptr(root, 2)->id, page_no2);
1373         slotptr(root, 2)->off = nxt;
1374
1375         bt_putid(root->right, 0);
1376         root->min = nxt;                // reset lowest used offset and key count
1377         root->cnt = 2;
1378         root->act = 2;
1379         root->lvl++;
1380
1381         // update and release root (bt->page)
1382
1383         if( bt_update(bt, root, bt->page_no) )
1384                 return bt->err;
1385
1386         return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1387 }
1388
1389 //  split already locked full node
1390 //      return unlocked.
1391
1392 BTERR bt_splitpage (BtDb *bt)
1393 {
1394 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1395 unsigned char oldkey[256], lowerkey[256];
1396 uid page_no = bt->page_no, right;
1397 BtPage page = bt->page;
1398 uint lvl = page->lvl;
1399 uid new_page;
1400 BtKey key;
1401 uint tod;
1402
1403         //  split higher half of keys to bt->frame
1404         //      the last key (fence key) might be dead
1405
1406         tod = (uint)time(NULL);
1407
1408         memset (bt->frame, 0, bt->page_size);
1409         max = (int)page->cnt;
1410         cnt = max / 2;
1411         idx = 0;
1412
1413         while( cnt++ < max ) {
1414                 key = keyptr(page, cnt);
1415                 nxt -= key->len + 1;
1416                 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1417                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1418                 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1419                         bt->frame->act++;
1420                 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1421                 slotptr(bt->frame, idx)->off = nxt;
1422         }
1423
1424         // remember existing fence key for new page to the right
1425
1426         memcpy (oldkey, key, key->len + 1);
1427
1428         bt->frame->bits = bt->page_bits;
1429         bt->frame->min = nxt;
1430         bt->frame->cnt = idx;
1431         bt->frame->lvl = lvl;
1432
1433         // link right node
1434
1435         if( page_no > ROOT_page ) {
1436                 right = bt_getid (page->right);
1437                 bt_putid(bt->frame->right, right);
1438         }
1439
1440         //      get new free page and write frame to it.
1441
1442         if( !(new_page = bt_newpage(bt, bt->frame)) )
1443                 return bt->err;
1444
1445         //      update lower keys to continue in old page
1446
1447         memcpy (bt->frame, page, bt->page_size);
1448         memset (page+1, 0, bt->page_size - sizeof(*page));
1449         nxt = bt->page_size;
1450         page->act = 0;
1451         cnt = 0;
1452         idx = 0;
1453
1454         //  assemble page of smaller keys
1455         //      (they're all active keys)
1456
1457         while( cnt++ < max / 2 ) {
1458                 key = keyptr(bt->frame, cnt);
1459                 nxt -= key->len + 1;
1460                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1461                 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1462                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1463                 slotptr(page, idx)->off = nxt;
1464                 page->act++;
1465         }
1466
1467         // remember fence key for old page
1468
1469         memcpy(lowerkey, key, key->len + 1);
1470         bt_putid(page->right, new_page);
1471         page->min = nxt;
1472         page->cnt = idx;
1473
1474         // if current page is the root page, split it
1475
1476         if( page_no == ROOT_page )
1477                 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1478
1479         // update left (containing) node
1480
1481         if( bt_update(bt, page, page_no) )
1482                 return bt->err;
1483
1484         // obtain Parent/Write locks
1485         // for left and right node pages
1486
1487         if( bt_lockpage (bt, new_page, BtLockParent) )
1488                 return bt->err;
1489
1490         if( bt_lockpage (bt, page_no, BtLockParent) )
1491                 return bt->err;
1492
1493         //  release wr lock on left page
1494
1495         if( bt_unlockpage (bt, page_no, BtLockWrite) )
1496                 return bt->err;
1497
1498         // insert new fence for reformulated left block
1499
1500         if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1501                 return bt->err;
1502
1503         // fix old fence for newly allocated right block page
1504
1505         if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1506                 return bt->err;
1507
1508         // release Parent & Write locks
1509
1510         if( bt_unlockpage (bt, new_page, BtLockParent) )
1511                 return bt->err;
1512
1513         if( bt_unlockpage (bt, page_no, BtLockParent) )
1514                 return bt->err;
1515
1516         return 0;
1517 }
1518
1519 //  Insert new key into the btree at requested level.
1520 //  Level zero pages are leaf pages and are unlocked at exit.
1521 //      Interior nodes remain locked.
1522
1523 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1524 {
1525 uint slot, idx;
1526 BtPage page;
1527 BtKey ptr;
1528
1529   while( 1 ) {
1530         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1531                 ptr = keyptr(bt->page, slot);
1532         else
1533         {
1534                 if ( !bt->err )
1535                         bt->err = BTERR_ovflw;
1536                 return bt->err;
1537         }
1538
1539         // if key already exists, update id and return
1540
1541         page = bt->page;
1542
1543         if( !keycmp (ptr, key, len) ) {
1544                 slotptr(page, slot)->dead = 0;
1545                 slotptr(page, slot)->tod = tod;
1546                 bt_putid(slotptr(page,slot)->id, id);
1547                 if ( bt_update(bt, bt->page, bt->page_no) )
1548                         return bt->err;
1549                 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1550         }
1551
1552         // check if page has enough space
1553
1554         if( slot = bt_cleanpage (bt, len, slot) )
1555                 break;
1556
1557         if( bt_splitpage (bt) )
1558                 return bt->err;
1559   }
1560
1561   // calculate next available slot and copy key into page
1562
1563   page->min -= len + 1; // reset lowest used offset
1564   ((unsigned char *)page)[page->min] = len;
1565   memcpy ((unsigned char *)page + page->min +1, key, len );
1566
1567   for( idx = slot; idx < page->cnt; idx++ )
1568         if( slotptr(page, idx)->dead )
1569                 break;
1570
1571   // now insert key into array before slot
1572   // preserving the fence slot
1573
1574   if( idx == page->cnt )
1575         idx++, page->cnt++;
1576
1577   page->act++;
1578
1579   while( idx > slot )
1580         *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1581
1582   bt_putid(slotptr(page,slot)->id, id);
1583   slotptr(page, slot)->off = page->min;
1584   slotptr(page, slot)->tod = tod;
1585   slotptr(page, slot)->dead = 0;
1586
1587   if ( bt_update(bt, bt->page, bt->page_no) )
1588           return bt->err;
1589
1590   return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1591 }
1592
1593 //  cache page of keys into cursor and return starting slot for given key
1594
1595 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1596 {
1597 uint slot;
1598
1599         // cache page for retrieval
1600         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1601                 memcpy (bt->cursor, bt->page, bt->page_size);
1602         bt->cursor_page = bt->page_no;
1603         if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1604                 return 0;
1605
1606         return slot;
1607 }
1608
1609 //  return next slot for cursor page
1610 //  or slide cursor right into next page
1611
1612 uint bt_nextkey (BtDb *bt, uint slot)
1613 {
1614 off64_t right;
1615
1616   do {
1617         right = bt_getid(bt->cursor->right);
1618         while( slot++ < bt->cursor->cnt )
1619           if( slotptr(bt->cursor,slot)->dead )
1620                 continue;
1621           else if( right || (slot < bt->cursor->cnt))
1622                 return slot;
1623           else
1624                 break;
1625
1626         if( !right )
1627                 break;
1628
1629         bt->cursor_page = right;
1630
1631     if( bt_lockpage(bt, right,BtLockRead) )
1632                 return 0;
1633
1634         if( bt_mappage (bt, &bt->page, right) )
1635                 break;
1636
1637         memcpy (bt->cursor, bt->page, bt->page_size);
1638         if ( bt_unlockpage(bt, right, BtLockRead) )
1639                 return 0;
1640
1641         slot = 0;
1642   } while( 1 );
1643
1644   return bt->err = 0;
1645 }
1646
1647 BtKey bt_key(BtDb *bt, uint slot)
1648 {
1649         return keyptr(bt->cursor, slot);
1650 }
1651
1652 uid bt_uid(BtDb *bt, uint slot)
1653 {
1654         return bt_getid(slotptr(bt->cursor,slot)->id);
1655 }
1656
1657 uint bt_tod(BtDb *bt, uint slot)
1658 {
1659         return slotptr(bt->cursor,slot)->tod;
1660 }
1661
1662
1663 #ifdef STANDALONE
1664 //  standalone program to index file of keys
1665 //  then list them onto std-out
1666
1667 int main (int argc, char **argv)
1668 {
1669 uint slot, line = 0, off = 0, found = 0;
1670 int dead, ch, cnt = 0, bits = 12;
1671 unsigned char key[256];
1672 clock_t done, start;
1673 uint pgblk = 0;
1674 time_t tod[1];
1675 uint scan = 0;
1676 uint len = 0;
1677 uint map = 0;
1678 BtKey ptr;
1679 BtDb *bt;
1680 FILE *in;
1681
1682         if( argc < 4 ) {
1683                 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]);
1684                 fprintf (stderr, "  page_bits: size of btree page in bits\n");
1685                 fprintf (stderr, "  mapped_pool_segments: size of buffer pool in segments\n");
1686                 fprintf (stderr, "  pages_per_segment: size of buffer pool segment in pages in bits\n");
1687                 exit(0);
1688         }
1689
1690         start = clock();
1691         time(tod);
1692
1693         if( argc > 4 )
1694                 bits = atoi(argv[4]);
1695
1696         if( argc > 5 )
1697                 map = atoi(argv[5]);
1698
1699         if( map > 65536 )
1700                 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
1701
1702         if( map && map < 8 )
1703                 fprintf (stderr, "Buffer_pool too small\n");
1704
1705         if( argc > 6 )
1706                 pgblk = atoi(argv[6]);
1707
1708         if( bits + pgblk > 30 )
1709                 fprintf (stderr, "Warning: very large buffer pool segment size\n");
1710
1711         if( argc > 7 )
1712                 off = atoi(argv[7]);
1713
1714         bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
1715
1716         if( !bt ) {
1717                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
1718                 exit (1);
1719         }
1720
1721         switch(argv[3][0]| 0x20)
1722         {
1723         case 'w':
1724                 fprintf(stderr, "started indexing for %s\n", argv[2]);
1725                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1726                   while( ch = getc(in), ch != EOF )
1727                         if( ch == '\n' )
1728                         {
1729                           if( off )
1730                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1731
1732                           if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
1733                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1734                           len = 0;
1735                         }
1736                         else if( len < 245 )
1737                                 key[len++] = ch;
1738                 fprintf(stderr, "finished adding keys, %d \n", line);
1739                 break;
1740
1741         case 'd':
1742                 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
1743                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1744                   while( ch = getc(in), ch != EOF )
1745                         if( ch == '\n' )
1746                         {
1747                           if( off )
1748                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1749                           line++;
1750                           if( bt_deletekey (bt, key, len, 0) )
1751                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1752                           len = 0;
1753                         }
1754                         else if( len < 245 )
1755                                 key[len++] = ch;
1756                 fprintf(stderr, "finished deleting keys, %d \n", line);
1757                 break;
1758
1759         case 'f':
1760                 fprintf(stderr, "started finding keys for %s\n", argv[2]);
1761                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1762                   while( ch = getc(in), ch != EOF )
1763                         if( ch == '\n' )
1764                         {
1765                           if( off )
1766                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1767                           line++;
1768                           if( bt_findkey (bt, key, len) )
1769                                 found++;
1770                           else if( bt->err )
1771                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1772                           len = 0;
1773                         }
1774                         else if( len < 245 )
1775                                 key[len++] = ch;
1776                 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
1777                 break;
1778
1779         case 's':
1780                 scan++;
1781                 break;
1782
1783         }
1784
1785         done = clock();
1786         fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
1787
1788         dead = cnt = 0;
1789         len = key[0] = 0;
1790
1791         fprintf(stderr, "started reading\n");
1792
1793         if( slot = bt_startkey (bt, key, len) )
1794           slot--;
1795         else
1796           fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1797
1798         while( slot = bt_nextkey (bt, slot) )
1799           if( cnt++, scan ) {
1800                         ptr = bt_key(bt, slot);
1801                         fwrite (ptr->key, ptr->len, 1, stdout);
1802                         fputc ('\n', stdout);
1803           }
1804
1805         fprintf(stderr, " Total keys read %d\n", cnt);
1806         return 0;
1807 }
1808
1809 #endif  //STANDALONE