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