Update copyright dates
[src/app-framework-binder.git] / src / jobs.c
1 /*
2  * Copyright (C) 2015-2020 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <stdint.h>
22 #include <unistd.h>
23 #include <signal.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/syscall.h>
27 #include <pthread.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <sys/eventfd.h>
31
32 #include <systemd/sd-event.h>
33
34 #include "jobs.h"
35 #include "evmgr.h"
36 #include "sig-monitor.h"
37 #include "verbose.h"
38 #include "systemd.h"
39
40 #define EVENT_TIMEOUT_TOP       ((uint64_t)-1)
41 #define EVENT_TIMEOUT_CHILD     ((uint64_t)10000)
42
43 /** Internal shortcut for callback */
44 typedef void (*job_cb_t)(int, void*);
45
46 /** starting mode for jobs */
47 enum start_mode
48 {
49         Start_Default,  /**< Start a thread if more than one jobs is pending */
50         Start_Urgent,   /**< Always start a thread */
51         Start_Lazy      /**< Never start a thread */
52 };
53
54 /** Description of a pending job */
55 struct job
56 {
57         struct job *next;    /**< link to the next job enqueued */
58         const void *group;   /**< group of the request */
59         job_cb_t callback;   /**< processing callback */
60         void *arg;           /**< argument */
61         int timeout;         /**< timeout in second for processing the request */
62         unsigned blocked: 1; /**< is an other request blocking this one ? */
63         unsigned dropped: 1; /**< is removed ? */
64 };
65
66 /** Description of threads */
67 struct thread
68 {
69         struct thread *next;   /**< next thread of the list */
70         struct thread *upper;  /**< upper same thread */
71         struct thread *nholder;/**< next holder for evloop */
72         pthread_cond_t *cwhold;/**< condition wait for holding */
73         struct job *job;       /**< currently processed job */
74         pthread_t tid;         /**< the thread id */
75         volatile unsigned stop: 1;      /**< stop requested */
76         volatile unsigned waits: 1;     /**< is waiting? */
77         volatile unsigned leaved: 1;    /**< was leaved? */
78 };
79
80 /**
81  * Description of synchronous callback
82  */
83 struct sync
84 {
85         struct thread thread;   /**< thread loop data */
86         union {
87                 void (*callback)(int, void*);   /**< the synchronous callback */
88                 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
89                                 /**< the entering synchronous routine */
90         };
91         void *arg;              /**< the argument of the callback */
92 };
93
94 /* synchronisation of threads */
95 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
96 static pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;
97
98 /* counts for threads */
99 static int allowed_thread_count = 0; /** allowed count of threads */
100 static int started_thread_count = 0; /** started count of threads */
101 static int busy_thread_count = 0;    /** count of busy threads */
102
103 /* list of threads */
104 static struct thread *threads;
105 static _Thread_local struct thread *current_thread;
106
107 /* counts for jobs */
108 static int remaining_job_count = 0;  /** count of job that can be created */
109 static int allowed_job_count = 0;    /** allowed count of pending jobs */
110
111 /* queue of pending jobs */
112 static struct job *first_pending_job;
113 static struct job *first_free_job;
114
115 /* event loop */
116 static struct evmgr *evmgr;
117
118 static void (*exit_handler)();
119
120 /**
121  * Create a new job with the given parameters
122  * @param group    the group of the job
123  * @param timeout  the timeout of the job (0 if none)
124  * @param callback the function that achieves the job
125  * @param arg      the argument of the callback
126  * @return the created job unblock or NULL when no more memory
127  */
128 static struct job *job_create(
129                 const void *group,
130                 int timeout,
131                 job_cb_t callback,
132                 void *arg)
133 {
134         struct job *job;
135
136         /* try recyle existing job */
137         job = first_free_job;
138         if (job)
139                 first_free_job = job->next;
140         else {
141                 /* allocation without blocking */
142                 pthread_mutex_unlock(&mutex);
143                 job = malloc(sizeof *job);
144                 pthread_mutex_lock(&mutex);
145                 if (!job) {
146                         ERROR("out of memory");
147                         errno = ENOMEM;
148                         goto end;
149                 }
150         }
151         /* initialises the job */
152         job->group = group;
153         job->timeout = timeout;
154         job->callback = callback;
155         job->arg = arg;
156         job->blocked = 0;
157         job->dropped = 0;
158 end:
159         return job;
160 }
161
162 /**
163  * Adds 'job' at the end of the list of jobs, marking it
164  * as blocked if an other job with the same group is pending.
165  * @param job the job to add
166  */
167 static void job_add(struct job *job)
168 {
169         const void *group;
170         struct job *ijob, **pjob;
171
172         /* prepare to add */
173         group = job->group;
174         job->next = NULL;
175
176         /* search end and blockers */
177         pjob = &first_pending_job;
178         ijob = first_pending_job;
179         while (ijob) {
180                 if (group && ijob->group == group)
181                         job->blocked = 1;
182                 pjob = &ijob->next;
183                 ijob = ijob->next;
184         }
185
186         /* queue the jobs */
187         *pjob = job;
188         remaining_job_count--;
189 }
190
191 /**
192  * Get the next job to process or NULL if none.
193  * @return the first job that isn't blocked or NULL
194  */
195 static inline struct job *job_get()
196 {
197         struct job *job = first_pending_job;
198         while (job && job->blocked)
199                 job = job->next;
200         if (job)
201                 remaining_job_count++;
202         return job;
203 }
204
205 /**
206  * Releases the processed 'job': removes it
207  * from the list of jobs and unblock the first
208  * pending job of the same group if any.
209  * @param job the job to release
210  */
211 static inline void job_release(struct job *job)
212 {
213         struct job *ijob, **pjob;
214         const void *group;
215
216         /* first unqueue the job */
217         pjob = &first_pending_job;
218         ijob = first_pending_job;
219         while (ijob != job) {
220                 pjob = &ijob->next;
221                 ijob = ijob->next;
222         }
223         *pjob = job->next;
224
225         /* then unblock jobs of the same group */
226         group = job->group;
227         if (group) {
228                 ijob = job->next;
229                 while (ijob && ijob->group != group)
230                         ijob = ijob->next;
231                 if (ijob)
232                         ijob->blocked = 0;
233         }
234
235         /* recycle the job */
236         job->next = first_free_job;
237         first_free_job = job;
238 }
239
240 /**
241  * Monitored cancel callback for a job.
242  * This function is called by the monitor
243  * to cancel the job when the safe environment
244  * is set.
245  * @param signum 0 on normal flow or the number
246  *               of the signal that interrupted the normal
247  *               flow, isn't used
248  * @param arg    the job to run
249  */
250 __attribute__((unused))
251 static void job_cancel(int signum, void *arg)
252 {
253         struct job *job = arg;
254         job->callback(SIGABRT, job->arg);
255 }
256
257 /**
258  * wakeup the event loop if needed by sending
259  * an event.
260  */
261 static void evloop_wakeup()
262 {
263         if (evmgr)
264                 evmgr_wakeup(evmgr);
265 }
266
267 /**
268  * Release the currently held event loop
269  */
270 static void evloop_release()
271 {
272         struct thread *nh, *ct = current_thread;
273
274         if (ct && evmgr && evmgr_release_if(evmgr, ct)) {
275                 nh = ct->nholder;
276                 ct->nholder = 0;
277                 if (nh) {
278                         evmgr_try_hold(evmgr, nh);
279                         pthread_cond_signal(nh->cwhold);
280                 }
281         }
282 }
283
284 /**
285  * get the eventloop for the current thread
286  */
287 static int evloop_get()
288 {
289         return evmgr && evmgr_try_hold(evmgr, current_thread);
290 }
291
292 /**
293  * acquire the eventloop for the current thread
294  */
295 static void evloop_acquire()
296 {
297         struct thread *pwait, *ct;
298         pthread_cond_t cond;
299
300         /* try to get the evloop */
301         if (!evloop_get()) {
302                 /* failed, init waiting state */
303                 ct = current_thread;
304                 ct->nholder = NULL;
305                 ct->cwhold = &cond;
306                 pthread_cond_init(&cond, NULL);
307
308                 /* queue current thread in holder list */
309                 pwait = evmgr_holder(evmgr);
310                 while (pwait->nholder)
311                         pwait = pwait->nholder;
312                 pwait->nholder = ct;
313
314                 /* wake up the evloop */
315                 evloop_wakeup();
316
317                 /* wait to acquire the evloop */
318                 pthread_cond_wait(&cond, &mutex);
319                 pthread_cond_destroy(&cond);
320         }
321 }
322
323 /**
324  * Enter the thread
325  * @param me the description of the thread to enter
326  */
327 static void thread_enter(volatile struct thread *me)
328 {
329         evloop_release();
330         /* initialize description of itself and link it in the list */
331         me->tid = pthread_self();
332         me->stop = 0;
333         me->waits = 0;
334         me->leaved = 0;
335         me->nholder = 0;
336         me->upper = current_thread;
337         me->next = threads;
338         threads = (struct thread*)me;
339         current_thread = (struct thread*)me;
340 }
341
342 /**
343  * leave the thread
344  * @param me the description of the thread to leave
345  */
346 static void thread_leave()
347 {
348         struct thread **prv, *me;
349
350         /* unlink the current thread and cleanup */
351         me = current_thread;
352         prv = &threads;
353         while (*prv != me)
354                 prv = &(*prv)->next;
355         *prv = me->next;
356
357         current_thread = me->upper;
358 }
359
360 /**
361  * Main processing loop of internal threads with processing jobs.
362  * The loop must be called with the mutex locked
363  * and it returns with the mutex locked.
364  * @param me the description of the thread to use
365  * TODO: how are timeout handled when reentering?
366  */
367 static void thread_run_internal(volatile struct thread *me)
368 {
369         struct job *job;
370
371         /* enter thread */
372         thread_enter(me);
373
374         /* loop until stopped */
375         while (!me->stop) {
376                 /* release the current event loop */
377                 evloop_release();
378
379                 /* get a job */
380                 job = job_get();
381                 if (job) {
382                         /* prepare running the job */
383                         job->blocked = 1; /* mark job as blocked */
384                         me->job = job; /* record the job (only for terminate) */
385
386                         /* run the job */
387                         pthread_mutex_unlock(&mutex);
388                         sig_monitor(job->timeout, job->callback, job->arg);
389                         pthread_mutex_lock(&mutex);
390
391                         /* release the run job */
392                         job_release(job);
393                 /* no job, check event loop wait */
394                 } else if (evloop_get()) {
395                         if (!evmgr_can_run(evmgr)) {
396                                 /* busy ? */
397                                 CRITICAL("Can't enter dispatch while in dispatch!");
398                                 abort();
399                         }
400                         /* run the events */
401                         evmgr_prepare_run(evmgr);
402                         pthread_mutex_unlock(&mutex);
403                         sig_monitor(0, (void(*)(int,void*))evmgr_job_run, evmgr);
404                         pthread_mutex_lock(&mutex);
405                 } else {
406                         /* no job and no event loop */
407                         busy_thread_count--;
408                         if (!busy_thread_count)
409                                 ERROR("Entering job deep sleep! Check your bindings.");
410                         me->waits = 1;
411                         pthread_cond_wait(&cond, &mutex);
412                         me->waits = 0;
413                         busy_thread_count++;
414                 }
415         }
416         /* cleanup */
417         evloop_release();
418         thread_leave();
419 }
420
421 /**
422  * Main processing loop of external threads.
423  * The loop must be called with the mutex locked
424  * and it returns with the mutex locked.
425  * @param me the description of the thread to use
426  */
427 static void thread_run_external(volatile struct thread *me)
428 {
429         /* enter thread */
430         thread_enter(me);
431
432         /* loop until stopped */
433         me->waits = 1;
434         while (!me->stop)
435                 pthread_cond_wait(&cond, &mutex);
436         me->waits = 0;
437         thread_leave();
438 }
439
440 /**
441  * Root for created threads.
442  */
443 static void thread_main()
444 {
445         struct thread me;
446
447         busy_thread_count++;
448         started_thread_count++;
449         sig_monitor_init_timeouts();
450         thread_run_internal(&me);
451         sig_monitor_clean_timeouts();
452         started_thread_count--;
453         busy_thread_count--;
454 }
455
456 /**
457  * Entry point for created threads.
458  * @param data not used
459  * @return NULL
460  */
461 static void *thread_starter(void *data)
462 {
463         pthread_mutex_lock(&mutex);
464         thread_main();
465         pthread_mutex_unlock(&mutex);
466         return NULL;
467 }
468
469 /**
470  * Starts a new thread
471  * @return 0 in case of success or -1 in case of error
472  */
473 static int start_one_thread()
474 {
475         pthread_t tid;
476         int rc;
477
478         rc = pthread_create(&tid, NULL, thread_starter, NULL);
479         if (rc != 0) {
480                 /* errno = rc; */
481                 WARNING("not able to start thread: %m");
482                 rc = -1;
483         }
484         return rc;
485 }
486
487 /**
488  * Queues a new asynchronous job represented by 'callback' and 'arg'
489  * for the 'group' and the 'timeout'.
490  * Jobs are queued FIFO and are possibly executed in parallel
491  * concurrently except for job of the same group that are
492  * executed sequentially in FIFO order.
493  * @param group    The group of the job or NULL when no group.
494  * @param timeout  The maximum execution time in seconds of the job
495  *                 or 0 for unlimited time.
496  * @param callback The function to execute for achieving the job.
497  *                 Its first parameter is either 0 on normal flow
498  *                 or the signal number that broke the normal flow.
499  *                 The remaining parameter is the parameter 'arg1'
500  *                 given here.
501  * @param arg      The second argument for 'callback'
502  * @param start    The start mode for threads
503  * @return 0 in case of success or -1 in case of error
504  */
505 static int queue_job_internal(
506                 const void *group,
507                 int timeout,
508                 void (*callback)(int, void*),
509                 void *arg,
510                 enum start_mode start_mode)
511 {
512         struct job *job;
513         int rc, busy;
514
515         /* check availability */
516         if (remaining_job_count <= 0) {
517                 ERROR("can't process job with threads: too many jobs");
518                 errno = EBUSY;
519                 goto error;
520         }
521
522         /* allocates the job */
523         job = job_create(group, timeout, callback, arg);
524         if (!job)
525                 goto error;
526
527         /* start a thread if needed */
528         busy = busy_thread_count == started_thread_count;
529         if (start_mode != Start_Lazy
530          && busy
531          && (start_mode == Start_Urgent || remaining_job_count + started_thread_count < allowed_job_count)
532          && started_thread_count < allowed_thread_count) {
533                 /* all threads are busy and a new can be started */
534                 rc = start_one_thread();
535                 if (rc < 0 && started_thread_count == 0) {
536                         ERROR("can't start initial thread: %m");
537                         goto error2;
538                 }
539                 busy = 0;
540         }
541
542         /* queues the job */
543         job_add(job);
544
545         /* wakeup an evloop if needed */
546         if (busy)
547                 evloop_wakeup();
548
549         pthread_cond_signal(&cond);
550         return 0;
551
552 error2:
553         job->next = first_free_job;
554         first_free_job = job;
555 error:
556         return -1;
557 }
558
559 /**
560  * Queues a new asynchronous job represented by 'callback' and 'arg'
561  * for the 'group' and the 'timeout'.
562  * Jobs are queued FIFO and are possibly executed in parallel
563  * concurrently except for job of the same group that are
564  * executed sequentially in FIFO order.
565  * @param group    The group of the job or NULL when no group.
566  * @param timeout  The maximum execution time in seconds of the job
567  *                 or 0 for unlimited time.
568  * @param callback The function to execute for achieving the job.
569  *                 Its first parameter is either 0 on normal flow
570  *                 or the signal number that broke the normal flow.
571  *                 The remaining parameter is the parameter 'arg1'
572  *                 given here.
573  * @param arg      The second argument for 'callback'
574  * @param start    The start mode for threads
575  * @return 0 in case of success or -1 in case of error
576  */
577 static int queue_job(
578                 const void *group,
579                 int timeout,
580                 void (*callback)(int, void*),
581                 void *arg,
582                 enum start_mode start_mode)
583 {
584         int rc;
585
586         pthread_mutex_lock(&mutex);
587         rc = queue_job_internal(group, timeout, callback, arg, start_mode);
588         pthread_mutex_unlock(&mutex);
589         return rc;
590
591 }
592
593 /**
594  * Queues a new asynchronous job represented by 'callback' and 'arg'
595  * for the 'group' and the 'timeout'.
596  * Jobs are queued FIFO and are possibly executed in parallel
597  * concurrently except for job of the same group that are
598  * executed sequentially in FIFO order.
599  * @param group    The group of the job or NULL when no group.
600  * @param timeout  The maximum execution time in seconds of the job
601  *                 or 0 for unlimited time.
602  * @param callback The function to execute for achieving the job.
603  *                 Its first parameter is either 0 on normal flow
604  *                 or the signal number that broke the normal flow.
605  *                 The remaining parameter is the parameter 'arg1'
606  *                 given here.
607  * @param arg      The second argument for 'callback'
608  * @return 0 in case of success or -1 in case of error
609  */
610 int jobs_queue(
611                 const void *group,
612                 int timeout,
613                 void (*callback)(int, void*),
614                 void *arg)
615 {
616         return queue_job(group, timeout, callback, arg, Start_Default);
617 }
618
619 /**
620  * Queues lazyly a new asynchronous job represented by 'callback' and 'arg'
621  * for the 'group' and the 'timeout'.
622  * Jobs are queued FIFO and are possibly executed in parallel
623  * concurrently except for job of the same group that are
624  * executed sequentially in FIFO order.
625  * @param group    The group of the job or NULL when no group.
626  * @param timeout  The maximum execution time in seconds of the job
627  *                 or 0 for unlimited time.
628  * @param callback The function to execute for achieving the job.
629  *                 Its first parameter is either 0 on normal flow
630  *                 or the signal number that broke the normal flow.
631  *                 The remaining parameter is the parameter 'arg1'
632  *                 given here.
633  * @param arg      The second argument for 'callback'
634  * @return 0 in case of success or -1 in case of error
635  */
636 int jobs_queue_lazy(
637                 const void *group,
638                 int timeout,
639                 void (*callback)(int, void*),
640                 void *arg)
641 {
642         return queue_job(group, timeout, callback, arg, Start_Lazy);
643 }
644
645 /**
646  * Queues urgently a new asynchronous job represented by 'callback' and 'arg'
647  * for the 'group' and the 'timeout'.
648  * Jobs are queued FIFO and are possibly executed in parallel
649  * concurrently except for job of the same group that are
650  * executed sequentially in FIFO order.
651  * @param group    The group of the job or NULL when no group.
652  * @param timeout  The maximum execution time in seconds of the job
653  *                 or 0 for unlimited time.
654  * @param callback The function to execute for achieving the job.
655  *                 Its first parameter is either 0 on normal flow
656  *                 or the signal number that broke the normal flow.
657  *                 The remaining parameter is the parameter 'arg1'
658  *                 given here.
659  * @param arg      The second argument for 'callback'
660  * @return 0 in case of success or -1 in case of error
661  */
662 int jobs_queue_urgent(
663                 const void *group,
664                 int timeout,
665                 void (*callback)(int, void*),
666                 void *arg)
667 {
668         return queue_job(group, timeout, callback, arg, Start_Urgent);
669 }
670
671 /**
672  * Internal helper function for 'jobs_enter'.
673  * @see jobs_enter, jobs_leave
674  */
675 static void enter_cb(int signum, void *closure)
676 {
677         struct sync *sync = closure;
678         sync->enter(signum, sync->arg, (void*)&sync->thread);
679 }
680
681 /**
682  * Internal helper function for 'jobs_call'.
683  * @see jobs_call
684  */
685 static void call_cb(int signum, void *closure)
686 {
687         struct sync *sync = closure;
688         sync->callback(signum, sync->arg);
689         jobs_leave((void*)&sync->thread);
690 }
691
692 /**
693  * Internal helper for synchronous jobs. It enters
694  * a new thread loop for evaluating the given job
695  * as recorded by the couple 'sync_cb' and 'sync'.
696  * @see jobs_call, jobs_enter, jobs_leave
697  */
698 static int do_sync(
699                 const void *group,
700                 int timeout,
701                 void (*sync_cb)(int signum, void *closure),
702                 struct sync *sync
703 )
704 {
705         int rc;
706
707         pthread_mutex_lock(&mutex);
708
709         rc = queue_job_internal(group, timeout, sync_cb, sync, Start_Default);
710         if (rc == 0) {
711                 /* run until stopped */
712                 if (current_thread)
713                         thread_run_internal(&sync->thread);
714                 else
715                         thread_run_external(&sync->thread);
716                 if (!sync->thread.leaved) {
717                         errno = EINTR;
718                         rc = -1;
719                 }
720         }
721         pthread_mutex_unlock(&mutex);
722         return rc;
723 }
724
725 /**
726  * Enter a synchronisation point: activates the job given by 'callback'
727  * and 'closure' using 'group' and 'timeout' to control sequencing and
728  * execution time.
729  * @param group the group for sequencing jobs
730  * @param timeout the time in seconds allocated to the job
731  * @param callback the callback that will handle the job.
732  *                 it receives 3 parameters: 'signum' that will be 0
733  *                 on normal flow or the catched signal number in case
734  *                 of interrupted flow, the context 'closure' as given and
735  *                 a 'jobloop' reference that must be used when the job is
736  *                 terminated to unlock the current execution flow.
737  * @param closure the argument to the callback
738  * @return 0 on success or -1 in case of error
739  */
740 int jobs_enter(
741                 const void *group,
742                 int timeout,
743                 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
744                 void *closure
745 )
746 {
747         struct sync sync;
748
749         sync.enter = callback;
750         sync.arg = closure;
751         return do_sync(group, timeout, enter_cb, &sync);
752 }
753
754 /**
755  * Unlocks the execution flow designed by 'jobloop'.
756  * @param jobloop indication of the flow to unlock
757  * @return 0 in case of success of -1 on error
758  */
759 int jobs_leave(struct jobloop *jobloop)
760 {
761         struct thread *t;
762
763         pthread_mutex_lock(&mutex);
764         t = threads;
765         while (t && t != (struct thread*)jobloop)
766                 t = t->next;
767         if (!t) {
768                 errno = EINVAL;
769         } else {
770                 t->leaved = 1;
771                 t->stop = 1;
772                 if (t->waits)
773                         pthread_cond_broadcast(&cond);
774                 else
775                         evloop_wakeup();
776         }
777         pthread_mutex_unlock(&mutex);
778         return -!t;
779 }
780
781 /**
782  * Calls synchronously the job represented by 'callback' and 'arg1'
783  * for the 'group' and the 'timeout' and waits for its completion.
784  * @param group    The group of the job or NULL when no group.
785  * @param timeout  The maximum execution time in seconds of the job
786  *                 or 0 for unlimited time.
787  * @param callback The function to execute for achieving the job.
788  *                 Its first parameter is either 0 on normal flow
789  *                 or the signal number that broke the normal flow.
790  *                 The remaining parameter is the parameter 'arg1'
791  *                 given here.
792  * @param arg      The second argument for 'callback'
793  * @return 0 in case of success or -1 in case of error
794  */
795 int jobs_call(
796                 const void *group,
797                 int timeout,
798                 void (*callback)(int, void*),
799                 void *arg)
800 {
801         struct sync sync;
802
803         sync.callback = callback;
804         sync.arg = arg;
805
806         return do_sync(group, timeout, call_cb, &sync);
807 }
808
809 /**
810  * Ensure that the current running thread can control the event loop.
811  */
812 void jobs_acquire_event_manager()
813 {
814         struct thread lt;
815
816         /* ensure an existing thread environment */
817         if (!current_thread) {
818                 memset(&lt, 0, sizeof lt);
819                 current_thread = &lt;
820         }
821
822         /* lock */
823         pthread_mutex_lock(&mutex);
824
825         /* creates the evloop on need */
826         if (!evmgr)
827                 evmgr_create(&evmgr);
828
829         /* acquire the event loop under lock */
830         if (evmgr)
831                 evloop_acquire();
832
833         /* unlock */
834         pthread_mutex_unlock(&mutex);
835
836         /* release the faked thread environment if needed */
837         if (current_thread == &lt) {
838                 /*
839                  * Releasing it is needed because there is no way to guess
840                  * when it has to be released really. But here is where it is
841                  * hazardous: if the caller modifies the eventloop when it
842                  * is waiting, there is no way to make the change effective.
843                  * A workaround to achieve that goal is for the caller to
844                  * require the event loop a second time after having modified it.
845                  */
846                 NOTICE("Requiring event manager/loop from outside of binder's callback is hazardous!");
847                 if (verbose_wants(Log_Level_Info))
848                         sig_monitor_dumpstack();
849                 evloop_release();
850                 current_thread = NULL;
851         }
852 }
853
854 /**
855  * Enter the jobs processing loop.
856  * @param allowed_count Maximum count of thread for jobs including this one
857  * @param start_count   Count of thread to start now, must be lower.
858  * @param waiter_count  Maximum count of jobs that can be waiting.
859  * @param start         The start routine to activate (can't be NULL)
860  * @return 0 in case of success or -1 in case of error.
861  */
862 int jobs_start(
863         int allowed_count,
864         int start_count,
865         int waiter_count,
866         void (*start)(int signum, void* arg),
867         void *arg)
868 {
869         int rc, launched;
870         struct job *job;
871
872         assert(allowed_count >= 1);
873         assert(start_count >= 0);
874         assert(waiter_count > 0);
875         assert(start_count <= allowed_count);
876
877         rc = -1;
878         pthread_mutex_lock(&mutex);
879
880         /* check whether already running */
881         if (current_thread || allowed_thread_count) {
882                 ERROR("thread already started");
883                 errno = EINVAL;
884                 goto error;
885         }
886
887         /* records the allowed count */
888         allowed_thread_count = allowed_count;
889         started_thread_count = 0;
890         busy_thread_count = 0;
891         remaining_job_count = waiter_count;
892         allowed_job_count = waiter_count;
893
894         /* start at least one thread: the current one */
895         launched = 1;
896         while (launched < start_count) {
897                 if (start_one_thread() != 0) {
898                         ERROR("Not all threads can be started");
899                         goto error;
900                 }
901                 launched++;
902         }
903
904         /* queue the start job */
905         job = job_create(NULL, 0, start, arg);
906         if (!job)
907                 goto error;
908         job_add(job);
909
910         /* run until end */
911         thread_main();
912         rc = 0;
913 error:
914         pthread_mutex_unlock(&mutex);
915         if (exit_handler)
916                 exit_handler();
917         return rc;
918 }
919
920 /**
921  * Exit jobs threads and call handler if not NULL.
922  */
923 void jobs_exit(void (*handler)())
924 {
925         struct thread *t;
926
927         /* request all threads to stop */
928         pthread_mutex_lock(&mutex);
929
930         /* set the handler */
931         exit_handler = handler;
932
933         /* stops the threads */
934         t = threads;
935         while (t) {
936                 t->stop = 1;
937                 t = t->next;
938         }
939
940         /* wake up the threads */
941         evloop_wakeup();
942         pthread_cond_broadcast(&cond);
943
944         /* leave */
945         pthread_mutex_unlock(&mutex);
946 }