]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/idl.c
ITS#5086
[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         DBTzero( &data );
700         data.size = sizeof( ID );
701         data.ulen = data.size;
702         data.flags = DB_DBT_USERMEM;
703
704         BDB_ID2DISK( id, &nid );
705
706         rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
707         if ( rc != 0 ) {
708                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
709                         "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
710                 return rc;
711         }
712         data.data = &nlo;
713         /* Fetch the first data item for this key, to see if it
714          * exists and if it's a range.
715          */
716         rc = cursor->c_get( cursor, key, &data, DB_SET );
717         err = "c_get";
718         if ( rc == 0 ) {
719                 if ( nlo != 0 ) {
720                         /* not a range, count the number of items */
721                         db_recno_t count;
722                         rc = cursor->c_count( cursor, &count, 0 );
723                         if ( rc != 0 ) {
724                                 err = "c_count";
725                                 goto fail;
726                         }
727                         if ( count >= BDB_IDL_DB_MAX ) {
728                         /* No room, convert to a range */
729                                 DBT key2 = *key;
730                                 db_recno_t i;
731
732                                 key2.dlen = key2.ulen;
733                                 key2.flags |= DB_DBT_PARTIAL;
734
735                                 BDB_DISK2ID( &nlo, &lo );
736                                 data.data = &nhi;
737
738                                 rc = cursor->c_get( cursor, &key2, &data, DB_NEXT_NODUP );
739                                 if ( rc != 0 && rc != DB_NOTFOUND ) {
740                                         err = "c_get next_nodup";
741                                         goto fail;
742                                 }
743                                 if ( rc == DB_NOTFOUND ) {
744                                         rc = cursor->c_get( cursor, key, &data, DB_LAST );
745                                         if ( rc != 0 ) {
746                                                 err = "c_get last";
747                                                 goto fail;
748                                         }
749                                 } else {
750                                         rc = cursor->c_get( cursor, key, &data, DB_PREV );
751                                         if ( rc != 0 ) {
752                                                 err = "c_get prev";
753                                                 goto fail;
754                                         }
755                                 }
756                                 BDB_DISK2ID( &nhi, &hi );
757                                 /* Update hi/lo if needed, then delete all the items
758                                  * between lo and hi
759                                  */
760                                 if ( id < lo ) {
761                                         lo = id;
762                                         nlo = nid;
763                                 } else if ( id > hi ) {
764                                         hi = id;
765                                         nhi = nid;
766                                 }
767                                 data.data = &nid;
768                                 /* Don't fetch anything, just position cursor */
769                                 data.flags = DB_DBT_USERMEM | DB_DBT_PARTIAL;
770                                 data.dlen = data.ulen = 0;
771                                 rc = cursor->c_get( cursor, key, &data, DB_SET );
772                                 if ( rc != 0 ) {
773                                         err = "c_get 2";
774                                         goto fail;
775                                 }
776                                 rc = cursor->c_del( cursor, 0 );
777                                 if ( rc != 0 ) {
778                                         err = "c_del range1";
779                                         goto fail;
780                                 }
781                                 /* Delete all the records */
782                                 for ( i=1; i<count; i++ ) {
783                                         rc = cursor->c_get( cursor, &key2, &data, DB_NEXT_DUP );
784                                         if ( rc != 0 ) {
785                                                 err = "c_get next_dup";
786                                                 goto fail;
787                                         }
788                                         rc = cursor->c_del( cursor, 0 );
789                                         if ( rc != 0 ) {
790                                                 err = "c_del range";
791                                                 goto fail;
792                                         }
793                                 }
794                                 /* Store the range marker */
795                                 data.size = data.ulen = sizeof(ID);
796                                 data.flags = DB_DBT_USERMEM;
797                                 nid = 0;
798                                 rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
799                                 if ( rc != 0 ) {
800                                         err = "c_put range";
801                                         goto fail;
802                                 }
803                                 nid = nlo;
804                                 rc = cursor->c_put( cursor, key, &data, DB_KEYLAST );
805                                 if ( rc != 0 ) {
806                                         err = "c_put lo";
807                                         goto fail;
808                                 }
809                                 nid = nhi;
810                                 rc = cursor->c_put( cursor, key, &data, DB_KEYLAST );
811                                 if ( rc != 0 ) {
812                                         err = "c_put hi";
813                                         goto fail;
814                                 }
815                         } else {
816                         /* There's room, just store it */
817                                 goto put1;
818                         }
819                 } else {
820                         /* It's a range, see if we need to rewrite
821                          * the boundaries
822                          */
823                         hi = id;
824                         data.data = &nlo;
825                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
826                         if ( rc != 0 ) {
827                                 err = "c_get lo";
828                                 goto fail;
829                         }
830                         BDB_DISK2ID( &nlo, &lo );
831                         if ( id > lo ) {
832                                 data.data = &nhi;
833                                 rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
834                                 if ( rc != 0 ) {
835                                         err = "c_get hi";
836                                         goto fail;
837                                 }
838                                 BDB_DISK2ID( &nhi, &hi );
839                         }
840                         if ( id < lo || id > hi ) {
841                                 /* Delete the current lo/hi */
842                                 rc = cursor->c_del( cursor, 0 );
843                                 if ( rc != 0 ) {
844                                         err = "c_del";
845                                         goto fail;
846                                 }
847                                 data.data = &nid;
848                                 rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
849                                 if ( rc != 0 ) {
850                                         err = "c_put lo/hi";
851                                         goto fail;
852                                 }
853                         }
854                 }
855         } else if ( rc == DB_NOTFOUND ) {
856 put1:           data.data = &nid;
857                 rc = cursor->c_put( cursor, key, &data, DB_NODUPDATA );
858                 /* Don't worry if it's already there */
859                 if ( rc != 0 && rc != DB_KEYEXIST ) {
860                         err = "c_put id";
861                         goto fail;
862                 }
863         } else {
864                 /* initial c_get failed, nothing was done */
865 fail:
866                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
867                         "%s failed: %s (%d)\n", err, db_strerror(rc), rc );
868                 cursor->c_close( cursor );
869                 return rc;
870         }
871         /* If key was added (didn't already exist) and using IDL cache,
872          * update key in IDL cache.
873          */
874         if ( !rc && bdb->bi_idl_cache_max_size ) {
875                 bdb_idl_cache_add_id( bdb, db, key, id );
876         }
877         rc = cursor->c_close( cursor );
878         if( rc != 0 ) {
879                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
880                         "c_close failed: %s (%d)\n",
881                         db_strerror(rc), rc, 0 );
882         }
883         return rc;
884 }
885
886 int
887 bdb_idl_delete_key(
888         BackendDB       *be,
889         DB                      *db,
890         DB_TXN          *tid,
891         DBT                     *key,
892         ID                      id )
893 {
894         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
895         int     rc;
896         DBT data;
897         DBC *cursor;
898         ID lo, hi, tmp, nid, nlo, nhi;
899         char *err;
900
901         {
902                 char buf[16];
903                 Debug( LDAP_DEBUG_ARGS,
904                         "bdb_idl_delete_key: %lx %s\n", 
905                         (long) id, bdb_show_key( key, buf ), 0 );
906         }
907         assert( id != NOID );
908
909         if ( bdb->bi_idl_cache_size ) {
910                 bdb_idl_cache_del( bdb, db, key );
911         }
912
913         BDB_ID2DISK( id, &nid );
914
915         DBTzero( &data );
916         data.data = &tmp;
917         data.size = sizeof( id );
918         data.ulen = data.size;
919         data.flags = DB_DBT_USERMEM;
920
921         rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
922         if ( rc != 0 ) {
923                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_delete_key: "
924                         "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
925                 return rc;
926         }
927         /* Fetch the first data item for this key, to see if it
928          * exists and if it's a range.
929          */
930         rc = cursor->c_get( cursor, key, &data, DB_SET );
931         err = "c_get";
932         if ( rc == 0 ) {
933                 if ( tmp != 0 ) {
934                         /* Not a range, just delete it */
935                         if (tmp != nid) {
936                                 /* position to correct item */
937                                 tmp = nid;
938                                 rc = cursor->c_get( cursor, key, &data, DB_GET_BOTH );
939                                 if ( rc != 0 ) {
940                                         err = "c_get id";
941                                         goto fail;
942                                 }
943                         }
944                         rc = cursor->c_del( cursor, 0 );
945                         if ( rc != 0 ) {
946                                 err = "c_del id";
947                                 goto fail;
948                         }
949                 } else {
950                         /* It's a range, see if we need to rewrite
951                          * the boundaries
952                          */
953                         data.data = &nlo;
954                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
955                         if ( rc != 0 ) {
956                                 err = "c_get lo";
957                                 goto fail;
958                         }
959                         BDB_DISK2ID( &nlo, &lo );
960                         data.data = &nhi;
961                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
962                         if ( rc != 0 ) {
963                                 err = "c_get hi";
964                                 goto fail;
965                         }
966                         BDB_DISK2ID( &nhi, &hi );
967                         if ( id == lo || id == hi ) {
968                                 if ( id == lo ) {
969                                         id++;
970                                         lo = id;
971                                 } else if ( id == hi ) {
972                                         id--;
973                                         hi = id;
974                                 }
975                                 if ( lo >= hi ) {
976                                 /* The range has collapsed... */
977                                         rc = db->del( db, tid, key, 0 );
978                                         if ( rc != 0 ) {
979                                                 err = "del";
980                                                 goto fail;
981                                         }
982                                 } else {
983                                         if ( id == lo ) {
984                                                 /* reposition on lo slot */
985                                                 data.data = &nlo;
986                                                 cursor->c_get( cursor, key, &data, DB_PREV );
987                                         }
988                                         rc = cursor->c_del( cursor, 0 );
989                                         if ( rc != 0 ) {
990                                                 err = "c_del";
991                                                 goto fail;
992                                         }
993                                 }
994                                 if ( lo <= hi ) {
995                                         BDB_ID2DISK( id, &nid );
996                                         data.data = &nid;
997                                         rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
998                                         if ( rc != 0 ) {
999                                                 err = "c_put lo/hi";
1000                                                 goto fail;
1001                                         }
1002                                 }
1003                         }
1004                 }
1005         } else {
1006                 /* initial c_get failed, nothing was done */
1007 fail:
1008                 if ( rc != DB_NOTFOUND ) {
1009                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_delete_key: "
1010                         "%s failed: %s (%d)\n", err, db_strerror(rc), rc );
1011                 }
1012                 cursor->c_close( cursor );
1013                 return rc;
1014         }
1015         rc = cursor->c_close( cursor );
1016         if( rc != 0 ) {
1017                 Debug( LDAP_DEBUG_ANY,
1018                         "=> bdb_idl_delete_key: c_close failed: %s (%d)\n",
1019                         db_strerror(rc), rc, 0 );
1020         }
1021
1022         return rc;
1023 }
1024
1025
1026 /*
1027  * idl_intersection - return a = a intersection b
1028  */
1029 int
1030 bdb_idl_intersection(
1031         ID *a,
1032         ID *b )
1033 {
1034         ID ida, idb;
1035         ID idmax, idmin;
1036         ID cursora = 0, cursorb = 0, cursorc;
1037         int swap = 0;
1038
1039         if ( BDB_IDL_IS_ZERO( a ) || BDB_IDL_IS_ZERO( b ) ) {
1040                 a[0] = 0;
1041                 return 0;
1042         }
1043
1044         idmin = IDL_MAX( BDB_IDL_FIRST(a), BDB_IDL_FIRST(b) );
1045         idmax = IDL_MIN( BDB_IDL_LAST(a), BDB_IDL_LAST(b) );
1046         if ( idmin > idmax ) {
1047                 a[0] = 0;
1048                 return 0;
1049         } else if ( idmin == idmax ) {
1050                 a[0] = 1;
1051                 a[1] = idmin;
1052                 return 0;
1053         }
1054
1055         if ( BDB_IDL_IS_RANGE( a ) ) {
1056                 if ( BDB_IDL_IS_RANGE(b) ) {
1057                 /* If both are ranges, just shrink the boundaries */
1058                         a[1] = idmin;
1059                         a[2] = idmax;
1060                         return 0;
1061                 } else {
1062                 /* Else swap so that b is the range, a is a list */
1063                         ID *tmp = a;
1064                         a = b;
1065                         b = tmp;
1066                         swap = 1;
1067                 }
1068         }
1069
1070         /* If a range completely covers the list, the result is
1071          * just the list. If idmin to idmax is contiguous, just
1072          * turn it into a range.
1073          */
1074         if ( BDB_IDL_IS_RANGE( b )
1075                 && BDB_IDL_FIRST( b ) <= BDB_IDL_FIRST( a )
1076                 && BDB_IDL_LAST( b ) >= BDB_IDL_LAST( a ) ) {
1077                 if (idmax - idmin + 1 == a[0])
1078                 {
1079                         a[0] = NOID;
1080                         a[1] = idmin;
1081                         a[2] = idmax;
1082                 }
1083                 goto done;
1084         }
1085
1086         /* Fine, do the intersection one element at a time.
1087          * First advance to idmin in both IDLs.
1088          */
1089         cursora = cursorb = idmin;
1090         ida = bdb_idl_first( a, &cursora );
1091         idb = bdb_idl_first( b, &cursorb );
1092         cursorc = 0;
1093
1094         while( ida <= idmax || idb <= idmax ) {
1095                 if( ida == idb ) {
1096                         a[++cursorc] = ida;
1097                         ida = bdb_idl_next( a, &cursora );
1098                         idb = bdb_idl_next( b, &cursorb );
1099                 } else if ( ida < idb ) {
1100                         ida = bdb_idl_next( a, &cursora );
1101                 } else {
1102                         idb = bdb_idl_next( b, &cursorb );
1103                 }
1104         }
1105         a[0] = cursorc;
1106 done:
1107         if (swap)
1108                 BDB_IDL_CPY( b, a );
1109
1110         return 0;
1111 }
1112
1113
1114 /*
1115  * idl_union - return a = a union b
1116  */
1117 int
1118 bdb_idl_union(
1119         ID      *a,
1120         ID      *b )
1121 {
1122         ID ida, idb;
1123         ID cursora = 0, cursorb = 0, cursorc;
1124
1125         if ( BDB_IDL_IS_ZERO( b ) ) {
1126                 return 0;
1127         }
1128
1129         if ( BDB_IDL_IS_ZERO( a ) ) {
1130                 BDB_IDL_CPY( a, b );
1131                 return 0;
1132         }
1133
1134         if ( BDB_IDL_IS_RANGE( a ) || BDB_IDL_IS_RANGE(b) ) {
1135 over:           ida = IDL_MIN( BDB_IDL_FIRST(a), BDB_IDL_FIRST(b) );
1136                 idb = IDL_MAX( BDB_IDL_LAST(a), BDB_IDL_LAST(b) );
1137                 a[0] = NOID;
1138                 a[1] = ida;
1139                 a[2] = idb;
1140                 return 0;
1141         }
1142
1143         ida = bdb_idl_first( a, &cursora );
1144         idb = bdb_idl_first( b, &cursorb );
1145
1146         cursorc = b[0];
1147
1148         /* The distinct elements of a are cat'd to b */
1149         while( ida != NOID || idb != NOID ) {
1150                 if ( ida < idb ) {
1151                         if( ++cursorc > BDB_IDL_UM_MAX ) {
1152                                 goto over;
1153                         }
1154                         b[cursorc] = ida;
1155                         ida = bdb_idl_next( a, &cursora );
1156
1157                 } else {
1158                         if ( ida == idb )
1159                                 ida = bdb_idl_next( a, &cursora );
1160                         idb = bdb_idl_next( b, &cursorb );
1161                 }
1162         }
1163
1164         /* b is copied back to a in sorted order */
1165         a[0] = cursorc;
1166         cursora = 1;
1167         cursorb = 1;
1168         cursorc = b[0]+1;
1169         while (cursorb <= b[0] || cursorc <= a[0]) {
1170                 if (cursorc > a[0])
1171                         idb = NOID;
1172                 else
1173                         idb = b[cursorc];
1174                 if (cursorb <= b[0] && b[cursorb] < idb)
1175                         a[cursora++] = b[cursorb++];
1176                 else {
1177                         a[cursora++] = idb;
1178                         cursorc++;
1179                 }
1180         }
1181
1182         return 0;
1183 }
1184
1185
1186 #if 0
1187 /*
1188  * bdb_idl_notin - return a intersection ~b (or a minus b)
1189  */
1190 int
1191 bdb_idl_notin(
1192         ID      *a,
1193         ID      *b,
1194         ID *ids )
1195 {
1196         ID ida, idb;
1197         ID cursora = 0, cursorb = 0;
1198
1199         if( BDB_IDL_IS_ZERO( a ) ||
1200                 BDB_IDL_IS_ZERO( b ) ||
1201                 BDB_IDL_IS_RANGE( b ) )
1202         {
1203                 BDB_IDL_CPY( ids, a );
1204                 return 0;
1205         }
1206
1207         if( BDB_IDL_IS_RANGE( a ) ) {
1208                 BDB_IDL_CPY( ids, a );
1209                 return 0;
1210         }
1211
1212         ida = bdb_idl_first( a, &cursora ),
1213         idb = bdb_idl_first( b, &cursorb );
1214
1215         ids[0] = 0;
1216
1217         while( ida != NOID ) {
1218                 if ( idb == NOID ) {
1219                         /* we could shortcut this */
1220                         ids[++ids[0]] = ida;
1221                         ida = bdb_idl_next( a, &cursora );
1222
1223                 } else if ( ida < idb ) {
1224                         ids[++ids[0]] = ida;
1225                         ida = bdb_idl_next( a, &cursora );
1226
1227                 } else if ( ida > idb ) {
1228                         idb = bdb_idl_next( b, &cursorb );
1229
1230                 } else {
1231                         ida = bdb_idl_next( a, &cursora );
1232                         idb = bdb_idl_next( b, &cursorb );
1233                 }
1234         }
1235
1236         return 0;
1237 }
1238 #endif
1239
1240 ID bdb_idl_first( ID *ids, ID *cursor )
1241 {
1242         ID pos;
1243
1244         if ( ids[0] == 0 ) {
1245                 *cursor = NOID;
1246                 return NOID;
1247         }
1248
1249         if ( BDB_IDL_IS_RANGE( ids ) ) {
1250                 if( *cursor < ids[1] ) {
1251                         *cursor = ids[1];
1252                 }
1253                 return *cursor;
1254         }
1255
1256         if ( *cursor == 0 )
1257                 pos = 1;
1258         else
1259                 pos = bdb_idl_search( ids, *cursor );
1260
1261         if( pos > ids[0] ) {
1262                 return NOID;
1263         }
1264
1265         *cursor = pos;
1266         return ids[pos];
1267 }
1268
1269 ID bdb_idl_next( ID *ids, ID *cursor )
1270 {
1271         if ( BDB_IDL_IS_RANGE( ids ) ) {
1272                 if( ids[2] < ++(*cursor) ) {
1273                         return NOID;
1274                 }
1275                 return *cursor;
1276         }
1277
1278         if ( ++(*cursor) <= ids[0] ) {
1279                 return ids[*cursor];
1280         }
1281
1282         return NOID;
1283 }
1284
1285 #ifdef BDB_HIER
1286
1287 /* Add one ID to an unsorted list. We ensure that the first element is the
1288  * minimum and the last element is the maximum, for fast range compaction.
1289  *   this means IDLs up to length 3 are always sorted...
1290  */
1291 int bdb_idl_append_one( ID *ids, ID id )
1292 {
1293         if (BDB_IDL_IS_RANGE( ids )) {
1294                 /* if already in range, treat as a dup */
1295                 if (id >= BDB_IDL_FIRST(ids) && id <= BDB_IDL_LAST(ids))
1296                         return -1;
1297                 if (id < BDB_IDL_FIRST(ids))
1298                         ids[1] = id;
1299                 else if (id > BDB_IDL_LAST(ids))
1300                         ids[2] = id;
1301                 return 0;
1302         }
1303         if ( ids[0] ) {
1304                 ID tmp;
1305
1306                 if (id < ids[1]) {
1307                         tmp = ids[1];
1308                         ids[1] = id;
1309                         id = tmp;
1310                 }
1311                 if ( ids[0] > 1 && id < ids[ids[0]] ) {
1312                         tmp = ids[ids[0]];
1313                         ids[ids[0]] = id;
1314                         id = tmp;
1315                 }
1316         }
1317         ids[0]++;
1318         if ( ids[0] >= BDB_IDL_UM_MAX ) {
1319                 ids[0] = NOID;
1320                 ids[2] = id;
1321         } else {
1322                 ids[ids[0]] = id;
1323         }
1324         return 0;
1325 }
1326
1327 /* Append sorted list b to sorted list a. The result is unsorted but
1328  * a[1] is the min of the result and a[a[0]] is the max.
1329  */
1330 int bdb_idl_append( ID *a, ID *b )
1331 {
1332         ID ida, idb, tmp, swap = 0;
1333
1334         if ( BDB_IDL_IS_ZERO( b ) ) {
1335                 return 0;
1336         }
1337
1338         if ( BDB_IDL_IS_ZERO( a ) ) {
1339                 BDB_IDL_CPY( a, b );
1340                 return 0;
1341         }
1342
1343         ida = BDB_IDL_LAST( a );
1344         idb = BDB_IDL_LAST( b );
1345         if ( BDB_IDL_IS_RANGE( a ) || BDB_IDL_IS_RANGE(b) ||
1346                 a[0] + b[0] >= BDB_IDL_UM_MAX ) {
1347                 a[2] = IDL_MAX( ida, idb );
1348                 a[1] = IDL_MIN( a[1], b[1] );
1349                 a[0] = NOID;
1350                 return 0;
1351         }
1352
1353         if ( b[0] > 1 && ida > idb ) {
1354                 swap = idb;
1355                 a[a[0]] = idb;
1356                 b[b[0]] = ida;
1357         }
1358
1359         if ( b[1] < a[1] ) {
1360                 tmp = a[1];
1361                 a[1] = b[1];
1362         } else {
1363                 tmp = b[1];
1364         }
1365         a[0]++;
1366         a[a[0]] = tmp;
1367
1368         if ( b[0] > 1 ) {
1369                 int i = b[0] - 1;
1370                 AC_MEMCPY(a+a[0]+1, b+2, i * sizeof(ID));
1371                 a[0] += i;
1372         }
1373         if ( swap ) {
1374                 b[b[0]] = swap;
1375         }
1376         return 0;
1377 }
1378
1379 #if 1
1380
1381 /* Quicksort + Insertion sort for small arrays */
1382
1383 #define SMALL   8
1384 #define SWAP(a,b)       itmp=(a);(a)=(b);(b)=itmp
1385
1386 void
1387 bdb_idl_sort( ID *ids, ID *tmp )
1388 {
1389         int *istack = (int *)tmp;
1390         int i,j,k,l,ir,jstack;
1391         ID a, itmp;
1392
1393         if ( BDB_IDL_IS_RANGE( ids ))
1394                 return;
1395
1396         ir = ids[0];
1397         l = 1;
1398         jstack = 0;
1399         for(;;) {
1400                 if (ir - l < SMALL) {   /* Insertion sort */
1401                         for (j=l+1;j<=ir;j++) {
1402                                 a = ids[j];
1403                                 for (i=j-1;i>=1;i--) {
1404                                         if (ids[i] <= a) break;
1405                                         ids[i+1] = ids[i];
1406                                 }
1407                                 ids[i+1] = a;
1408                         }
1409                         if (jstack == 0) break;
1410                         ir = istack[jstack--];
1411                         l = istack[jstack--];
1412                 } else {
1413                         k = (l + ir) >> 1;      /* Choose median of left, center, right */
1414                         SWAP(ids[k], ids[l+1]);
1415                         if (ids[l] > ids[ir]) {
1416                                 SWAP(ids[l], ids[ir]);
1417                         }
1418                         if (ids[l+1] > ids[ir]) {
1419                                 SWAP(ids[l+1], ids[ir]);
1420                         }
1421                         if (ids[l] > ids[l+1]) {
1422                                 SWAP(ids[l], ids[l+1]);
1423                         }
1424                         i = l+1;
1425                         j = ir;
1426                         a = ids[l+1];
1427                         for(;;) {
1428                                 do i++; while(ids[i] < a);
1429                                 do j--; while(ids[j] > a);
1430                                 if (j < i) break;
1431                                 SWAP(ids[i],ids[j]);
1432                         }
1433                         ids[l+1] = ids[j];
1434                         ids[j] = a;
1435                         jstack += 2;
1436                         if (ir-i+1 >= j-1) {
1437                                 istack[jstack] = ir;
1438                                 istack[jstack-1] = i;
1439                                 ir = j-1;
1440                         } else {
1441                                 istack[jstack] = j-1;
1442                                 istack[jstack-1] = l;
1443                                 l = i;
1444                         }
1445                 }
1446         }
1447 }
1448
1449 #else
1450
1451 /* 8 bit Radix sort + insertion sort
1452  * 
1453  * based on code from http://www.cubic.org/docs/radix.htm
1454  * with improvements by mbackes@symas.com and hyc@symas.com
1455  *
1456  * This code is O(n) but has a relatively high constant factor. For lists
1457  * up to ~50 Quicksort is slightly faster; up to ~100 they are even.
1458  * Much faster than quicksort for lists longer than ~100. Insertion
1459  * sort is actually superior for lists <50.
1460  */
1461
1462 #define BUCKETS (1<<8)
1463 #define SMALL   50
1464
1465 void
1466 bdb_idl_sort( ID *ids, ID *tmp )
1467 {
1468         int count, soft_limit, phase = 0, size = ids[0];
1469         ID *idls[2];
1470         unsigned char *maxv = (unsigned char *)&ids[size];
1471
1472         if ( BDB_IDL_IS_RANGE( ids ))
1473                 return;
1474
1475         /* Use insertion sort for small lists */
1476         if ( size <= SMALL ) {
1477                 int i,j;
1478                 ID a;
1479
1480                 for (j=1;j<=size;j++) {
1481                         a = ids[j];
1482                         for (i=j-1;i>=1;i--) {
1483                                 if (ids[i] <= a) break;
1484                                 ids[i+1] = ids[i];
1485                         }
1486                         ids[i+1] = a;
1487                 }
1488                 return;
1489         }
1490
1491         tmp[0] = size;
1492         idls[0] = ids;
1493         idls[1] = tmp;
1494
1495 #if BYTE_ORDER == BIG_ENDIAN
1496     for (soft_limit = 0; !maxv[soft_limit]; soft_limit++);
1497 #else
1498     for (soft_limit = sizeof(ID)-1; !maxv[soft_limit]; soft_limit--);
1499 #endif
1500
1501         for (
1502 #if BYTE_ORDER == BIG_ENDIAN
1503         count = sizeof(ID)-1; count >= soft_limit; --count
1504 #else
1505         count = 0; count <= soft_limit; ++count
1506 #endif
1507         ) {
1508                 unsigned int num[BUCKETS], * np, n, sum;
1509                 int i;
1510         ID *sp, *source, *dest;
1511         unsigned char *bp, *source_start;
1512
1513                 source = idls[phase]+1;
1514                 dest = idls[phase^1]+1;
1515                 source_start =  ((unsigned char *) source) + count;
1516
1517         np = num;
1518         for ( i = BUCKETS; i > 0; --i ) *np++ = 0;
1519
1520                 /* count occurences of every byte value */
1521                 bp = source_start;
1522         for ( i = size; i > 0; --i, bp += sizeof(ID) )
1523                                 num[*bp]++;
1524
1525                 /* transform count into index by summing elements and storing
1526                  * into same array
1527                  */
1528         sum = 0;
1529         np = num;
1530         for ( i = BUCKETS; i > 0; --i ) {
1531                 n = *np;
1532                 *np++ = sum;
1533                 sum += n;
1534         }
1535
1536                 /* fill dest with the right values in the right place */
1537                 bp = source_start;
1538         sp = source;
1539         for ( i = size; i > 0; --i, bp += sizeof(ID) ) {
1540                 np = num + *bp;
1541                 dest[*np] = *sp++;
1542                 ++(*np);
1543         }
1544                 phase ^= 1;
1545         }
1546
1547         /* copy back from temp if needed */
1548         if ( phase ) {
1549                 ids++; tmp++;
1550                 for ( count = 0; count < size; ++count ) 
1551                         *ids++ = *tmp++;
1552         }
1553 }
1554 #endif  /* Quick vs Radix */
1555
1556 #endif  /* BDB_HIER */