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