2 * Copyright (C) 2016, 2017 "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.
25 #include <sys/syscall.h>
29 #include <sys/eventfd.h>
31 #include <systemd/sd-event.h>
34 #include "sig-monitor.h"
38 #define _alert_ "do you really want to remove monitoring?"
39 #define sig_monitor_init_timeouts() ((void)0)
40 #define sig_monitor_clean_timeouts() ((void)0)
41 #define sig_monitor(to,cb,arg) (cb(0,arg))
44 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
45 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
47 /** Internal shortcut for callback */
48 typedef void (*job_cb_t)(int, void*);
50 /** Description of a pending job */
53 struct job *next; /**< link to the next job enqueued */
54 const void *group; /**< group of the request */
55 job_cb_t callback; /**< processing callback */
56 void *arg; /**< argument */
57 int timeout; /**< timeout in second for processing the request */
58 unsigned blocked: 1; /**< is an other request blocking this one ? */
59 unsigned dropped: 1; /**< is removed ? */
62 /** Description of handled event loops */
65 unsigned state; /**< encoded state */
66 int efd; /**< event notification */
67 struct sd_event *sdev; /**< the systemd event loop */
68 pthread_cond_t cond; /**< condition */
71 #define EVLOOP_STATE_WAIT 1U
72 #define EVLOOP_STATE_RUN 2U
73 #define EVLOOP_STATE_LOCK 4U
75 /** Description of threads */
78 struct thread *next; /**< next thread of the list */
79 struct thread *upper; /**< upper same thread */
80 struct job *job; /**< currently processed job */
81 pthread_t tid; /**< the thread id */
82 unsigned stop: 1; /**< stop requested */
83 unsigned waits: 1; /**< is waiting? */
87 * Description of synchonous callback
91 struct thread thread; /**< thread loop data */
93 void (*callback)(int, void*); /**< the synchronous callback */
94 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
95 /**< the entering synchronous routine */
97 void *arg; /**< the argument of the callback */
101 /* synchronisation of threads */
102 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
103 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
105 /* count allowed, started and running threads */
106 static int allowed = 0; /** allowed count of threads */
107 static int started = 0; /** started count of threads */
108 static int running = 0; /** running count of threads */
109 static int remains = 0; /** allowed count of waiting jobs */
111 /* list of threads */
112 static struct thread *threads;
113 static _Thread_local struct thread *current_thread;
114 static _Thread_local struct evloop *current_evloop;
116 /* queue of pending jobs */
117 static struct job *first_job;
118 static struct job *free_jobs;
121 static struct evloop evloop[1];
124 * Create a new job with the given parameters
125 * @param group the group of the job
126 * @param timeout the timeout of the job (0 if none)
127 * @param callback the function that achieves the job
128 * @param arg the argument of the callback
129 * @return the created job unblock or NULL when no more memory
131 static struct job *job_create(
139 /* try recyle existing job */
142 free_jobs = job->next;
144 /* allocation without blocking */
145 pthread_mutex_unlock(&mutex);
146 job = malloc(sizeof *job);
147 pthread_mutex_lock(&mutex);
153 /* initialises the job */
155 job->timeout = timeout;
156 job->callback = callback;
165 * Adds 'job' at the end of the list of jobs, marking it
166 * as blocked if an other job with the same group is pending.
167 * @param job the job to add
169 static void job_add(struct job *job)
172 struct job *ijob, **pjob;
178 /* search end and blockers */
182 if (group && ijob->group == group)
193 * Get the next job to process or NULL if none.
194 * @return the first job that isn't blocked or NULL
196 static inline struct job *job_get()
198 struct job *job = first_job;
199 while (job && job->blocked)
205 * Releases the processed 'job': removes it
206 * from the list of jobs and unblock the first
207 * pending job of the same group if any.
208 * @param job the job to release
210 static inline void job_release(struct job *job)
212 struct job *ijob, **pjob;
215 /* first unqueue the job */
218 while (ijob != job) {
224 /* then unblock jobs of the same group */
228 while (ijob && ijob->group != group)
234 /* recycle the job */
235 job->next = free_jobs;
240 * Monitored cancel callback for a job.
241 * This function is called by the monitor
242 * to cancel the job when the safe environment
244 * @param signum 0 on normal flow or the number
245 * of the signal that interrupted the normal
247 * @param arg the job to run
249 static void job_cancel(int signum, void *arg)
251 struct job *job = arg;
252 job->callback(SIGABRT, job->arg);
256 * Monitored normal callback for events.
257 * This function is called by the monitor
258 * to run the event loop when the safe environment
260 * @param signum 0 on normal flow or the number
261 * of the signal that interrupted the normal
263 * @param arg the events to run
265 static void evloop_run(int signum, void *arg)
269 struct evloop *el = arg;
273 rc = sd_event_prepare(se);
276 ERROR("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
279 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
282 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
285 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT), __ATOMIC_RELAXED);
288 rc = sd_event_dispatch(se);
291 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
296 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT|EVLOOP_STATE_RUN), __ATOMIC_RELAXED);
301 * Main processing loop of threads processing jobs.
302 * The loop must be called with the mutex locked
303 * and it returns with the mutex locked.
304 * @param me the description of the thread to use
305 * TODO: how are timeout handled when reentering?
307 static void thread_run(volatile struct thread *me)
313 /* initialize description of itself and link it in the list */
314 me->tid = pthread_self();
317 me->upper = current_thread;
318 if (!current_thread) {
320 sig_monitor_init_timeouts();
323 threads = (struct thread*)me;
324 current_thread = (struct thread*)me;
326 /* loop until stopped */
328 /* release the event loop */
329 if (current_evloop) {
330 __atomic_sub_fetch(¤t_evloop->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
331 current_evloop = NULL;
335 job = job_get(first_job);
337 /* prepare running the job */
338 remains++; /* increases count of job that can wait */
339 job->blocked = 1; /* mark job as blocked */
340 me->job = job; /* record the job (only for terminate) */
343 pthread_mutex_unlock(&mutex);
344 sig_monitor(job->timeout, job->callback, job->arg);
345 pthread_mutex_lock(&mutex);
347 /* release the run job */
350 /* no job, check events */
352 if (el->sdev && !__atomic_load_n(&el->state, __ATOMIC_RELAXED)) {
354 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
356 pthread_mutex_unlock(&mutex);
357 sig_monitor(0, evloop_run, el);
358 pthread_mutex_lock(&mutex);
360 /* no job and not events */
363 ERROR("Entering job deep sleep! Check your bindings.");
365 pthread_cond_wait(&cond, &mutex);
372 /* release the event loop */
373 if (current_evloop) {
374 __atomic_sub_fetch(¤t_evloop->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
375 current_evloop = NULL;
378 /* unlink the current thread and cleanup */
383 current_thread = me->upper;
384 if (!current_thread) {
385 sig_monitor_clean_timeouts();
391 * Entry point for created threads.
392 * @param data not used
395 static void *thread_main(void *data)
399 pthread_mutex_lock(&mutex);
403 pthread_mutex_unlock(&mutex);
408 * Starts a new thread
409 * @return 0 in case of success or -1 in case of error
411 static int start_one_thread()
416 rc = pthread_create(&tid, NULL, thread_main, NULL);
419 WARNING("not able to start thread: %m");
426 * Queues a new asynchronous job represented by 'callback' and 'arg'
427 * for the 'group' and the 'timeout'.
428 * Jobs are queued FIFO and are possibly executed in parallel
429 * concurrently except for job of the same group that are
430 * executed sequentially in FIFO order.
431 * @param group The group of the job or NULL when no group.
432 * @param timeout The maximum execution time in seconds of the job
433 * or 0 for unlimited time.
434 * @param callback The function to execute for achieving the job.
435 * Its first parameter is either 0 on normal flow
436 * or the signal number that broke the normal flow.
437 * The remaining parameter is the parameter 'arg1'
439 * @param arg The second argument for 'callback'
440 * @return 0 in case of success or -1 in case of error
445 void (*callback)(int, void*),
452 pthread_mutex_lock(&mutex);
454 /* allocates the job */
455 job = job_create(group, timeout, callback, arg);
458 info = "out of memory";
462 /* check availability */
465 info = "too many jobs";
469 /* start a thread if needed */
470 if (running == started && started < allowed) {
471 /* all threads are busy and a new can be started */
472 rc = start_one_thread();
473 if (rc < 0 && started == 0) {
474 info = "can't start first thread";
483 /* signal an existing job */
484 pthread_cond_signal(&cond);
485 pthread_mutex_unlock(&mutex);
489 job->next = free_jobs;
492 ERROR("can't process job with threads: %s, %m", info);
493 pthread_mutex_unlock(&mutex);
498 * Internal helper function for 'jobs_enter'.
499 * @see jobs_enter, jobs_leave
501 static void enter_cb(int signum, void *closure)
503 struct sync *sync = closure;
504 sync->enter(signum, sync->arg, (void*)&sync->thread);
508 * Internal helper function for 'jobs_call'.
511 static void call_cb(int signum, void *closure)
513 struct sync *sync = closure;
514 sync->callback(signum, sync->arg);
515 jobs_leave((void*)&sync->thread);
519 * Internal helper for synchronous jobs. It enters
520 * a new thread loop for evaluating the given job
521 * as recorded by the couple 'sync_cb' and 'sync'.
522 * @see jobs_call, jobs_enter, jobs_leave
527 void (*sync_cb)(int signum, void *closure),
533 pthread_mutex_lock(&mutex);
535 /* allocates the job */
536 job = job_create(group, timeout, sync_cb, sync);
538 ERROR("out of memory");
540 pthread_mutex_unlock(&mutex);
547 /* run until stopped */
548 thread_run(&sync->thread);
549 pthread_mutex_unlock(&mutex);
554 * Enter a synchronisation point: activates the job given by 'callback'
555 * and 'closure' using 'group' and 'timeout' to control sequencing and
557 * @param group the group for sequencing jobs
558 * @param timeout the time in seconds allocated to the job
559 * @param callback the callback that will handle the job.
560 * it receives 3 parameters: 'signum' that will be 0
561 * on normal flow or the catched signal number in case
562 * of interrupted flow, the context 'closure' as given and
563 * a 'jobloop' reference that must be used when the job is
564 * terminated to unlock the current execution flow.
565 * @param arg the argument to the callback
566 * @return 0 on success or -1 in case of error
571 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
577 sync.enter = callback;
579 return do_sync(group, timeout, enter_cb, &sync);
583 * Unlocks the execution flow designed by 'jobloop'.
584 * @param jobloop indication of the flow to unlock
585 * @return 0 in case of success of -1 on error
587 int jobs_leave(struct jobloop *jobloop)
591 pthread_mutex_lock(&mutex);
593 while (t && t != (struct thread*)jobloop)
600 pthread_cond_broadcast(&cond);
602 pthread_mutex_unlock(&mutex);
607 * Calls synchronously the job represented by 'callback' and 'arg1'
608 * for the 'group' and the 'timeout' and waits for its completion.
609 * @param group The group of the job or NULL when no group.
610 * @param timeout The maximum execution time in seconds of the job
611 * or 0 for unlimited time.
612 * @param callback The function to execute for achieving the job.
613 * Its first parameter is either 0 on normal flow
614 * or the signal number that broke the normal flow.
615 * The remaining parameter is the parameter 'arg1'
617 * @param arg The second argument for 'callback'
618 * @return 0 in case of success or -1 in case of error
623 void (*callback)(int, void*),
628 sync.callback = callback;
631 return do_sync(group, timeout, call_cb, &sync);
635 * Internal callback for evloop management.
636 * The effect of this function is hidden: it exits
637 * the waiting poll if any. Then it wakes up a thread
638 * awaiting the evloop using signal.
640 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
643 struct evloop *evloop = userdata;
644 read(evloop->efd, &x, sizeof x);
645 pthread_mutex_lock(&mutex);
646 pthread_cond_broadcast(&evloop->cond);
647 pthread_mutex_unlock(&mutex);
652 * Gets a sd_event item for the current thread.
653 * @return a sd_event or NULL in case of error
655 struct sd_event *jobs_get_sd_event()
661 pthread_mutex_lock(&mutex);
663 /* creates the evloop on need */
666 /* start the creation */
668 /* creates the eventfd for waking up polls */
669 el->efd = eventfd(0, EFD_CLOEXEC);
671 ERROR("can't make eventfd for events");
674 /* create the systemd event loop */
675 rc = sd_event_new(&el->sdev);
677 ERROR("can't make new event loop");
680 /* put the eventfd in the event loop */
681 rc = sd_event_add_io(el->sdev, NULL, el->efd, EPOLLIN, on_evloop_efd, el);
683 ERROR("can't register eventfd");
684 sd_event_unref(el->sdev);
689 pthread_mutex_unlock(&mutex);
694 /* attach the event loop to the current thread */
695 if (current_evloop != el) {
697 __atomic_sub_fetch(¤t_evloop->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
699 __atomic_add_fetch(&el->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
702 /* wait for a modifiable event loop */
703 while (__atomic_load_n(&el->state, __ATOMIC_RELAXED) & EVLOOP_STATE_WAIT) {
705 write(el->efd, &x, sizeof x);
706 pthread_cond_wait(&el->cond, &mutex);
709 pthread_mutex_unlock(&mutex);
714 * Enter the jobs processing loop.
715 * @param allowed_count Maximum count of thread for jobs including this one
716 * @param start_count Count of thread to start now, must be lower.
717 * @param waiter_count Maximum count of jobs that can be waiting.
718 * @param start The start routine to activate (can't be NULL)
719 * @return 0 in case of success or -1 in case of error.
721 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum))
727 assert(allowed_count >= 1);
728 assert(start_count >= 0);
729 assert(waiter_count > 0);
730 assert(start_count <= allowed_count);
733 pthread_mutex_lock(&mutex);
735 /* check whether already running */
736 if (current_thread || allowed) {
737 ERROR("thread already started");
743 if (sig_monitor_init() < 0) {
744 ERROR("failed to initialise signal handlers");
748 /* records the allowed count */
749 allowed = allowed_count;
752 remains = waiter_count;
754 /* start at least one thread */
756 while ((launched + 1) < start_count) {
757 if (start_one_thread() != 0) {
758 ERROR("Not all threads can be started");
764 /* queue the start job */
765 job = job_create(NULL, 0, (job_cb_t)start, NULL);
767 ERROR("out of memory");
778 pthread_mutex_unlock(&mutex);
783 * Terminate all the threads and cancel all pending jobs.
785 void jobs_terminate()
787 struct job *job, *head, *tail;
788 pthread_t me, *others;
795 /* request all threads to stop */
796 pthread_mutex_lock(&mutex);
799 /* count the number of threads */
803 if (!t->upper && !pthread_equal(t->tid, me))
808 /* fill the array of threads */
809 others = alloca(count * sizeof *others);
813 if (!t->upper && !pthread_equal(t->tid, me))
814 others[count++] = t->tid;
818 /* stops the threads */
825 /* wait the threads */
826 pthread_cond_broadcast(&cond);
827 pthread_mutex_unlock(&mutex);
829 pthread_join(others[--count], NULL);
830 pthread_mutex_lock(&mutex);
832 /* cancel pending jobs of other threads */
842 /* search if job is stacked for current */
844 while (t && t->job != job)
847 /* yes, relink it at end */
855 /* no cancel the job */
856 pthread_mutex_unlock(&mutex);
857 sig_monitor(0, job_cancel, job);
859 pthread_mutex_lock(&mutex);
862 pthread_mutex_unlock(&mutex);