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