]> git.sur5r.net Git - openldap/blob - libraries/libldap_r/tpool.c
7d6c3afdf643dcd7befcaef9802488100c81b7a7
[openldap] / libraries / libldap_r / tpool.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2007 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15
16 #include "portable.h"
17
18 #include <stdio.h>
19
20 #include <ac/stdarg.h>
21 #include <ac/stdlib.h>
22 #include <ac/string.h>
23 #include <ac/time.h>
24 #include <ac/errno.h>
25
26 #include "ldap-int.h"
27 #include "ldap_pvt_thread.h" /* Get the thread interface */
28 #include "ldap_queue.h"
29 #define LDAP_THREAD_POOL_IMPLEMENTATION
30 #include "ldap_thr_debug.h"  /* May rename symbols defined below */
31
32 #ifndef LDAP_THREAD_HAVE_TPOOL
33
34 typedef enum ldap_int_thread_pool_state_e {
35         LDAP_INT_THREAD_POOL_RUNNING,
36         LDAP_INT_THREAD_POOL_FINISHING,
37         LDAP_INT_THREAD_POOL_STOPPING
38 } ldap_int_thread_pool_state_t;
39
40 typedef struct ldap_int_thread_key_s {
41         void *ltk_key;
42         void *ltk_data;
43         ldap_pvt_thread_pool_keyfree_t *ltk_free;
44 } ldap_int_thread_key_t;
45
46 /* Max number of thread-specific keys we store per thread.
47  * We don't expect to use many...
48  */
49 #define MAXKEYS 32
50 #define LDAP_MAXTHR     1024    /* must be a power of 2 */
51
52 typedef struct ldap_int_thread_userctx_s {
53         ldap_pvt_thread_t ltu_id;
54         ldap_int_thread_key_t ltu_key[MAXKEYS];
55 } ldap_int_thread_userctx_t;
56
57 static ldap_pvt_thread_t tid_zero;
58
59 /* Thread ID -> context mapping (poor open-addressed hash table).
60  * Protected by ldap_pvt_thread_pool_mutex except during pauses,
61  * when it is read-only (used by pool_purgekey and pool_context).
62  */
63 static struct {
64         ldap_pvt_thread_t id;
65         ldap_int_thread_userctx_t *ctx;         /* set when id != tid_zero */
66 #       define DELETED_THREAD_CTX (&ldap_int_main_thrctx + 1) /* dummy addr */
67 } thread_keys[LDAP_MAXTHR];
68
69 #define TID_HASH(tid, hash) do { \
70         unsigned const char *ptr_ = (unsigned const char *)&(tid); \
71         unsigned i_; \
72         for (i_ = 0, (hash) = ptr_[0]; ++i_ < sizeof(tid);) \
73                 (hash) += ((hash) << 5) ^ ptr_[i_]; \
74 } while(0)
75
76
77 typedef struct ldap_int_thread_ctx_s {
78         union {
79         LDAP_STAILQ_ENTRY(ldap_int_thread_ctx_s) q;
80         LDAP_SLIST_ENTRY(ldap_int_thread_ctx_s) l;
81         LDAP_SLIST_ENTRY(ldap_int_thread_ctx_s) al;
82         } ltc_next;
83         ldap_pvt_thread_start_t *ltc_start_routine;
84         void *ltc_arg;
85 } ldap_int_thread_ctx_t;
86
87 struct ldap_int_thread_pool_s {
88         LDAP_STAILQ_ENTRY(ldap_int_thread_pool_s) ltp_next;
89         ldap_pvt_thread_mutex_t ltp_mutex;
90         ldap_pvt_thread_cond_t ltp_cond;
91         ldap_pvt_thread_cond_t ltp_pcond;
92         LDAP_STAILQ_HEAD(tcq, ldap_int_thread_ctx_s) ltp_pending_list;
93         LDAP_SLIST_HEAD(tcl, ldap_int_thread_ctx_s) ltp_free_list;
94         LDAP_SLIST_HEAD(tclq, ldap_int_thread_ctx_s) ltp_active_list;
95         ldap_int_thread_pool_state_t ltp_state;
96         int ltp_pause;
97         long ltp_max_count;
98         long ltp_max_pending;
99         long ltp_pending_count;
100         long ltp_active_count;
101         long ltp_open_count;
102         long ltp_starting;
103 };
104
105 static LDAP_STAILQ_HEAD(tpq, ldap_int_thread_pool_s)
106         ldap_int_thread_pool_list =
107         LDAP_STAILQ_HEAD_INITIALIZER(ldap_int_thread_pool_list);
108
109 static ldap_pvt_thread_mutex_t ldap_pvt_thread_pool_mutex;
110
111 static void *ldap_int_thread_pool_wrapper( void *pool );
112
113 static ldap_pvt_thread_t ldap_int_main_tid;
114
115 static ldap_int_thread_userctx_t ldap_int_main_thrctx;
116
117 int
118 ldap_int_thread_pool_startup ( void )
119 {
120         ldap_int_main_tid = ldap_pvt_thread_self();
121         ldap_int_main_thrctx.ltu_id = ldap_int_main_tid;
122
123         return ldap_pvt_thread_mutex_init(&ldap_pvt_thread_pool_mutex);
124 }
125
126 int
127 ldap_int_thread_pool_shutdown ( void )
128 {
129         struct ldap_int_thread_pool_s *pool;
130
131         while ((pool = LDAP_STAILQ_FIRST(&ldap_int_thread_pool_list)) != NULL) {
132                 (ldap_pvt_thread_pool_destroy)(&pool, 0); /* ignore thr_debug macro */
133         }
134         ldap_pvt_thread_mutex_destroy(&ldap_pvt_thread_pool_mutex);
135         return(0);
136 }
137
138 typedef struct ldap_lazy_sem_t {
139         ldap_pvt_thread_mutex_t ls_mutex;
140         ldap_pvt_thread_cond_t  ls_cond;
141         int ls_sem_value;
142         /*
143          * when more than ls_lazy_count number of resources
144          * becmoes available, the thread wating for the resources will
145          * be waken up in order to prevent frequent blocking/waking-up
146          */
147         unsigned int ls_lazy_count;
148         /*
149          * only one thread(listener) will wait on this semaphore
150          * using a flag instead of a list
151          */
152         int ls_wait;
153 } ldap_lazy_sem_t;
154
155 ldap_lazy_sem_t* thread_pool_sem = NULL;
156
157 int
158 ldap_lazy_sem_init( unsigned int value, unsigned int lazyness )
159 {
160         thread_pool_sem = (ldap_lazy_sem_t*) LDAP_CALLOC(1,
161                 sizeof( ldap_lazy_sem_t ));
162
163         if( thread_pool_sem == NULL ) return -1;
164
165         ldap_pvt_thread_mutex_init( &thread_pool_sem->ls_mutex );
166         ldap_pvt_thread_cond_init( &thread_pool_sem->ls_cond );
167         thread_pool_sem->ls_sem_value = value;
168         thread_pool_sem->ls_lazy_count = lazyness;
169         thread_pool_sem->ls_wait = 0;
170
171         return 0;
172 }
173
174 /* FIXME: move to some approprite header */
175 int ldap_lazy_sem_dec( ldap_lazy_sem_t* ls );
176 int ldap_lazy_sem_wait ( ldap_lazy_sem_t* ls );
177
178 /*
179  * ldap_lazy_sem_wait is used if a caller is blockable(listener).
180  * Otherwise use ldap_lazy_sem_dec (worker)
181  */
182 int
183 ldap_lazy_sem_op_submit( ldap_lazy_sem_t* ls )
184 {
185         if ( ls == NULL ) return -1;
186
187         /* only worker thread has its thread ctx */
188         if ( ldap_pvt_thread_pool_context() ) {
189                 /* worker thread */
190                 return ldap_lazy_sem_dec( ls );
191         } else {
192                 /* listener */
193                 return ldap_lazy_sem_wait( ls );
194         }
195 }
196
197 /*
198  * test if given semaphore's count is zero.
199  * If 0, the caller is blocked 
200  * If not, the count is decremented.
201  */
202 int
203 ldap_lazy_sem_wait ( ldap_lazy_sem_t* ls )
204 {
205         ldap_pvt_thread_mutex_lock( &ls->ls_mutex );
206
207 lazy_sem_retry:
208         if ( ls->ls_sem_value <= 0 ) {
209                 /* no more avaliable resources */
210                 ls->ls_wait = 1;
211                 ldap_pvt_thread_cond_wait( &ls->ls_cond, &ls->ls_mutex );
212                 goto lazy_sem_retry;
213         } else {
214                 /* avaliable resources */
215                 ls->ls_sem_value--;
216         }
217
218         ldap_pvt_thread_mutex_unlock( &ls->ls_mutex );
219
220         return 0;
221 }
222
223 /*
224  * decrement the count without blocking
225  * even when the count becomes less than or equal to 0
226  */
227 int
228 ldap_lazy_sem_dec( ldap_lazy_sem_t* ls )
229 {
230         ldap_pvt_thread_mutex_lock( &ls->ls_mutex );
231
232         ls->ls_sem_value--;
233
234         ldap_pvt_thread_mutex_unlock( &ls->ls_mutex );
235
236         return 0;
237 }
238
239 /*
240  * Increment the count by one and test if it is greater or
241  * equal to lazyness. If it is, wake up a blocked thread.
242  */
243 int
244 ldap_lazy_sem_post( ldap_lazy_sem_t* ls )
245 {
246         if( ls == NULL ) return (-1);
247
248         ldap_pvt_thread_mutex_lock( &ls->ls_mutex );
249
250         ls->ls_sem_value++;
251         if ( ls->ls_wait ) {
252                 if ( ls->ls_sem_value >= ls->ls_lazy_count ) {
253                         ls->ls_wait = 0;
254                         ldap_pvt_thread_cond_signal( &ls->ls_cond );
255                 }
256         }
257
258         ldap_pvt_thread_mutex_unlock( &ls->ls_mutex );
259
260         return 0;
261 }
262
263 int
264 ldap_pvt_thread_pool_init (
265         ldap_pvt_thread_pool_t *tpool,
266         int max_threads,
267         int max_pending )
268 {
269         ldap_pvt_thread_pool_t pool;
270         int rc;
271
272         if (! (0 <= max_threads && max_threads <= LDAP_MAXTHR))
273                 max_threads = 0;
274
275         *tpool = NULL;
276         pool = (ldap_pvt_thread_pool_t) LDAP_CALLOC(1,
277                 sizeof(struct ldap_int_thread_pool_s));
278
279         if (pool == NULL) return(-1);
280
281         rc = ldap_pvt_thread_mutex_init(&pool->ltp_mutex);
282         if (rc != 0)
283                 return(rc);
284         rc = ldap_pvt_thread_cond_init(&pool->ltp_cond);
285         if (rc != 0)
286                 return(rc);
287         rc = ldap_pvt_thread_cond_init(&pool->ltp_pcond);
288         if (rc != 0)
289                 return(rc);
290         pool->ltp_state = LDAP_INT_THREAD_POOL_RUNNING;
291         pool->ltp_max_count = max_threads;
292         pool->ltp_max_pending = max_pending;
293         LDAP_STAILQ_INIT(&pool->ltp_pending_list);
294         LDAP_SLIST_INIT(&pool->ltp_free_list);
295         LDAP_SLIST_INIT(&pool->ltp_active_list);
296         ldap_pvt_thread_mutex_lock(&ldap_pvt_thread_pool_mutex);
297         LDAP_STAILQ_INSERT_TAIL(&ldap_int_thread_pool_list, pool, ltp_next);
298         ldap_pvt_thread_mutex_unlock(&ldap_pvt_thread_pool_mutex);
299
300 #if 0
301         /* THIS WILL NOT WORK on some systems.  If the process
302          * forks after starting a thread, there is no guarantee
303          * that the thread will survive the fork.  For example,
304          * slapd forks in order to daemonize, and does so after
305          * calling ldap_pvt_thread_pool_init.  On some systems,
306          * this initial thread does not run in the child process,
307          * but ltp_open_count == 1, so two things happen: 
308          * 1) the first client connection fails, and 2) when
309          * slapd is kill'ed, it never terminates since it waits
310          * for all worker threads to exit. */
311
312         /* start up one thread, just so there is one. no need to
313          * lock the mutex right now, since no threads are running.
314          */
315         pool->ltp_open_count++;
316
317         ldap_pvt_thread_t thr;
318         rc = ldap_pvt_thread_create( &thr, 1, ldap_int_thread_pool_wrapper, pool );
319
320         if( rc != 0) {
321                 /* couldn't start one?  then don't start any */
322                 ldap_pvt_thread_mutex_lock(&ldap_pvt_thread_pool_mutex);
323                 LDAP_STAILQ_REMOVE(ldap_int_thread_pool_list, pool, 
324                         ldap_int_thread_pool_s, ltp_next);
325                 ldap_pvt_thread_mutex_unlock(&ldap_pvt_thread_pool_mutex);
326                 ldap_pvt_thread_cond_destroy(&pool->ltp_pcond);
327                 ldap_pvt_thread_cond_destroy(&pool->ltp_cond);
328                 ldap_pvt_thread_mutex_destroy(&pool->ltp_mutex);
329                 LDAP_FREE(pool);
330                 return(-1);
331         }
332 #endif
333
334         *tpool = pool;
335         return(0);
336 }
337
338
339 int
340 ldap_pvt_thread_pool_submit (
341         ldap_pvt_thread_pool_t *tpool,
342         ldap_pvt_thread_start_t *start_routine, void *arg )
343 {
344         struct ldap_int_thread_pool_s *pool;
345         ldap_int_thread_ctx_t *ctx;
346         int need_thread = 0;
347         ldap_pvt_thread_t thr;
348
349         if (tpool == NULL)
350                 return(-1);
351
352         pool = *tpool;
353
354         if (pool == NULL)
355                 return(-1);
356
357         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
358         if (pool->ltp_state != LDAP_INT_THREAD_POOL_RUNNING
359                 || (pool->ltp_max_pending > 0
360                         && pool->ltp_pending_count >= pool->ltp_max_pending))
361         {
362                 ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
363                 return(-1);
364         }
365
366         ctx = LDAP_SLIST_FIRST(&pool->ltp_free_list);
367         if (ctx) {
368                 LDAP_SLIST_REMOVE_HEAD(&pool->ltp_free_list, ltc_next.l);
369         } else {
370                 ctx = (ldap_int_thread_ctx_t *) LDAP_MALLOC(
371                         sizeof(ldap_int_thread_ctx_t));
372                 if (ctx == NULL) {
373                         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
374                         return(-1);
375                 }
376         }
377
378         ctx->ltc_start_routine = start_routine;
379         ctx->ltc_arg = arg;
380
381         pool->ltp_pending_count++;
382         LDAP_STAILQ_INSERT_TAIL(&pool->ltp_pending_list, ctx, ltc_next.q);
383         if (pool->ltp_pause) {
384                 ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
385                 return(0);
386         }
387         ldap_pvt_thread_cond_signal(&pool->ltp_cond);
388         if (pool->ltp_open_count < pool->ltp_active_count + pool->ltp_pending_count
389                 && (pool->ltp_open_count <
390                         (pool->ltp_max_count ? pool->ltp_max_count : LDAP_MAXTHR)))
391         {
392                 pool->ltp_open_count++;
393                 pool->ltp_starting++;
394                 need_thread = 1;
395         }
396         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
397
398 #ifdef LDAP_PVT_THREAD_POOL_SEM_LOAD_CONTROL
399         ldap_lazy_sem_op_submit( thread_pool_sem );
400 #endif
401
402         if (need_thread) {
403                 int rc;
404
405                 ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
406
407                 rc = ldap_pvt_thread_create( &thr, 1,
408                         ldap_int_thread_pool_wrapper, pool );
409                 pool->ltp_starting--;
410                 if (rc != 0) {
411                         /* couldn't create thread.  back out of
412                          * ltp_open_count and check for even worse things.
413                          */
414                         pool->ltp_open_count--;
415                         if (pool->ltp_open_count == 0) {
416                                 /* no open threads at all?!?
417                                  */
418                                 ldap_int_thread_ctx_t *ptr;
419
420                                 /* let pool_destroy know there are no more threads */
421                                 ldap_pvt_thread_cond_signal(&pool->ltp_cond);
422
423                                 LDAP_STAILQ_FOREACH(ptr, &pool->ltp_pending_list, ltc_next.q)
424                                         if (ptr == ctx) break;
425                                 if (ptr == ctx) {
426                                         /* no open threads, context not handled, so
427                                          * back out of ltp_pending_count, free the context,
428                                          * report the error.
429                                          */
430                                         LDAP_STAILQ_REMOVE(&pool->ltp_pending_list, ctx, 
431                                                 ldap_int_thread_ctx_s, ltc_next.q);
432                                         pool->ltp_pending_count--;
433                                         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
434                                         LDAP_FREE(ctx);
435                                         return(-1);
436                                 }
437                         }
438                         /* there is another open thread, so this
439                          * context will be handled eventually.
440                          * continue on, we have signalled that
441                          * the context is waiting.
442                          */
443                 }
444                 ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
445         }
446
447         return(0);
448 }
449
450 int
451 ldap_pvt_thread_pool_maxthreads ( ldap_pvt_thread_pool_t *tpool, int max_threads )
452 {
453         struct ldap_int_thread_pool_s *pool;
454
455         if (! (0 <= max_threads && max_threads <= LDAP_MAXTHR))
456                 max_threads = 0;
457
458         if (tpool == NULL)
459                 return(-1);
460
461         pool = *tpool;
462
463         if (pool == NULL)
464                 return(-1);
465
466         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
467         pool->ltp_max_count = max_threads;
468         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
469         return(0);
470 }
471
472 int
473 ldap_pvt_thread_pool_query ( ldap_pvt_thread_pool_t *tpool, ldap_pvt_thread_pool_param_t param, void *value )
474 {
475         struct ldap_int_thread_pool_s   *pool;
476         int                             count = -1;
477
478         if ( tpool == NULL || value == NULL ) {
479                 return -1;
480         }
481
482         pool = *tpool;
483
484         if ( pool == NULL ) {
485                 return 0;
486         }
487
488         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
489         switch ( param ) {
490         case LDAP_PVT_THREAD_POOL_PARAM_MAX:
491                 count = pool->ltp_max_count;
492                 break;
493
494         case LDAP_PVT_THREAD_POOL_PARAM_MAX_PENDING:
495                 count = pool->ltp_max_pending;
496                 break;
497
498         case LDAP_PVT_THREAD_POOL_PARAM_OPEN:
499                 count = pool->ltp_open_count;
500                 break;
501
502         case LDAP_PVT_THREAD_POOL_PARAM_STARTING:
503                 count = pool->ltp_starting;
504                 break;
505
506         case LDAP_PVT_THREAD_POOL_PARAM_ACTIVE:
507                 count = pool->ltp_active_count;
508                 break;
509
510         case LDAP_PVT_THREAD_POOL_PARAM_PENDING:
511                 count = pool->ltp_pending_count;
512                 break;
513
514         case LDAP_PVT_THREAD_POOL_PARAM_BACKLOAD:
515                 count = pool->ltp_pending_count + pool->ltp_active_count;
516                 break;
517
518         case LDAP_PVT_THREAD_POOL_PARAM_ACTIVE_MAX:
519                 break;
520
521         case LDAP_PVT_THREAD_POOL_PARAM_PENDING_MAX:
522                 break;
523
524         case LDAP_PVT_THREAD_POOL_PARAM_BACKLOAD_MAX:
525                 break;
526
527         case LDAP_PVT_THREAD_POOL_PARAM_STATE: {
528                 static struct {
529                         char                            *name;
530                         ldap_int_thread_pool_state_t    state;
531                 }               str2state[] = {
532                         { "running",    LDAP_INT_THREAD_POOL_RUNNING },
533                         { "finishing",  LDAP_INT_THREAD_POOL_FINISHING },
534                         { "stopping",   LDAP_INT_THREAD_POOL_STOPPING },
535                         { NULL }
536                 };
537                 int             i;
538
539                 if ( pool->ltp_pause ) {
540                         *((char **)value) = "pausing";
541                 } else {
542                         for ( i = 0; str2state[ i ].name != NULL; i++ ) {
543                                 if ( str2state[ i ].state == pool->ltp_state ) {
544                                         break;
545                                 }
546                         }
547                         *((char **)value) = str2state[ i ].name;
548                 }
549                 if ( *((char **)value) != NULL ) {
550                         count = -2;
551                 }
552                 } break;
553         }
554         ldap_pvt_thread_mutex_unlock( &pool->ltp_mutex );
555
556         if ( count > -1 ) {
557                 *((int *)value) = count;
558         }
559
560         return ( count == -1 ? -1 : 0 );
561 }
562
563 /*
564  * wrapper for ldap_pvt_thread_pool_query(), left around
565  * for backwards compatibility
566  */
567 int
568 ldap_pvt_thread_pool_backload ( ldap_pvt_thread_pool_t *tpool )
569 {
570         int     rc, count;
571
572         rc = ldap_pvt_thread_pool_query( tpool,
573                 LDAP_PVT_THREAD_POOL_PARAM_BACKLOAD, (void *)&count );
574
575         if ( rc == 0 ) {
576                 return count;
577         }
578
579         return rc;
580 }
581
582 int
583 ldap_pvt_thread_pool_destroy ( ldap_pvt_thread_pool_t *tpool, int run_pending )
584 {
585         struct ldap_int_thread_pool_s *pool, *pptr;
586         ldap_int_thread_ctx_t *ctx;
587
588         if (tpool == NULL)
589                 return(-1);
590
591         pool = *tpool;
592
593         if (pool == NULL) return(-1);
594
595         ldap_pvt_thread_mutex_lock(&ldap_pvt_thread_pool_mutex);
596         LDAP_STAILQ_FOREACH(pptr, &ldap_int_thread_pool_list, ltp_next)
597                 if (pptr == pool) break;
598         if (pptr == pool)
599                 LDAP_STAILQ_REMOVE(&ldap_int_thread_pool_list, pool,
600                         ldap_int_thread_pool_s, ltp_next);
601         ldap_pvt_thread_mutex_unlock(&ldap_pvt_thread_pool_mutex);
602
603         if (pool != pptr) return(-1);
604
605         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
606         pool->ltp_state = run_pending
607                 ? LDAP_INT_THREAD_POOL_FINISHING
608                 : LDAP_INT_THREAD_POOL_STOPPING;
609
610         while (pool->ltp_open_count) {
611                 if (!pool->ltp_pause)
612                         ldap_pvt_thread_cond_broadcast(&pool->ltp_cond);
613                 ldap_pvt_thread_cond_wait(&pool->ltp_cond, &pool->ltp_mutex);
614         }
615         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
616
617         while ((ctx = LDAP_STAILQ_FIRST(&pool->ltp_pending_list)) != NULL)
618         {
619                 LDAP_STAILQ_REMOVE_HEAD(&pool->ltp_pending_list, ltc_next.q);
620                 LDAP_FREE(ctx);
621         }
622
623         while ((ctx = LDAP_SLIST_FIRST(&pool->ltp_free_list)) != NULL)
624         {
625                 LDAP_SLIST_REMOVE_HEAD(&pool->ltp_free_list, ltc_next.l);
626                 LDAP_FREE(ctx);
627         }
628
629         ldap_pvt_thread_cond_destroy(&pool->ltp_pcond);
630         ldap_pvt_thread_cond_destroy(&pool->ltp_cond);
631         ldap_pvt_thread_mutex_destroy(&pool->ltp_mutex);
632         LDAP_FREE(pool);
633 #ifdef LDAP_PVT_THREAD_POOL_SEM_LOAD_CONTROL
634         if ( thread_pool_sem ) {
635                 LDAP_FREE( thread_pool_sem );
636         }
637 #endif
638         return(0);
639 }
640
641 static void *
642 ldap_int_thread_pool_wrapper ( 
643         void *xpool )
644 {
645         struct ldap_int_thread_pool_s *pool = xpool;
646         ldap_int_thread_ctx_t *ctx;
647         ldap_int_thread_userctx_t uctx;
648         unsigned i, keyslot, hash;
649
650         if (pool == NULL)
651                 return NULL;
652
653         for ( i=0; i<MAXKEYS; i++ ) {
654                 uctx.ltu_key[i].ltk_key = NULL;
655         }
656
657         uctx.ltu_id = ldap_pvt_thread_self();
658         TID_HASH(uctx.ltu_id, hash);
659
660         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
661
662         /* thread_keys[] is read-only when paused */
663         while (pool->ltp_pause)
664                 ldap_pvt_thread_cond_wait(&pool->ltp_cond, &pool->ltp_mutex);
665
666         /* find a key slot to give this thread ID and store a
667          * pointer to our keys there; start at the thread ID
668          * itself (mod LDAP_MAXTHR) and look for an empty slot.
669          */
670         ldap_pvt_thread_mutex_lock(&ldap_pvt_thread_pool_mutex);
671         for (keyslot = hash & (LDAP_MAXTHR-1);
672                 !ldap_pvt_thread_equal(thread_keys[keyslot].id, tid_zero);
673                 keyslot = (keyslot+1) & (LDAP_MAXTHR-1));
674         thread_keys[keyslot].id = uctx.ltu_id;
675         thread_keys[keyslot].ctx = &uctx;
676         ldap_pvt_thread_mutex_unlock(&ldap_pvt_thread_pool_mutex);
677
678         for (;;) {
679                 while (pool->ltp_pause)
680                         ldap_pvt_thread_cond_wait(&pool->ltp_cond, &pool->ltp_mutex);
681
682                 if (pool->ltp_state == LDAP_INT_THREAD_POOL_STOPPING)
683                         break;
684
685                 ctx = LDAP_STAILQ_FIRST(&pool->ltp_pending_list);
686                 if (ctx == NULL) {
687                         if (pool->ltp_state == LDAP_INT_THREAD_POOL_FINISHING)
688                                 break;
689
690                         if (pool->ltp_open_count >
691                                 (pool->ltp_max_count ? pool->ltp_max_count : LDAP_MAXTHR))
692                         {
693                                 /* too many threads running (can happen if the
694                                  * maximum threads value is set during ongoing
695                                  * operation using ldap_pvt_thread_pool_maxthreads)
696                                  * so let this thread die.
697                                  */
698                                 break;
699                         }
700
701                         /* we could check an idle timer here, and let the
702                          * thread die if it has been inactive for a while.
703                          * only die if there are other open threads (i.e.,
704                          * always have at least one thread open).  the check
705                          * should be like this:
706                          *   if (pool->ltp_open_count > 1 && pool->ltp_starting == 0)
707                          *       check timer, wait if ltp_pause, leave thread (break;)
708                          *
709                          * Just use pthread_cond_timedwait if we want to
710                          * check idle time.
711                          */
712
713                         assert(pool->ltp_state == LDAP_INT_THREAD_POOL_RUNNING);
714                         ldap_pvt_thread_cond_wait(&pool->ltp_cond, &pool->ltp_mutex);
715                         continue;
716                 }
717
718                 LDAP_STAILQ_REMOVE_HEAD(&pool->ltp_pending_list, ltc_next.q);
719                 pool->ltp_pending_count--;
720
721                 LDAP_SLIST_INSERT_HEAD(&pool->ltp_active_list, ctx, ltc_next.al);
722                 pool->ltp_active_count++;
723                 ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
724
725                 ctx->ltc_start_routine(&uctx, ctx->ltc_arg);
726
727 #ifdef LDAP_PVT_THREAD_POOL_SEM_LOAD_CONTROL
728                 ldap_lazy_sem_post( thread_pool_sem );
729 #endif
730                 ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
731                 LDAP_SLIST_REMOVE(&pool->ltp_active_list, ctx,
732                         ldap_int_thread_ctx_s, ltc_next.al);
733                 LDAP_SLIST_INSERT_HEAD(&pool->ltp_free_list, ctx, ltc_next.l);
734                 pool->ltp_active_count--;
735
736                 /* let pool_pause know when it is the sole active thread */
737                 if (pool->ltp_active_count < 2)
738                         ldap_pvt_thread_cond_signal(&pool->ltp_pcond);
739         }
740
741         ldap_pvt_thread_pool_context_reset(&uctx);
742
743         /* Needed if context_reset can let another thread request a pause */
744         while (pool->ltp_pause)
745                 ldap_pvt_thread_cond_wait(&pool->ltp_cond, &pool->ltp_mutex);
746
747         ldap_pvt_thread_mutex_lock(&ldap_pvt_thread_pool_mutex);
748         thread_keys[keyslot].ctx = DELETED_THREAD_CTX;
749         thread_keys[keyslot].id = tid_zero;
750         ldap_pvt_thread_mutex_unlock(&ldap_pvt_thread_pool_mutex);
751
752         pool->ltp_open_count--;
753
754         /* let pool_destroy know we're all done */
755         if (pool->ltp_open_count < 1)
756                 ldap_pvt_thread_cond_signal(&pool->ltp_cond);
757
758         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
759
760         ldap_pvt_thread_exit(NULL);
761         return(NULL);
762 }
763
764 int
765 ldap_pvt_thread_pool_pause ( 
766         ldap_pvt_thread_pool_t *tpool )
767 {
768         struct ldap_int_thread_pool_s *pool;
769
770         if (tpool == NULL)
771                 return(-1);
772
773         pool = *tpool;
774
775         if (pool == NULL)
776                 return(0);
777
778         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
779
780         /* If someone else has already requested a pause, we have to wait */
781         while (pool->ltp_pause) {
782                 pool->ltp_pending_count++;
783                 pool->ltp_active_count--;
784                 /* let the other pool_pause() know when it can proceed */
785                 if (pool->ltp_active_count < 2)
786                         ldap_pvt_thread_cond_signal(&pool->ltp_pcond);
787                 ldap_pvt_thread_cond_wait(&pool->ltp_cond, &pool->ltp_mutex);
788                 pool->ltp_pending_count--;
789                 pool->ltp_active_count++;
790         }
791
792         /* Wait for everyone else to pause or finish */
793         pool->ltp_pause = 1;
794         while (pool->ltp_active_count > 1) {
795                 ldap_pvt_thread_cond_wait(&pool->ltp_pcond, &pool->ltp_mutex);
796         }
797
798         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
799         return(0);
800 }
801
802 int
803 ldap_pvt_thread_pool_resume ( 
804         ldap_pvt_thread_pool_t *tpool )
805 {
806         struct ldap_int_thread_pool_s *pool;
807
808         if (tpool == NULL)
809                 return(-1);
810
811         pool = *tpool;
812
813         if (pool == NULL)
814                 return(0);
815
816         ldap_pvt_thread_mutex_lock(&pool->ltp_mutex);
817         pool->ltp_pause = 0;
818         ldap_pvt_thread_cond_broadcast(&pool->ltp_cond);
819         ldap_pvt_thread_mutex_unlock(&pool->ltp_mutex);
820         return(0);
821 }
822
823 int ldap_pvt_thread_pool_getkey(
824         void *xctx,
825         void *key,
826         void **data,
827         ldap_pvt_thread_pool_keyfree_t **kfree )
828 {
829         ldap_int_thread_userctx_t *ctx = xctx;
830         int i;
831
832         if ( !ctx || !key || !data ) return EINVAL;
833
834         for ( i=0; i<MAXKEYS && ctx->ltu_key[i].ltk_key; i++ ) {
835                 if ( ctx->ltu_key[i].ltk_key == key ) {
836                         *data = ctx->ltu_key[i].ltk_data;
837                         if ( kfree ) *kfree = ctx->ltu_key[i].ltk_free;
838                         return 0;
839                 }
840         }
841         return ENOENT;
842 }
843
844 static void
845 clear_key_idx( ldap_int_thread_userctx_t *ctx, int i )
846 {
847         int j = i;
848         while ( ++j < MAXKEYS && ctx->ltu_key[j].ltk_key );
849         if ( --j != i ) {
850                 ctx->ltu_key[i] = ctx->ltu_key[j];
851                 i = j;
852         }
853         ctx->ltu_key[i].ltk_key = NULL;
854 }
855
856 int ldap_pvt_thread_pool_setkey(
857         void *xctx,
858         void *key,
859         void *data,
860         ldap_pvt_thread_pool_keyfree_t *kfree )
861 {
862         ldap_int_thread_userctx_t *ctx = xctx;
863         int i, found;
864
865         if ( !ctx || !key ) return EINVAL;
866
867         for ( i=found=0; i<MAXKEYS; i++ ) {
868                 if ( ctx->ltu_key[i].ltk_key == key ) {
869                         found = 1;
870                         break;
871                 } else if ( !ctx->ltu_key[i].ltk_key ) {
872                         break;
873                 }
874         }
875
876         if ( data || kfree ) {
877                 if ( i>=MAXKEYS )
878                         return ENOMEM;
879                 ctx->ltu_key[i].ltk_key = key;
880                 ctx->ltu_key[i].ltk_data = data;
881                 ctx->ltu_key[i].ltk_free = kfree;
882         } else if ( found ) {
883                 clear_key_idx( ctx, i );
884         }
885
886         return 0;
887 }
888
889 /* Free all elements with this key, no matter which thread they're in.
890  * May only be called while the pool is paused.
891  */
892 void ldap_pvt_thread_pool_purgekey( void *key )
893 {
894         int i, j;
895         ldap_int_thread_userctx_t *ctx;
896
897         assert ( key != NULL );
898
899         for ( i=0; i<LDAP_MAXTHR; i++ ) {
900                 ctx = thread_keys[i].ctx;
901                 if ( ctx && ctx != DELETED_THREAD_CTX ) {
902                         for ( j=0; j<MAXKEYS && ctx->ltu_key[j].ltk_key; j++ ) {
903                                 if ( ctx->ltu_key[j].ltk_key == key ) {
904                                         if (ctx->ltu_key[j].ltk_free)
905                                                 ctx->ltu_key[j].ltk_free( ctx->ltu_key[j].ltk_key,
906                                                 ctx->ltu_key[j].ltk_data );
907                                         clear_key_idx( ctx, j );
908                                         break;
909                                 }
910                         }
911                 }
912         }
913 }
914
915 /*
916  * This is necessary if the caller does not have access to the
917  * thread context handle (for example, a slapd plugin calling
918  * slapi_search_internal()). No doubt it is more efficient
919  * for the application to keep track of the thread context
920  * handles itself.
921  */
922 void *ldap_pvt_thread_pool_context( )
923 {
924         ldap_pvt_thread_t tid;
925         unsigned i, hash;
926         ldap_int_thread_userctx_t *ctx;
927
928         tid = ldap_pvt_thread_self();
929         if ( ldap_pvt_thread_equal( tid, ldap_int_main_tid ))
930                 return &ldap_int_main_thrctx;
931
932         TID_HASH( tid, hash );
933         i = hash &= (LDAP_MAXTHR-1);
934         ldap_pvt_thread_mutex_lock(&ldap_pvt_thread_pool_mutex);
935         do {
936                 ctx = thread_keys[i].ctx;
937                 if ( ctx != DELETED_THREAD_CTX )
938                         if ( ldap_pvt_thread_equal(thread_keys[i].id, tid) || !ctx )
939                                 goto done;
940         } while ( (i = (i+1) & (LDAP_MAXTHR-1)) != hash );
941         ctx = NULL;
942  done:
943         ldap_pvt_thread_mutex_unlock(&ldap_pvt_thread_pool_mutex);
944
945         return ctx;
946 }
947
948 void ldap_pvt_thread_pool_context_reset( void *vctx )
949 {
950         ldap_int_thread_userctx_t *ctx = vctx;
951         int i;
952
953         for ( i=MAXKEYS-1; i>=0; i--) {
954                 if ( !ctx->ltu_key[i].ltk_key )
955                         continue;
956                 if ( ctx->ltu_key[i].ltk_free )
957                         ctx->ltu_key[i].ltk_free( ctx->ltu_key[i].ltk_key,
958                         ctx->ltu_key[i].ltk_data );
959                 ctx->ltu_key[i].ltk_key = NULL;
960         }
961 }
962
963 ldap_pvt_thread_t ldap_pvt_thread_pool_tid( void *vctx )
964 {
965         ldap_int_thread_userctx_t *ctx = vctx;
966
967         return ctx->ltu_id;
968 }
969 #endif /* LDAP_THREAD_HAVE_TPOOL */