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