]> git.sur5r.net Git - openldap/blob - servers/slapd/back-bdb/cache.c
ITS#6111 connection_state_closing() -> connection_valid()
[openldap] / servers / slapd / back-bdb / cache.c
1 /* cache.c - routines to maintain an in-core cache of entries */
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
21 #include <ac/errno.h>
22 #include <ac/string.h>
23 #include <ac/socket.h>
24
25 #include "slap.h"
26
27 #include "back-bdb.h"
28
29 #include "ldap_rq.h"
30
31 #ifdef BDB_HIER
32 #define bdb_cache_lru_purge     hdb_cache_lru_purge
33 #endif
34 static void bdb_cache_lru_purge( struct bdb_info *bdb );
35
36 static int      bdb_cache_delete_internal(Cache *cache, EntryInfo *e, int decr);
37 #ifdef LDAP_DEBUG
38 #define SLAPD_UNUSED
39 #ifdef SLAPD_UNUSED
40 static void     bdb_lru_print(Cache *cache);
41 static void     bdb_idtree_print(Cache *cache);
42 #endif
43 #endif
44
45 /* For concurrency experiments only! */
46 #if 0
47 #define ldap_pvt_thread_rdwr_wlock(a)   0
48 #define ldap_pvt_thread_rdwr_wunlock(a) 0
49 #define ldap_pvt_thread_rdwr_rlock(a)   0
50 #define ldap_pvt_thread_rdwr_runlock(a) 0
51 #endif
52
53 #if 0
54 #define ldap_pvt_thread_mutex_trylock(a) 0
55 #endif
56
57 static EntryInfo *
58 bdb_cache_entryinfo_new( Cache *cache )
59 {
60         EntryInfo *ei = NULL;
61
62         if ( cache->c_eifree ) {
63                 ldap_pvt_thread_mutex_lock( &cache->c_eifree_mutex );
64                 if ( cache->c_eifree ) {
65                         ei = cache->c_eifree;
66                         cache->c_eifree = ei->bei_lrunext;
67                         ei->bei_finders = 0;
68                         ei->bei_lrunext = NULL;
69                 }
70                 ldap_pvt_thread_mutex_unlock( &cache->c_eifree_mutex );
71         }
72         if ( !ei ) {
73                 ei = ch_calloc(1, sizeof(EntryInfo));
74                 ldap_pvt_thread_mutex_init( &ei->bei_kids_mutex );
75         }
76
77         ei->bei_state = CACHE_ENTRY_REFERENCED;
78
79         return ei;
80 }
81
82 static void
83 bdb_cache_entryinfo_free( Cache *cache, EntryInfo *ei )
84 {
85         free( ei->bei_nrdn.bv_val );
86         BER_BVZERO( &ei->bei_nrdn );
87 #ifdef BDB_HIER
88         free( ei->bei_rdn.bv_val );
89         BER_BVZERO( &ei->bei_rdn );
90         ei->bei_modrdns = 0;
91         ei->bei_ckids = 0;
92         ei->bei_dkids = 0;
93 #endif
94         ei->bei_parent = NULL;
95         ei->bei_kids = NULL;
96         ei->bei_lruprev = NULL;
97
98 #if 0
99         ldap_pvt_thread_mutex_lock( &cache->c_eifree_mutex );
100         ei->bei_lrunext = cache->c_eifree;
101         cache->c_eifree = ei;
102         ldap_pvt_thread_mutex_unlock( &cache->c_eifree_mutex );
103 #else
104         ch_free( ei );
105 #endif
106 }
107
108 #define LRU_DEL( c, e ) do { \
109         if ( e == (c)->c_lruhead ) (c)->c_lruhead = e->bei_lruprev; \
110         if ( e == (c)->c_lrutail ) (c)->c_lrutail = e->bei_lruprev; \
111         e->bei_lrunext->bei_lruprev = e->bei_lruprev; \
112         e->bei_lruprev->bei_lrunext = e->bei_lrunext; \
113         e->bei_lruprev = NULL; \
114 } while ( 0 )
115
116 /* Note - we now use a Second-Chance / Clock algorithm instead of
117  * Least-Recently-Used. This tremendously improves concurrency
118  * because we no longer need to manipulate the lists every time an
119  * entry is touched. We only need to lock the lists when adding
120  * or deleting an entry. It's now a circular doubly-linked list.
121  * We always append to the tail, but the head traverses the circle
122  * during a purge operation.
123  */
124 static void
125 bdb_cache_lru_link( struct bdb_info *bdb, EntryInfo *ei )
126 {
127
128         /* Already linked, ignore */
129         if ( ei->bei_lruprev )
130                 return;
131
132         /* Insert into circular LRU list */
133         ldap_pvt_thread_mutex_lock( &bdb->bi_cache.c_lru_mutex );
134
135         ei->bei_lruprev = bdb->bi_cache.c_lrutail;
136         if ( bdb->bi_cache.c_lrutail ) {
137                 ei->bei_lrunext = bdb->bi_cache.c_lrutail->bei_lrunext;
138                 bdb->bi_cache.c_lrutail->bei_lrunext = ei;
139                 if ( ei->bei_lrunext )
140                         ei->bei_lrunext->bei_lruprev = ei;
141         } else {
142                 ei->bei_lrunext = ei->bei_lruprev = ei;
143                 bdb->bi_cache.c_lruhead = ei;
144         }
145         bdb->bi_cache.c_lrutail = ei;
146         ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_lru_mutex );
147 }
148
149 #ifdef NO_THREADS
150 #define NO_DB_LOCK
151 #endif
152
153 /* #define NO_DB_LOCK 1 */
154 /* Note: The BerkeleyDB locks are much slower than regular
155  * mutexes or rdwr locks. But the BDB implementation has the
156  * advantage of using a fixed size lock table, instead of
157  * allocating a lock object per entry in the DB. That's a
158  * key benefit for scaling. It also frees us from worrying
159  * about undetectable deadlocks between BDB activity and our
160  * own cache activity. It's still worth exploring faster
161  * alternatives though.
162  */
163
164 /* Atomically release and reacquire a lock */
165 int
166 bdb_cache_entry_db_relock(
167         struct bdb_info *bdb,
168         DB_TXN *txn,
169         EntryInfo *ei,
170         int rw,
171         int tryOnly,
172         DB_LOCK *lock )
173 {
174 #ifdef NO_DB_LOCK
175         return 0;
176 #else
177         int     rc;
178         DBT     lockobj;
179         DB_LOCKREQ list[2];
180
181         if ( !lock ) return 0;
182
183         lockobj.data = &ei->bei_id;
184         lockobj.size = sizeof(ei->bei_id) + 1;
185
186         list[0].op = DB_LOCK_PUT;
187         list[0].lock = *lock;
188         list[1].op = DB_LOCK_GET;
189         list[1].lock = *lock;
190         list[1].mode = rw ? DB_LOCK_WRITE : DB_LOCK_READ;
191         list[1].obj = &lockobj;
192         rc = bdb->bi_dbenv->lock_vec(bdb->bi_dbenv, TXN_ID(txn), tryOnly ? DB_LOCK_NOWAIT : 0,
193                 list, 2, NULL );
194
195         if (rc && !tryOnly) {
196                 Debug( LDAP_DEBUG_TRACE,
197                         "bdb_cache_entry_db_relock: entry %ld, rw %d, rc %d\n",
198                         ei->bei_id, rw, rc );
199         } else {
200                 *lock = list[1].lock;
201         }
202         return rc;
203 #endif
204 }
205
206 static int
207 bdb_cache_entry_db_lock( struct bdb_info *bdb, DB_TXN *txn, EntryInfo *ei,
208         int rw, int tryOnly, DB_LOCK *lock )
209 {
210 #ifdef NO_DB_LOCK
211         return 0;
212 #else
213         int       rc;
214         DBT       lockobj;
215         int       db_rw;
216
217         if ( !lock ) return 0;
218
219         if (rw)
220                 db_rw = DB_LOCK_WRITE;
221         else
222                 db_rw = DB_LOCK_READ;
223
224         lockobj.data = &ei->bei_id;
225         lockobj.size = sizeof(ei->bei_id) + 1;
226
227         rc = LOCK_GET(bdb->bi_dbenv, TXN_ID(txn), tryOnly ? DB_LOCK_NOWAIT : 0,
228                                         &lockobj, db_rw, lock);
229         if (rc && !tryOnly) {
230                 Debug( LDAP_DEBUG_TRACE,
231                         "bdb_cache_entry_db_lock: entry %ld, rw %d, rc %d\n",
232                         ei->bei_id, rw, rc );
233         }
234         return rc;
235 #endif /* NO_DB_LOCK */
236 }
237
238 int
239 bdb_cache_entry_db_unlock ( struct bdb_info *bdb, DB_LOCK *lock )
240 {
241 #ifdef NO_DB_LOCK
242         return 0;
243 #else
244         int rc;
245
246         if ( !lock || lock->mode == DB_LOCK_NG ) return 0;
247
248         rc = LOCK_PUT ( bdb->bi_dbenv, lock );
249         return rc;
250 #endif
251 }
252
253 void
254 bdb_cache_return_entry_rw( struct bdb_info *bdb, Entry *e,
255         int rw, DB_LOCK *lock )
256 {
257         EntryInfo *ei;
258         int free = 0;
259
260         ei = e->e_private;
261         if ( ei &&
262                 ( ei->bei_state & CACHE_ENTRY_NOT_CACHED ) &&
263                 ( bdb_cache_entryinfo_trylock( ei ) == 0 )) {
264                 if ( ei->bei_state & CACHE_ENTRY_NOT_CACHED ) {
265                         /* Releasing the entry can only be done when
266                          * we know that nobody else is using it, i.e we
267                          * should have an entry_db writelock.  But the
268                          * flag is only set by the thread that loads the
269                          * entry, and only if no other threads has found
270                          * it while it was working.  All other threads
271                          * clear the flag, which mean that we should be
272                          * the only thread using the entry if the flag
273                          * is set here.
274                          */
275                         ei->bei_e = NULL;
276                         ei->bei_state ^= CACHE_ENTRY_NOT_CACHED;
277                         free = 1;
278                 }
279                 bdb_cache_entryinfo_unlock( ei );
280         }
281         bdb_cache_entry_db_unlock( bdb, lock );
282         if ( free ) {
283                 e->e_private = NULL;
284                 bdb_entry_return( e );
285         }
286 }
287
288 static int
289 bdb_cache_entryinfo_destroy( EntryInfo *e )
290 {
291         ldap_pvt_thread_mutex_destroy( &e->bei_kids_mutex );
292         free( e->bei_nrdn.bv_val );
293 #ifdef BDB_HIER
294         free( e->bei_rdn.bv_val );
295 #endif
296         free( e );
297         return 0;
298 }
299
300 /* Do a length-ordered sort on normalized RDNs */
301 static int
302 bdb_rdn_cmp( const void *v_e1, const void *v_e2 )
303 {
304         const EntryInfo *e1 = v_e1, *e2 = v_e2;
305         int rc = e1->bei_nrdn.bv_len - e2->bei_nrdn.bv_len;
306         if (rc == 0) {
307                 rc = strncmp( e1->bei_nrdn.bv_val, e2->bei_nrdn.bv_val,
308                         e1->bei_nrdn.bv_len );
309         }
310         return rc;
311 }
312
313 static int
314 bdb_id_cmp( const void *v_e1, const void *v_e2 )
315 {
316         const EntryInfo *e1 = v_e1, *e2 = v_e2;
317         return e1->bei_id - e2->bei_id;
318 }
319
320 static int
321 bdb_id_dup_err( void *v1, void *v2 )
322 {
323         EntryInfo *e2 = v2;
324         e2->bei_lrunext = v1;
325         return -1;
326 }
327
328 /* Create an entryinfo in the cache. Caller must release the locks later.
329  */
330 static int
331 bdb_entryinfo_add_internal(
332         struct bdb_info *bdb,
333         EntryInfo *ei,
334         EntryInfo **res )
335 {
336         EntryInfo *ei2 = NULL;
337
338         *res = NULL;
339
340         ei2 = bdb_cache_entryinfo_new( &bdb->bi_cache );
341
342         bdb_cache_entryinfo_lock( ei->bei_parent );
343         ldap_pvt_thread_rdwr_wlock( &bdb->bi_cache.c_rwlock );
344
345         ei2->bei_id = ei->bei_id;
346         ei2->bei_parent = ei->bei_parent;
347 #ifdef BDB_HIER
348         ei2->bei_rdn = ei->bei_rdn;
349 #endif
350 #ifdef SLAP_ZONE_ALLOC
351         ei2->bei_bdb = bdb;
352 #endif
353
354         /* Add to cache ID tree */
355         if (avl_insert( &bdb->bi_cache.c_idtree, ei2, bdb_id_cmp,
356                 bdb_id_dup_err )) {
357                 EntryInfo *eix = ei2->bei_lrunext;
358                 bdb_cache_entryinfo_free( &bdb->bi_cache, ei2 );
359                 ei2 = eix;
360 #ifdef BDB_HIER
361                 /* It got freed above because its value was
362                  * assigned to ei2.
363                  */
364                 ei->bei_rdn.bv_val = NULL;
365 #endif
366         } else {
367                 int rc;
368
369                 bdb->bi_cache.c_eiused++;
370                 ber_dupbv( &ei2->bei_nrdn, &ei->bei_nrdn );
371
372                 /* This is a new leaf node. But if parent had no kids, then it was
373                  * a leaf and we would be decrementing that. So, only increment if
374                  * the parent already has kids.
375                  */
376                 if ( ei->bei_parent->bei_kids || !ei->bei_parent->bei_id )
377                         bdb->bi_cache.c_leaves++;
378                 rc = avl_insert( &ei->bei_parent->bei_kids, ei2, bdb_rdn_cmp,
379                         avl_dup_error );
380 #ifdef BDB_HIER
381                 /* it's possible for hdb_cache_find_parent to beat us to it */
382                 if ( !rc ) {
383                         ei->bei_parent->bei_ckids++;
384                 }
385 #endif
386         }
387
388         *res = ei2;
389         return 0;
390 }
391
392 /* Find the EntryInfo for the requested DN. If the DN cannot be found, return
393  * the info for its closest ancestor. *res should be NULL to process a
394  * complete DN starting from the tree root. Otherwise *res must be the
395  * immediate parent of the requested DN, and only the RDN will be searched.
396  * The EntryInfo is locked upon return and must be unlocked by the caller.
397  */
398 int
399 bdb_cache_find_ndn(
400         Operation       *op,
401         DB_TXN          *txn,
402         struct berval   *ndn,
403         EntryInfo       **res )
404 {
405         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
406         EntryInfo       ei, *eip, *ei2;
407         int rc = 0;
408         char *ptr;
409
410         /* this function is always called with normalized DN */
411         if ( *res ) {
412                 /* we're doing a onelevel search for an RDN */
413                 ei.bei_nrdn.bv_val = ndn->bv_val;
414                 ei.bei_nrdn.bv_len = dn_rdnlen( op->o_bd, ndn );
415                 eip = *res;
416         } else {
417                 /* we're searching a full DN from the root */
418                 ptr = ndn->bv_val + ndn->bv_len - op->o_bd->be_nsuffix[0].bv_len;
419                 ei.bei_nrdn.bv_val = ptr;
420                 ei.bei_nrdn.bv_len = op->o_bd->be_nsuffix[0].bv_len;
421                 /* Skip to next rdn if suffix is empty */
422                 if ( ei.bei_nrdn.bv_len == 0 ) {
423                         for (ptr = ei.bei_nrdn.bv_val - 2; ptr > ndn->bv_val
424                                 && !DN_SEPARATOR(*ptr); ptr--) /* empty */;
425                         if ( ptr >= ndn->bv_val ) {
426                                 if (DN_SEPARATOR(*ptr)) ptr++;
427                                 ei.bei_nrdn.bv_len = ei.bei_nrdn.bv_val - ptr;
428                                 ei.bei_nrdn.bv_val = ptr;
429                         }
430                 }
431                 eip = &bdb->bi_cache.c_dntree;
432         }
433         
434         for ( bdb_cache_entryinfo_lock( eip ); eip; ) {
435                 eip->bei_state |= CACHE_ENTRY_REFERENCED;
436                 ei.bei_parent = eip;
437                 ei2 = (EntryInfo *)avl_find( eip->bei_kids, &ei, bdb_rdn_cmp );
438                 if ( !ei2 ) {
439                         DB_LOCK lock;
440                         int len = ei.bei_nrdn.bv_len;
441                                 
442                         if ( BER_BVISEMPTY( ndn )) {
443                                 *res = eip;
444                                 return LDAP_SUCCESS;
445                         }
446
447                         ei.bei_nrdn.bv_len = ndn->bv_len -
448                                 (ei.bei_nrdn.bv_val - ndn->bv_val);
449                         eip->bei_finders++;
450                         bdb_cache_entryinfo_unlock( eip );
451
452                         BDB_LOG_PRINTF( bdb->bi_dbenv, NULL, "slapd Reading %s",
453                                 ei.bei_nrdn.bv_val );
454
455                         lock.mode = DB_LOCK_NG;
456                         rc = bdb_dn2id( op, &ei.bei_nrdn, &ei, txn, &lock );
457                         if (rc) {
458                                 bdb_cache_entryinfo_lock( eip );
459                                 eip->bei_finders--;
460                                 bdb_cache_entry_db_unlock( bdb, &lock );
461                                 *res = eip;
462                                 return rc;
463                         }
464
465                         BDB_LOG_PRINTF( bdb->bi_dbenv, NULL, "slapd Read got %s(%d)",
466                                 ei.bei_nrdn.bv_val, ei.bei_id );
467
468                         /* DN exists but needs to be added to cache */
469                         ei.bei_nrdn.bv_len = len;
470                         rc = bdb_entryinfo_add_internal( bdb, &ei, &ei2 );
471                         /* add_internal left eip and c_rwlock locked */
472                         eip->bei_finders--;
473                         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
474                         bdb_cache_entry_db_unlock( bdb, &lock );
475                         if ( rc ) {
476                                 *res = eip;
477                                 return rc;
478                         }
479                 } else if ( ei2->bei_state & CACHE_ENTRY_DELETED ) {
480                         /* In the midst of deleting? Give it a chance to
481                          * complete.
482                          */
483                         bdb_cache_entryinfo_unlock( eip );
484                         ldap_pvt_thread_yield();
485                         bdb_cache_entryinfo_lock( eip );
486                         *res = eip;
487                         return DB_NOTFOUND;
488                 }
489                 bdb_cache_entryinfo_lock( ei2 );
490                 bdb_cache_entryinfo_unlock( eip );
491
492                 eip = ei2;
493
494                 /* Advance to next lower RDN */
495                 for (ptr = ei.bei_nrdn.bv_val - 2; ptr > ndn->bv_val
496                         && !DN_SEPARATOR(*ptr); ptr--) /* empty */;
497                 if ( ptr >= ndn->bv_val ) {
498                         if (DN_SEPARATOR(*ptr)) ptr++;
499                         ei.bei_nrdn.bv_len = ei.bei_nrdn.bv_val - ptr - 1;
500                         ei.bei_nrdn.bv_val = ptr;
501                 }
502                 if ( ptr < ndn->bv_val ) {
503                         *res = eip;
504                         break;
505                 }
506         }
507
508         return rc;
509 }
510
511 #ifdef BDB_HIER
512 /* Walk up the tree from a child node, looking for an ID that's already
513  * been linked into the cache.
514  */
515 int
516 hdb_cache_find_parent(
517         Operation *op,
518         DB_TXN  *txn,
519         ID id,
520         EntryInfo **res )
521 {
522         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
523         EntryInfo ei, eip, *ei2 = NULL, *ein = NULL, *eir = NULL;
524         int rc, add;
525
526         ei.bei_id = id;
527         ei.bei_kids = NULL;
528         ei.bei_ckids = 0;
529
530         for (;;) {
531                 rc = hdb_dn2id_parent( op, txn, &ei, &eip.bei_id );
532                 if ( rc ) break;
533
534                 /* Save the previous node, if any */
535                 ei2 = ein;
536
537                 /* Create a new node for the current ID */
538                 ein = bdb_cache_entryinfo_new( &bdb->bi_cache );
539                 ein->bei_id = ei.bei_id;
540                 ein->bei_kids = ei.bei_kids;
541                 ein->bei_nrdn = ei.bei_nrdn;
542                 ein->bei_rdn = ei.bei_rdn;
543                 ein->bei_ckids = ei.bei_ckids;
544 #ifdef SLAP_ZONE_ALLOC
545                 ein->bei_bdb = bdb;
546 #endif
547                 ei.bei_ckids = 0;
548                 add = 1;
549                 
550                 /* This node is not fully connected yet */
551                 ein->bei_state |= CACHE_ENTRY_NOT_LINKED;
552
553                 /* If this is the first time, save this node
554                  * to be returned later.
555                  */
556                 if ( eir == NULL ) {
557                         eir = ein;
558                         ein->bei_finders++;
559                 }
560
561 again:
562                 /* Insert this node into the ID tree */
563                 ldap_pvt_thread_rdwr_wlock( &bdb->bi_cache.c_rwlock );
564                 if ( avl_insert( &bdb->bi_cache.c_idtree, (caddr_t)ein,
565                         bdb_id_cmp, bdb_id_dup_err ) ) {
566                         EntryInfo *eix = ein->bei_lrunext;
567
568                         if ( bdb_cache_entryinfo_trylock( eix )) {
569                                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
570                                 ldap_pvt_thread_yield();
571                                 goto again;
572                         }
573                         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
574
575                         /* Someone else created this node just before us.
576                          * Free our new copy and use the existing one.
577                          */
578                         bdb_cache_entryinfo_free( &bdb->bi_cache, ein );
579
580                         /* if it was the node we were looking for, just return it */
581                         if ( eir == ein ) {
582                                 *res = eix;
583                                 rc = 0;
584                                 break;
585                         }
586
587                         ein = ei2;
588                         ei2 = eix;
589                         add = 0;
590
591                         /* otherwise, link up what we have and return */
592                         goto gotparent;
593                 }
594
595                 /* If there was a previous node, link it to this one */
596                 if ( ei2 ) ei2->bei_parent = ein;
597
598                 /* Look for this node's parent */
599 par2:
600                 if ( eip.bei_id ) {
601                         ei2 = (EntryInfo *) avl_find( bdb->bi_cache.c_idtree,
602                                         (caddr_t) &eip, bdb_id_cmp );
603                 } else {
604                         ei2 = &bdb->bi_cache.c_dntree;
605                 }
606                 if ( ei2 && bdb_cache_entryinfo_trylock( ei2 )) {
607                         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
608                         ldap_pvt_thread_yield();
609                         ldap_pvt_thread_rdwr_wlock( &bdb->bi_cache.c_rwlock );
610                         goto par2;
611                 }
612                 if ( add )
613                         bdb->bi_cache.c_eiused++;
614                 if ( ei2 && ( ei2->bei_kids || !ei2->bei_id ))
615                         bdb->bi_cache.c_leaves++;
616                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
617
618 gotparent:
619                 /* Got the parent, link in and we're done. */
620                 if ( ei2 ) {
621                         bdb_cache_entryinfo_lock( eir );
622                         ein->bei_parent = ei2;
623
624                         if ( avl_insert( &ei2->bei_kids, (caddr_t)ein, bdb_rdn_cmp,
625                                 avl_dup_error) == 0 )
626                                 ei2->bei_ckids++;
627
628                         /* Reset all the state info */
629                         for (ein = eir; ein != ei2; ein=ein->bei_parent)
630                                 ein->bei_state &= ~CACHE_ENTRY_NOT_LINKED;
631
632                         bdb_cache_entryinfo_unlock( ei2 );
633                         eir->bei_finders--;
634
635                         *res = eir;
636                         break;
637                 }
638                 ei.bei_kids = NULL;
639                 ei.bei_id = eip.bei_id;
640                 ei.bei_ckids = 1;
641                 avl_insert( &ei.bei_kids, (caddr_t)ein, bdb_rdn_cmp,
642                         avl_dup_error );
643         }
644         return rc;
645 }
646
647 /* Used by hdb_dn2idl when loading the EntryInfo for all the children
648  * of a given node
649  */
650 int hdb_cache_load(
651         struct bdb_info *bdb,
652         EntryInfo *ei,
653         EntryInfo **res )
654 {
655         EntryInfo *ei2;
656         int rc;
657
658         /* See if we already have this one */
659         bdb_cache_entryinfo_lock( ei->bei_parent );
660         ei2 = (EntryInfo *)avl_find( ei->bei_parent->bei_kids, ei, bdb_rdn_cmp );
661         bdb_cache_entryinfo_unlock( ei->bei_parent );
662
663         if ( !ei2 ) {
664                 /* Not found, add it */
665                 struct berval bv;
666
667                 /* bei_rdn was not malloc'd before, do it now */
668                 ber_dupbv( &bv, &ei->bei_rdn );
669                 ei->bei_rdn = bv;
670
671                 rc = bdb_entryinfo_add_internal( bdb, ei, res );
672                 bdb_cache_entryinfo_unlock( ei->bei_parent );
673                 ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
674         } else {
675                 /* Found, return it */
676                 *res = ei2;
677                 return 0;
678         }
679         return rc;
680 }
681 #endif
682
683 /* This is best-effort only. If all entries in the cache are
684  * busy, they will all be kept. This is unlikely to happen
685  * unless the cache is very much smaller than the working set.
686  */
687 static void
688 bdb_cache_lru_purge( struct bdb_info *bdb )
689 {
690         DB_LOCK         lock, *lockp;
691         EntryInfo *elru, *elnext = NULL;
692         int count, islocked, eimax;
693         int efree = 0, eifree = 0, eicount, ecount;
694 #ifdef LDAP_DEBUG
695         int iter;
696 #endif
697
698         /* Wait for the mutex; we're the only one trying to purge. */
699         ldap_pvt_thread_mutex_lock( &bdb->bi_cache.c_lru_mutex );
700
701         /* maximum number of EntryInfo leaves to cache. In slapcat
702          * we always free all leaf nodes.
703          */
704         if ( slapMode & SLAP_TOOL_READONLY )
705                 eimax = 0;
706         else
707                 eimax = bdb->bi_cache.c_eimax;
708
709         efree = bdb->bi_cache.c_cursize - bdb->bi_cache.c_maxsize;
710         if ( efree < 1 )
711                 efree = 0;
712         else 
713                 efree += bdb->bi_cache.c_minfree;
714
715         if ( bdb->bi_cache.c_leaves > eimax ) {
716                 eifree = bdb->bi_cache.c_minfree * 10;
717                 if ( eifree >= eimax )
718                         eifree = eimax / 2;
719         }
720
721         if ( !efree && !eifree ) {
722                 ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_lru_mutex );
723                 bdb->bi_cache.c_purging = 0;
724                 return;
725         }
726
727         if ( bdb->bi_cache.c_txn ) {
728                 lockp = &lock;
729         } else {
730                 lockp = NULL;
731         }
732
733         count = 0;
734         eicount = 0;
735         ecount = 0;
736 #ifdef LDAP_DEBUG
737         iter = 0;
738 #endif
739
740         /* Look for an unused entry to remove */
741         for ( elru = bdb->bi_cache.c_lruhead; elru; elru = elnext ) {
742                 elnext = elru->bei_lrunext;
743
744                 if ( bdb_cache_entryinfo_trylock( elru ))
745                         goto bottom;
746
747                 /* This flag implements the clock replacement behavior */
748                 if ( elru->bei_state & ( CACHE_ENTRY_REFERENCED )) {
749                         elru->bei_state &= ~CACHE_ENTRY_REFERENCED;
750                         bdb_cache_entryinfo_unlock( elru );
751                         goto bottom;
752                 }
753
754                 /* If this node is in the process of linking into the cache,
755                  * or this node is being deleted, skip it.
756                  */
757                 if (( elru->bei_state & ( CACHE_ENTRY_NOT_LINKED |
758                         CACHE_ENTRY_DELETED | CACHE_ENTRY_LOADING |
759                         CACHE_ENTRY_ONELEVEL )) ||
760                         elru->bei_finders > 0 ) {
761                         bdb_cache_entryinfo_unlock( elru );
762                         goto bottom;
763                 }
764
765                 if ( bdb_cache_entryinfo_trylock( elru->bei_parent )) {
766                         bdb_cache_entryinfo_unlock( elru );
767                         goto bottom;
768                 }
769
770                 /* entryinfo is locked */
771                 islocked = 1;
772
773                 /* If we can successfully writelock it, then
774                  * the object is idle.
775                  */
776                 if ( bdb_cache_entry_db_lock( bdb,
777                         bdb->bi_cache.c_txn, elru, 1, 1, lockp ) == 0 ) {
778
779                         /* Free entry for this node if it's present */
780                         if ( elru->bei_e ) {
781                                 ecount++;
782
783                                 /* the cache may have gone over the limit while we
784                                  * weren't looking, so double check.
785                                  */
786                                 if ( !efree && ecount > bdb->bi_cache.c_maxsize )
787                                         efree = bdb->bi_cache.c_minfree;
788
789                                 if ( count < efree ) {
790                                         elru->bei_e->e_private = NULL;
791 #ifdef SLAP_ZONE_ALLOC
792                                         bdb_entry_return( bdb, elru->bei_e, elru->bei_zseq );
793 #else
794                                         bdb_entry_return( elru->bei_e );
795 #endif
796                                         elru->bei_e = NULL;
797                                         count++;
798                                 } else {
799                                         /* Keep this node cached, skip to next */
800                                         bdb_cache_entry_db_unlock( bdb, lockp );
801                                         goto next;
802                                 }
803                         }
804                         bdb_cache_entry_db_unlock( bdb, lockp );
805
806                         /* 
807                          * If it is a leaf node, and we're over the limit, free it.
808                          */
809                         if ( elru->bei_kids ) {
810                                 /* Drop from list, we ignore it... */
811                                 LRU_DEL( &bdb->bi_cache, elru );
812                         } else if ( eicount < eifree ) {
813                                 /* Too many leaf nodes, free this one */
814                                 bdb_cache_delete_internal( &bdb->bi_cache, elru, 0 );
815                                 bdb_cache_delete_cleanup( &bdb->bi_cache, elru );
816                                 islocked = 0;
817                                 eicount++;
818                         }       /* Leave on list until we need to free it */
819                 }
820
821 next:
822                 if ( islocked ) {
823                         bdb_cache_entryinfo_unlock( elru );
824                         bdb_cache_entryinfo_unlock( elru->bei_parent );
825                 }
826
827                 if ( count >= efree && eicount >= eifree )
828                         break;
829 bottom:
830                 if ( elnext == bdb->bi_cache.c_lruhead )
831                         break;
832 #ifdef LDAP_DEBUG
833                 iter++;
834 #endif
835         }
836
837         if ( count || ecount > bdb->bi_cache.c_cursize ) {
838                 ldap_pvt_thread_mutex_lock( &bdb->bi_cache.c_count_mutex );
839                 /* HACK: we seem to be losing track, fix up now */
840                 if ( ecount > bdb->bi_cache.c_cursize )
841                         bdb->bi_cache.c_cursize = ecount;
842                 bdb->bi_cache.c_cursize -= count;
843                 ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_count_mutex );
844         }
845         bdb->bi_cache.c_lruhead = elnext;
846         ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_lru_mutex );
847         bdb->bi_cache.c_purging = 0;
848 }
849
850 /*
851  * cache_find_id - find an entry in the cache, given id.
852  * The entry is locked for Read upon return. Call with flag ID_LOCKED if
853  * the supplied *eip was already locked.
854  */
855
856 int
857 bdb_cache_find_id(
858         Operation *op,
859         DB_TXN  *tid,
860         ID                              id,
861         EntryInfo       **eip,
862         int             flag,
863         DB_LOCK         *lock )
864 {
865         struct bdb_info *bdb = (struct bdb_info *) op->o_bd->be_private;
866         Entry   *ep = NULL;
867         int     rc = 0, load = 0;
868         EntryInfo ei = { 0 };
869
870         ei.bei_id = id;
871
872 #ifdef SLAP_ZONE_ALLOC
873         slap_zh_rlock(bdb->bi_cache.c_zctx);
874 #endif
875         /* If we weren't given any info, see if we have it already cached */
876         if ( !*eip ) {
877 again:  ldap_pvt_thread_rdwr_rlock( &bdb->bi_cache.c_rwlock );
878                 *eip = (EntryInfo *) avl_find( bdb->bi_cache.c_idtree,
879                         (caddr_t) &ei, bdb_id_cmp );
880                 if ( *eip ) {
881                         /* If the lock attempt fails, the info is in use */
882                         if ( bdb_cache_entryinfo_trylock( *eip )) {
883                                 int del = (*eip)->bei_state & CACHE_ENTRY_DELETED;
884                                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_cache.c_rwlock );
885                                 /* If this node is being deleted, treat
886                                  * as if the delete has already finished
887                                  */
888                                 if ( del ) {
889                                         return DB_NOTFOUND;
890                                 }
891                                 /* otherwise, wait for the info to free up */
892                                 ldap_pvt_thread_yield();
893                                 goto again;
894                         }
895                         /* If this info isn't hooked up to its parent yet,
896                          * unlock and wait for it to be fully initialized
897                          */
898                         if ( (*eip)->bei_state & CACHE_ENTRY_NOT_LINKED ) {
899                                 bdb_cache_entryinfo_unlock( *eip );
900                                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_cache.c_rwlock );
901                                 ldap_pvt_thread_yield();
902                                 goto again;
903                         }
904                         flag |= ID_LOCKED;
905                 }
906                 ldap_pvt_thread_rdwr_runlock( &bdb->bi_cache.c_rwlock );
907         }
908
909         /* See if the ID exists in the database; add it to the cache if so */
910         if ( !*eip ) {
911 #ifndef BDB_HIER
912                 rc = bdb_id2entry( op->o_bd, tid, id, &ep );
913                 if ( rc == 0 ) {
914                         rc = bdb_cache_find_ndn( op, tid,
915                                 &ep->e_nname, eip );
916                         if ( *eip ) flag |= ID_LOCKED;
917                         if ( rc ) {
918                                 ep->e_private = NULL;
919 #ifdef SLAP_ZONE_ALLOC
920                                 bdb_entry_return( bdb, ep, (*eip)->bei_zseq );
921 #else
922                                 bdb_entry_return( ep );
923 #endif
924                                 ep = NULL;
925                         }
926                 }
927 #else
928                 rc = hdb_cache_find_parent(op, tid, id, eip );
929                 if ( rc == 0 ) flag |= ID_LOCKED;
930 #endif
931         }
932
933         /* Ok, we found the info, do we have the entry? */
934         if ( rc == 0 ) {
935                 if ( !( flag & ID_LOCKED )) {
936                         bdb_cache_entryinfo_lock( *eip );
937                         flag |= ID_LOCKED;
938                 }
939
940                 if ( (*eip)->bei_state & CACHE_ENTRY_DELETED ) {
941                         rc = DB_NOTFOUND;
942                 } else {
943                         (*eip)->bei_finders++;
944                         (*eip)->bei_state |= CACHE_ENTRY_REFERENCED;
945                         if ( flag & ID_NOENTRY ) {
946                                 bdb_cache_entryinfo_unlock( *eip );
947                                 return 0;
948                         }
949                         /* Make sure only one thread tries to load the entry */
950 load1:
951 #ifdef SLAP_ZONE_ALLOC
952                         if ((*eip)->bei_e && !slap_zn_validate(
953                                         bdb->bi_cache.c_zctx, (*eip)->bei_e, (*eip)->bei_zseq)) {
954                                 (*eip)->bei_e = NULL;
955                                 (*eip)->bei_zseq = 0;
956                         }
957 #endif
958                         if ( !(*eip)->bei_e && !((*eip)->bei_state & CACHE_ENTRY_LOADING)) {
959                                 load = 1;
960                                 (*eip)->bei_state |= CACHE_ENTRY_LOADING;
961                         }
962
963                         if ( !load ) {
964                                 /* Clear the uncached state if we are not
965                                  * loading it, i.e it is already cached or
966                                  * another thread is currently loading it.
967                                  */
968                                 if ( (*eip)->bei_state & CACHE_ENTRY_NOT_CACHED ) {
969                                         (*eip)->bei_state &= ~CACHE_ENTRY_NOT_CACHED;
970                                 }
971                                 flag &= ~ID_NOCACHE;
972                         }
973
974                         if ( flag & ID_LOCKED ) {
975                                 bdb_cache_entryinfo_unlock( *eip );
976                                 flag ^= ID_LOCKED;
977                         }
978                         rc = bdb_cache_entry_db_lock( bdb, tid, *eip, load, 0, lock );
979                         if ( (*eip)->bei_state & CACHE_ENTRY_DELETED ) {
980                                 rc = DB_NOTFOUND;
981                                 bdb_cache_entry_db_unlock( bdb, lock );
982                         } else if ( rc == 0 ) {
983                                 if ( load ) {
984                                         if ( !ep) {
985                                                 rc = bdb_id2entry( op->o_bd, tid, id, &ep );
986                                         }
987                                         if ( rc == 0 ) {
988                                                 ep->e_private = *eip;
989 #ifdef BDB_HIER
990                                                 while ( (*eip)->bei_state & CACHE_ENTRY_NOT_LINKED )
991                                                         ldap_pvt_thread_yield();
992                                                 bdb_fix_dn( ep, 0 );
993 #endif
994                                                 (*eip)->bei_e = ep;
995 #ifdef SLAP_ZONE_ALLOC
996                                                 (*eip)->bei_zseq = *((ber_len_t *)ep - 2);
997 #endif
998                                                 ep = NULL;
999                                                 bdb_cache_lru_link( bdb, *eip );
1000                                                 if (( flag & ID_NOCACHE ) &&
1001                                                         ( bdb_cache_entryinfo_trylock( *eip ) == 0 )) {
1002                                                         /* Set the cached state only if no other thread
1003                                                          * found the info while we were loading the entry.
1004                                                          */
1005                                                         if ( (*eip)->bei_finders == 1 )
1006                                                                 (*eip)->bei_state |= CACHE_ENTRY_NOT_CACHED;
1007                                                         bdb_cache_entryinfo_unlock( *eip );
1008                                                 }
1009                                         }
1010                                         if ( rc == 0 ) {
1011                                                 /* If we succeeded, downgrade back to a readlock. */
1012                                                 rc = bdb_cache_entry_db_relock( bdb, tid,
1013                                                         *eip, 0, 0, lock );
1014                                         } else {
1015                                                 /* Otherwise, release the lock. */
1016                                                 bdb_cache_entry_db_unlock( bdb, lock );
1017                                         }
1018                                 } else if ( !(*eip)->bei_e ) {
1019                                         /* Some other thread is trying to load the entry,
1020                                          * wait for it to finish.
1021                                          */
1022                                         bdb_cache_entry_db_unlock( bdb, lock );
1023                                         bdb_cache_entryinfo_lock( *eip );
1024                                         flag |= ID_LOCKED;
1025                                         goto load1;
1026 #ifdef BDB_HIER
1027                                 } else {
1028                                         /* Check for subtree renames
1029                                          */
1030                                         rc = bdb_fix_dn( (*eip)->bei_e, 1 );
1031                                         if ( rc ) {
1032                                                 bdb_cache_entry_db_relock( bdb,
1033                                                         tid, *eip, 1, 0, lock );
1034                                                 /* check again in case other modifier did it already */
1035                                                 if ( bdb_fix_dn( (*eip)->bei_e, 1 ) )
1036                                                         rc = bdb_fix_dn( (*eip)->bei_e, 2 );
1037                                                 bdb_cache_entry_db_relock( bdb,
1038                                                         tid, *eip, 0, 0, lock );
1039                                         }
1040 #endif
1041                                 }
1042                                 bdb_cache_entryinfo_lock( *eip );
1043                                 (*eip)->bei_finders--;
1044                                 if ( load )
1045                                         (*eip)->bei_state ^= CACHE_ENTRY_LOADING;
1046                                 bdb_cache_entryinfo_unlock( *eip );
1047                         }
1048                 }
1049         }
1050         if ( flag & ID_LOCKED ) {
1051                 bdb_cache_entryinfo_unlock( *eip );
1052         }
1053         if ( ep ) {
1054                 ep->e_private = NULL;
1055 #ifdef SLAP_ZONE_ALLOC
1056                 bdb_entry_return( bdb, ep, (*eip)->bei_zseq );
1057 #else
1058                 bdb_entry_return( ep );
1059 #endif
1060         }
1061         if ( rc == 0 ) {
1062                 int purge = 0;
1063
1064                 if ( bdb->bi_cache.c_cursize > bdb->bi_cache.c_maxsize ||
1065                         bdb->bi_cache.c_leaves > bdb->bi_cache.c_eimax ) {
1066                         ldap_pvt_thread_mutex_lock( &bdb->bi_cache.c_count_mutex );
1067                         if ( !bdb->bi_cache.c_purging ) {
1068                                 if ( load && !( flag & ID_NOCACHE )) {
1069                                         bdb->bi_cache.c_cursize++;
1070                                         if ( bdb->bi_cache.c_cursize > bdb->bi_cache.c_maxsize ) {
1071                                                 purge = 1;
1072                                                 bdb->bi_cache.c_purging = 1;
1073                                         }
1074                                 } else if ( bdb->bi_cache.c_leaves > bdb->bi_cache.c_eimax ) {
1075                                         purge = 1;
1076                                         bdb->bi_cache.c_purging = 1;
1077                                 }
1078                         }
1079                         ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_count_mutex );
1080                 }
1081                 if ( purge )
1082                         bdb_cache_lru_purge( bdb );
1083         }
1084
1085 #ifdef SLAP_ZONE_ALLOC
1086         if (rc == 0 && (*eip)->bei_e) {
1087                 slap_zn_rlock(bdb->bi_cache.c_zctx, (*eip)->bei_e);
1088         }
1089         slap_zh_runlock(bdb->bi_cache.c_zctx);
1090 #endif
1091         return rc;
1092 }
1093
1094 int
1095 bdb_cache_children(
1096         Operation *op,
1097         DB_TXN *txn,
1098         Entry *e )
1099 {
1100         int rc;
1101
1102         if ( BEI(e)->bei_kids ) {
1103                 return 0;
1104         }
1105         if ( BEI(e)->bei_state & CACHE_ENTRY_NO_KIDS ) {
1106                 return DB_NOTFOUND;
1107         }
1108         rc = bdb_dn2id_children( op, txn, e );
1109         if ( rc == DB_NOTFOUND ) {
1110                 BEI(e)->bei_state |= CACHE_ENTRY_NO_KIDS | CACHE_ENTRY_NO_GRANDKIDS;
1111         }
1112         return rc;
1113 }
1114
1115 /* Update the cache after a successful database Add. */
1116 int
1117 bdb_cache_add(
1118         struct bdb_info *bdb,
1119         EntryInfo *eip,
1120         Entry *e,
1121         struct berval *nrdn,
1122         DB_TXN *txn,
1123         DB_LOCK *lock )
1124 {
1125         EntryInfo *new, ei;
1126         int rc, purge = 0;
1127 #ifdef BDB_HIER
1128         struct berval rdn = e->e_name;
1129 #endif
1130
1131         ei.bei_id = e->e_id;
1132         ei.bei_parent = eip;
1133         ei.bei_nrdn = *nrdn;
1134         ei.bei_lockpad = 0;
1135
1136         /* Lock this entry so that bdb_add can run to completion.
1137          * It can only fail if BDB has run out of lock resources.
1138          */
1139         rc = bdb_cache_entry_db_lock( bdb, txn, &ei, 0, 0, lock );
1140         if ( rc ) {
1141                 bdb_cache_entryinfo_unlock( eip );
1142                 return rc;
1143         }
1144
1145 #ifdef BDB_HIER
1146         if ( nrdn->bv_len != e->e_nname.bv_len ) {
1147                 char *ptr = ber_bvchr( &rdn, ',' );
1148                 assert( ptr != NULL );
1149                 rdn.bv_len = ptr - rdn.bv_val;
1150         }
1151         ber_dupbv( &ei.bei_rdn, &rdn );
1152         if ( eip->bei_dkids ) eip->bei_dkids++;
1153 #endif
1154
1155         if (eip->bei_parent) {
1156                 bdb_cache_entryinfo_lock( eip->bei_parent );
1157                 eip->bei_parent->bei_state &= ~CACHE_ENTRY_NO_GRANDKIDS;
1158                 bdb_cache_entryinfo_unlock( eip->bei_parent );
1159         }
1160
1161         rc = bdb_entryinfo_add_internal( bdb, &ei, &new );
1162         /* bdb_csn_commit can cause this when adding the database root entry */
1163         if ( new->bei_e ) {
1164                 new->bei_e->e_private = NULL;
1165 #ifdef SLAP_ZONE_ALLOC
1166                 bdb_entry_return( bdb, new->bei_e, new->bei_zseq );
1167 #else
1168                 bdb_entry_return( new->bei_e );
1169 #endif
1170         }
1171         new->bei_e = e;
1172         e->e_private = new;
1173         new->bei_state |= CACHE_ENTRY_NO_KIDS | CACHE_ENTRY_NO_GRANDKIDS;
1174         eip->bei_state &= ~CACHE_ENTRY_NO_KIDS;
1175         bdb_cache_entryinfo_unlock( eip );
1176
1177         ldap_pvt_thread_rdwr_wunlock( &bdb->bi_cache.c_rwlock );
1178         ldap_pvt_thread_mutex_lock( &bdb->bi_cache.c_count_mutex );
1179         ++bdb->bi_cache.c_cursize;
1180         if ( bdb->bi_cache.c_cursize > bdb->bi_cache.c_maxsize &&
1181                 !bdb->bi_cache.c_purging ) {
1182                 purge = 1;
1183                 bdb->bi_cache.c_purging = 1;
1184         }
1185         ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_count_mutex );
1186
1187         bdb_cache_lru_link( bdb, new );
1188
1189         if ( purge )
1190                 bdb_cache_lru_purge( bdb );
1191
1192         return rc;
1193 }
1194
1195 int
1196 bdb_cache_modify(
1197         struct bdb_info *bdb,
1198         Entry *e,
1199         Attribute *newAttrs,
1200         DB_TXN *txn,
1201         DB_LOCK *lock )
1202 {
1203         EntryInfo *ei = BEI(e);
1204         int rc;
1205         /* Get write lock on data */
1206         rc = bdb_cache_entry_db_relock( bdb, txn, ei, 1, 0, lock );
1207
1208         /* If we've done repeated mods on a cached entry, then e_attrs
1209          * is no longer contiguous with the entry, and must be freed.
1210          */
1211         if ( ! rc ) {
1212                 if ( (void *)e->e_attrs != (void *)(e+1) ) {
1213                         attrs_free( e->e_attrs ); 
1214                 }
1215                 e->e_attrs = newAttrs;
1216         }
1217         return rc;
1218 }
1219
1220 /*
1221  * Change the rdn in the entryinfo. Also move to a new parent if needed.
1222  */
1223 int
1224 bdb_cache_modrdn(
1225         struct bdb_info *bdb,
1226         Entry *e,
1227         struct berval *nrdn,
1228         Entry *new,
1229         EntryInfo *ein,
1230         DB_TXN *txn,
1231         DB_LOCK *lock )
1232 {
1233         EntryInfo *ei = BEI(e), *pei;
1234         int rc;
1235 #ifdef BDB_HIER
1236         struct berval rdn;
1237 #endif
1238
1239         /* Get write lock on data */
1240         rc =  bdb_cache_entry_db_relock( bdb, txn, ei, 1, 0, lock );
1241         if ( rc ) return rc;
1242
1243         /* If we've done repeated mods on a cached entry, then e_attrs
1244          * is no longer contiguous with the entry, and must be freed.
1245          */
1246         if ( (void *)e->e_attrs != (void *)(e+1) ) {
1247                 attrs_free( e->e_attrs );
1248         }
1249         e->e_attrs = new->e_attrs;
1250         if( e->e_nname.bv_val < e->e_bv.bv_val ||
1251                 e->e_nname.bv_val > e->e_bv.bv_val + e->e_bv.bv_len )
1252         {
1253                 ch_free(e->e_name.bv_val);
1254                 ch_free(e->e_nname.bv_val);
1255         }
1256         e->e_name = new->e_name;
1257         e->e_nname = new->e_nname;
1258
1259         /* Lock the parent's kids AVL tree */
1260         pei = ei->bei_parent;
1261         bdb_cache_entryinfo_lock( pei );
1262         avl_delete( &pei->bei_kids, (caddr_t) ei, bdb_rdn_cmp );
1263         free( ei->bei_nrdn.bv_val );
1264         ber_dupbv( &ei->bei_nrdn, nrdn );
1265
1266 #ifdef BDB_HIER
1267         free( ei->bei_rdn.bv_val );
1268
1269         rdn = e->e_name;
1270         if ( nrdn->bv_len != e->e_nname.bv_len ) {
1271                 char *ptr = ber_bvchr(&rdn, ',');
1272                 assert( ptr != NULL );
1273                 rdn.bv_len = ptr - rdn.bv_val;
1274         }
1275         ber_dupbv( &ei->bei_rdn, &rdn );
1276
1277         /* If new parent, decrement kid counts */
1278         if ( ein ) {
1279                 pei->bei_ckids--;
1280                 if ( pei->bei_dkids ) {
1281                         pei->bei_dkids--;
1282                         if ( pei->bei_dkids < 2 )
1283                                 pei->bei_state |= CACHE_ENTRY_NO_KIDS | CACHE_ENTRY_NO_GRANDKIDS;
1284                 }
1285         }
1286 #endif
1287
1288         if (!ein) {
1289                 ein = ei->bei_parent;
1290         } else {
1291                 ei->bei_parent = ein;
1292                 bdb_cache_entryinfo_unlock( pei );
1293                 bdb_cache_entryinfo_lock( ein );
1294
1295                 /* new parent now has kids */
1296                 if ( ein->bei_state & CACHE_ENTRY_NO_KIDS )
1297                         ein->bei_state ^= CACHE_ENTRY_NO_KIDS;
1298                 /* grandparent has grandkids */
1299                 if ( ein->bei_parent )
1300                         ein->bei_parent->bei_state &= ~CACHE_ENTRY_NO_GRANDKIDS;
1301 #ifdef BDB_HIER
1302                 /* parent might now have grandkids */
1303                 if ( ein->bei_state & CACHE_ENTRY_NO_GRANDKIDS &&
1304                         !(ei->bei_state & CACHE_ENTRY_NO_KIDS))
1305                         ein->bei_state ^= CACHE_ENTRY_NO_GRANDKIDS;
1306
1307                 ein->bei_ckids++;
1308                 if ( ein->bei_dkids ) ein->bei_dkids++;
1309 #endif
1310         }
1311
1312 #ifdef BDB_HIER
1313         /* Record the generation number of this change */
1314         ldap_pvt_thread_mutex_lock( &bdb->bi_modrdns_mutex );
1315         bdb->bi_modrdns++;
1316         ei->bei_modrdns = bdb->bi_modrdns;
1317         ldap_pvt_thread_mutex_unlock( &bdb->bi_modrdns_mutex );
1318 #endif
1319
1320         avl_insert( &ein->bei_kids, ei, bdb_rdn_cmp, avl_dup_error );
1321         bdb_cache_entryinfo_unlock( ein );
1322         return rc;
1323 }
1324 /*
1325  * cache_delete - delete the entry e from the cache. 
1326  *
1327  * returns:     0       e was deleted ok
1328  *              1       e was not in the cache
1329  *              -1      something bad happened
1330  */
1331 int
1332 bdb_cache_delete(
1333         struct bdb_info *bdb,
1334     Entry               *e,
1335     DB_TXN *txn,
1336     DB_LOCK     *lock )
1337 {
1338         EntryInfo *ei = BEI(e);
1339         int     rc;
1340
1341         assert( e->e_private != NULL );
1342
1343         /* Lock the entry's info */
1344         bdb_cache_entryinfo_lock( ei );
1345
1346         /* Set this early, warn off any queriers */
1347         ei->bei_state |= CACHE_ENTRY_DELETED;
1348
1349         bdb_cache_entryinfo_unlock( ei );
1350
1351         /* Get write lock on the data */
1352         rc = bdb_cache_entry_db_relock( bdb, txn, ei, 1, 0, lock );
1353         if ( rc ) {
1354                 bdb_cache_entryinfo_lock( ei );
1355                 /* couldn't lock, undo and give up */
1356                 ei->bei_state ^= CACHE_ENTRY_DELETED;
1357                 bdb_cache_entryinfo_unlock( ei );
1358                 return rc;
1359         }
1360
1361         Debug( LDAP_DEBUG_TRACE, "====> bdb_cache_delete( %ld )\n",
1362                 e->e_id, 0, 0 );
1363
1364         /* set lru mutex */
1365         ldap_pvt_thread_mutex_lock( &bdb->bi_cache.c_lru_mutex );
1366
1367         bdb_cache_entryinfo_lock( ei->bei_parent );
1368         bdb_cache_entryinfo_lock( ei );
1369         rc = bdb_cache_delete_internal( &bdb->bi_cache, e->e_private, 1 );
1370         bdb_cache_entryinfo_unlock( ei );
1371
1372         /* free lru mutex */
1373         ldap_pvt_thread_mutex_unlock( &bdb->bi_cache.c_lru_mutex );
1374
1375         return( rc );
1376 }
1377
1378 void
1379 bdb_cache_delete_cleanup(
1380         Cache *cache,
1381         EntryInfo *ei )
1382 {
1383         /* Enter with ei locked */
1384
1385         /* already freed? */
1386         if ( !ei->bei_parent ) return;
1387
1388         if ( ei->bei_e ) {
1389                 ei->bei_e->e_private = NULL;
1390 #ifdef SLAP_ZONE_ALLOC
1391                 bdb_entry_return( ei->bei_bdb, ei->bei_e, ei->bei_zseq );
1392 #else
1393                 bdb_entry_return( ei->bei_e );
1394 #endif
1395                 ei->bei_e = NULL;
1396         }
1397
1398         bdb_cache_entryinfo_unlock( ei );
1399         bdb_cache_entryinfo_free( cache, ei );
1400 }
1401
1402 static int
1403 bdb_cache_delete_internal(
1404     Cache       *cache,
1405     EntryInfo           *e,
1406     int         decr )
1407 {
1408         int rc = 0;     /* return code */
1409         int decr_leaf = 0;
1410
1411         /* already freed? */
1412         if ( !e->bei_parent ) {
1413                 assert(0);
1414                 return -1;
1415         }
1416
1417 #ifdef BDB_HIER
1418         e->bei_parent->bei_ckids--;
1419         if ( decr && e->bei_parent->bei_dkids ) e->bei_parent->bei_dkids--;
1420 #endif
1421         /* dn tree */
1422         if ( avl_delete( &e->bei_parent->bei_kids, (caddr_t) e, bdb_rdn_cmp )
1423                 == NULL )
1424         {
1425                 rc = -1;
1426                 assert(0);
1427         }
1428         if ( e->bei_parent->bei_kids )
1429                 decr_leaf = 1;
1430
1431         ldap_pvt_thread_rdwr_wlock( &cache->c_rwlock );
1432         /* id tree */
1433         if ( avl_delete( &cache->c_idtree, (caddr_t) e, bdb_id_cmp )) {
1434                 cache->c_eiused--;
1435                 if ( decr_leaf )
1436                         cache->c_leaves--;
1437         } else {
1438                 rc = -1;
1439                 assert(0);
1440         }
1441         ldap_pvt_thread_rdwr_wunlock( &cache->c_rwlock );
1442         bdb_cache_entryinfo_unlock( e->bei_parent );
1443
1444         if ( rc == 0 ){
1445                 /* lru */
1446                 LRU_DEL( cache, e );
1447
1448                 if ( e->bei_e ) {
1449                         ldap_pvt_thread_mutex_lock( &cache->c_count_mutex );
1450                         cache->c_cursize--;
1451                         ldap_pvt_thread_mutex_unlock( &cache->c_count_mutex );
1452                 }
1453         }
1454
1455         return( rc );
1456 }
1457
1458 static void
1459 bdb_entryinfo_release( void *data )
1460 {
1461         EntryInfo *ei = (EntryInfo *)data;
1462         if ( ei->bei_kids ) {
1463                 avl_free( ei->bei_kids, NULL );
1464         }
1465         if ( ei->bei_e ) {
1466                 ei->bei_e->e_private = NULL;
1467 #ifdef SLAP_ZONE_ALLOC
1468                 bdb_entry_return( ei->bei_bdb, ei->bei_e, ei->bei_zseq );
1469 #else
1470                 bdb_entry_return( ei->bei_e );
1471 #endif
1472         }
1473         bdb_cache_entryinfo_destroy( ei );
1474 }
1475
1476 void
1477 bdb_cache_release_all( Cache *cache )
1478 {
1479         /* set cache write lock */
1480         ldap_pvt_thread_rdwr_wlock( &cache->c_rwlock );
1481         /* set lru mutex */
1482         ldap_pvt_thread_mutex_lock( &cache->c_lru_mutex );
1483
1484         Debug( LDAP_DEBUG_TRACE, "====> bdb_cache_release_all\n", 0, 0, 0 );
1485
1486         avl_free( cache->c_dntree.bei_kids, NULL );
1487         avl_free( cache->c_idtree, bdb_entryinfo_release );
1488         for (;cache->c_eifree;cache->c_eifree = cache->c_lruhead) {
1489                 cache->c_lruhead = cache->c_eifree->bei_lrunext;
1490                 bdb_cache_entryinfo_destroy(cache->c_eifree);
1491         }
1492         cache->c_cursize = 0;
1493         cache->c_eiused = 0;
1494         cache->c_leaves = 0;
1495         cache->c_idtree = NULL;
1496         cache->c_lruhead = NULL;
1497         cache->c_lrutail = NULL;
1498         cache->c_dntree.bei_kids = NULL;
1499
1500         /* free lru mutex */
1501         ldap_pvt_thread_mutex_unlock( &cache->c_lru_mutex );
1502         /* free cache write lock */
1503         ldap_pvt_thread_rdwr_wunlock( &cache->c_rwlock );
1504 }
1505
1506 #ifdef LDAP_DEBUG
1507 #ifdef SLAPD_UNUSED
1508 static void
1509 bdb_lru_print( Cache *cache )
1510 {
1511         EntryInfo       *e;
1512
1513         fprintf( stderr, "LRU circle head: %p\n", (void *) cache->c_lruhead );
1514         fprintf( stderr, "LRU circle (tail forward):\n" );
1515         for ( e = cache->c_lrutail; ; ) {
1516                 fprintf( stderr, "\t%p, %p id %ld rdn \"%s\"\n",
1517                         (void *) e, (void *) e->bei_e, e->bei_id, e->bei_nrdn.bv_val );
1518                 e = e->bei_lrunext;
1519                 if ( e == cache->c_lrutail )
1520                         break;
1521         }
1522         fprintf( stderr, "LRU circle (tail backward):\n" );
1523         for ( e = cache->c_lrutail; ; ) {
1524                 fprintf( stderr, "\t%p, %p id %ld rdn \"%s\"\n",
1525                         (void *) e, (void *) e->bei_e, e->bei_id, e->bei_nrdn.bv_val );
1526                 e = e->bei_lruprev;
1527                 if ( e == cache->c_lrutail )
1528                         break;
1529         }
1530 }
1531
1532 static int
1533 bdb_entryinfo_print(void *data, void *arg)
1534 {
1535         EntryInfo *e = data;
1536         fprintf( stderr, "\t%p, %p id %ld rdn \"%s\"\n",
1537                 (void *) e, (void *) e->bei_e, e->bei_id, e->bei_nrdn.bv_val );
1538         return 0;
1539 }
1540
1541 static void
1542 bdb_idtree_print(Cache *cache)
1543 {
1544         avl_apply( cache->c_idtree, bdb_entryinfo_print, NULL, -1, AVL_INORDER );
1545 }
1546 #endif
1547 #endif
1548
1549 static void
1550 bdb_reader_free( void *key, void *data )
1551 {
1552         /* DB_ENV *env = key; */
1553         DB_TXN *txn = data;
1554
1555         if ( txn ) TXN_ABORT( txn );
1556 }
1557
1558 /* free up any keys used by the main thread */
1559 void
1560 bdb_reader_flush( DB_ENV *env )
1561 {
1562         void *data;
1563         void *ctx = ldap_pvt_thread_pool_context();
1564
1565         if ( !ldap_pvt_thread_pool_getkey( ctx, env, &data, NULL ) ) {
1566                 ldap_pvt_thread_pool_setkey( ctx, env, NULL, 0, NULL, NULL );
1567                 bdb_reader_free( env, data );
1568         }
1569 }
1570
1571 int
1572 bdb_reader_get( Operation *op, DB_ENV *env, DB_TXN **txn )
1573 {
1574         int i, rc;
1575         void *data;
1576         void *ctx;
1577
1578         if ( !env || !txn ) return -1;
1579
1580         /* If no op was provided, try to find the ctx anyway... */
1581         if ( op ) {
1582                 ctx = op->o_threadctx;
1583         } else {
1584                 ctx = ldap_pvt_thread_pool_context();
1585         }
1586
1587         /* Shouldn't happen unless we're single-threaded */
1588         if ( !ctx ) {
1589                 *txn = NULL;
1590                 return 0;
1591         }
1592
1593         if ( ldap_pvt_thread_pool_getkey( ctx, env, &data, NULL ) ) {
1594                 for ( i=0, rc=1; rc != 0 && i<4; i++ ) {
1595                         rc = TXN_BEGIN( env, NULL, txn, DB_READ_COMMITTED );
1596                         if (rc) ldap_pvt_thread_yield();
1597                 }
1598                 if ( rc != 0) {
1599                         return rc;
1600                 }
1601                 data = *txn;
1602                 if ( ( rc = ldap_pvt_thread_pool_setkey( ctx, env,
1603                         data, bdb_reader_free, NULL, NULL ) ) ) {
1604                         TXN_ABORT( *txn );
1605                         Debug( LDAP_DEBUG_ANY, "bdb_reader_get: err %s(%d)\n",
1606                                 db_strerror(rc), rc, 0 );
1607
1608                         return rc;
1609                 }
1610         } else {
1611                 *txn = data;
1612         }
1613         return 0;
1614 }