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