centos build workarounds
[goodguy/history.git] / cinelerra-5.0 / db / tdb.h
1 #ifndef __DB_H__
2 #define __DB_H__
3 #include <cstring>
4 #include <stdint.h>
5 #include <malloc.h>
6 #include <limits.h>
7 #include <sys/types.h>
8
9 #define freeStoreIndex indecies[freeStoreIdx]
10 #define addrStoreIndex indecies[addrStoreIdx]
11 #define freeSpaceIndex indecies[freeSpaceIdx]
12 #define addrSpaceIndex indecies[addrSpaceIdx]
13 #define entityIdIndex indecies[entityIdIdx]
14 #define entityNmIndex indecies[entityNmIdx]
15
16 #define noThrow std::nothrow
17 #ifndef likely
18 #define likely(x)   (__builtin_constant_p(x) ? !!(x) : __builtin_expect(!!(x), 1))
19 #define unlikely(x) (__builtin_constant_p(x) ? !!(x) : __builtin_expect(!!(x), 0))
20 #endif
21 #ifndef lengthof
22 #define lengthof(x) ((int)(sizeof(x)/sizeof(x[0])))
23 #endif
24
25 #if 0
26 inline void *operator new(size_t n) { void *vp = malloc(n); bzero(vp,n); return vp; }
27 inline void operator delete(void *t) { free(t); }
28 inline void operator delete(void *t,size_t n) { free(t); }
29 inline void *operator new[](size_t n) { void *vp = malloc(n); bzero(vp,n); return vp; }
30 inline void operator delete[](void *t) { free(t); }
31 inline void operator delete[](void *t,size_t n) { free(t); }
32 #endif
33
34 #define ZMEDIA
35 #define ZFUTEX
36 #ifdef ZFUTEX
37 #include <unistd.h>
38 #include <endian.h>
39 #include <linux/futex.h>
40 #include <sys/syscall.h>
41 #else
42 #include <pthread.h>
43 #endif
44
45 #if 1
46 //entity definitions
47 #define DbObj(nm) \
48   class nm##Obj : public Db::Obj { public:
49
50 #define DbLoc(nm) \
51   class nm##Loc : public Db::ObjectLoc { public: \
52     nm##Obj *operator ->() { return (nm##Obj *)addr(); } \
53     nm##Loc(Db::Entity *ep) : Db::ObjectLoc(ep) {} \
54     nm##Loc(Db::Entity &e) : Db::ObjectLoc(&e) {}
55
56 //basic definitions
57 #define basic_def(ty,n) class t_##n { public: ty v; t_##n() {} \
58  t_##n(const ty &i) : v(i) {} \
59  t_##n(const t_##n &i) : v(i.v) {} \
60  t_##n &operator =(const t_##n &i) { v = i.v; return *this; } \
61  ty &operator =(const ty &i) { return v = i; } \
62  ty *addr() { return &v; } int size() { return sizeof(v); } \
63  } v_##n \
64
65 //array definitions
66 #define array_def(ty,n,l) class t_##n { public: ty v[l]; t_##n() {} \
67  t_##n(const t_##n &i) { memcpy(&v,&i.v,sizeof(v)); } \
68  t_##n(ty *i) { memcpy(&v,i,sizeof(v)); } \
69  t_##n(ty(*i)[l]) { memcpy(&v,i,sizeof(v)); } \
70  ty *operator =(const ty *i) { memcpy(&v,i,sizeof(v)); return &v[0]; } \
71  ty *addr() { return &v[0]; } int size() { return sizeof(v); } \
72  } v_##n \
73
74 // variable array definitions
75 #define varray_def(ty,n) \
76  class t_##n { public: char *v; int l; t_##n() {} \
77  t_##n(const char *i, int sz) { v = (char *)i; l = sz; } \
78  t_##n(const unsigned char *i, int sz) { v = (char *)i; l = sz; } \
79  ty *addr() { return (ty *)v; } int size() { return l; } \
80  }; Db::varObj v_##n \
81
82 // string array definitions
83 #define sarray_def(ty,n) \
84  class t_##n { public: char *v; int l; t_##n() {} \
85  t_##n(const char *i, int sz) { v = (char *)i; l = sz; } \
86  t_##n(const unsigned char *i, int sz) { v = (char *)i; l = sz; } \
87  t_##n(const char *i) { t_##n(i,strlen(i)+1); } \
88  t_##n(const unsigned char *i) { t_##n(i,strlen(v)+1); } \
89  ty *addr() { return (ty *)v; } int size() { return l; } \
90  }; Db::varObj v_##n \
91
92 //basic type ref
93 #define basic_ref(ty,n) \
94  ty *_##n() { return (*this)->v_##n.addr(); } \
95  ty n() { return *_##n(); } \
96  void n(ty i) { _wr(); *_##n() = i; } \
97  int size_##n() { return (*this)->v_##n.size(); } \
98
99 //array type ref
100 #define array_ref(ty,n,l) \
101  ty *_##n() { return (*this)->v_##n.addr(); } \
102  ty (&n())[l] { return *(ty (*)[l])_##n(); } \
103  void n(const ty *i,int m) { _wr(); if( m > 0 ) memcpy(n(),i,m); } \
104  void n(const ty *i) { n(i,(*this)->v_##n.size()); } \
105  int size_##n() { return (*this)->v_##n.size(); } \
106
107 //variable array type ref
108 #define varray_ref(ty,n) \
109  ty *_##n() { return (ty *)addr((*this)->v_##n); } \
110  ty *_##n(int sz) { size((*this)->v_##n, sz); \
111    return sz > 0 ? (ty *)addr_wr((*this)->v_##n) : 0; } \
112  ty (&n())[] { return *(ty (*)[])_##n(); } \
113  int n(const ty *v, int sz) { ty *vp=_##n(sz); \
114   if( vp && sz > 0 ) memcpy(vp, v, sz); return 0; } \
115  int size_##n() { return (*this)->v_##n.size(); } \
116
117 //string array type ref
118 #define sarray_ref(ty,n) \
119  ty *_##n() { return (ty *)addr((*this)->v_##n); } \
120  ty *_##n(int sz) { size((*this)->v_##n, sz); \
121    return sz > 0 ? (ty *)addr_wr((*this)->v_##n) : 0; } \
122  ty (&n())[] { return *(ty (*)[])_##n(); } \
123  int n(const ty *v, int sz) { ty *vp=_##n(sz); \
124   if( vp && sz > 0 ) memcpy(vp, v, sz); return 0; } \
125  int n(const char *v) { return n((ty *)v,strlen(v)+1); } \
126  int n(const unsigned char *v) { return n((const char *)v); } \
127  int size_##n() { return (*this)->v_##n.size(); } \
128
129 #endif
130
131 #define DEBUG
132 #define DEBUG_TIMESTAMPS
133 #define DBBUG_ERR   0x00000001
134 #define DBBUG_FAIL  0x00000002
135 #define CHK
136 //#define CHK 1 ? 0 :
137
138 class Db;
139
140 class Db {
141 public:
142   typedef int pageId;
143   typedef int transId;
144   typedef long ioAddr;
145
146 private:
147   int root_info_id;
148   int index_info_id;
149   int page_info_id;
150
151   class RootInfo {
152   public:
153     int root_magic;           // info_magic label
154     int root_info_size;       // root_info blob size
155     int last_info_size;
156     int entity_max_id;
157     int entity_count;
158     ioAddr root_info_addr;
159     ioAddr last_info_addr;
160     transId transaction_id;   // current transaction
161     ioAddr file_size;         // current file size
162     pageId freePages;         // free page table page list
163     int indeciesUsed;         // number of active indecies
164     int pageTableUsed;        // number of active pages
165
166     int init();
167   } *root_info;
168
169   int shm_init, no_shm;
170
171   static void *get_mem8_t(int id);
172   static void *new_mem8_t(int size, int &id);
173   static int del_mem8_t(const void *vp, int id);
174   static void *get_shm8_t(int id);
175   static void *new_shm8_t(int size, int &id);
176   static int del_shm8_t(const void *vp, int id);
177   void *(*get_mem)(int id);
178   void *(*new_mem)(int size, int &id);
179   int (*del_mem)(const void *vp, int id);
180
181 protected:
182   uint8_t *get_uint8_t(int id, int pg=-1);
183   uint8_t *new_uint8_t(int size, int &id, int pg=-1);
184   int del_uint8_t(const void *vp, int id=-1, int pg=-1);
185
186 public:
187   typedef int (*CmprFn)(char *,char *);
188   static int cmprFrSt(char *a, char *b);
189   static int cmprAdSt(char *a, char *b);
190   static int cmprFrSp(char *a, char *b);
191   static int cmprAdSp(char *a, char *b);
192   static int cmprOIds(char *a, char *b);
193   static int cmprStr(char *a, char *b);
194   static int cmprKey(char *a, char *b);
195   static int cmprLast(char *a, char *b);
196   static CmprFn cmprFns[];
197   typedef void (*errCallback)(Db *db, int v);
198   static const pageId NIL=-1, DDONE=-2;
199   enum {
200     errNoCmprFn = 0,
201     errNotFound = -1,
202     errDuplicate = -2,
203     errNoPage = -3,
204     errNoMemory = -4,
205     errIoRead = -5,
206     errIoWrite = -6,
207     errIoSeek = -7,
208     errIoStat = -8,
209     errBadMagic = -9,
210     errCorrupt = -10,
211     errInvalid = -11,
212     errPrevious = -12,
213     errObjEntity = -13,
214     errLimit = -14,
215     errUser = -15,
216     idxId = 0, nmSz = 32,
217     keysz = 256,
218     keyLT=-2, keyLE=-1, keyEQ=0, keyGE=1, keyGT=2,
219   };
220
221   class pgRef {
222   public:
223     pageId id;
224     int offset;
225   };
226
227   static void zincr(volatile int &v) { /* atomic(++v) */
228     asm ( " lock incl %1\n" : "+m" (v) :: );
229   }
230   static void zdecr(volatile int &v) { /* atomic(--v) */
231     asm ( " lock decl %1\n" : "+m" (v) :: );
232   }
233   static char tdecr(volatile int &v) {
234     char ret; /* ret = atomic(--loc >= 0 ? 1 : 0) */
235     asm ( " lock decl %1\n setge %0\n" : "=r" (ret), "+m" (v) :: );
236     return ret;
237   }
238   static char tincr(volatile int &v) {
239     char ret; /* ret = atomic(++loc > 0 ? 1 : 0) */
240     asm ( " lock incl %1\n setg %0\n" : "=r" (ret), "+m" (v) :: );
241     return ret;
242   }
243   static int zcmpxchg(int old, int val, volatile int &v) {
244     int ret = old;
245     asm volatile( " lock\n cmpxchgl %2,%1\n"
246       : "+a" (ret), "+m" (v) :  "r" (val) : "memory" );
247     return ret;
248   }
249   static int zxchg(int val, volatile int &v) {
250     asm volatile( " xchgl %0,%1\n"
251       : "+r" (val), "+m" (v) :: "memory" );
252     return val;
253   }
254   static int zadd(int n, volatile int &v) {
255     int old, mod, val;
256     do { val = (old=v)+n; mod = zcmpxchg(old,val,v);
257     } while( mod != old );
258     return val;
259   }
260   static void zmfence() {
261     asm volatile ( " mfence\n" ::: "memory" );
262   }
263
264   class zlock_t;
265   class zblock_t;
266   class zrwlock_t;
267
268 #ifdef ZFUTEX
269 #define ZLOCK_INIT zzlock_t()
270   class zloc_t {
271   protected:
272     volatile int loc;
273     int zfutex(int op, int val, timespec *time=0) {
274       return syscall(SYS_futex,&loc,op,val,time,0,0);
275     }
276     int zyield();
277     int zgettid();
278   public:
279     int zwake(int nwakeups);
280     int zwait(int val, timespec *ts=0);
281     int zwait() { return zwait(loc); }
282     zloc_t() : loc(-1) {}
283     ~zloc_t() {}
284   };
285
286   class zlock_t : zloc_t {
287     void *owner;
288     void *self() {
289 #ifdef __x86_64__
290      void *vp; asm ("movq %%fs:%c1,%q0" : "=r" (vp) : "i" (16));
291 #else
292      void *vp; asm ("mov %%fs:%c1,%q0" : "=r" (vp) : "i" (16));
293 #endif
294      return vp;
295    }
296   protected:
297     friend class zblock_t;
298     friend class zrwlock_t;
299     int zlock(int v);
300     int zunlock(int nwakeups=1);
301     static int zemsg1();
302   public:
303     int lock() {
304       int v, ret = unlikely( (v=zcmpxchg(-1,0,loc)) >= 0 ) ? zlock(v) : 0;
305       owner = self();
306       return ret;
307     }
308     int unlock() {
309       if( unlikely(loc < 0) ) { return zemsg1(); }
310       owner = 0;
311       int v, ret = unlikely( (v=zcmpxchg(0,-1,loc)) != 0 ) ? zunlock() : 0;
312       return ret;
313     }
314     zlock_t() { owner = 0; }
315     ~zlock_t() {}
316   };
317
318   class zblock_t : zlock_t {
319   public:
320     void block() { loc = 0; zwait(0); }
321     void unblock() { loc = -1; zwake(INT_MAX); }
322     zblock_t() {}
323     ~zblock_t() {}
324   };
325
326   class zrwlock_t : zloc_t {
327     zlock_t lk;
328     void zenter();
329     void zleave();
330   public:
331     void enter() { zincr(loc); if( unlikely( lk.loc >= 0 ) ) zenter(); }
332     void leave() { if( unlikely( !tdecr(loc) ) ) zleave(); }
333     void write_enter();
334     void write_leave();
335     int locked() { return loc >= 0 ? 0 : lk.loc >= 0 ? 1 : -1; }
336     int blocked() { return lk.loc >= 0 ? 1 : 0; }
337     zrwlock_t() {}
338     ~zrwlock_t() {}
339   };
340
341 #else
342 #define ZLOCK_INIT { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }
343
344   class zlock_t {
345   protected:
346     pthread_mutex_t zlock;
347   public:
348     void lock() { pthread_mutex_lock(&zlock); }
349     void unlock() { pthread_mutex_unlock(&zlock); }
350     zlock_t() { pthread_mutex_init(&zlock, 0); }
351     ~zlock_t() { pthread_mutex_destroy(&zlock); }
352   };
353
354   class zblock_t {
355     pthread_mutex_t zblock;
356     pthread_cond_t cond;
357   public:
358     zblock_t() {
359       pthread_mutex_init(&zblock, 0);
360       pthread_cond_init(&cond, 0);
361     }
362     ~zblock_t() {
363       pthread_mutex_destroy(&zblock);
364       pthread_cond_destroy(&cond);
365     }
366     void block() {
367       pthread_mutex_lock(&zblock);
368       pthread_cond_wait(&cond, &zblock);
369       pthread_mutex_unlock(&zblock);
370     }
371     void unblock() { pthread_cond_broadcast(&cond); }
372   };
373
374   class zrwlock_t : zlock_t {
375     volatile int blocking, users;
376     zlock_t lk;
377     pthread_cond_t cond;
378     void wait() { pthread_cond_wait(&cond, &zlock); }
379     void wake() { pthread_cond_signal(&cond); }
380   public:
381     void enter() { lock();
382       while( blocking ) { unlock(); lk.lock(); lk.unlock(); lock(); }
383       ++users;  unlock();
384     }
385     void leave() { lock();  if( !--users && blocking ) wake();  unlock(); }
386     void write_enter() { lk.lock();  blocking = 1;
387       lock(); while( users ) wait(); unlock();
388     }
389     void write_leave() { blocking = 0; lk.unlock(); }
390     int count() { return users; }
391     int locked() { return users ? 0 : blocking ? 1 : -1; }
392     int blocked() { return blocking; }
393
394     zrwlock_t() { pthread_cond_init(&cond, 0); users = 0; blocking = 0; }
395     ~zrwlock_t() { pthread_cond_destroy(&cond); }
396   };
397
398 #endif
399
400   class locked {
401     zlock_t &lk;
402   public:
403     locked(zlock_t &l) : lk(l) { lk.lock(); }
404     ~locked() { lk.unlock(); }
405   };
406
407   class read_locked {
408     zrwlock_t &rwlk;
409   public:
410     read_locked(zrwlock_t &l) : rwlk(l) { rwlk.enter(); }
411     ~read_locked() { rwlk.leave(); }
412   };
413
414   class write_blocked {
415     zrwlock_t &rwlk;
416   public:
417     write_blocked(zrwlock_t &l) : rwlk(l) { rwlk.write_enter(); }
418     ~write_blocked() { rwlk.write_leave(); }
419   };
420
421 private:
422   enum {
423     db_magic_offset=0,
424     db_magic=0x00624474,   // tDb
425     idx_magic=0x00786469,  // idx
426     info_magic=0x6f666e69, // info
427     root_magic=0x746f6f72, // root
428     page_magic=0x6770,     // pg
429     entity_magic = 0x6d65, // em
430     root_info_offset=4,
431     root_info_extra_pages = 2,
432     idxNil=0, idxBin=1, idxStr=2,
433     opDelete=-1, opFind=0, opInsert=1,
434     pg_unknown=0, pg_root_info=1, pg_free=2,
435     pg_entity=0x0100, pg_index=0x1000,
436     max_entity_type = pg_index-pg_entity-1,
437     max_index_type = 0x10000-pg_index-1,
438     min_heap_allocation = 32,
439     freeStoreIdx = 0, addrStoreIdx = 1,
440     freeSpaceIdx = 2, addrSpaceIdx = 3,
441     entityIdIdx = 4, entityNmIdx = 5, usrIdx = 6,
442     fl_wr=1, fl_rd=2, fl_new=4, fl_free=8,
443     defaultNoShm = 1,
444     defaultStoreBlockSize = 8192,
445     defaultPageTableHunkSize = 8192,
446     defaultIndexTableHunkSize = 4096,
447     defaultBinaryBlockSize = 16384,
448     defaultStringBlockSize = 4096,
449     defaultEntityPageSize = 65536,
450   };
451
452   int key, fd;
453   int err_no;
454   errCallback err_callback;
455   int my_pid;
456   transId active_transaction;
457
458 #ifdef DEBUG
459   static int debug;
460   static const char *errMsgs[];
461   static void dmsg(int msk, const char *msg,...);
462   int _err_(int v,const char *fn,int ln);
463   int _fail_(int v,const char *fn,int ln);
464 #define err_(v) _err_(v,__func__,__LINE__)
465 #define fail_(v) _fail_(v,__func__,__LINE__)
466 #else
467   static void dmsg(int msk, const char *msg,...) {}
468   int _err_(int v) { error(v); return v; }
469   int _fail_(int v) { return v; }
470 #define err_(v) _err_(v)
471 #define fail_(v) _fail_(v)
472 #endif
473
474 #define Err(v) return err_(v)
475 #define Fail(v) return fail_(v)
476
477 #define if_ret(fn) do{ int _ret; \
478  if(unlikely((_ret=(fn))<0)) return _ret; \
479 }while(0)
480 #define if_err(fn) do{ int _ret; \
481  if(unlikely((_ret=(fn))<0)) Err(_ret); \
482 }while(0)
483 #define if_fail(fn) do{ int _ret; \
484  if(unlikely((_ret=(fn))<0)) Fail(_ret); \
485 }while(0)
486
487   class DbInfo {
488   public:
489     int magic;
490     int owner, last_owner;
491     int info_key, info_id;
492     int root_info_id;
493     int index_info_id;
494     int page_info_id;
495     zlock_t infoLk;   // lock dbinfo up to here
496     zrwlock_t dbRwLk; // global lock
497     zrwlock_t pgTblLk;// pageTable realloc
498     zlock_t pgAlLk;   // new page pagesUsed/pagesAllocated
499     zlock_t pgLdLk;   // pageLoad
500     zlock_t blkAlLk;  // blockAllocate/Free
501     zlock_t objAlLk;  // objectAllocate/Free
502     zrwlock_t rw_locks[max_entity_type];
503
504     DbInfo(int pid, int key, int id);
505   } *db_info;
506   int new_info(int key);
507   int get_info(int key);
508   int del_info();
509
510   int attach_wr();
511   int attach_rd();
512   int attach_rw(int zrw) { return zrw ? attach_wr() : attach_rd(); }
513   void detach_rw();
514
515   class Page;
516
517   class pagePrefix {
518   public:
519     unsigned short magic;
520     unsigned short type;
521     int used;
522   };
523
524   Page *get_Page(pageId pid) volatile { return pageTable[pid]; }
525   void set_Page(pageId pid, Page *pp) { pageTable[pid] = pp; }
526   //Page *get_page(pageId pid) { blocked by(pgTblk); return get_Page(pid); }
527   Page *get_page(pageId pid); // locked pageTable access
528
529   static pageId getPageId(unsigned char *&bp) {
530     int i = sizeof(pageId);  pageId id;
531     for( id = *bp++; --i > 0; id |= *bp++ ) id <<= 8;
532     return id;
533   }
534   static void putPageId(unsigned char *&bp, pageId id) {
535     int i = sizeof(pageId) * 8;
536     while( (i -= 8) >= 0 ) *bp++ = id >> i;
537   }
538   static pageId readPageId(char *cp) {
539     unsigned char *bp = (unsigned char *)cp;
540     return getPageId(bp);
541   }
542   static void writePageId(char *cp, pageId id) {
543     unsigned char *bp = (unsigned char *)cp;
544     putPageId(bp,id);
545   }
546
547   class keyBlock : public pagePrefix {
548     char rightLink[sizeof(pageId)];
549   public:
550     int right_link() { return readPageId(&rightLink[0]); }
551     void right_link(pageId id) { writePageId(&rightLink[0],id); }
552   };
553
554   static int defaultBlockSizes[];
555
556   class IndexTypeInfo {
557   public:
558     int magic;
559     int type;                      /* type of index */
560     char name[nmSz];               /* index string identifier */
561   };
562
563   class IndexBaseType : public IndexTypeInfo {
564   public:
565     IndexBaseType(int typ);
566   };
567
568   class IndexRecdInfo {
569   public:
570     int idx;                       /* index in db->indecies[] */
571     int keySz, dataSz;             /* sizeof key/data fields in bytes */
572     pageId rootPageId;             /* index root page ID */
573     pageId rightHandSide;          /* the right hand side of the tree for this index */
574     pageId freeBlocks;             /* free index page list */
575     unsigned int blockSize;        /* size of new index blocks */
576     int pad1;
577     long count;                    /* index population count */
578   };
579
580   class IndexBaseRecd : public IndexRecdInfo {
581   public:
582     IndexBaseRecd(int typ, int zidx, int ksz, int dsz);
583   };
584
585   class IndexBaseStorage;
586   class IndexBaseInfo : public IndexTypeInfo, public IndexRecdInfo {
587   public:
588     operator IndexBaseStorage *() { return (IndexBaseStorage *)this; }
589   };
590  
591   class IndexBaseStorage : public IndexBaseInfo { 
592   public:
593     IndexBaseStorage(int typ, int zidx, int ksz, int dsz);
594     IndexBaseStorage() {}
595     ~IndexBaseStorage() {}
596   };
597
598   class IndexBase {
599     IndexBaseStorage *st;
600     friend class Db;
601     Db *db;                        /* owner db */
602     pgRef lastAccess, lastFind;    /* last operational access/find location */
603     pgRef lastInsert, lastDelete;  /* last operational insert/delete location */
604     pgRef lastNext;                /* last operational next location */
605     int kdSz;                      /* keySz + dataSz */
606     int lastOp;                    /* last operation, delete=-1/find=0/insert=1 */
607     int cInsCount;                 /* number of consecutive insertions */
608     int cFindCount;                /* number of consecutive finds */
609     int cDelCount;                 /* number of consecutive deletions */
610
611     void init(Db *zdb);
612     virtual int keyMap(pageId s, int(IndexBase::*fn)(pageId id)) = 0;
613     virtual int keyCopy(pageId s, IndexBase *ib) = 0;
614     int blockAllocate(pageId &pid, keyBlock *&bp);
615     int blockAllocate(pageId &pid, keyBlock *&bp, Page *&pp, char *&cp) {
616       pp = 0;  cp = 0;  if_err( blockAllocate(pid, bp) );
617       pp = db->get_page(pid);  cp = (char *)(bp + 1);
618       return 0;
619     }
620     int blockFree(pageId pid);
621     int blockRelease(pageId pid);
622     int deleteFreeBlocks();
623     int chkLast(pgRef &last, int &count);
624     void chkLastInsert();
625     void chkLastDelete();
626     void chkLastFind();
627   public:
628 #ifdef DEBUG
629     int _err_(int v,const char *fn,int ln) { return db->_err_(v,fn,ln); }
630     int _fail_(int v,const char *fn,int ln) { return db->_fail_(v,fn,ln); }
631 #else
632     int _err_(int v) { return db->_err_(v); }
633     int _fail_(int v) { return db->_fail_(v); }
634 #endif
635     virtual int Locate(int op,void *key,CmprFn cmpr,void *rtnKey,void *rtnData) = 0;
636     int Locate(int op,void *key,void *rtnKey,void *rtnData) {
637       return Locate(op,key,0,rtnKey,rtnData);
638     }
639     virtual int Find(void *key,void *rtnData) = 0;
640     virtual int Insert(void *key,void *data) = 0;
641     virtual int Delete(void *key) = 0;
642     virtual int First(void *rtnKey,void *rtnData) = 0;
643     virtual int Last(void *rtnKey,void *rtnData) = 0;
644     virtual int Modify(void *key,void *recd) = 0;
645     virtual int Next(pgRef &loc,void *rtnKey,void *rtnData) = 0;
646     int First(pgRef &loc,void *rtnKey,void *rtnData) {
647       if_fail( First(rtnKey, rtnData) );
648       loc = lastNext;
649       return 0;
650     }
651     int Next(void *rtnKey,void *rtnData) {
652       if( lastNext.id < 0 ) Fail(errInvalid);
653       return Next(lastNext,rtnKey,rtnData);
654     }
655     long Count() { return st->count; }
656     int MakeRoot();
657     int UnmakeRoot();
658     int Clear();
659     int NextLoc(pgRef &loc) { loc = lastNext; return 0; }
660     IndexBase(Db *zdb, int typ, int zidx, int ksz, int dsz);
661     IndexBase(Db *zdb, IndexBaseStorage &d);
662     virtual ~IndexBase();
663   } **indecies;
664
665   int indeciesAllocated, indecies_sz;
666
667   class IndexBinaryStorage;
668   class IndexBinaryInfo {
669   public:
670     operator IndexBinaryStorage *() { return (IndexBinaryStorage *)this; }
671     int cmprId;
672   };
673
674   class IndexBinaryStorage : public IndexBinaryInfo {
675   public:
676     IndexBinaryStorage(int cmprId) { this->cmprId = cmprId; }
677     IndexBinaryStorage() {}
678     ~IndexBinaryStorage() {}
679   };
680
681   class IndexBinary : public IndexBase {
682     IndexBinaryStorage *bst;
683     friend class Db;
684     CmprFn compare;                /* the key compare function type */
685     int relationship;              /* key relation in keyLT..keyGT */
686     char *key;                     /* pointer to key argument */
687     int keyInterior;               /* last insert interior/exterior */
688     int idf;                       /* interior delete flag */
689     char *iky, *tky;               /* search/promoted temp key storage */
690
691     void init();
692     int keyMap(pageId s, int(IndexBase::*fn)(pageId id));
693     int keyCopy(pageId s, IndexBase *ib);
694     int keyBlockUnderflow(int &t,keyBlock *lbb,pageId p,keyBlock *pbb,int pi);
695     void makeKey(char *cp,char *key,int l,char *recd,int n);
696     void setLastKey(pageId s,pageId u,int k);
697     int keyLocate(pageId s, CmprFn cmpr);
698     int chkNext(pgRef &loc, char *&kp);
699     int keyNext(pgRef &loc, char *kp);
700     int chkFind(char *key, pgRef *last);
701     int keyFind(pageId s);
702     int chkInsert(void *key,void *data);
703     int keyInsert(pageId s, pageId &t);
704     int keyDelete(int &t,void *kp,pageId s,pageId p,keyBlock *pbb,int pi);
705     int keyFirst(pageId s);
706     int keyLast(pageId s);
707
708     int Locate(int op,void *key,CmprFn cmpr,void *rtnKey,void *rtnData);
709     int Find(void *key,void *rtnData);
710     int Insert(void *key,void *data);
711     int Delete(void *key);
712     int First(void *rtnKey,void *rtnData);
713     int Last(void *rtnKey,void *rtnData);
714     int Modify(void *key,void *recd);
715     int Next(pgRef &loc,void *rtnKey,void *rtnData);
716     int Next(void *rtnKey,void *rtnData) {
717       return IndexBase::Next(rtnKey,rtnData);
718     }
719
720     char *ikey() { return iky; }
721     char *tkey() { return tky; }
722   public:
723     IndexBinary(Db *zdb, int zidx, int ksz, int dsz, CmprFn cmpr);
724     IndexBinary(Db *zdb, IndexBaseStorage *b, IndexBinaryStorage *d);
725     IndexBinary(IndexBase *ib, IndexBaseStorage *b, IndexBinaryStorage *d);
726     ~IndexBinary();
727   };
728   friend class IndexBinary;
729
730   class IndexStringStorage;
731   class IndexStringInfo {
732     char dummy; // compiler needs this for some reason
733   public:
734     operator IndexStringStorage *() { return (IndexStringStorage *)this; }
735   };
736
737   class IndexStringStorage : public IndexStringInfo {
738   public:
739     IndexStringStorage() {}
740     ~IndexStringStorage() {}
741   };
742
743   class IndexString : public IndexBase {
744     IndexStringStorage *sst;
745     friend class Db;
746     static int ustrcmp(unsigned char *a, unsigned char *b) {
747       return strncmp((char *)a,(char *)b,keysz);
748     }
749     static void ustrcpy(unsigned char *a, unsigned char *b) {
750       strncpy((char *)a,(char *)b,keysz);
751     }
752     static void umemmove(unsigned char *&a, unsigned char *b, int n) {
753       memmove(a,b,n);  a += n;
754     }
755     static int kpress(unsigned char *kp, unsigned char *lp, unsigned char *cp);
756     int split(int n, int i, pageId s, pageId &l, pageId r);
757     void init();
758     int keyMap(pageId s, int(IndexBase::*fn)(pageId id));
759     int keyCopy(pageId s, IndexBase *ib);
760     int chkInsert(void *key,void *data);
761     int keyInsert(pageId &t, pageId s);
762     int keyFirst(pageId s);
763     int keyLast(pageId s);
764     int keyLocate(pageId s,int &t, CmprFn cmpr);
765     int chkFind(char *key, pgRef *last, unsigned char *lkey, unsigned char *lky=0);
766     int keyFind();
767     int chkNext(pgRef &loc);
768     int keyNext(pgRef &loc);
769     int keyUnderflow(pageId s, pageId &t, int k);
770     int keyOverflow(pageId s, pageId &t, int k, int o);
771     int keyRemap(pageId s, pageId &t, int k, int o);
772     int keyDelete(pageId s, pageId &t);
773
774     unsigned char lastAccKey[keysz], lastFndKey[keysz];
775     unsigned char lastInsKey[keysz], lastDelKey[keysz];
776     unsigned char lastNxtKey[keysz];
777     unsigned char *tky, *dky;   // dataSz+keysz+1
778     unsigned char *tbfr;        // 3*allocated
779     unsigned char key[keysz];   // key in use
780     int idf;                    /* interior delete flag */
781     int relationship;           /* key relation in keyLT..keyGT */
782
783     int Locate(int op,void *key,CmprFn cmpr,void *rtnKey,void *rtnData);
784     int Find(void *key,void *rtnData);
785     int Insert(void *key,void *data);
786     int Delete(void *key);
787     int First(void *rtnKey,void *rtnData);
788     int Last(void *rtnKey,void *rtnData);
789     int Modify(void *key,void *recd);
790     int Next(pgRef &loc,void *rtnKey,void *rtnData);
791     int Next(void *rtnKey,void *rtnData) {
792       return IndexBase::Next(rtnKey,rtnData);
793     }
794
795   public:
796     IndexString(Db *zdb, int zidx, int dsz);
797     IndexString(Db *zdb, IndexBaseStorage *b, IndexStringStorage *d);
798     IndexString(IndexBase *ib, IndexBaseStorage *b, IndexStringStorage *d);
799     ~IndexString();
800   };
801   friend class IndexString;
802
803   class IndexBinaryData : public IndexBaseInfo, public IndexBinaryInfo {};
804   class IndexStringData : public IndexBaseInfo, public IndexStringInfo {};
805
806   typedef union {
807     IndexBaseInfo base;
808     IndexBinaryData bin;
809     IndexStringData str;
810   } IndexInfo;
811   IndexInfo *index_info;        /* image for index storage */
812
813   class allocPrefix {
814   public:
815     unsigned short magic;
816     unsigned short type;
817     int size;
818   };
819
820   class freeStoreRecord {
821   public:
822     long size;
823     ioAddr io_addr;
824   };
825
826   class addrStoreRecord {
827   public:
828     ioAddr io_addr;
829     long size;
830   };
831
832   class freeSpaceRecord {
833   public:
834     long size;
835     pageId id;
836     int offset;
837   };
838
839   class addrSpaceRecord {
840   public:
841     pageId id;
842     int offset;
843     long size;
844   };
845
846   class AllocCache {
847     pgRef loc;
848     int avail;
849   public:
850     int cacheFlush(Db *db);
851     int Get(Db *db,int &size, pgRef &ref);
852     int Load(Db *db, pageId id, int ofs, int sz);
853     void init() { loc.id = NIL; loc.offset = 0; avail = 0; }
854     void init(pageId id, int ofs, int sz) {
855       loc.id = id; loc.offset = ofs; avail = sz;
856     }
857   } alloc_cache;
858   int cacheFlush() {
859     return alloc_cache.cacheFlush(this);
860   }
861   int cache_all_flush();
862
863   class PageStorage {
864   public:
865     unsigned int used;
866     unsigned int allocated;
867     unsigned short flags;
868     unsigned short type;
869     int io_allocated;
870     int wr_allocated;
871     int shmid;
872     pageId link;
873     transId trans_id;
874     ioAddr io_addr;
875     ioAddr wr_io_addr;
876
877     PageStorage();
878     ~PageStorage() {}
879     int chk_flags(int fl) { return flags & fl; }
880     int set_flags(int fl) { return flags |= fl; }
881     int clr_flags(int fl) { return flags &= ~fl; }
882   } *page_info;
883
884   class Page {
885     PageStorage *st;
886     pagePrefix *addr;
887     int shm_id;
888     void init();
889   public:
890     // PageStorage access
891     int iused() { return st->used-sizeof(keyBlock); }
892     void iused(int v) { st->used = v+sizeof(keyBlock); }
893     int iallocated() { return st->allocated-sizeof(keyBlock); }
894     void iallocated(int v) { st->allocated = v+sizeof(keyBlock); }
895     PageStorage *operator ->() { return st; }
896     int release();
897     Page(PageStorage &d) { st = &d; init(); }
898     ~Page() {}
899     friend class Db;
900   } **pageTable;
901   int pageTableAllocated, page_table_sz;
902
903   int entityPageSize;
904   int storeBlockSize;
905   int pageTableHunkSize;
906   int indexTableHunkSize;
907
908   class undoData {
909   public:
910     class cfnData {
911       public:
912       int cmprId;
913       CmprFn compare;
914     } *cfn;
915     int cfnAllocated, cfnUsed;
916     undoData() : cfn(0), cfnAllocated(0), cfnUsed(0) {}
917     ~undoData() { delete [] cfn; cfnAllocated = cfnUsed = 0; }
918     int save(Db *db);
919     int restore(Db *db);
920   } undata;
921
922   ioAddr file_position;
923
924   char *bfr, *lmt, *inp;
925   int open_bfr();
926   int close_bfr();
927   int flush_bfr();
928   int write_bfr(char *dp, int sz);
929
930 public:
931 #ifdef ZMEDIA
932
933   // count of on bits
934   inline static unsigned int on_bits(unsigned int n) {
935     n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
936     n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
937     n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
938     n += n >> 8;  n += n >> 16;  //ok, fldsz > 5 bits
939     return n & 0x1f;
940   }
941
942   // lowest on bit
943   inline static unsigned int low_bit(unsigned int n) {
944     return n & ~(n-1);
945   }
946
947   // bit number of lowest on bit
948   inline static unsigned int low_bit_no(unsigned int n) {
949     return on_bits(low_bit(n) - 1);
950   }
951
952   // highest on bit, and all lower bits set
953   inline static unsigned int high_bit_mask(unsigned int n) {
954     n |= n >> 1;   n |= n >> 2;
955     n |= n >> 4;   n |= n >> 8;
956     n |= n >> 16;
957     return n;
958   }
959
960   // highest on bit
961   inline static unsigned int high_bit(unsigned int n) {
962     unsigned m = high_bit_mask(n);
963     return m & ~(m>>1);
964   }
965
966   // bit number of highest on bit
967   inline static unsigned int high_bit_no(unsigned int n) {
968     return on_bits(high_bit_mask(n)) - 1;
969   }
970
971   class pack {
972     static inline int cpu_aligned() {
973       unsigned long flags;
974       asm volatile( "pushf\n" "pop %0\n" : "=rm" (flags) );
975       return (flags>>18) & 1;
976     }
977     static int aligned;
978     int idx;
979     uint8_t *bits;
980     uint64_t vmx;
981     uint64_t clip(int64_t v) { return v<0 ? 0 : (uint64_t)v>vmx ? vmx : v; }
982   public:
983     enum { alignBits = 8, };
984
985     static void init(int v=-1) { aligned = v >= 0 ? v : cpu_aligned(); }
986     void put(uint64_t v, int n);
987     void putc(uint64_t v, int n) { put(clip(v), n); }
988     void iput(int v) { put(v, 8*sizeof(int)); }
989     void lput(int64_t v) { put(v, 8*sizeof(int64_t)); }
990     uint64_t get(int n);
991     int iget() { return get(8*sizeof(int)); }
992     int64_t lget() { return get(8*sizeof(int64_t)); }
993     int pos() { return idx; }
994     void seek(int i) { idx = i; }
995     void init(uint8_t *bp) { bits = bp; idx = 0; vmx = 0; }
996     uint8_t *bfr() { return this->bits; }
997     void align() { idx = (idx+alignBits-1) & ~(alignBits-1); }
998     void *addr() { return &bits[idx/8]; }
999     void set_max(uint64_t v) { vmx = v; }
1000
1001     pack() : bits(0) { idx = 0; }
1002     pack(uint8_t *bp) { init(bp); }
1003     ~pack() {}
1004   };
1005
1006   class mediaKey {
1007     int w, len;
1008     int64_t cnt;
1009     uint8_t *bp;
1010
1011   public:
1012     static int64_t bit_size(int len, int w);
1013     static int64_t byte_size(int len, int w);
1014     static void build(uint8_t *kp, uint8_t *bp, int w, int len) {
1015       mediaKey key(kp, bp, w, len);
1016     }
1017     static int64_t count(void *kp) {
1018       mediaKey *mkp = (mediaKey *)kp;
1019       return be64toh(mkp->cnt);
1020     }
1021     static int64_t set_count(void *kp, int64_t v) {
1022       mediaKey *mkp = (mediaKey *)kp;
1023       return mkp->cnt = htobe64(v);
1024     }
1025     static int64_t incr_count(void *kp, int64_t dv) {
1026       return set_count(kp, count(kp) + dv);
1027     }
1028     static int64_t count1(uint8_t *kp);
1029     mediaKey(uint8_t *kp, uint8_t *bp, int w, int len);
1030     ~mediaKey();
1031   };
1032
1033   class mediaLoad {
1034     pack pb, pk;
1035     int w, len, dsz, psz, spos;
1036     int64_t cnt, *dat, **dp;
1037     void get_fields(int n, int k);
1038     int dsize(int n) { int m = (n+1)/2; return m>1 ? m+dsize(m) : 1; }
1039
1040   public:
1041     void load(uint8_t *kp);
1042
1043     mediaLoad(uint8_t *bp);
1044     ~mediaLoad();
1045   };
1046
1047   class mediaCmpr {
1048     pack pb, pk;
1049     int w, len, dsz, psz, spos;
1050     int64_t acnt, bcnt, *adat, *bdat, **adp, **bdp;
1051     uint64_t err, lmt;
1052     uint64_t sqr(int64_t v) { return v*v; }
1053     int dsize(int n) { int m = (n+1)/2; return m>1 ? m+dsize(m) : 1; }
1054     uint64_t chk_fields(int m, int k);
1055     int cmpr_fields(int m, int k);
1056
1057   public:
1058     uint64_t chk(uint8_t *kp, uint64_t lmt=~0);
1059     int cmpr(uint8_t *kp, uint64_t lmt=~0);
1060
1061     mediaCmpr(uint8_t *bp);
1062     ~mediaCmpr();
1063   };
1064 #endif
1065
1066   class Entity;
1067   class ObjectLoc;
1068   typedef IndexBase *Index;
1069   int new_entity(Entity &entity, const char *nm, int sz);
1070   int get_entity(Entity &entity, const char *nm);
1071   int del_entity(Entity &entity);
1072
1073   class Obj {                    /* per object storage base class */
1074   public:
1075     int id;
1076   };
1077
1078   class varObj {
1079   public:
1080     int len;  pgRef loc;
1081     int size() { return len; }
1082     void init() { len = -1;  loc.id = NIL;  loc.offset = 0; }
1083     void del(Db *db) { len = -1;  db->deallocate(loc); }
1084   };
1085   typedef varObj Obj::*vRef;
1086
1087   class ObjectLoc {
1088   public:
1089     Entity *entity;
1090     pgRef obj;
1091     Obj *addr(pgRef &loc) { 
1092       char *op = 0;
1093       return loc.id < 0 || entity->db->addrRead(loc,op) ? 0 : (Obj *)op;
1094     }
1095     Obj *addr_wr(pgRef &loc) { 
1096       char *op = 0;
1097       return loc.id < 0 || entity->db->addrWrite(loc,op) ? 0 : (Obj *)op;
1098     }
1099     void _wr() { Page &pg = *entity->db->get_page(obj.id); pg->set_flags(fl_wr); }
1100     Obj *addr() { return addr(obj); }
1101     Obj *addr_wr() { return addr_wr(obj); }
1102     void *addr(varObj &vobj) { return addr(vobj.loc); }
1103     void *addr_wr(varObj &vobj) { return addr_wr(vobj.loc); }
1104     Obj *operator ->() { return (Obj *)addr(); }
1105     ObjectLoc(Entity *ep) : entity(ep) { obj.id = NIL;  obj.offset = 0; }
1106     ~ObjectLoc() {}
1107
1108     virtual int allocate(int sz=0) { return entity->allocate(*this,sz); }
1109     virtual int construct() { return entity->construct(*this); }
1110     virtual int destruct() { return entity->destruct(*this); }
1111     virtual int deallocate() { return entity->deallocate(*this); }
1112     virtual int insertCascade() { return 0; }
1113     virtual int insertProhibit() { return 0; }
1114     virtual int deleteCascade() { return 0; }
1115     virtual int deleteProhibit() { return 0; }
1116     virtual int modifyCascade() { return 0; }
1117     virtual int modifyProhibit() { return 0; }
1118     virtual int copy(ObjectLoc &dobj);
1119     int id() { ObjectLoc &oloc = *this; return oloc->id; }
1120     const int *_id() { ObjectLoc &oloc = *this; return &oloc->id; }
1121     int _id_size() { return sizeof(int); }
1122     int size(varObj &vobj) { return vobj.len; }
1123     int size(varObj &vobj, int sz);
1124     Index index(int i) { return entity->index(i); }
1125     void v_init();
1126     void v_del();
1127
1128     int FindId(int id) { return index(idxId)->Find(&id,&obj); }
1129     int LocateId(int op, int id) { return index(idxId)->Locate(op,&id,0,&obj); }
1130     int FirstId() { return index(idxId)->First(0,&obj); }
1131     int LastId() { return index(idxId)->Last(0,&obj); }
1132     int NextId() { return index(idxId)->Next(0,&obj); }
1133     int FirstId(pgRef &loc) { return index(idxId)->First(loc,0,&obj); }
1134     int NextId(pgRef &loc) { return index(idxId)->Next(loc,0,&obj); }
1135     int NextLocId(pgRef &loc) { return index(idxId)->NextLoc(loc); }
1136
1137     static int cmpr_char(const char *ap, int asz, const char *bp, int bsz);
1138     static int cmpr_uchar(const unsigned char *ap, int asz, const unsigned char *bp, int bsz);
1139     static int cmpr_short(const short *ap, int asz, const short *bp, int bsz);
1140     static int cmpr_ushort(const unsigned short *ap, int asz, const unsigned short *bp, int bsz);
1141     static int cmpr_int(const int *ap, int asz, const int *bp, int bsz);
1142     static int cmpr_uint(const unsigned int *ap, int asz, const unsigned int *bp, int bsz);
1143     static int cmpr_long(const long *ap, int asz, const long *bp, int bsz);
1144     static int cmpr_ulong(const unsigned long *ap, int asz, const unsigned long *bp, int bsz);
1145     static int cmpr_float(const float *ap, int asz, const float *bp, int bsz);
1146     static int cmpr_double(const double *ap, int asz, const double *bp, int bsz);
1147 #ifdef ZMEDIA
1148     static int cmpr_media(const unsigned char *ap, int asz, const unsigned char *bp, int bsz);
1149 #endif
1150
1151 #ifdef DEBUG
1152     int _err_(int v,const char *fn,int ln) { return entity->db->_err_(v,fn,ln); }
1153     int _fail_(int v,const char *fn,int ln) { return entity->db->_fail_(v,fn,ln); }
1154 #else
1155     int _err_(int v) { return entity->db->_err_(v); }
1156     int _fail_(int v) { return entity->db->_fail_(v); }
1157 #endif
1158
1159     int last(int idx,int (ObjectLoc::*ip)());
1160     int last(const char *nm,int (ObjectLoc::*ip)());
1161     unsigned int last(int idx,unsigned int (ObjectLoc::*ip)());
1162     unsigned int last(const char *nm,unsigned int (ObjectLoc::*ip)());
1163   };
1164
1165   class Key {
1166   public:
1167     ObjectLoc &loc;
1168     Index idx;
1169     CmprFn cmpr;
1170     Key(Index i, ObjectLoc &l, CmprFn c) : loc(l), idx(i), cmpr(c) {}
1171     Key(const char *nm, ObjectLoc &l, CmprFn c) : loc(l), cmpr(c) {
1172       idx = loc.entity->index(nm);
1173     }
1174     operator void *() { return (void *)this; }
1175 #ifdef DEBUG
1176     int _err_(int v,const char *fn,int ln) { return loc._err_(v,fn,ln); }
1177     int _fail_(int v,const char *fn,int ln) { return loc._fail_(v,fn,ln); }
1178 #else
1179     int _err_(int v) { return loc._err_(v); }
1180     int _fail_(int v) { return loc._fail_(v); }
1181 #endif
1182   };
1183
1184   class iKey : public Key {
1185   public:
1186     iKey(Index i, ObjectLoc &l, CmprFn c) : Key(i,l,c) {}
1187     iKey(const char *nm, ObjectLoc &l, CmprFn c) : Key(nm,l,c) {}
1188     int NextLoc(pgRef &pos) { return idx->NextLoc(pos); }
1189     int Find();
1190     int Locate(int op=keyGE);
1191   };
1192
1193   class rKey : public Key {
1194   public:
1195     rKey(Index i, ObjectLoc &l, CmprFn c) : Key(i,l,c) {}
1196     rKey(const char *nm, ObjectLoc &l, CmprFn c) : Key(nm,l,c) {}
1197     int NextLoc(pgRef &pos) { return idx->NextLoc(pos); }
1198     int First();  int First(pgRef &pos);
1199     int Next();   int Next(pgRef &pos);
1200     int Last();
1201     int Locate(int op=keyGE);
1202   };
1203
1204 private:
1205   class EntityObj : public Obj { /* entity storage */
1206   public:
1207     char name[nmSz];             /* string identifier */
1208     AllocCache alloc_cache;      /* entity allocator cache */
1209     int maxId;                   /* highest ID value */
1210     int recdSz;                  /* record size in bytes */
1211     int count;                   /* number of records */
1212     int nidxs;                   /* index count */
1213     int indexs[1];               /* id/loc index */
1214     EntityObj(EntityObj &eobj, int eid);
1215   };
1216
1217   class EntityLoc : public ObjectLoc {
1218   public:
1219     EntityObj *operator ->() { return (EntityObj *)addr(); }
1220     EntityLoc(Entity *ep) : ObjectLoc(ep) {}
1221     ~EntityLoc() {}
1222     int cacheFlush() {
1223       EntityLoc &eloc = *this;  _wr();
1224       return eloc->alloc_cache.cacheFlush(entity->db);
1225     }
1226   };
1227
1228   class varObjRef;
1229   typedef varObjRef *varObjs;
1230   class varObjRef {
1231   public:
1232     varObjs next;
1233     vRef ref;
1234     varObjRef(varObjs &lp, vRef rp) : next(lp), ref(rp) {}
1235   };
1236    
1237 public:
1238
1239   class Entity {
1240   public:
1241     Db *const db;
1242     EntityLoc ent;
1243     varObjs vobjs;
1244     zrwlock_t *rw_lock;
1245     operator zrwlock_t&() { return *rw_lock; }
1246
1247 #ifdef DEBUG
1248     int _err_(int v,const char *fn,int ln) { return db->_err_(v,fn,ln); }
1249     int _fail_(int v,const char *fn,int ln) { return db->_fail_(v,fn,ln); }
1250 #else
1251     int _err_(int v) { return db->_err_(v); }
1252     int _fail_(int v) { return db->_fail_(v); }
1253 #endif
1254     Entity(Db *const db) : db(db), ent(this), vobjs(0) {}
1255     ~Entity() {}
1256
1257     int allocate(ObjectLoc &loc,int sz=0);
1258     int construct_(ObjectLoc &loc, int id);
1259     int construct(ObjectLoc &loc) { return construct_(loc,ent->maxId); }
1260     int destruct_(ObjectLoc &loc, int id);
1261     int destruct(ObjectLoc &loc) { return destruct_(loc, loc->id); }
1262     int deallocate(ObjectLoc &loc);
1263     int get_index(const char *nm, CmprFn cmpr=0);
1264     int key_index(const char *nm) { return get_index(nm,Db::cmprKey); }
1265     Index index(int i) { return db->indecies[ent->indexs[i]]; }
1266     Index index(const char *nm) {
1267       int idx = get_index(nm);
1268       return idx >= 0 ? index(idx) : 0;
1269     }
1270     int MaxId() { return ent->maxId; }
1271     int Count() { return ent->count; }
1272     int add_index(int idx);
1273     int add_bindex(const char *nm,int keySz,int dataSz) {
1274       int idx = db->new_binary_index(nm,keySz,dataSz);
1275       if_err( idx );  if_err( add_index(idx) );
1276       return 0;
1277     }
1278     int add_kindex(const char *nm) { return add_bindex(nm,0,sizeof(int)); }
1279     int add_sindex(const char *nm,int dataSz) {
1280       int idx = db->new_string_index(nm,dataSz);
1281       if_err( idx );  if_err( add_index(idx) );
1282       return 0;
1283     }
1284     int del_index_(int idx);
1285     int del_index(int idx);
1286     int new_entity(const char *nm, int sz) { return db->new_entity(*this,nm,sz); }
1287     int get_entity(const char *nm) { return db->get_entity(*this,nm); }
1288     int del_entity() { return db->del_entity(*this); }
1289     void add_vref(vRef rp) { vobjs = new varObjRef(vobjs,rp); }
1290   };
1291
1292   class ObjectList;
1293   typedef ObjectList *Objects;
1294   static void finit(Objects objects);
1295
1296   class ObjectList {
1297   public:
1298     Objects next;
1299     ObjectLoc *obj;
1300     ObjectList(Objects op, ObjectLoc &o) : next(op), obj(&o) {}
1301   };
1302
1303 private:
1304   int new_entity_(Entity &entity, const char *nm, int sz);
1305
1306   int findCmprFn(CmprFn fn);
1307   int pageLoad(pageId id);
1308   int addrRead_(pgRef &loc, char *&vp, int mpsz=0) {
1309     Page &pg = *get_page(loc.id);  vp = 0;
1310     if( unlikely( !pg.addr || pg->chk_flags(fl_rd) ) )
1311       if_err( pageLoad(loc.id) );
1312     vp = (char *)pg.addr+loc.offset+mpsz;
1313     return 0;
1314   }
1315   int addrRead_(pgRef &loc, keyBlock *&vp, int mpsz=0) {
1316     return addrRead_(loc,*(char**)&vp, mpsz);
1317   }
1318   int addrRead_(pgRef &loc, allocPrefix *&vp, int mpsz=0) {
1319     return addrRead_(loc,*(char**)&vp, mpsz);
1320   }
1321   int addrRead_(pgRef &loc, pagePrefix *&vp, int mpsz=0) {
1322     return addrRead_(loc,*(char**)&vp, mpsz);
1323   }
1324   int addrWrite_(pgRef &loc, char *&vp, int mpsz=0) {
1325     Page &pg = *get_page(loc.id);  vp = 0;
1326     if( unlikely( !pg.addr || pg->chk_flags(fl_rd) ) )
1327       if_err( pageLoad(loc.id) );
1328     pg->set_flags(fl_wr);
1329     vp = (char *)pg.addr+loc.offset+mpsz;
1330     return 0;
1331   }
1332   int addrWrite_(pgRef &loc, keyBlock *&vp, int mpsz=0) {
1333     return addrWrite_(loc,*(char**)&vp, mpsz);
1334   }
1335   int addrWrite_(pgRef &loc, allocPrefix *&vp, int mpsz=0) {
1336     return addrWrite_(loc,*(char**)&vp, mpsz);
1337   }
1338   int addrWrite_(pgRef &loc, pagePrefix *&vp, int mpsz=0) {
1339     return addrWrite_(loc,*(char**)&vp, mpsz);
1340   }
1341   int addrRead(pgRef &loc, char *&vp) {
1342     return addrRead_(loc, vp, sizeof(allocPrefix));
1343   }
1344   int addrWrite(pgRef &loc, char *&vp) {
1345     return addrWrite_(loc, vp, sizeof(allocPrefix));
1346   }
1347
1348   int objectHeapInsert(int sz,int pg,int off);
1349   int objectHeapDelete(int sz,int pg,int off);
1350   int objectAllocate(int typ, int &size, pgRef &loc,AllocCache &cache);
1351   int objectFree(pgRef &loc);
1352   int pgRefGet(int &size, pgRef &loc,AllocCache &cache);
1353   int pgRefNew(int &size, pgRef &lo,AllocCache &cache);
1354   int pgRefAllocate(int &size, pgRef &lo,AllocCache &cache);
1355
1356   int storeInsert(long size, ioAddr io_addr);
1357   int storeDelete(long size, ioAddr io_addr);
1358   int storeGet(int &size, ioAddr &io_addr);
1359   int storeNew(int &size, ioAddr &io_addr);
1360   int storeAllocate(int &size, ioAddr &io_addr);
1361   int storeFree(int size, ioAddr io_addr);
1362
1363   int icommit(int force);
1364   int iundo();
1365   int iclose();
1366   int ireopen();
1367   int iattach();
1368   int iopen(int undo_save=1);
1369
1370 protected:
1371
1372   pageId new_page();
1373   void del_page(int id);
1374   int alloc_pageTable(int sz);
1375   void free_page(int pid);
1376   int alloc_indecies(int n);
1377   int new_index();
1378   void del_index(int idx);
1379   int new_index(IndexBase *&ibp, IndexBaseInfo *b, IndexBinaryInfo *d);
1380   int new_index(IndexBase *&ibp, IndexBaseInfo *b, IndexStringInfo *d);
1381   int indexRead(pageId pid, int df, keyBlock *&bp) {
1382     pgRef pg;  pg.id = pid;  pg.offset = 0;
1383     return !df ? addrRead_(pg,*(char**)&bp) : addrWrite_(pg,*(char**)&bp);
1384   }
1385   int indexRead(pageId pid,int df,keyBlock *&bp, Page *&pp, char *&cp) {
1386     pp = 0;  cp = 0;  if_err( indexRead(pid, df, bp) );
1387     pp = get_page(pid);  cp = (char *)(bp + 1);
1388     return 0;
1389   }
1390   void pageDealloc(Page &pg, int mode=1);
1391   int pageRead(Page &pg);
1392   int pageWrite(Page &pg);
1393   int seek_data(ioAddr io_addr);
1394   int size_data(char *dp, int sz);
1395   int read_data(char *dp, int sz);
1396   int write_data(char *dp, int sz);
1397   int write_zeros(ioAddr io_addr);
1398   int write_padding(ioAddr io_addr);
1399   int readRootInfo(int(Db::*fn)(char *dp,int sz));
1400   int writeRootInfo(int(Db::*fn)(char *dp,int sz));
1401   ioAddr storeBlocks(ioAddr sz) { return (sz+storeBlockSize-1)/storeBlockSize; }
1402   ioAddr entityPages(ioAddr sz) { return (sz+entityPageSize-1)/entityPageSize; }
1403   int indeciesHunks(int sz) { return (sz+indexTableHunkSize-1)/indexTableHunkSize; }
1404   int pageTableHunks(int sz) { return (sz+pageTableHunkSize-1)/pageTableHunkSize; }
1405   int pagePrefixHunks(int sz) { return (sz+sizeof(pagePrefix)-1)/sizeof(pagePrefix); }
1406   int init_idx();
1407   void init_shm();
1408   void init();
1409   void deinit();
1410   void reset();
1411   int start_transaction(int undo_save=1);
1412   void enter() { db_info->dbRwLk.enter(); }
1413   void leave() { db_info->dbRwLk.leave(); }
1414   void write_enter() { db_info->dbRwLk.write_enter(); }
1415   void write_leave() { db_info->dbRwLk.write_leave(); }
1416
1417 public:
1418   // 1:wr, 0:rd, -1:unlocked
1419   int is_locked() { return db_info->dbRwLk.locked(); }
1420   int is_blocked() { return db_info->dbRwLk.blocked(); }
1421
1422   int make(int zfd);
1423   int open(int zfd, int zkey=-1);
1424   int close();
1425
1426   int attach(int zrw, int zfd, int zkey);
1427   int attach(int zrw=0) { return attach(fd, key, zrw); }
1428   int detach();
1429
1430   int copy(Db *db, Objects objs);
1431   int new_binary_index(const char *nm, int ksz, int dsz, CmprFn cmpr=0);
1432   int new_string_index(const char *nm, int dsz);
1433   int get_index(const char *nm, CmprFn cmpr=0);
1434   long get_count(int r);
1435   int ins   (int r, void *key, void *data);
1436   int del   (int r, void *key);
1437   int find  (int r, void *key, void *rtnData=0);
1438   int locate(int r, int op, void *key, CmprFn cmpr, void *rtnKey, void *rtnData=0);
1439   int locate(int r, int op, void *key, void *rtnKey, void *rtnData=0) {
1440     return locate(r,op,key,0,rtnKey,rtnData);
1441   }
1442   int first (int r, void *key, void *rtnData=0);
1443   int last  (int r, void *key, void *rtnData=0);
1444   int next  (int r, void *key, void *rtnData=0);
1445   int nextloc(int r, pgRef &loc);
1446   int allocate(int typ, int size, pgRef &loc, AllocCache &cache);
1447   int allocate(int typ, int size, pgRef &loc) {
1448     return allocate(typ, size, loc, alloc_cache);
1449   }
1450   int reallocate(int size, pgRef &loc, AllocCache &cache);
1451   int deallocate(pgRef &loc);
1452   int commit(int force=0);
1453   int flush ();
1454   int undo  ();
1455
1456   int transaction() { return !root_info ? -1 : root_info->transaction_id; }
1457   int64_t filesize() { return !root_info ? -1 : root_info->file_size; }
1458   int opened() { return fd>=0 ? 1 : 0; }
1459   void use_shm(int v) { no_shm = v ? 0 : 1; }
1460   int error() { return err_no; }
1461   void error(int v);
1462   void Error(int v,const char *msg);
1463
1464   Db();
1465   ~Db();
1466
1467 #ifdef DEBUG
1468   void dmp();
1469   void fdmp();
1470   void admp(); void achk(); void fchk();
1471   void edmp();
1472   void bdmp();
1473   void stats(int chk=1);
1474 #endif
1475
1476 };
1477
1478 #endif