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