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