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