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