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