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