]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/idl.c
84629c10cf6e777a09059c966b5b96f990b1ecab
[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-2006 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                         if ( cache_entry->idl )
477                                 free( cache_entry->idl );
478                         free( cache_entry );
479                 }
480         }
481         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_idl_tree_rwlock );
482 }
483
484 int
485 bdb_idl_fetch_key(
486         BackendDB       *be,
487         DB                      *db,
488         DB_TXN          *tid,
489         DBT                     *key,
490         ID                      *ids,
491         DBC                     **saved_cursor,
492         int                     get_flag )
493 {
494         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
495         int rc;
496         DBT data, key2, *kptr;
497         DBC *cursor;
498         ID *i;
499         void *ptr;
500         size_t len;
501         int rc2;
502         int flags = bdb->bi_db_opflags | DB_MULTIPLE;
503         int opflag;
504
505         /* If using BerkeleyDB 4.0, the buf must be large enough to
506          * grab the entire IDL in one get(), otherwise BDB will leak
507          * resources on subsequent get's.  We can safely call get()
508          * twice - once for the data, and once to get the DB_NOTFOUND
509          * result meaning there's no more data. See ITS#2040 for details.
510          * This bug is fixed in BDB 4.1 so a smaller buffer will work if
511          * stack space is too limited.
512          *
513          * configure now requires Berkeley DB 4.1.
514          */
515 #if DB_VERSION_FULL < 0x04010000
516 #       define BDB_ENOUGH 5
517 #else
518         /* We sometimes test with tiny IDLs, and BDB always wants buffers
519          * that are at least one page in size.
520          */
521 # if BDB_IDL_DB_SIZE < 4096
522 #   define BDB_ENOUGH 2048
523 # else
524 #       define BDB_ENOUGH 1
525 # endif
526 #endif
527         ID buf[BDB_IDL_DB_SIZE*BDB_ENOUGH];
528
529         char keybuf[16];
530
531         Debug( LDAP_DEBUG_ARGS,
532                 "bdb_idl_fetch_key: %s\n", 
533                 bdb_show_key( key, keybuf ), 0, 0 );
534
535         assert( ids != NULL );
536
537         if ( saved_cursor && *saved_cursor ) {
538                 opflag = DB_NEXT;
539         } else if ( get_flag == LDAP_FILTER_GE ) {
540                 opflag = DB_SET_RANGE;
541         } else if ( get_flag == LDAP_FILTER_LE ) {
542                 opflag = DB_FIRST;
543         } else {
544                 opflag = DB_SET;
545         }
546
547         /* only non-range lookups can use the IDL cache */
548         if ( bdb->bi_idl_cache_size && opflag == DB_SET ) {
549                 rc = bdb_idl_cache_get( bdb, db, key, ids );
550                 if ( rc != LDAP_NO_SUCH_OBJECT ) return rc;
551         }
552
553         DBTzero( &data );
554
555         data.data = buf;
556         data.ulen = sizeof(buf);
557         data.flags = DB_DBT_USERMEM;
558
559         /* If we're not reusing an existing cursor, get a new one */
560         if( opflag != DB_NEXT ) {
561                 rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
562                 if( rc != 0 ) {
563                         Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
564                                 "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
565                         return rc;
566                 }
567         } else {
568                 cursor = *saved_cursor;
569         }
570         
571         /* If this is a LE lookup, save original key so we can determine
572          * when to stop. If this is a GE lookup, save the key since it
573          * will be overwritten.
574          */
575         if ( get_flag == LDAP_FILTER_LE || get_flag == LDAP_FILTER_GE ) {
576                 DBTzero( &key2 );
577                 key2.flags = DB_DBT_USERMEM;
578                 key2.ulen = sizeof(keybuf);
579                 key2.data = keybuf;
580                 key2.size = key->size;
581                 AC_MEMCPY( keybuf, key->data, key->size );
582                 kptr = &key2;
583         } else {
584                 kptr = key;
585         }
586         len = key->size;
587         rc = cursor->c_get( cursor, kptr, &data, flags | opflag );
588
589         /* skip presence key on range inequality lookups */
590         while (rc == 0 && kptr->size != len) {
591                 rc = cursor->c_get( cursor, kptr, &data, flags | DB_NEXT_NODUP );
592         }
593         /* If we're doing a LE compare and the new key is greater than
594          * our search key, we're done
595          */
596         if (rc == 0 && get_flag == LDAP_FILTER_LE && memcmp( kptr->data,
597                 key->data, key->size ) > 0 ) {
598                 rc = DB_NOTFOUND;
599         }
600         if (rc == 0) {
601                 i = ids;
602                 while (rc == 0) {
603                         u_int8_t *j;
604
605                         DB_MULTIPLE_INIT( ptr, &data );
606                         while (ptr) {
607                                 DB_MULTIPLE_NEXT(ptr, &data, j, len);
608                                 if (j) {
609                                         ++i;
610                                         BDB_DISK2ID( j, i );
611                                 }
612                         }
613                         rc = cursor->c_get( cursor, key, &data, flags | DB_NEXT_DUP );
614                 }
615                 if ( rc == DB_NOTFOUND ) rc = 0;
616                 ids[0] = i - ids;
617                 /* On disk, a range is denoted by 0 in the first element */
618                 if (ids[1] == 0) {
619                         if (ids[0] != BDB_IDL_RANGE_SIZE) {
620                                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
621                                         "range size mismatch: expected %d, got %ld\n",
622                                         BDB_IDL_RANGE_SIZE, ids[0], 0 );
623                                 cursor->c_close( cursor );
624                                 return -1;
625                         }
626                         BDB_IDL_RANGE( ids, ids[2], ids[3] );
627                 }
628                 data.size = BDB_IDL_SIZEOF(ids);
629         }
630
631         if ( saved_cursor && rc == 0 ) {
632                 if ( !*saved_cursor )
633                         *saved_cursor = cursor;
634                 rc2 = 0;
635         }
636         else
637                 rc2 = cursor->c_close( cursor );
638         if (rc2) {
639                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
640                         "close failed: %s (%d)\n", db_strerror(rc2), rc2, 0 );
641                 return rc2;
642         }
643
644         if( rc == DB_NOTFOUND ) {
645                 return rc;
646
647         } else if( rc != 0 ) {
648                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
649                         "get failed: %s (%d)\n",
650                         db_strerror(rc), rc, 0 );
651                 return rc;
652
653         } else if ( data.size == 0 || data.size % sizeof( ID ) ) {
654                 /* size not multiple of ID size */
655                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
656                         "odd size: expected %ld multiple, got %ld\n",
657                         (long) sizeof( ID ), (long) data.size, 0 );
658                 return -1;
659
660         } else if ( data.size != BDB_IDL_SIZEOF(ids) ) {
661                 /* size mismatch */
662                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_fetch_key: "
663                         "get size mismatch: expected %ld, got %ld\n",
664                         (long) ((1 + ids[0]) * sizeof( ID )), (long) data.size, 0 );
665                 return -1;
666         }
667
668         if ( bdb->bi_idl_cache_max_size ) {
669                 bdb_idl_cache_put( bdb, db, key, ids, rc );
670         }
671
672         return rc;
673 }
674
675
676 int
677 bdb_idl_insert_key(
678         BackendDB       *be,
679         DB                      *db,
680         DB_TXN          *tid,
681         DBT                     *key,
682         ID                      id )
683 {
684         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
685         int     rc;
686         DBT data;
687         DBC *cursor;
688         ID lo, hi, nlo, nhi, nid;
689         char *err;
690
691         {
692                 char buf[16];
693                 Debug( LDAP_DEBUG_ARGS,
694                         "bdb_idl_insert_key: %lx %s\n", 
695                         (long) id, bdb_show_key( key, buf ), 0 );
696         }
697
698         assert( id != NOID );
699
700         if ( bdb->bi_idl_cache_size ) {
701                 bdb_idl_cache_del( bdb, db, key );
702         }
703
704         DBTzero( &data );
705         data.size = sizeof( ID );
706         data.ulen = data.size;
707         data.flags = DB_DBT_USERMEM;
708
709         BDB_ID2DISK( id, &nid );
710
711         rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
712         if ( rc != 0 ) {
713                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
714                         "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
715                 return rc;
716         }
717         data.data = &nlo;
718         /* Fetch the first data item for this key, to see if it
719          * exists and if it's a range.
720          */
721         rc = cursor->c_get( cursor, key, &data, DB_SET );
722         err = "c_get";
723         if ( rc == 0 ) {
724                 if ( nlo != 0 ) {
725                         /* not a range, count the number of items */
726                         db_recno_t count;
727                         rc = cursor->c_count( cursor, &count, 0 );
728                         if ( rc != 0 ) {
729                                 err = "c_count";
730                                 goto fail;
731                         }
732                         if ( count >= BDB_IDL_DB_MAX ) {
733                         /* No room, convert to a range */
734                                 DBT key2 = *key;
735                                 db_recno_t i;
736
737                                 key2.dlen = key2.ulen;
738                                 key2.flags |= DB_DBT_PARTIAL;
739
740                                 BDB_DISK2ID( &nlo, &lo );
741                                 data.data = &nhi;
742
743                                 rc = cursor->c_get( cursor, &key2, &data, DB_NEXT_NODUP );
744                                 if ( rc != 0 && rc != DB_NOTFOUND ) {
745                                         err = "c_get next_nodup";
746                                         goto fail;
747                                 }
748                                 if ( rc == DB_NOTFOUND ) {
749                                         rc = cursor->c_get( cursor, key, &data, DB_LAST );
750                                         if ( rc != 0 ) {
751                                                 err = "c_get last";
752                                                 goto fail;
753                                         }
754                                 } else {
755                                         rc = cursor->c_get( cursor, key, &data, DB_PREV );
756                                         if ( rc != 0 ) {
757                                                 err = "c_get prev";
758                                                 goto fail;
759                                         }
760                                 }
761                                 BDB_DISK2ID( &nhi, &hi );
762                                 /* Update hi/lo if needed, then delete all the items
763                                  * between lo and hi
764                                  */
765                                 if ( id < lo ) {
766                                         lo = id;
767                                         nlo = nid;
768                                 } else if ( id > hi ) {
769                                         hi = id;
770                                         nhi = nid;
771                                 }
772                                 data.data = &nid;
773                                 /* Don't fetch anything, just position cursor */
774                                 data.flags = DB_DBT_USERMEM | DB_DBT_PARTIAL;
775                                 data.dlen = data.ulen = 0;
776                                 rc = cursor->c_get( cursor, key, &data, DB_SET );
777                                 if ( rc != 0 ) {
778                                         err = "c_get 2";
779                                         goto fail;
780                                 }
781                                 rc = cursor->c_del( cursor, 0 );
782                                 if ( rc != 0 ) {
783                                         err = "c_del range1";
784                                         goto fail;
785                                 }
786                                 /* Delete all the records */
787                                 for ( i=1; i<count; i++ ) {
788                                         rc = cursor->c_get( cursor, &key2, &data, DB_NEXT_DUP );
789                                         if ( rc != 0 ) {
790                                                 err = "c_get next_dup";
791                                                 goto fail;
792                                         }
793                                         rc = cursor->c_del( cursor, 0 );
794                                         if ( rc != 0 ) {
795                                                 err = "c_del range";
796                                                 goto fail;
797                                         }
798                                 }
799                                 /* Store the range marker */
800                                 data.size = data.ulen = sizeof(ID);
801                                 data.flags = DB_DBT_USERMEM;
802                                 nid = 0;
803                                 rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
804                                 if ( rc != 0 ) {
805                                         err = "c_put range";
806                                         goto fail;
807                                 }
808                                 nid = nlo;
809                                 rc = cursor->c_put( cursor, key, &data, DB_KEYLAST );
810                                 if ( rc != 0 ) {
811                                         err = "c_put lo";
812                                         goto fail;
813                                 }
814                                 nid = nhi;
815                                 rc = cursor->c_put( cursor, key, &data, DB_KEYLAST );
816                                 if ( rc != 0 ) {
817                                         err = "c_put hi";
818                                         goto fail;
819                                 }
820                         } else {
821                         /* There's room, just store it */
822                                 goto put1;
823                         }
824                 } else {
825                         /* It's a range, see if we need to rewrite
826                          * the boundaries
827                          */
828                         hi = id;
829                         data.data = &nlo;
830                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
831                         if ( rc != 0 ) {
832                                 err = "c_get lo";
833                                 goto fail;
834                         }
835                         BDB_DISK2ID( &nlo, &lo );
836                         if ( id > lo ) {
837                                 data.data = &nhi;
838                                 rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
839                                 if ( rc != 0 ) {
840                                         err = "c_get hi";
841                                         goto fail;
842                                 }
843                                 BDB_DISK2ID( &nhi, &hi );
844                         }
845                         if ( id < lo || id > hi ) {
846                                 /* Delete the current lo/hi */
847                                 rc = cursor->c_del( cursor, 0 );
848                                 if ( rc != 0 ) {
849                                         err = "c_del";
850                                         goto fail;
851                                 }
852                                 data.data = &nid;
853                                 rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
854                                 if ( rc != 0 ) {
855                                         err = "c_put lo/hi";
856                                         goto fail;
857                                 }
858                         }
859                 }
860         } else if ( rc == DB_NOTFOUND ) {
861 put1:           data.data = &nid;
862                 rc = cursor->c_put( cursor, key, &data, DB_NODUPDATA );
863                 /* Don't worry if it's already there */
864                 if ( rc != 0 && rc != DB_KEYEXIST ) {
865                         err = "c_put id";
866                         goto fail;
867                 }
868         } else {
869                 /* initial c_get failed, nothing was done */
870 fail:
871                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
872                         "%s failed: %s (%d)\n", err, db_strerror(rc), rc );
873                 cursor->c_close( cursor );
874                 return rc;
875         }
876         rc = cursor->c_close( cursor );
877         if( rc != 0 ) {
878                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_insert_key: "
879                         "c_close failed: %s (%d)\n",
880                         db_strerror(rc), rc, 0 );
881         }
882         return rc;
883 }
884
885 int
886 bdb_idl_delete_key(
887         BackendDB       *be,
888         DB                      *db,
889         DB_TXN          *tid,
890         DBT                     *key,
891         ID                      id )
892 {
893         struct bdb_info *bdb = (struct bdb_info *) be->be_private;
894         int     rc;
895         DBT data;
896         DBC *cursor;
897         ID lo, hi, tmp, nid, nlo, nhi;
898         char *err;
899
900         {
901                 char buf[16];
902                 Debug( LDAP_DEBUG_ARGS,
903                         "bdb_idl_delete_key: %lx %s\n", 
904                         (long) id, bdb_show_key( key, buf ), 0 );
905         }
906         assert( id != NOID );
907
908         if ( bdb->bi_idl_cache_max_size ) {
909                 bdb_idl_cache_del( bdb, db, key );
910         }
911
912         BDB_ID2DISK( id, &nid );
913
914         DBTzero( &data );
915         data.data = &tmp;
916         data.size = sizeof( id );
917         data.ulen = data.size;
918         data.flags = DB_DBT_USERMEM;
919
920         rc = db->cursor( db, tid, &cursor, bdb->bi_db_opflags );
921         if ( rc != 0 ) {
922                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_delete_key: "
923                         "cursor failed: %s (%d)\n", db_strerror(rc), rc, 0 );
924                 return rc;
925         }
926         /* Fetch the first data item for this key, to see if it
927          * exists and if it's a range.
928          */
929         rc = cursor->c_get( cursor, key, &data, DB_SET );
930         err = "c_get";
931         if ( rc == 0 ) {
932                 if ( tmp != 0 ) {
933                         /* Not a range, just delete it */
934                         if (tmp != nid) {
935                                 /* position to correct item */
936                                 tmp = nid;
937                                 rc = cursor->c_get( cursor, key, &data, DB_GET_BOTH );
938                                 if ( rc != 0 ) {
939                                         err = "c_get id";
940                                         goto fail;
941                                 }
942                         }
943                         rc = cursor->c_del( cursor, 0 );
944                         if ( rc != 0 ) {
945                                 err = "c_del id";
946                                 goto fail;
947                         }
948                 } else {
949                         /* It's a range, see if we need to rewrite
950                          * the boundaries
951                          */
952                         data.data = &nlo;
953                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
954                         if ( rc != 0 ) {
955                                 err = "c_get lo";
956                                 goto fail;
957                         }
958                         BDB_DISK2ID( &nlo, &lo );
959                         data.data = &nhi;
960                         rc = cursor->c_get( cursor, key, &data, DB_NEXT_DUP );
961                         if ( rc != 0 ) {
962                                 err = "c_get hi";
963                                 goto fail;
964                         }
965                         BDB_DISK2ID( &nhi, &hi );
966                         if ( id == lo || id == hi ) {
967                                 if ( id == lo ) {
968                                         id++;
969                                         lo = id;
970                                 } else if ( id == hi ) {
971                                         id--;
972                                         hi = id;
973                                 }
974                                 if ( lo >= hi ) {
975                                 /* The range has collapsed... */
976                                         rc = db->del( db, tid, key, 0 );
977                                         if ( rc != 0 ) {
978                                                 err = "del";
979                                                 goto fail;
980                                         }
981                                 } else {
982                                         if ( id == lo ) {
983                                                 /* reposition on lo slot */
984                                                 data.data = &nlo;
985                                                 cursor->c_get( cursor, key, &data, DB_PREV );
986                                         }
987                                         rc = cursor->c_del( cursor, 0 );
988                                         if ( rc != 0 ) {
989                                                 err = "c_del";
990                                                 goto fail;
991                                         }
992                                 }
993                                 if ( lo <= hi ) {
994                                         BDB_ID2DISK( id, &nid );
995                                         data.data = &nid;
996                                         rc = cursor->c_put( cursor, key, &data, DB_KEYFIRST );
997                                         if ( rc != 0 ) {
998                                                 err = "c_put lo/hi";
999                                                 goto fail;
1000                                         }
1001                                 }
1002                         }
1003                 }
1004         } else {
1005                 /* initial c_get failed, nothing was done */
1006 fail:
1007                 if ( rc != DB_NOTFOUND ) {
1008                 Debug( LDAP_DEBUG_ANY, "=> bdb_idl_delete_key: "
1009                         "%s failed: %s (%d)\n", err, db_strerror(rc), rc );
1010                 }
1011                 cursor->c_close( cursor );
1012                 return rc;
1013         }
1014         rc = cursor->c_close( cursor );
1015         if( rc != 0 ) {
1016                 Debug( LDAP_DEBUG_ANY,
1017                         "=> bdb_idl_delete_key: c_close failed: %s (%d)\n",
1018                         db_strerror(rc), rc, 0 );
1019         }
1020
1021         return rc;
1022 }
1023
1024
1025 /*
1026  * idl_intersection - return a = a intersection b
1027  */
1028 int
1029 bdb_idl_intersection(
1030         ID *a,
1031         ID *b )
1032 {
1033         ID ida, idb;
1034         ID idmax, idmin;
1035         ID cursora = 0, cursorb = 0, cursorc;
1036         int swap = 0;
1037
1038         if ( BDB_IDL_IS_ZERO( a ) || BDB_IDL_IS_ZERO( b ) ) {
1039                 a[0] = 0;
1040                 return 0;
1041         }
1042
1043         idmin = IDL_MAX( BDB_IDL_FIRST(a), BDB_IDL_FIRST(b) );
1044         idmax = IDL_MIN( BDB_IDL_LAST(a), BDB_IDL_LAST(b) );
1045         if ( idmin > idmax ) {
1046                 a[0] = 0;
1047                 return 0;
1048         } else if ( idmin == idmax ) {
1049                 a[0] = 1;
1050                 a[1] = idmin;
1051                 return 0;
1052         }
1053
1054         if ( BDB_IDL_IS_RANGE( a ) ) {
1055                 if ( BDB_IDL_IS_RANGE(b) ) {
1056                 /* If both are ranges, just shrink the boundaries */
1057                         a[1] = idmin;
1058                         a[2] = idmax;
1059                         return 0;
1060                 } else {
1061                 /* Else swap so that b is the range, a is a list */
1062                         ID *tmp = a;
1063                         a = b;
1064                         b = tmp;
1065                         swap = 1;
1066                 }
1067         }
1068
1069         /* If a range completely covers the list, the result is
1070          * just the list. If idmin to idmax is contiguous, just
1071          * turn it into a range.
1072          */
1073         if ( BDB_IDL_IS_RANGE( b )
1074                 && BDB_IDL_FIRST( b ) <= BDB_IDL_FIRST( a )
1075                 && BDB_IDL_LAST( b ) >= BDB_IDL_LAST( a ) ) {
1076                 if (idmax - idmin + 1 == a[0])
1077                 {
1078                         a[0] = NOID;
1079                         a[1] = idmin;
1080                         a[2] = idmax;
1081                 }
1082                 goto done;
1083         }
1084
1085         /* Fine, do the intersection one element at a time.
1086          * First advance to idmin in both IDLs.
1087          */
1088         cursora = cursorb = idmin;
1089         ida = bdb_idl_first( a, &cursora );
1090         idb = bdb_idl_first( b, &cursorb );
1091         cursorc = 0;
1092
1093         while( ida <= idmax || idb <= idmax ) {
1094                 if( ida == idb ) {
1095                         a[++cursorc] = ida;
1096                         ida = bdb_idl_next( a, &cursora );
1097                         idb = bdb_idl_next( b, &cursorb );
1098                 } else if ( ida < idb ) {
1099                         ida = bdb_idl_next( a, &cursora );
1100                 } else {
1101                         idb = bdb_idl_next( b, &cursorb );
1102                 }
1103         }
1104         a[0] = cursorc;
1105 done:
1106         if (swap)
1107                 BDB_IDL_CPY( b, a );
1108
1109         return 0;
1110 }
1111
1112
1113 /*
1114  * idl_union - return a = a union b
1115  */
1116 int
1117 bdb_idl_union(
1118         ID      *a,
1119         ID      *b )
1120 {
1121         ID ida, idb;
1122         ID cursora = 0, cursorb = 0, cursorc;
1123
1124         if ( BDB_IDL_IS_ZERO( b ) ) {
1125                 return 0;
1126         }
1127
1128         if ( BDB_IDL_IS_ZERO( a ) ) {
1129                 BDB_IDL_CPY( a, b );
1130                 return 0;
1131         }
1132
1133         if ( BDB_IDL_IS_RANGE( a ) || BDB_IDL_IS_RANGE(b) ) {
1134 over:           ida = IDL_MIN( BDB_IDL_FIRST(a), BDB_IDL_FIRST(b) );
1135                 idb = IDL_MAX( BDB_IDL_LAST(a), BDB_IDL_LAST(b) );
1136                 a[0] = NOID;
1137                 a[1] = ida;
1138                 a[2] = idb;
1139                 return 0;
1140         }
1141
1142         ida = bdb_idl_first( a, &cursora );
1143         idb = bdb_idl_first( b, &cursorb );
1144
1145         cursorc = b[0];
1146
1147         /* The distinct elements of a are cat'd to b */
1148         while( ida != NOID || idb != NOID ) {
1149                 if ( ida < idb ) {
1150                         if( ++cursorc > BDB_IDL_UM_MAX ) {
1151                                 goto over;
1152                         }
1153                         b[cursorc] = ida;
1154                         ida = bdb_idl_next( a, &cursora );
1155
1156                 } else {
1157                         if ( ida == idb )
1158                                 ida = bdb_idl_next( a, &cursora );
1159                         idb = bdb_idl_next( b, &cursorb );
1160                 }
1161         }
1162
1163         /* b is copied back to a in sorted order */
1164         a[0] = cursorc;
1165         cursora = 1;
1166         cursorb = 1;
1167         cursorc = b[0]+1;
1168         while (cursorb <= b[0] || cursorc <= a[0]) {
1169                 if (cursorc > a[0])
1170                         idb = NOID;
1171                 else
1172                         idb = b[cursorc];
1173                 if (cursorb <= b[0] && b[cursorb] < idb)
1174                         a[cursora++] = b[cursorb++];
1175                 else {
1176                         a[cursora++] = idb;
1177                         cursorc++;
1178                 }
1179         }
1180
1181         return 0;
1182 }
1183
1184
1185 #if 0
1186 /*
1187  * bdb_idl_notin - return a intersection ~b (or a minus b)
1188  */
1189 int
1190 bdb_idl_notin(
1191         ID      *a,
1192         ID      *b,
1193         ID *ids )
1194 {
1195         ID ida, idb;
1196         ID cursora = 0, cursorb = 0;
1197
1198         if( BDB_IDL_IS_ZERO( a ) ||
1199                 BDB_IDL_IS_ZERO( b ) ||
1200                 BDB_IDL_IS_RANGE( b ) )
1201         {
1202                 BDB_IDL_CPY( ids, a );
1203                 return 0;
1204         }
1205
1206         if( BDB_IDL_IS_RANGE( a ) ) {
1207                 BDB_IDL_CPY( ids, a );
1208                 return 0;
1209         }
1210
1211         ida = bdb_idl_first( a, &cursora ),
1212         idb = bdb_idl_first( b, &cursorb );
1213
1214         ids[0] = 0;
1215
1216         while( ida != NOID ) {
1217                 if ( idb == NOID ) {
1218                         /* we could shortcut this */
1219                         ids[++ids[0]] = ida;
1220                         ida = bdb_idl_next( a, &cursora );
1221
1222                 } else if ( ida < idb ) {
1223                         ids[++ids[0]] = ida;
1224                         ida = bdb_idl_next( a, &cursora );
1225
1226                 } else if ( ida > idb ) {
1227                         idb = bdb_idl_next( b, &cursorb );
1228
1229                 } else {
1230                         ida = bdb_idl_next( a, &cursora );
1231                         idb = bdb_idl_next( b, &cursorb );
1232                 }
1233         }
1234
1235         return 0;
1236 }
1237 #endif
1238
1239 ID bdb_idl_first( ID *ids, ID *cursor )
1240 {
1241         ID pos;
1242
1243         if ( ids[0] == 0 ) {
1244                 *cursor = NOID;
1245                 return NOID;
1246         }
1247
1248         if ( BDB_IDL_IS_RANGE( ids ) ) {
1249                 if( *cursor < ids[1] ) {
1250                         *cursor = ids[1];
1251                 }
1252                 return *cursor;
1253         }
1254
1255         if ( *cursor == 0 )
1256                 pos = 1;
1257         else
1258                 pos = bdb_idl_search( ids, *cursor );
1259
1260         if( pos > ids[0] ) {
1261                 return NOID;
1262         }
1263
1264         *cursor = pos;
1265         return ids[pos];
1266 }
1267
1268 ID bdb_idl_next( ID *ids, ID *cursor )
1269 {
1270         if ( BDB_IDL_IS_RANGE( ids ) ) {
1271                 if( ids[2] < ++(*cursor) ) {
1272                         return NOID;
1273                 }
1274                 return *cursor;
1275         }
1276
1277         if ( ++(*cursor) <= ids[0] ) {
1278                 return ids[*cursor];
1279         }
1280
1281         return NOID;
1282 }
1283
1284 #ifdef BDB_HIER
1285
1286 /* Add one ID to an unsorted list. We ensure that the first element is the
1287  * minimum and the last element is the maximum, for fast range compaction.
1288  *   this means IDLs up to length 3 are always sorted...
1289  */
1290 int bdb_idl_append_one( ID *ids, ID id )
1291 {
1292         if (BDB_IDL_IS_RANGE( ids )) {
1293                 /* if already in range, treat as a dup */
1294                 if (id >= BDB_IDL_FIRST(ids) && id <= BDB_IDL_LAST(ids))
1295                         return -1;
1296                 if (id < BDB_IDL_FIRST(ids))
1297                         ids[1] = id;
1298                 else if (id > BDB_IDL_LAST(ids))
1299                         ids[2] = id;
1300                 return 0;
1301         }
1302         if ( ids[0] ) {
1303                 ID tmp;
1304
1305                 if (id < ids[1]) {
1306                         tmp = ids[1];
1307                         ids[1] = id;
1308                         id = tmp;
1309                 }
1310                 if ( ids[0] > 1 && id < ids[ids[0]] ) {
1311                         tmp = ids[ids[0]];
1312                         ids[ids[0]] = id;
1313                         id = tmp;
1314                 }
1315         }
1316         ids[0]++;
1317         if ( ids[0] >= BDB_IDL_UM_MAX ) {
1318                 ids[0] = NOID;
1319                 ids[2] = id;
1320         } else {
1321                 ids[ids[0]] = id;
1322         }
1323         return 0;
1324 }
1325
1326 /* Append sorted list b to sorted list a. The result is unsorted but
1327  * a[1] is the min of the result and a[a[0]] is the max.
1328  */
1329 int bdb_idl_append( ID *a, ID *b )
1330 {
1331         ID ida, idb, tmp, swap = 0;
1332
1333         if ( BDB_IDL_IS_ZERO( b ) ) {
1334                 return 0;
1335         }
1336
1337         if ( BDB_IDL_IS_ZERO( a ) ) {
1338                 BDB_IDL_CPY( a, b );
1339                 return 0;
1340         }
1341
1342         ida = BDB_IDL_LAST( a );
1343         idb = BDB_IDL_LAST( b );
1344         if ( BDB_IDL_IS_RANGE( a ) || BDB_IDL_IS_RANGE(b) ||
1345                 a[0] + b[0] >= BDB_IDL_UM_MAX ) {
1346                 a[2] = IDL_MAX( ida, idb );
1347                 a[1] = IDL_MIN( a[1], b[1] );
1348                 a[0] = NOID;
1349                 return 0;
1350         }
1351
1352         if ( b[0] > 1 && ida > idb ) {
1353                 swap = idb;
1354                 a[a[0]] = idb;
1355                 b[b[0]] = ida;
1356         }
1357
1358         if ( b[1] < a[1] ) {
1359                 tmp = a[1];
1360                 a[1] = b[1];
1361         } else {
1362                 tmp = b[1];
1363         }
1364         a[0]++;
1365         a[a[0]] = tmp;
1366
1367         if ( b[0] > 1 ) {
1368                 int i = b[0] - 1;
1369                 AC_MEMCPY(a+a[0]+1, b+2, i * sizeof(ID));
1370                 a[0] += i;
1371         }
1372         if ( swap ) {
1373                 b[b[0]] = swap;
1374         }
1375         return 0;
1376 }
1377
1378 #if 0
1379
1380 /* Quicksort + Insertion sort for small arrays */
1381
1382 #define SMALL   8
1383 #define SWAP(a,b)       itmp=(a);(a)=(b);(b)=itmp
1384
1385 void
1386 bdb_idl_sort( ID *ids, ID *tmp )
1387 {
1388         int *istack = (int *)tmp;
1389         int i,j,k,l,ir,jstack;
1390         ID a, itmp;
1391
1392         if ( BDB_IDL_IS_RANGE( ids ))
1393                 return;
1394
1395         ir = ids[0];
1396         l = 1;
1397         jstack = 0;
1398         for(;;) {
1399                 if (ir - l < SMALL) {   /* Insertion sort */
1400                         for (j=l+1;j<=ir;j++) {
1401                                 a = ids[j];
1402                                 for (i=j-1;i>=1;i--) {
1403                                         if (ids[i] <= a) break;
1404                                         ids[i+1] = ids[i];
1405                                 }
1406                                 ids[i+1] = a;
1407                         }
1408                         if (jstack == 0) break;
1409                         ir = istack[jstack--];
1410                         l = istack[jstack--];
1411                 } else {
1412                         k = (l + ir) >> 1;      /* Choose median of left, center, right */
1413                         SWAP(ids[k], ids[l+1]);
1414                         if (ids[l] > ids[ir]) {
1415                                 SWAP(ids[l], ids[ir]);
1416                         }
1417                         if (ids[l+1] > ids[ir]) {
1418                                 SWAP(ids[l+1], ids[ir]);
1419                         }
1420                         if (ids[l] > ids[l+1]) {
1421                                 SWAP(ids[l], ids[l+1]);
1422                         }
1423                         i = l+1;
1424                         j = ir;
1425                         a = ids[l+1];
1426                         for(;;) {
1427                                 do i++; while(ids[i] < a);
1428                                 do j--; while(ids[j] > a);
1429                                 if (j < i) break;
1430                                 SWAP(ids[i],ids[j]);
1431                         }
1432                         ids[l+1] = ids[j];
1433                         ids[j] = a;
1434                         jstack += 2;
1435                         if (ir-i+1 >= j-1) {
1436                                 istack[jstack] = ir;
1437                                 istack[jstack-1] = i;
1438                                 ir = j-1;
1439                         } else {
1440                                 istack[jstack] = j-1;
1441                                 istack[jstack-1] = l;
1442                                 l = i;
1443                         }
1444                 }
1445         }
1446 }
1447
1448 #else
1449
1450 /* 8 bit Radix sort + insertion sort
1451  * 
1452  * based on code from http://www.cubic.org/docs/radix.htm
1453  * with improvements by mbackes@symas.com and hyc@symas.com
1454  *
1455  * This code is O(n) but has a relatively high constant factor. For lists
1456  * up to ~50 Quicksort is slightly faster; up to ~100 they are even.
1457  * Much faster than quicksort for lists longer than ~100. Insertion
1458  * sort is actually superior for lists <50.
1459  */
1460
1461 #define BUCKETS (1<<8)
1462 #define SMALL   50
1463
1464 void
1465 bdb_idl_sort( ID *ids, ID *tmp )
1466 {
1467         int count, soft_limit, phase = 0, size = ids[0];
1468         ID *idls[2];
1469         unsigned char *maxv = (unsigned char *)&ids[size];
1470
1471         if ( BDB_IDL_IS_RANGE( ids ))
1472                 return;
1473
1474         /* Use insertion sort for small lists */
1475         if ( size <= SMALL ) {
1476                 int i,j;
1477                 ID a;
1478
1479                 for (j=1;j<=size;j++) {
1480                         a = ids[j];
1481                         for (i=j-1;i>=1;i--) {
1482                                 if (ids[i] <= a) break;
1483                                 ids[i+1] = ids[i];
1484                         }
1485                         ids[i+1] = a;
1486                 }
1487                 return;
1488         }
1489
1490         tmp[0] = size;
1491         idls[0] = ids;
1492         idls[1] = tmp;
1493
1494 #if BYTE_ORDER == BIG_ENDIAN
1495     for (soft_limit = 0; !maxv[soft_limit]; soft_limit++);
1496 #else
1497     for (soft_limit = sizeof(ID)-1; !maxv[soft_limit]; soft_limit--);
1498 #endif
1499
1500         for (
1501 #if BYTE_ORDER == BIG_ENDIAN
1502         count = sizeof(ID)-1; count >= soft_limit; --count
1503 #else
1504         count = 0; count <= soft_limit; ++count
1505 #endif
1506         ) {
1507                 unsigned int num[BUCKETS], * np, n, sum;
1508                 int i;
1509         ID *sp, *source, *dest;
1510         unsigned char *bp, *source_start;
1511
1512                 source = idls[phase]+1;
1513                 dest = idls[phase^1]+1;
1514                 source_start =  ((unsigned char *) source) + count;
1515
1516         np = num;
1517         for ( i = BUCKETS; i > 0; --i ) *np++ = 0;
1518
1519                 /* count occurences of every byte value */
1520                 bp = source_start;
1521         for ( i = size; i > 0; --i, bp += sizeof(ID) )
1522                                 num[*bp]++;
1523
1524                 /* transform count into index by summing elements and storing
1525                  * into same array
1526                  */
1527         sum = 0;
1528         np = num;
1529         for ( i = BUCKETS; i > 0; --i ) {
1530                 n = *np;
1531                 *np++ = sum;
1532                 sum += n;
1533         }
1534
1535                 /* fill dest with the right values in the right place */
1536                 bp = source_start;
1537         sp = source;
1538         for ( i = size; i > 0; --i, bp += sizeof(ID) ) {
1539                 np = num + *bp;
1540                 dest[*np] = *sp++;
1541                 ++(*np);
1542         }
1543                 phase ^= 1;
1544         }
1545
1546         /* copy back from temp if needed */
1547         if ( phase ) {
1548                 ids++; tmp++;
1549                 for ( count = 0; count < size; ++count ) 
1550                         *ids++ = *tmp++;
1551         }
1552 }
1553 #endif  /* Quick vs Radix */
1554
1555 #endif  /* BDB_HIER */