2 * Copyright (C) 2016-2019 "IoT.bzh"
3 * Author José Bollo <jose.bollo@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
31 #include "sig-monitor.h"
34 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
35 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
39 /** Internal shortcut for callback */
40 typedef void (*job_cb_t)(int, void*);
42 /** Description of a pending job */
45 struct job *next; /**< link to the next job enqueued */
46 const void *group; /**< group of the request */
47 job_cb_t callback; /**< processing callback */
48 void *arg; /**< argument */
49 int timeout; /**< timeout in second for processing the request */
50 unsigned blocked: 1; /**< is an other request blocking this one ? */
51 unsigned dropped: 1; /**< is removed ? */
54 /** Description of threads */
57 struct thread *next; /**< next thread of the list */
58 struct thread *upper; /**< upper same thread */
59 struct thread *nholder;/**< next holder for evloop */
60 pthread_cond_t *cwhold;/**< condition wait for holding */
61 struct job *job; /**< currently processed job */
62 pthread_t tid; /**< the thread id */
63 volatile unsigned stop: 1; /**< stop requested */
64 volatile unsigned waits: 1; /**< is waiting? */
65 volatile unsigned leaved: 1; /**< was leaved? */
69 * Description of synchronous callback
73 struct thread thread; /**< thread loop data */
75 void (*callback)(int, void*); /**< the synchronous callback */
76 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
77 /**< the entering synchronous routine */
79 void *arg; /**< the argument of the callback */
82 /* synchronisation of threads */
83 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
84 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
86 /* count allowed, started and running threads */
87 static int allowed = 0; /** allowed count of threads */
88 static int started = 0; /** started count of threads */
89 static int running = 0; /** running count of threads */
90 static int remains = 0; /** allowed count of waiting jobs */
93 static struct thread *threads;
94 static _Thread_local struct thread *current_thread;
96 /* queue of pending jobs */
97 static struct job *first_job;
98 static struct job *free_jobs;
101 static struct evmgr *evmgr;
103 static void (*exit_handler)();
106 * Create a new job with the given parameters
107 * @param group the group of the job
108 * @param timeout the timeout of the job (0 if none)
109 * @param callback the function that achieves the job
110 * @param arg the argument of the callback
111 * @return the created job unblock or NULL when no more memory
113 static struct job *job_create(
121 /* try recyle existing job */
124 free_jobs = job->next;
126 /* allocation without blocking */
127 pthread_mutex_unlock(&mutex);
128 job = malloc(sizeof *job);
129 pthread_mutex_lock(&mutex);
131 ERROR("out of memory");
136 /* initialises the job */
138 job->timeout = timeout;
139 job->callback = callback;
148 * Adds 'job' at the end of the list of jobs, marking it
149 * as blocked if an other job with the same group is pending.
150 * @param job the job to add
152 static void job_add(struct job *job)
155 struct job *ijob, **pjob;
161 /* search end and blockers */
165 if (group && ijob->group == group)
177 * Get the next job to process or NULL if none.
178 * @return the first job that isn't blocked or NULL
180 static inline struct job *job_get()
182 struct job *job = first_job;
183 while (job && job->blocked)
191 * Releases the processed 'job': removes it
192 * from the list of jobs and unblock the first
193 * pending job of the same group if any.
194 * @param job the job to release
196 static inline void job_release(struct job *job)
198 struct job *ijob, **pjob;
201 /* first unqueue the job */
204 while (ijob != job) {
210 /* then unblock jobs of the same group */
214 while (ijob && ijob->group != group)
220 /* recycle the job */
221 job->next = free_jobs;
226 * Monitored cancel callback for a job.
227 * This function is called by the monitor
228 * to cancel the job when the safe environment
230 * @param signum 0 on normal flow or the number
231 * of the signal that interrupted the normal
233 * @param arg the job to run
235 __attribute__((unused))
236 static void job_cancel(int signum, void *arg)
238 struct job *job = arg;
239 job->callback(SIGABRT, job->arg);
243 * wakeup the event loop if needed by sending
246 static void evloop_wakeup()
253 * Release the currently held event loop
255 static void evloop_release()
257 struct thread *nh, *ct = current_thread;
259 if (ct && evmgr && evmgr_release_if(evmgr, ct)) {
263 evmgr_try_hold(evmgr, nh);
264 pthread_cond_signal(nh->cwhold);
270 * get the eventloop for the current thread
272 static int evloop_get()
274 return evmgr && evmgr_try_hold(evmgr, current_thread);
278 * acquire the eventloop for the current thread
280 static void evloop_acquire()
282 struct thread *pwait, *ct;
285 /* try to get the evloop */
287 /* failed, init waiting state */
291 pthread_cond_init(&cond, NULL);
293 /* queue current thread in holder list */
294 pwait = evmgr_holder(evmgr);
295 while (pwait->nholder)
296 pwait = pwait->nholder;
299 /* wake up the evloop */
302 /* wait to acquire the evloop */
303 pthread_cond_wait(&cond, &mutex);
304 pthread_cond_destroy(&cond);
310 * @param me the description of the thread to enter
312 static void thread_enter(volatile struct thread *me)
315 /* initialize description of itself and link it in the list */
316 me->tid = pthread_self();
321 me->upper = current_thread;
323 threads = (struct thread*)me;
324 current_thread = (struct thread*)me;
329 * @param me the description of the thread to leave
331 static void thread_leave()
333 struct thread **prv, *me;
335 /* unlink the current thread and cleanup */
342 current_thread = me->upper;
346 * Main processing loop of internal threads with processing jobs.
347 * The loop must be called with the mutex locked
348 * and it returns with the mutex locked.
349 * @param me the description of the thread to use
350 * TODO: how are timeout handled when reentering?
352 static void thread_run_internal(volatile struct thread *me)
359 /* loop until stopped */
361 /* release the current event loop */
367 /* prepare running the job */
368 job->blocked = 1; /* mark job as blocked */
369 me->job = job; /* record the job (only for terminate) */
372 pthread_mutex_unlock(&mutex);
373 sig_monitor(job->timeout, job->callback, job->arg);
374 pthread_mutex_lock(&mutex);
376 /* release the run job */
378 /* no job, check event loop wait */
379 } else if (evloop_get()) {
380 if (!evmgr_can_run(evmgr)) {
382 CRITICAL("Can't enter dispatch while in dispatch!");
386 pthread_mutex_unlock(&mutex);
387 sig_monitor(0, (void(*)(int,void*))evmgr_job_run, evmgr);
388 pthread_mutex_lock(&mutex);
390 /* no job and no event loop */
393 ERROR("Entering job deep sleep! Check your bindings.");
395 pthread_cond_wait(&cond, &mutex);
406 * Main processing loop of external threads.
407 * The loop must be called with the mutex locked
408 * and it returns with the mutex locked.
409 * @param me the description of the thread to use
411 static void thread_run_external(volatile struct thread *me)
416 /* loop until stopped */
419 pthread_cond_wait(&cond, &mutex);
425 * Root for created threads.
427 static void thread_main()
433 sig_monitor_init_timeouts();
434 thread_run_internal(&me);
435 sig_monitor_clean_timeouts();
441 * Entry point for created threads.
442 * @param data not used
445 static void *thread_starter(void *data)
447 pthread_mutex_lock(&mutex);
449 pthread_mutex_unlock(&mutex);
454 * Starts a new thread
455 * @return 0 in case of success or -1 in case of error
457 static int start_one_thread()
462 rc = pthread_create(&tid, NULL, thread_starter, NULL);
465 WARNING("not able to start thread: %m");
472 * Queues a new asynchronous job represented by 'callback' and 'arg'
473 * for the 'group' and the 'timeout'.
474 * Jobs are queued FIFO and are possibly executed in parallel
475 * concurrently except for job of the same group that are
476 * executed sequentially in FIFO order.
477 * @param group The group of the job or NULL when no group.
478 * @param timeout The maximum execution time in seconds of the job
479 * or 0 for unlimited time.
480 * @param callback The function to execute for achieving the job.
481 * Its first parameter is either 0 on normal flow
482 * or the signal number that broke the normal flow.
483 * The remaining parameter is the parameter 'arg1'
485 * @param arg The second argument for 'callback'
486 * @param start Allow to start a thread if not zero
487 * @return 0 in case of success or -1 in case of error
489 static int queue_job(
492 void (*callback)(int, void*),
499 pthread_mutex_lock(&mutex);
501 /* allocates the job */
502 job = job_create(group, timeout, callback, arg);
506 /* check availability */
508 ERROR("can't process job with threads: too many jobs");
513 /* start a thread if needed */
514 if (start && running == started && started < allowed) {
515 /* all threads are busy and a new can be started */
516 rc = start_one_thread();
517 if (rc < 0 && started == 0) {
518 ERROR("can't start initial thread: %m");
526 /* signal an existing job */
527 pthread_cond_signal(&cond);
528 pthread_mutex_unlock(&mutex);
532 job->next = free_jobs;
535 pthread_mutex_unlock(&mutex);
540 * Queues a new asynchronous job represented by 'callback' and 'arg'
541 * for the 'group' and the 'timeout'.
542 * Jobs are queued FIFO and are possibly executed in parallel
543 * concurrently except for job of the same group that are
544 * executed sequentially in FIFO order.
545 * @param group The group of the job or NULL when no group.
546 * @param timeout The maximum execution time in seconds of the job
547 * or 0 for unlimited time.
548 * @param callback The function to execute for achieving the job.
549 * Its first parameter is either 0 on normal flow
550 * or the signal number that broke the normal flow.
551 * The remaining parameter is the parameter 'arg1'
553 * @param arg The second argument for 'callback'
554 * @return 0 in case of success or -1 in case of error
559 void (*callback)(int, void*),
562 return queue_job(group, timeout, callback, arg, 1);
566 * Internal helper function for 'jobs_enter'.
567 * @see jobs_enter, jobs_leave
569 static void enter_cb(int signum, void *closure)
571 struct sync *sync = closure;
572 sync->enter(signum, sync->arg, (void*)&sync->thread);
576 * Internal helper function for 'jobs_call'.
579 static void call_cb(int signum, void *closure)
581 struct sync *sync = closure;
582 sync->callback(signum, sync->arg);
583 jobs_leave((void*)&sync->thread);
587 * Internal helper for synchronous jobs. It enters
588 * a new thread loop for evaluating the given job
589 * as recorded by the couple 'sync_cb' and 'sync'.
590 * @see jobs_call, jobs_enter, jobs_leave
595 void (*sync_cb)(int signum, void *closure),
601 pthread_mutex_lock(&mutex);
603 /* allocates the job */
604 job = job_create(group, timeout, sync_cb, sync);
606 pthread_mutex_unlock(&mutex);
613 /* run until stopped */
615 thread_run_internal(&sync->thread);
617 thread_run_external(&sync->thread);
618 pthread_mutex_unlock(&mutex);
619 if (sync->thread.leaved)
626 * Enter a synchronisation point: activates the job given by 'callback'
627 * and 'closure' using 'group' and 'timeout' to control sequencing and
629 * @param group the group for sequencing jobs
630 * @param timeout the time in seconds allocated to the job
631 * @param callback the callback that will handle the job.
632 * it receives 3 parameters: 'signum' that will be 0
633 * on normal flow or the catched signal number in case
634 * of interrupted flow, the context 'closure' as given and
635 * a 'jobloop' reference that must be used when the job is
636 * terminated to unlock the current execution flow.
637 * @param closure the argument to the callback
638 * @return 0 on success or -1 in case of error
643 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
649 sync.enter = callback;
651 return do_sync(group, timeout, enter_cb, &sync);
655 * Unlocks the execution flow designed by 'jobloop'.
656 * @param jobloop indication of the flow to unlock
657 * @return 0 in case of success of -1 on error
659 int jobs_leave(struct jobloop *jobloop)
663 pthread_mutex_lock(&mutex);
665 while (t && t != (struct thread*)jobloop)
673 pthread_cond_broadcast(&cond);
677 pthread_mutex_unlock(&mutex);
682 * Calls synchronously the job represented by 'callback' and 'arg1'
683 * for the 'group' and the 'timeout' and waits for its completion.
684 * @param group The group of the job or NULL when no group.
685 * @param timeout The maximum execution time in seconds of the job
686 * or 0 for unlimited time.
687 * @param callback The function to execute for achieving the job.
688 * Its first parameter is either 0 on normal flow
689 * or the signal number that broke the normal flow.
690 * The remaining parameter is the parameter 'arg1'
692 * @param arg The second argument for 'callback'
693 * @return 0 in case of success or -1 in case of error
698 void (*callback)(int, void*),
703 sync.callback = callback;
706 return do_sync(group, timeout, call_cb, &sync);
710 * Ensure that the current running thread can control the event loop.
712 struct evmgr *jobs_acquire_event_manager()
716 /* ensure an existing thread environment */
717 if (!current_thread) {
718 memset(<, 0, sizeof lt);
719 current_thread = <
723 pthread_mutex_lock(&mutex);
725 /* creates the evloop on need */
727 evmgr_create(&evmgr);
729 /* acquire the event loop under lock */
734 pthread_mutex_unlock(&mutex);
736 /* release the faked thread environment if needed */
737 if (current_thread == <) {
739 * Releasing it is needed because there is no way to guess
740 * when it has to be released really. But here is where it is
741 * hazardous: if the caller modifies the eventloop when it
742 * is waiting, there is no way to make the change effective.
743 * A workaround to achieve that goal is for the caller to
744 * require the event loop a second time after having modified it.
746 NOTICE("Requiring event manager/loop from outside of binder's callback is hazardous!");
747 if (verbose_wants(Log_Level_Info))
748 sig_monitor_dumpstack();
750 current_thread = NULL;
756 * Enter the jobs processing loop.
757 * @param allowed_count Maximum count of thread for jobs including this one
758 * @param start_count Count of thread to start now, must be lower.
759 * @param waiter_count Maximum count of jobs that can be waiting.
760 * @param start The start routine to activate (can't be NULL)
761 * @return 0 in case of success or -1 in case of error.
763 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
768 assert(allowed_count >= 1);
769 assert(start_count >= 0);
770 assert(waiter_count > 0);
771 assert(start_count <= allowed_count);
774 pthread_mutex_lock(&mutex);
776 /* check whether already running */
777 if (current_thread || allowed) {
778 ERROR("thread already started");
783 /* records the allowed count */
784 allowed = allowed_count;
787 remains = waiter_count;
789 /* start at least one thread: the current one */
791 while (launched < start_count) {
792 if (start_one_thread() != 0) {
793 ERROR("Not all threads can be started");
799 /* queue the start job */
800 job = job_create(NULL, 0, start, arg);
809 pthread_mutex_unlock(&mutex);
816 * Exit jobs threads and call handler if not NULL.
818 void jobs_exit(void (*handler)())
822 /* request all threads to stop */
823 pthread_mutex_lock(&mutex);
825 /* set the handler */
826 exit_handler = handler;
828 /* stops the threads */
835 /* wait the threads */
836 pthread_cond_broadcast(&cond);
839 pthread_mutex_unlock(&mutex);