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