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