]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/idl.c
Sync with HEAD
[openldap] / servers / slapd / back-bdb / idl.c
1 /* idl.c - ldap id list handling routines */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2000-2005 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16
17 #include "portable.h"
18
19 #include <stdio.h>
20 #include <ac/string.h>
21
22 #include "back-bdb.h"
23 #include "idl.h"
24
25 #define IDL_MAX(x,y)    ( x > y ? x : y )
26 #define IDL_MIN(x,y)    ( x < y ? x : y )
27
28 #define IDL_CMP(x,y)    ( x < y ? -1 : ( x > y ? 1 : 0 ) )
29
30 #define IDL_LRU_DELETE( bdb, e ) do {                                   \
31         if ( e->idl_lru_prev != NULL ) {                                \
32                 e->idl_lru_prev->idl_lru_next = e->idl_lru_next;        \
33         } else {                                                        \
34                 bdb->bi_idl_lru_head = e->idl_lru_next;                 \
35         }                                                               \
36         if ( e->idl_lru_next != NULL ) {                                \
37                 e->idl_lru_next->idl_lru_prev = e->idl_lru_prev;        \
38         } else {                                                        \
39                 bdb->bi_idl_lru_tail = e->idl_lru_prev;                 \
40         }                                                               \
41 } while ( 0 )
42
43 #define IDL_LRU_ADD( bdb, e ) do {                                      \
44         e->idl_lru_next = bdb->bi_idl_lru_head;                         \
45         if ( e->idl_lru_next != NULL ) {                                \
46                 e->idl_lru_next->idl_lru_prev = (e);                    \
47         }                                                               \
48         (bdb)->bi_idl_lru_head = (e);                                   \
49         e->idl_lru_prev = NULL;                                         \
50         if ( (bdb)->bi_idl_lru_tail == NULL ) {                         \
51                 (bdb)->bi_idl_lru_tail = (e);                           \
52         }                                                               \
53 } while ( 0 )
54
55 static int
56 bdb_idl_entry_cmp( const void *v_idl1, const void *v_idl2 )
57 {
58         const bdb_idl_cache_entry_t *idl1 = v_idl1, *idl2 = v_idl2;
59         int rc;
60
61         if ((rc = SLAP_PTRCMP( idl1->db, idl2->db ))) return rc;
62         if ((rc = idl1->kstr.bv_len - idl2->kstr.bv_len )) return rc;
63         return ( memcmp ( idl1->kstr.bv_val, idl2->kstr.bv_val , idl1->kstr.bv_len ) );
64 }
65
66 #if IDL_DEBUG > 0
67 static void idl_check( ID *ids )
68 {
69         if( BDB_IDL_IS_RANGE( ids ) ) {
70                 assert( BDB_IDL_RANGE_FIRST(ids) <= BDB_IDL_RANGE_LAST(ids) );
71         } else {
72                 ID i;
73                 for( i=1; i < ids[0]; i++ ) {
74                         assert( ids[i+1] > ids[i] );
75                 }
76         }
77 }
78
79 #if IDL_DEBUG > 1
80 static void idl_dump( ID *ids )
81 {
82         if( BDB_IDL_IS_RANGE( ids ) ) {
83                 Debug( LDAP_DEBUG_ANY,
84                         "IDL: range ( %ld - %ld )\n",
85                         (long) BDB_IDL_RANGE_FIRST( ids ),
86                         (long) BDB_IDL_RANGE_LAST( ids ) );
87
88         } else {
89                 ID i;
90                 Debug( LDAP_DEBUG_ANY, "IDL: size %ld", (long) ids[0], 0, 0 );
91
92                 for( i=1; i<=ids[0]; i++ ) {
93                         if( i % 16 == 1 ) {
94                                 Debug( LDAP_DEBUG_ANY, "\n", 0, 0, 0 );
95                         }
96                         Debug( LDAP_DEBUG_ANY, "  %02lx", (long) ids[i], 0, 0 );
97                 }
98
99                 Debug( LDAP_DEBUG_ANY, "\n", 0, 0, 0 );
100         }
101
102         idl_check( ids );
103 }
104 #endif /* IDL_DEBUG > 1 */
105 #endif /* IDL_DEBUG > 0 */
106
107 unsigned bdb_idl_search( ID *ids, ID id )
108 {
109 #define IDL_BINARY_SEARCH 1
110 #ifdef IDL_BINARY_SEARCH
111         /*
112          * binary search of id in ids
113          * if found, returns position of id
114          * if not found, returns first postion greater than id
115          */
116         unsigned base = 0;
117         unsigned cursor = 0;
118         int val = 0;
119         unsigned n = ids[0];
120
121 #if IDL_DEBUG > 0
122         idl_check( ids );
123 #endif
124
125         while( 0 < n ) {
126                 int pivot = n >> 1;
127                 cursor = base + pivot;
128                 val = IDL_CMP( id, ids[cursor + 1] );
129
130                 if( val < 0 ) {
131                         n = pivot;
132
133                 } else if ( val > 0 ) {
134                         base = cursor + 1;
135                         n -= pivot + 1;
136
137                 } else {
138                         return cursor + 1;
139                 }
140         }
141         
142         if( val > 0 ) {
143                 return cursor + 2;
144         } else {
145                 return cursor + 1;
146         }
147
148 #else
149         /* (reverse) linear search */
150         int i;
151
152 #if IDL_DEBUG > 0
153         idl_check( ids );
154 #endif
155
156         for( i=ids[0]; i; i-- ) {
157                 if( id > ids[i] ) {
158                         break;
159                 }
160         }
161
162         return i+1;
163 #endif
164 }
165
166 int bdb_idl_insert( ID *ids, ID id )
167 {
168         unsigned x;
169
170 #if IDL_DEBUG > 1
171         Debug( LDAP_DEBUG_ANY, "insert: %04lx at %d\n", (long) id, x, 0 );
172         idl_dump( ids );
173 #elif IDL_DEBUG > 0
174         idl_check( ids );
175 #endif
176
177         if (BDB_IDL_IS_RANGE( ids )) {
178                 /* if already in range, treat as a dup */
179                 if (id >= BDB_IDL_FIRST(ids) && id <= BDB_IDL_LAST(ids))
180                         return -1;
181                 if (id < BDB_IDL_FIRST(ids))
182                         ids[1] = id;
183                 else if (id > BDB_IDL_LAST(ids))
184                         ids[2] = id;
185                 return 0;
186         }
187
188         x = bdb_idl_search( ids, id );
189         assert( x > 0 );
190
191         if( x < 1 ) {
192                 /* internal error */
193                 return -2;
194         }
195
196         if ( x <= ids[0] && ids[x] == id ) {
197                 /* duplicate */
198                 return -1;
199         }
200
201         if ( ++ids[0] >= BDB_IDL_DB_MAX ) {
202                 if( id < ids[1] ) {
203                         ids[1] = id;
204                         ids[2] = ids[ids[0]-1];
205                 } else if ( ids[ids[0]-1] < id ) {
206                         ids[2] = id;
207                 } else {
208                         ids[2] = ids[ids[0]-1];
209                 }
210                 ids[0] = NOID;
211         
212         } else {
213                 /* insert id */
214                 AC_MEMCPY( &ids[x+1], &ids[x], (ids[0]-x) * sizeof(ID) );
215                 ids[x] = id;
216         }
217
218 #if IDL_DEBUG > 1
219         idl_dump( ids );
220 #elif IDL_DEBUG > 0
221         idl_check( ids );
222 #endif
223
224         return 0;
225 }
226
227 static int bdb_idl_delete( ID *ids, ID id )
228 {
229         unsigned x = bdb_idl_search( ids, id );
230
231 #if IDL_DEBUG > 1
232         Debug( LDAP_DEBUG_ANY, "delete: %04lx at %d\n", (long) id, x, 0 );
233         idl_dump( ids );
234 #elif IDL_DEBUG > 0
235         idl_check( ids );
236 #endif
237
238         assert( x > 0 );
239
240         if( x <= 0 ) {
241                 /* internal error */
242                 return -2;
243         }
244
245         if( x > ids[0] || ids[x] != id ) {
246                 /* not found */
247                 return -1;
248
249         } else if ( --ids[0] == 0 ) {
250                 if( x != 1 ) {
251                         return -3;
252                 }
253
254         } else {
255                 AC_MEMCPY( &ids[x], &ids[x+1], (1+ids[0]-x) * sizeof(ID) );
256         }
257
258 #if IDL_DEBUG > 1
259         idl_dump( ids );
260 #elif IDL_DEBUG > 0
261         idl_check( ids );
262 #endif
263
264         return 0;
265 }
266
267 static char *
268 bdb_show_key(
269         DBT             *key,
270         char            *buf )
271 {
272         if ( key->size == 4 /* LUTIL_HASH_BYTES */ ) {
273                 unsigned char *c = key->data;
274                 sprintf( buf, "[%02x%02x%02x%02x]", c[0], c[1], c[2], c[3] );
275                 return buf;
276         } else {
277                 return key->data;
278         }
279 }
280
281 /* Find a db/key pair in the IDL cache. If ids is non-NULL,
282  * copy the cached IDL into it, otherwise just return the status.
283  */
284 int
285 bdb_idl_cache_get(
286         struct bdb_info *bdb,
287         DB                      *db,
288         DBT                     *key,
289         ID                      *ids )
290 {
291         bdb_idl_cache_entry_t idl_tmp;
292         bdb_idl_cache_entry_t *matched_idl_entry;
293         int rc = LDAP_NO_SUCH_OBJECT;
294
295         DBT2bv( key, &idl_tmp.kstr );
296         idl_tmp.db = db;
297         ldap_pvt_thread_rdwr_rlock( &bdb->bi_idl_tree_rwlock );
298         matched_idl_entry = avl_find( bdb->bi_idl_tree, &idl_tmp,
299                                       bdb_idl_entry_cmp );
300         if ( matched_idl_entry != NULL ) {
301                 if ( matched_idl_entry->idl && ids )
302                         BDB_IDL_CPY( ids, matched_idl_entry->idl );
303                 ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
304                 IDL_LRU_DELETE( bdb, matched_idl_entry );
305                 IDL_LRU_ADD( bdb, matched_idl_entry );
306                 ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
307                 if ( matched_idl_entry->idl )
308                         rc = LDAP_SUCCESS;
309                 else
310                         rc = DB_NOTFOUND;
311         }
312         ldap_pvt_thread_rdwr_runlock( &bdb->bi_idl_tree_rwlock );
313
314         return rc;
315 }
316
317 void
318 bdb_idl_cache_put(
319         struct bdb_info *bdb,
320         DB                      *db,
321         DBT                     *key,
322         ID                      *ids,
323         int                     rc )
324 {
325         bdb_idl_cache_entry_t idl_tmp;
326         bdb_idl_cache_entry_t *ee;
327
328         DBT2bv( key, &idl_tmp.kstr );
329
330         ee = (bdb_idl_cache_entry_t *) ch_malloc(
331                 sizeof( bdb_idl_cache_entry_t ) );
332         ee->db = db;
333         if ( rc == DB_NOTFOUND || BDB_IDL_IS_ZERO( ids )) {
334                 ee->idl = NULL;
335         } else {
336                 ee->idl = (ID*) ch_malloc( BDB_IDL_SIZEOF ( ids ) );
337                 BDB_IDL_CPY( ee->idl, ids );
338         }
339         ee->idl_lru_prev = NULL;
340         ee->idl_lru_next = NULL;
341         ber_dupbv( &ee->kstr, &idl_tmp.kstr );
342         ldap_pvt_thread_rdwr_wlock( &bdb->bi_idl_tree_rwlock );
343         if ( avl_insert( &bdb->bi_idl_tree, (caddr_t) ee,
344                 bdb_idl_entry_cmp, avl_dup_error ))
345         {
346                 ch_free( ee->kstr.bv_val );
347                 ch_free( ee->idl );
348                 ch_free( ee );
349                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_idl_tree_rwlock );
350                 return;
351         }
352         ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
353         IDL_LRU_ADD( bdb, ee );
354         if ( ++bdb->bi_idl_cache_size > bdb->bi_idl_cache_max_size ) {
355                 int i = 0;
356                 while ( bdb->bi_idl_lru_tail != NULL && i < 10 ) {
357                         ee = bdb->bi_idl_lru_tail;
358                         if ( avl_delete( &bdb->bi_idl_tree, (caddr_t) ee,
359                                     bdb_idl_entry_cmp ) == NULL ) {
360                                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_cache_put: "
361                                         "AVL delete failed\n",
362                                         0, 0, 0 );
363                         }
364                         IDL_LRU_DELETE( bdb, ee );
365                         i++;
366                         --bdb->bi_idl_cache_size;
367                         ch_free( ee->kstr.bv_val );
368                         ch_free( ee->idl );
369                         ch_free( ee );
370                 }
371         }
372
373         ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
374         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_idl_tree_rwlock );
375 }
376
377 void
378 bdb_idl_cache_del(
379         struct bdb_info *bdb,
380         DB                      *db,
381         DBT                     *key )
382 {
383         bdb_idl_cache_entry_t *matched_idl_entry, idl_tmp;
384         DBT2bv( key, &idl_tmp.kstr );
385         idl_tmp.db = db;
386         ldap_pvt_thread_rdwr_wlock( &bdb->bi_idl_tree_rwlock );
387         matched_idl_entry = avl_find( bdb->bi_idl_tree, &idl_tmp,
388                                       bdb_idl_entry_cmp );
389         if ( matched_idl_entry != NULL ) {
390                 if ( avl_delete( &bdb->bi_idl_tree, (caddr_t) matched_idl_entry,
391                                     bdb_idl_entry_cmp ) == NULL ) {
392                         Debug( LDAP_DEBUG_ANY, "=> bdb_idl_cache_del: "
393                                 "AVL delete failed\n",
394                                 0, 0, 0 );
395                 }
396                 --bdb->bi_idl_cache_size;
397                 ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
398                 IDL_LRU_DELETE( bdb, matched_idl_entry );
399                 ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
400                 free( matched_idl_entry->kstr.bv_val );
401                 if ( matched_idl_entry->idl )
402                         free( matched_idl_entry->idl );
403                 free( matched_idl_entry );
404         }
405         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_idl_tree_rwlock );
406 }
407
408 void
409 bdb_idl_cache_add_id(
410         struct bdb_info *bdb,
411         DB                      *db,
412         DBT                     *key,
413         ID                      id )
414 {
415         bdb_idl_cache_entry_t *cache_entry, idl_tmp;
416         DBT2bv( key, &idl_tmp.kstr );
417         idl_tmp.db = db;
418         ldap_pvt_thread_rdwr_wlock( &bdb->bi_idl_tree_rwlock );
419         cache_entry = avl_find( bdb->bi_idl_tree, &idl_tmp,
420                                       bdb_idl_entry_cmp );
421         if ( cache_entry != NULL ) {
422                 if ( !BDB_IDL_IS_RANGE( cache_entry->idl ) &&
423                         cache_entry->idl[0] < BDB_IDL_DB_MAX ) {
424                         size_t s = BDB_IDL_SIZEOF( cache_entry->idl ) + sizeof(ID);
425                         cache_entry->idl = ch_realloc( cache_entry->idl, s );
426                 }
427                 bdb_idl_insert( cache_entry->idl, id );
428         }
429         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_idl_tree_rwlock );
430 }
431
432 void
433 bdb_idl_cache_del_id(
434         struct bdb_info *bdb,
435         DB                      *db,
436         DBT                     *key,
437         ID                      id )
438 {
439         bdb_idl_cache_entry_t *cache_entry, idl_tmp;
440         DBT2bv( key, &idl_tmp.kstr );
441         idl_tmp.db = db;
442         ldap_pvt_thread_rdwr_wlock( &bdb->bi_idl_tree_rwlock );
443         cache_entry = avl_find( bdb->bi_idl_tree, &idl_tmp,
444                                       bdb_idl_entry_cmp );
445         if ( cache_entry != NULL ) {
446                 bdb_idl_delete( cache_entry->idl, id );
447                 if ( cache_entry->idl[0] == 0 ) {
448                         if ( avl_delete( &bdb->bi_idl_tree, (caddr_t) cache_entry,
449                                                 bdb_idl_entry_cmp ) == NULL ) {
450                                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_cache_del: "
451                                         "AVL delete failed\n",
452                                         0, 0, 0 );
453                         }
454                         --bdb->bi_idl_cache_size;
455                         ldap_pvt_thread_mutex_lock( &bdb->bi_idl_tree_lrulock );
456                         IDL_LRU_DELETE( bdb, cache_entry );
457                         ldap_pvt_thread_mutex_unlock( &bdb->bi_idl_tree_lrulock );
458                         free( cache_entry->kstr.bv_val );
459                         if ( cache_entry->idl )
460                                 free( cache_entry->idl );
461                         free( cache_entry );
462                 }
463         }
464         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_idl_tree_rwlock );
465 }
466
467 int
468 bdb_idl_fetch_key(
469         BackendDB       *be,
470         DB                      *db,
471         DB_TXN          *tid,
472         DBT                     *key,
473         ID                      *ids,
474         DBC                     **saved_cursor,
475         int                     get_flag )
476 {
477         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
478         int rc;
479         DBT data, key2, *kptr;
480         DBC *cursor;
481         ID *i;
482         void *ptr;
483         size_t len;
484         int rc2;
485         int flags = bdb->bi_db_opflags | DB_MULTIPLE;
486         int opflag;
487
488         /* If using BerkeleyDB 4.0, the buf must be large enough to
489          * grab the entire IDL in one get(), otherwise BDB will leak
490          * resources on subsequent get's.  We can safely call get()
491          * twice - once for the data, and once to get the DB_NOTFOUND
492          * result meaning there's no more data. See ITS#2040 for details.
493          * This bug is fixed in BDB 4.1 so a smaller buffer will work if
494          * stack space is too limited.
495          *
496          * configure now requires Berkeley DB 4.1.
497          */
498 #if DB_VERSION_FULL < 0x04010000
499 #       define BDB_ENOUGH 5
500 #else
501         /* We sometimes test with tiny IDLs, and BDB always wants buffers
502          * that are at least one page in size.
503          */
504 # if BDB_IDL_DB_SIZE < 4096
505 #   define BDB_ENOUGH 2048
506 # else
507 #       define BDB_ENOUGH 1
508 # endif
509 #endif
510         ID buf[BDB_IDL_DB_SIZE*BDB_ENOUGH];
511
512         char keybuf[16];
513
514         Debug( LDAP_DEBUG_ARGS,
515                 "bdb_idl_fetch_key: %s\n", 
516                 bdb_show_key( key, keybuf ), 0, 0 );
517
518         assert( ids != NULL );
519
520         if ( saved_cursor && *saved_cursor ) {
521                 opflag = DB_NEXT;
522         } else if ( get_flag == LDAP_FILTER_GE ) {
523                 opflag = DB_SET_RANGE;
524         } else if ( get_flag == LDAP_FILTER_LE ) {
525                 opflag = DB_FIRST;
526         } else {
527                 opflag = DB_SET;
528         }
529
530         /* only non-range lookups can use the IDL cache */
531         if ( bdb->bi_idl_cache_size && opflag == DB_SET ) {
532                 rc = bdb_idl_cache_get( bdb, db, key, ids );
533                 if ( rc != LDAP_NO_SUCH_OBJECT ) return rc;
534         }
535
536         DBTzero( &data );
537
538         data.data = buf;
539         data.ulen = sizeof(buf);
540         data.flags = DB_DBT_USERMEM;
541
542         /* If we're not reusing an existing cursor, get a new one */
543         if( opflag != DB_NEXT ) {
544                 rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
545                 if( rc != 0 ) {
546                         Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
547                                 "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
548                         return rc;
549                 }
550         } else {
551                 cursor = *saved_cursor;
552         }
553         
554         /* If this is a LE lookup, save original key so we can determine
555          * when to stop. If this is a GE lookup, save the key since it
556          * will be overwritten.
557          */
558         if ( get_flag == LDAP_FILTER_LE || get_flag == LDAP_FILTER_GE ) {
559                 DBTzero( &key2 );
560                 key2.flags = DB_DBT_USERMEM;
561                 key2.ulen = sizeof(keybuf);
562                 key2.data = keybuf;
563                 key2.size = key->size;
564                 AC_MEMCPY( keybuf, key->data, key->size );
565                 kptr = &key2;
566         } else {
567                 kptr = key;
568         }
569         len = key->size;
570         rc = cursor->c_get( cursor, kptr, &data, flags | opflag );
571
572         /* skip presence key on range inequality lookups */
573         while (rc == 0 && kptr->size != len) {
574                 rc = cursor->c_get( cursor, kptr, &data, flags | DB_NEXT_NODUP );
575         }
576         /* If we're doing a LE compare and the new key is greater than
577          * our search key, we're done
578          */
579         if (rc == 0 && get_flag == LDAP_FILTER_LE && memcmp( kptr->data,
580                 key->data, key->size ) > 0 ) {
581                 rc = DB_NOTFOUND;
582         }
583         if (rc == 0) {
584                 i = ids;
585                 while (rc == 0) {
586                         u_int8_t *j;
587
588                         DB_MULTIPLE_INIT( ptr, &data );
589                         while (ptr) {
590                                 DB_MULTIPLE_NEXT(ptr, &data, j, len);
591                                 if (j) {
592                                         ++i;
593                                         BDB_DISK2ID( j, i );
594                                 }
595                         }
596                         rc = cursor->c_get( cursor, key, &data, flags | DB_NEXT_DUP );
597                 }
598                 if ( rc == DB_NOTFOUND ) rc = 0;
599                 ids[0] = i - ids;
600                 /* On disk, a range is denoted by 0 in the first element */
601                 if (ids[1] == 0) {
602                         if (ids[0] != BDB_IDL_RANGE_SIZE) {
603                                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
604                                         "range size mismatch: expected %d, got %ld\n",
605                                         BDB_IDL_RANGE_SIZE, ids[0], 0 );
606                                 cursor->c_close( cursor );
607                                 return -1;
608                         }
609                         BDB_IDL_RANGE( ids, ids[2], ids[3] );
610                 }
611                 data.size = BDB_IDL_SIZEOF(ids);
612         }
613
614         if ( saved_cursor && rc == 0 ) {
615                 if ( !*saved_cursor )
616                         *saved_cursor = cursor;
617                 rc2 = 0;
618         }
619         else
620                 rc2 = cursor->c_close( cursor );
621         if (rc2) {
622                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
623                         "close failed: %s (%d)\n", db_strerror(rc2), rc2, 0 );
624                 return rc2;
625         }
626
627         if( rc == DB_NOTFOUND ) {
628                 return rc;
629
630         } else if( rc != 0 ) {
631                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
632                         "get failed: %s (%d)\n",
633                         db_strerror(rc), rc, 0 );
634                 return rc;
635
636         } else if ( data.size == 0 || data.size % sizeof( ID ) ) {
637                 /* size not multiple of ID size */
638                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
639                         "odd size: expected %ld multiple, got %ld\n",
640                         (long) sizeof( ID ), (long) data.size, 0 );
641                 return -1;
642
643         } else if ( data.size != BDB_IDL_SIZEOF(ids) ) {
644                 /* size mismatch */
645                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
646                         "get size mismatch: expected %ld, got %ld\n",
647                         (long) ((1 + ids[0]) * sizeof( ID )), (long) data.size, 0 );
648                 return -1;
649         }
650
651         if ( bdb->bi_idl_cache_max_size ) {
652                 bdb_idl_cache_put( bdb, db, key, ids, rc );
653         }
654
655         return rc;
656 }
657
658
659 int
660 bdb_idl_insert_key(
661         BackendDB       *be,
662         DB                      *db,
663         DB_TXN          *tid,
664         DBT                     *key,
665         ID                      id )
666 {
667         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
668         int     rc;
669         DBT data;
670         DBC *cursor;
671         ID lo, hi, nlo, nhi, nid;
672         char *err;
673
674         {
675                 char buf[16];
676                 Debug( LDAP_DEBUG_ARGS,
677                         "bdb_idl_insert_key: %lx %s\n", 
678                         (long) id, bdb_show_key( key, buf ), 0 );
679         }
680
681         assert( id != NOID );
682
683         if ( bdb->bi_idl_cache_size ) {
684                 bdb_idl_cache_del( bdb, db, key );
685         }
686
687         DBTzero( &data );
688         data.size = sizeof( ID );
689         data.ulen = data.size;
690         data.flags = DB_DBT_USERMEM;
691
692         BDB_ID2DISK( id, &nid );
693
694         rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
695         if ( rc != 0 ) {
696                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
697                         "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
698                 return rc;
699         }
700         data.data = &nlo;
701         /* Fetch the first data item for this key, to see if it
702          * exists and if it's a range.
703          */
704         rc = cursor->c_get( cursor, key, &data, DB_SET );
705         err = "c_get";
706         if ( rc == 0 ) {
707                 if ( nlo != 0 ) {
708                         /* not a range, count the number of items */
709                         db_recno_t count;
710                         rc = cursor->c_count( cursor, &count, 0 );
711                         if ( rc != 0 ) {
712                                 err = "c_count";
713                                 goto fail;
714                         }
715                         if ( count >= BDB_IDL_DB_MAX ) {
716                         /* No room, convert to a range */
717                                 DBT key2 = *key;
718                                 db_recno_t i;
719
720                                 key2.dlen = key2.ulen;
721                                 key2.flags |= DB_DBT_PARTIAL;
722
723                                 BDB_DISK2ID( &nlo, &lo );
724                                 data.data = &nhi;
725
726                                 rc = cursor->c_get( cursor, &key2, &data, DB_NEXT_NODUP );
727                                 if ( rc != 0 && rc != DB_NOTFOUND ) {
728                                         err = "c_get next_nodup";
729                                         goto fail;
730                                 }
731                                 if ( rc == DB_NOTFOUND ) {
732                                         rc = cursor->c_get( cursor, key, &data, DB_LAST );
733                                         if ( rc != 0 ) {
734                                                 err = "c_get last";
735                                                 goto fail;
736                                         }
737                                 } else {
738                                         rc = cursor->c_get( cursor, key, &data, DB_PREV );
739                                         if ( rc != 0 ) {
740                                                 err = "c_get prev";
741                                                 goto fail;
742                                         }
743                                 }
744                                 BDB_DISK2ID( &nhi, &hi );
745                                 /* Update hi/lo if needed, then delete all the items
746                                  * between lo and hi
747                                  */
748                                 if ( id < lo ) {
749                                         lo = id;
750                                         nlo = nid;
751                                 } else if ( id > hi ) {
752                                         hi = id;
753                                         nhi = nid;
754                                 }
755                                 data.data = &nid;
756                                 /* Don't fetch anything, just position cursor */
757                                 data.flags = DB_DBT_USERMEM | DB_DBT_PARTIAL;
758                                 data.dlen = data.ulen = 0;
759                                 rc = cursor->c_get( cursor, key, &data, DB_SET );
760                                 if ( rc != 0 ) {
761                                         err = "c_get 2";
762                                         goto fail;
763                                 }
764                                 rc = cursor->c_del( cursor, 0 );
765                                 if ( rc != 0 ) {
766                                         err = "c_del range1";
767                                         goto fail;
768                                 }
769                                 /* Delete all the records */
770                                 for ( i=1; i<count; i++ ) {
771                                         rc = cursor->c_get( cursor, &key2, &data, DB_NEXT_DUP );
772                                         if ( rc != 0 ) {
773                                                 err = "c_get next_dup";
774                                                 goto fail;
775                                         }
776                                         rc = cursor->c_del( cursor, 0 );
777                                         if ( rc != 0 ) {
778                                                 err = "c_del range";
779                                                 goto fail;
780                                         }
781                                 }
782                                 /* Store the range marker */
783                                 data.size = data.ulen = sizeof(ID);
784                                 data.flags = DB_DBT_USERMEM;
785                                 nid = 0;
786                                 rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
787                                 if ( rc != 0 ) {
788                                         err = "c_put range";
789                                         goto fail;
790                                 }
791                                 nid = nlo;
792                                 rc = cursor->c_put( cursor, key, &data, DB_KEYLAST );
793                                 if ( rc != 0 ) {
794                                         err = "c_put lo";
795                                         goto fail;
796                                 }
797                                 nid = nhi;
798                                 rc = cursor->c_put( cursor, key, &data, DB_KEYLAST );
799                                 if ( rc != 0 ) {
800                                         err = "c_put hi";
801                                         goto fail;
802                                 }
803                         } else {
804                         /* There's room, just store it */
805                                 goto put1;
806                         }
807                 } else {
808                         /* It's a range, see if we need to rewrite
809                          * the boundaries
810                          */
811                         hi = id;
812                         data.data = &nlo;
813                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
814                         if ( rc != 0 ) {
815                                 err = "c_get lo";
816                                 goto fail;
817                         }
818                         BDB_DISK2ID( &nlo, &lo );
819                         if ( id > lo ) {
820                                 data.data = &nhi;
821                                 rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
822                                 if ( rc != 0 ) {
823                                         err = "c_get hi";
824                                         goto fail;
825                                 }
826                                 BDB_DISK2ID( &nhi, &hi );
827                         }
828                         if ( id < lo || id > hi ) {
829                                 /* Delete the current lo/hi */
830                                 rc = cursor->c_del( cursor, 0 );
831                                 if ( rc != 0 ) {
832                                         err = "c_del";
833                                         goto fail;
834                                 }
835                                 data.data = &nid;
836                                 rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
837                                 if ( rc != 0 ) {
838                                         err = "c_put lo/hi";
839                                         goto fail;
840                                 }
841                         }
842                 }
843         } else if ( rc == DB_NOTFOUND ) {
844 put1:           data.data = &nid;
845                 rc = cursor->c_put( cursor, key, &data, DB_NODUPDATA );
846                 /* Don't worry if it's already there */
847                 if ( rc != 0 && rc != DB_KEYEXIST ) {
848                         err = "c_put id";
849                         goto fail;
850                 }
851         } else {
852                 /* initial c_get failed, nothing was done */
853 fail:
854                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
855                         "%s failed: %s (%d)\n", err, db_strerror(rc), rc );
856                 cursor->c_close( cursor );
857                 return rc;
858         }
859         rc = cursor->c_close( cursor );
860         if( rc != 0 ) {
861                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
862                         "c_close failed: %s (%d)\n",
863                         db_strerror(rc), rc, 0 );
864         }
865         return rc;
866 }
867
868 int
869 bdb_idl_delete_key(
870         BackendDB       *be,
871         DB                      *db,
872         DB_TXN          *tid,
873         DBT                     *key,
874         ID                      id )
875 {
876         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
877         int     rc;
878         DBT data;
879         DBC *cursor;
880         ID lo, hi, tmp, nid, nlo, nhi;
881         char *err;
882
883         {
884                 char buf[16];
885                 Debug( LDAP_DEBUG_ARGS,
886                         "bdb_idl_delete_key: %lx %s\n", 
887                         (long) id, bdb_show_key( key, buf ), 0 );
888         }
889         assert( id != NOID );
890
891         if ( bdb->bi_idl_cache_max_size ) {
892                 bdb_idl_cache_del( bdb, db, key );
893         }
894
895         BDB_ID2DISK( id, &nid );
896
897         DBTzero( &data );
898         data.data = &tmp;
899         data.size = sizeof( id );
900         data.ulen = data.size;
901         data.flags = DB_DBT_USERMEM;
902
903         rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
904         if ( rc != 0 ) {
905                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_delete_key: "
906                         "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
907                 return rc;
908         }
909         /* Fetch the first data item for this key, to see if it
910          * exists and if it's a range.
911          */
912         rc = cursor->c_get( cursor, key, &data, DB_SET );
913         err = "c_get";
914         if ( rc == 0 ) {
915                 if ( tmp != 0 ) {
916                         /* Not a range, just delete it */
917                         if (tmp != nid) {
918                                 /* position to correct item */
919                                 tmp = nid;
920                                 rc = cursor->c_get( cursor, key, &data, DB_GET_BOTH );
921                                 if ( rc != 0 ) {
922                                         err = "c_get id";
923                                         goto fail;
924                                 }
925                         }
926                         rc = cursor->c_del( cursor, 0 );
927                         if ( rc != 0 ) {
928                                 err = "c_del id";
929                                 goto fail;
930                         }
931                 } else {
932                         /* It's a range, see if we need to rewrite
933                          * the boundaries
934                          */
935                         data.data = &nlo;
936                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
937                         if ( rc != 0 ) {
938                                 err = "c_get lo";
939                                 goto fail;
940                         }
941                         BDB_DISK2ID( &nlo, &lo );
942                         data.data = &nhi;
943                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
944                         if ( rc != 0 ) {
945                                 err = "c_get hi";
946                                 goto fail;
947                         }
948                         BDB_DISK2ID( &nhi, &hi );
949                         if ( id == lo || id == hi ) {
950                                 if ( id == lo ) {
951                                         id++;
952                                         lo = id;
953                                 } else if ( id == hi ) {
954                                         id--;
955                                         hi = id;
956                                 }
957                                 if ( lo >= hi ) {
958                                 /* The range has collapsed... */
959                                         rc = db->del( db, tid, key, 0 );
960                                         if ( rc != 0 ) {
961                                                 err = "del";
962                                                 goto fail;
963                                         }
964                                 } else {
965                                         if ( id == lo ) {
966                                                 /* reposition on lo slot */
967                                                 data.data = &nlo;
968                                                 cursor->c_get( cursor, key, &data, DB_PREV );
969                                         }
970                                         rc = cursor->c_del( cursor, 0 );
971                                         if ( rc != 0 ) {
972                                                 err = "c_del";
973                                                 goto fail;
974                                         }
975                                 }
976                                 if ( lo <= hi ) {
977                                         BDB_ID2DISK( id, &nid );
978                                         data.data = &nid;
979                                         rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
980                                         if ( rc != 0 ) {
981                                                 err = "c_put lo/hi";
982                                                 goto fail;
983                                         }
984                                 }
985                         }
986                 }
987         } else {
988                 /* initial c_get failed, nothing was done */
989 fail:
990                 if ( rc != DB_NOTFOUND ) {
991                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_delete_key: "
992                         "%s failed: %s (%d)\n", err, db_strerror(rc), rc );
993                 }
994                 cursor->c_close( cursor );
995                 return rc;
996         }
997         rc = cursor->c_close( cursor );
998         if( rc != 0 ) {
999                 Debug( LDAP_DEBUG_ANY,
1000                         "=> bdb_idl_delete_key: c_close failed: %s (%d)\n",
1001                         db_strerror(rc), rc, 0 );
1002         }
1003
1004         return rc;
1005 }
1006
1007
1008 /*
1009  * idl_intersection - return a = a intersection b
1010  */
1011 int
1012 bdb_idl_intersection(
1013         ID *a,
1014         ID *b )
1015 {
1016         ID ida, idb;
1017         ID idmax, idmin;
1018         ID cursora = 0, cursorb = 0, cursorc;
1019         int swap = 0;
1020
1021         if ( BDB_IDL_IS_ZERO( a ) || BDB_IDL_IS_ZERO( b ) ) {
1022                 a[0] = 0;
1023                 return 0;
1024         }
1025
1026         idmin = IDL_MAX( BDB_IDL_FIRST(a), BDB_IDL_FIRST(b) );
1027         idmax = IDL_MIN( BDB_IDL_LAST(a), BDB_IDL_LAST(b) );
1028         if ( idmin > idmax ) {
1029                 a[0] = 0;
1030                 return 0;
1031         } else if ( idmin == idmax ) {
1032                 a[0] = 1;
1033                 a[1] = idmin;
1034                 return 0;
1035         }
1036
1037         if ( BDB_IDL_IS_RANGE( a ) ) {
1038                 if ( BDB_IDL_IS_RANGE(b) ) {
1039                 /* If both are ranges, just shrink the boundaries */
1040                         a[1] = idmin;
1041                         a[2] = idmax;
1042                         return 0;
1043                 } else {
1044                 /* Else swap so that b is the range, a is a list */
1045                         ID *tmp = a;
1046                         a = b;
1047                         b = tmp;
1048                         swap = 1;
1049                 }
1050         }
1051
1052         /* If a range completely covers the list, the result is
1053          * just the list. If idmin to idmax is contiguous, just
1054          * turn it into a range.
1055          */
1056         if ( BDB_IDL_IS_RANGE( b )
1057                 && BDB_IDL_FIRST( b ) <= BDB_IDL_FIRST( a )
1058                 && BDB_IDL_LAST( b ) >= BDB_IDL_LAST( a ) ) {
1059                 if (idmax - idmin + 1 == a[0])
1060                 {
1061                         a[0] = NOID;
1062                         a[1] = idmin;
1063                         a[2] = idmax;
1064                 }
1065                 goto done;
1066         }
1067
1068         /* Fine, do the intersection one element at a time.
1069          * First advance to idmin in both IDLs.
1070          */
1071         cursora = cursorb = idmin;
1072         ida = bdb_idl_first( a, &cursora );
1073         idb = bdb_idl_first( b, &cursorb );
1074         cursorc = 0;
1075
1076         while( ida <= idmax || idb <= idmax ) {
1077                 if( ida == idb ) {
1078                         a[++cursorc] = ida;
1079                         ida = bdb_idl_next( a, &cursora );
1080                         idb = bdb_idl_next( b, &cursorb );
1081                 } else if ( ida < idb ) {
1082                         ida = bdb_idl_next( a, &cursora );
1083                 } else {
1084                         idb = bdb_idl_next( b, &cursorb );
1085                 }
1086         }
1087         a[0] = cursorc;
1088 done:
1089         if (swap)
1090                 BDB_IDL_CPY( b, a );
1091
1092         return 0;
1093 }
1094
1095
1096 /*
1097  * idl_union - return a = a union b
1098  */
1099 int
1100 bdb_idl_union(
1101         ID      *a,
1102         ID      *b )
1103 {
1104         ID ida, idb;
1105         ID cursora = 0, cursorb = 0, cursorc;
1106
1107         if ( BDB_IDL_IS_ZERO( b ) ) {
1108                 return 0;
1109         }
1110
1111         if ( BDB_IDL_IS_ZERO( a ) ) {
1112                 BDB_IDL_CPY( a, b );
1113                 return 0;
1114         }
1115
1116         if ( BDB_IDL_IS_RANGE( a ) || BDB_IDL_IS_RANGE(b) ) {
1117 over:           ida = IDL_MIN( BDB_IDL_FIRST(a), BDB_IDL_FIRST(b) );
1118                 idb = IDL_MAX( BDB_IDL_LAST(a), BDB_IDL_LAST(b) );
1119                 a[0] = NOID;
1120                 a[1] = ida;
1121                 a[2] = idb;
1122                 return 0;
1123         }
1124
1125         ida = bdb_idl_first( a, &cursora );
1126         idb = bdb_idl_first( b, &cursorb );
1127
1128         cursorc = b[0];
1129
1130         /* The distinct elements of a are cat'd to b */
1131         while( ida != NOID || idb != NOID ) {
1132                 if ( ida < idb ) {
1133                         if( ++cursorc > BDB_IDL_UM_MAX ) {
1134                                 goto over;
1135                         }
1136                         b[cursorc] = ida;
1137                         ida = bdb_idl_next( a, &cursora );
1138
1139                 } else {
1140                         if ( ida == idb )
1141                                 ida = bdb_idl_next( a, &cursora );
1142                         idb = bdb_idl_next( b, &cursorb );
1143                 }
1144         }
1145
1146         /* b is copied back to a in sorted order */
1147         a[0] = cursorc;
1148         cursora = 1;
1149         cursorb = 1;
1150         cursorc = b[0]+1;
1151         while (cursorb <= b[0] || cursorc <= a[0]) {
1152                 if (cursorc > a[0])
1153                         idb = NOID;
1154                 else
1155                         idb = b[cursorc];
1156                 if (cursorb <= b[0] && b[cursorb] < idb)
1157                         a[cursora++] = b[cursorb++];
1158                 else {
1159                         a[cursora++] = idb;
1160                         cursorc++;
1161                 }
1162         }
1163
1164         return 0;
1165 }
1166
1167
1168 #if 0
1169 /*
1170  * bdb_idl_notin - return a intersection ~b (or a minus b)
1171  */
1172 int
1173 bdb_idl_notin(
1174         ID      *a,
1175         ID      *b,
1176         ID *ids )
1177 {
1178         ID ida, idb;
1179         ID cursora = 0, cursorb = 0;
1180
1181         if( BDB_IDL_IS_ZERO( a ) ||
1182                 BDB_IDL_IS_ZERO( b ) ||
1183                 BDB_IDL_IS_RANGE( b ) )
1184         {
1185                 BDB_IDL_CPY( ids, a );
1186                 return 0;
1187         }
1188
1189         if( BDB_IDL_IS_RANGE( a ) ) {
1190                 BDB_IDL_CPY( ids, a );
1191                 return 0;
1192         }
1193
1194         ida = bdb_idl_first( a, &cursora ),
1195         idb = bdb_idl_first( b, &cursorb );
1196
1197         ids[0] = 0;
1198
1199         while( ida != NOID ) {
1200                 if ( idb == NOID ) {
1201                         /* we could shortcut this */
1202                         ids[++ids[0]] = ida;
1203                         ida = bdb_idl_next( a, &cursora );
1204
1205                 } else if ( ida < idb ) {
1206                         ids[++ids[0]] = ida;
1207                         ida = bdb_idl_next( a, &cursora );
1208
1209                 } else if ( ida > idb ) {
1210                         idb = bdb_idl_next( b, &cursorb );
1211
1212                 } else {
1213                         ida = bdb_idl_next( a, &cursora );
1214                         idb = bdb_idl_next( b, &cursorb );
1215                 }
1216         }
1217
1218         return 0;
1219 }
1220 #endif
1221
1222 ID bdb_idl_first( ID *ids, ID *cursor )
1223 {
1224         ID pos;
1225
1226         if ( ids[0] == 0 ) {
1227                 *cursor = NOID;
1228                 return NOID;
1229         }
1230
1231         if ( BDB_IDL_IS_RANGE( ids ) ) {
1232                 if( *cursor < ids[1] ) {
1233                         *cursor = ids[1];
1234                 }
1235                 return *cursor;
1236         }
1237
1238         if ( *cursor == 0 )
1239                 pos = 1;
1240         else
1241                 pos = bdb_idl_search( ids, *cursor );
1242
1243         if( pos > ids[0] ) {
1244                 return NOID;
1245         }
1246
1247         *cursor = pos;
1248         return ids[pos];
1249 }
1250
1251 ID bdb_idl_next( ID *ids, ID *cursor )
1252 {
1253         if ( BDB_IDL_IS_RANGE( ids ) ) {
1254                 if( ids[2] < ++(*cursor) ) {
1255                         return NOID;
1256                 }
1257                 return *cursor;
1258         }
1259
1260         if ( ++(*cursor) <= ids[0] ) {
1261                 return ids[*cursor];
1262         }
1263
1264         return NOID;
1265 }
1266
1267 #ifdef BDB_HIER
1268
1269 /* Add one ID to an unsorted list. We ensure that the first element is the
1270  * minimum and the last element is the maximum, for fast range compaction.
1271  *   this means IDLs up to length 3 are always sorted...
1272  */
1273 int bdb_idl_append_one( ID *ids, ID id )
1274 {
1275         if (BDB_IDL_IS_RANGE( ids )) {
1276                 /* if already in range, treat as a dup */
1277                 if (id >= BDB_IDL_FIRST(ids) && id <= BDB_IDL_LAST(ids))
1278                         return -1;
1279                 if (id < BDB_IDL_FIRST(ids))
1280                         ids[1] = id;
1281                 else if (id > BDB_IDL_LAST(ids))
1282                         ids[2] = id;
1283                 return 0;
1284         }
1285         if ( ids[0] ) {
1286                 ID tmp;
1287
1288                 if (id < ids[1]) {
1289                         tmp = ids[1];
1290                         ids[1] = id;
1291                         id = tmp;
1292                 }
1293                 if ( ids[0] > 1 && id < ids[ids[0]] ) {
1294                         tmp = ids[ids[0]];
1295                         ids[ids[0]] = id;
1296                         id = tmp;
1297                 }
1298         }
1299         ids[0]++;
1300         if ( ids[0] >= BDB_IDL_UM_MAX ) {
1301                 ids[0] = NOID;
1302                 ids[2] = id;
1303         } else {
1304                 ids[ids[0]] = id;
1305         }
1306         return 0;
1307 }
1308
1309 /* Append sorted list b to sorted list a. The result is unsorted but
1310  * a[1] is the min of the result and a[a[0]] is the max.
1311  */
1312 int bdb_idl_append( ID *a, ID *b )
1313 {
1314         ID ida, idb, tmp;
1315
1316         if ( BDB_IDL_IS_ZERO( b ) ) {
1317                 return 0;
1318         }
1319
1320         if ( BDB_IDL_IS_ZERO( a ) ) {
1321                 BDB_IDL_CPY( a, b );
1322                 return 0;
1323         }
1324
1325         ida = BDB_IDL_LAST( a );
1326         idb = BDB_IDL_LAST( b );
1327         if ( BDB_IDL_IS_RANGE( a ) || BDB_IDL_IS_RANGE(b) ||
1328                 a[0] + b[0] >= BDB_IDL_UM_MAX ) {
1329                 a[2] = IDL_MAX( ida, idb );
1330                 a[1] = IDL_MIN( a[1], b[1] );
1331                 a[0] = NOID;
1332                 return 0;
1333         }
1334
1335         if ( b[0] > 1 && ida > idb ) {
1336                 a[a[0]] = idb;
1337                 b[b[0]] = ida;
1338         }
1339
1340         if ( b[1] < a[1] ) {
1341                 tmp = a[1];
1342                 a[1] = b[1];
1343         } else {
1344                 tmp = b[1];
1345         }
1346         a[0]++;
1347         a[a[0]] = tmp;
1348
1349         if ( b[0] > 1 ) {
1350                 int i = b[0] - 1;
1351                 AC_MEMCPY(a+a[0]+1, b+2, i * sizeof(ID));
1352                 a[0] += i;
1353         }
1354         return 0;
1355 }
1356
1357 #if 0
1358
1359 /* Quicksort + Insertion sort for small arrays */
1360
1361 #define SMALL   8
1362 #define SWAP(a,b)       itmp=(a);(a)=(b);(b)=itmp
1363
1364 void
1365 bdb_idl_sort( ID *ids, ID *tmp )
1366 {
1367         int *istack = (int *)tmp;
1368         int i,j,k,l,ir,jstack;
1369         ID a, itmp;
1370
1371         if ( BDB_IDL_IS_RANGE( ids ))
1372                 return;
1373
1374         ir = ids[0];
1375         l = 1;
1376         jstack = 0;
1377         for(;;) {
1378                 if (ir - l < SMALL) {   /* Insertion sort */
1379                         for (j=l+1;j<=ir;j++) {
1380                                 a = ids[j];
1381                                 for (i=j-1;i>=1;i--) {
1382                                         if (ids[i] <= a) break;
1383                                         ids[i+1] = ids[i];
1384                                 }
1385                                 ids[i+1] = a;
1386                         }
1387                         if (jstack == 0) break;
1388                         ir = istack[jstack--];
1389                         l = istack[jstack--];
1390                 } else {
1391                         k = (l + ir) >> 1;      /* Choose median of left, center, right */
1392                         SWAP(ids[k], ids[l+1]);
1393                         if (ids[l] > ids[ir]) {
1394                                 SWAP(ids[l], ids[ir]);
1395                         }
1396                         if (ids[l+1] > ids[ir]) {
1397                                 SWAP(ids[l+1], ids[ir]);
1398                         }
1399                         if (ids[l] > ids[l+1]) {
1400                                 SWAP(ids[l], ids[l+1]);
1401                         }
1402                         i = l+1;
1403                         j = ir;
1404                         a = ids[l+1];
1405                         for(;;) {
1406                                 do i++; while(ids[i] < a);
1407                                 do j--; while(ids[j] > a);
1408                                 if (j < i) break;
1409                                 SWAP(ids[i],ids[j]);
1410                         }
1411                         ids[l+1] = ids[j];
1412                         ids[j] = a;
1413                         jstack += 2;
1414                         if (ir-i+1 >= j-1) {
1415                                 istack[jstack] = ir;
1416                                 istack[jstack-1] = i;
1417                                 ir = j-1;
1418                         } else {
1419                                 istack[jstack] = j-1;
1420                                 istack[jstack-1] = l;
1421                                 l = i;
1422                         }
1423                 }
1424         }
1425 }
1426
1427 #else
1428
1429 /* 8 bit Radix sort + insertion sort
1430  * 
1431  * based on code from http://www.cubic.org/docs/radix.htm
1432  * with improvements by mbackes@symas.com and hyc@symas.com
1433  *
1434  * This code is O(n) but has a relatively high constant factor. For lists
1435  * up to ~50 Quicksort is slightly faster; up to ~100 they are even.
1436  * Much faster than quicksort for lists longer than ~100. Insertion
1437  * sort is actually superior for lists <50.
1438  */
1439
1440 #define BUCKETS (1<<8)
1441 #define SMALL   50
1442
1443 void
1444 bdb_idl_sort( ID *ids, ID *tmp )
1445 {
1446         int count, soft_limit, phase = 0, size = ids[0];
1447         ID *idls[2];
1448         unsigned char *maxv = (unsigned char *)&ids[size];
1449
1450         if ( BDB_IDL_IS_RANGE( ids ))
1451                 return;
1452
1453         /* Use insertion sort for small lists */
1454         if ( size <= SMALL ) {
1455                 int i,j;
1456                 ID a;
1457
1458                 for (j=1;j<=size;j++) {
1459                         a = ids[j];
1460                         for (i=j-1;i>=1;i--) {
1461                                 if (ids[i] <= a) break;
1462                                 ids[i+1] = ids[i];
1463                         }
1464                         ids[i+1] = a;
1465                 }
1466                 return;
1467         }
1468
1469         tmp[0] = size;
1470         idls[0] = ids;
1471         idls[1] = tmp;
1472
1473 #if BYTE_ORDER == BIG_ENDIAN
1474     for (soft_limit = 0; !maxv[soft_limit]; soft_limit++);
1475 #else
1476     for (soft_limit = sizeof(ID)-1; !maxv[soft_limit]; soft_limit--);
1477 #endif
1478
1479         for (
1480 #if BYTE_ORDER == BIG_ENDIAN
1481         count = sizeof(ID)-1; count >= soft_limit; --count
1482 #else
1483         count = 0; count <= soft_limit; ++count
1484 #endif
1485         ) {
1486                 unsigned int num[BUCKETS], * np, n, sum;
1487                 int i;
1488         ID *sp, *source, *dest;
1489         unsigned char *bp, *source_start;
1490
1491                 source = idls[phase]+1;
1492                 dest = idls[phase^1]+1;
1493                 source_start =  ((unsigned char *) source) + count;
1494
1495         np = num;
1496         for ( i = BUCKETS; i > 0; --i ) *np++ = 0;
1497
1498                 /* count occurences of every byte value */
1499                 bp = source_start;
1500         for ( i = size; i > 0; --i, bp += sizeof(ID) )
1501                                 num[*bp]++;
1502
1503                 /* transform count into index by summing elements and storing
1504                  * into same array
1505                  */
1506         sum = 0;
1507         np = num;
1508         for ( i = BUCKETS; i > 0; --i ) {
1509                 n = *np;
1510                 *np++ = sum;
1511                 sum += n;
1512         }
1513
1514                 /* fill dest with the right values in the right place */
1515                 bp = source_start;
1516         sp = source;
1517         for ( i = size; i > 0; --i, bp += sizeof(ID) ) {
1518                 np = num + *bp;
1519                 dest[*np] = *sp++;
1520                 ++(*np);
1521         }
1522                 phase ^= 1;
1523         }
1524
1525         /* copy back from temp if needed */
1526         if ( phase ) {
1527                 ids++; tmp++;
1528                 for ( count = 0; count < size; ++count ) 
1529                         *ids++ = *tmp++;
1530         }
1531 }
1532 #endif  /* Quick vs Radix */
1533
1534 #endif  /* BDB_HIER */