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