2 * Copyright (C) 2016, 2017, 2018 "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.
20 #if defined(NO_JOBS_WATCHDOG)
21 # define HAS_WATCHDOG 0
23 # define HAS_WATCHDOG 1
31 #include <sys/syscall.h>
35 #include <sys/eventfd.h>
37 #include <systemd/sd-event.h>
39 #include <systemd/sd-daemon.h>
43 #include "sig-monitor.h"
47 #define _alert_ "do you really want to remove signal monitoring?"
48 #define sig_monitor_init_timeouts() ((void)0)
49 #define sig_monitor_clean_timeouts() ((void)0)
50 #define sig_monitor(to,cb,arg) (cb(0,arg))
53 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
54 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
56 /** Internal shortcut for callback */
57 typedef void (*job_cb_t)(int, void*);
59 /** Description of a pending job */
62 struct job *next; /**< link to the next job enqueued */
63 const void *group; /**< group of the request */
64 job_cb_t callback; /**< processing callback */
65 void *arg; /**< argument */
66 int timeout; /**< timeout in second for processing the request */
67 unsigned blocked: 1; /**< is an other request blocking this one ? */
68 unsigned dropped: 1; /**< is removed ? */
71 /** Description of handled event loops */
74 unsigned state; /**< encoded state */
75 int efd; /**< event notification */
76 struct sd_event *sdev; /**< the systemd event loop */
77 pthread_cond_t cond; /**< condition */
80 #define EVLOOP_STATE_WAIT 1U
81 #define EVLOOP_STATE_RUN 2U
82 #define EVLOOP_STATE_LOCK 4U
84 /** Description of threads */
87 struct thread *next; /**< next thread of the list */
88 struct thread *upper; /**< upper same thread */
89 struct job *job; /**< currently processed job */
90 pthread_t tid; /**< the thread id */
91 unsigned stop: 1; /**< stop requested */
92 unsigned waits: 1; /**< is waiting? */
96 * Description of synchonous callback
100 struct thread thread; /**< thread loop data */
102 void (*callback)(int, void*); /**< the synchronous callback */
103 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
104 /**< the entering synchronous routine */
106 void *arg; /**< the argument of the callback */
110 /* synchronisation of threads */
111 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
112 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
114 /* count allowed, started and running threads */
115 static int allowed = 0; /** allowed count of threads */
116 static int started = 0; /** started count of threads */
117 static int running = 0; /** running count of threads */
118 static int remains = 0; /** allowed count of waiting jobs */
120 /* list of threads */
121 static struct thread *threads;
122 static _Thread_local struct thread *current_thread;
123 static _Thread_local struct evloop *current_evloop;
125 /* queue of pending jobs */
126 static struct job *first_job;
127 static struct job *free_jobs;
130 static struct evloop evloop[1];
133 * Create a new job with the given parameters
134 * @param group the group of the job
135 * @param timeout the timeout of the job (0 if none)
136 * @param callback the function that achieves the job
137 * @param arg the argument of the callback
138 * @return the created job unblock or NULL when no more memory
140 static struct job *job_create(
148 /* try recyle existing job */
151 free_jobs = job->next;
153 /* allocation without blocking */
154 pthread_mutex_unlock(&mutex);
155 job = malloc(sizeof *job);
156 pthread_mutex_lock(&mutex);
162 /* initialises the job */
164 job->timeout = timeout;
165 job->callback = callback;
174 * Adds 'job' at the end of the list of jobs, marking it
175 * as blocked if an other job with the same group is pending.
176 * @param job the job to add
178 static void job_add(struct job *job)
181 struct job *ijob, **pjob;
187 /* search end and blockers */
191 if (group && ijob->group == group)
202 * Get the next job to process or NULL if none.
203 * @return the first job that isn't blocked or NULL
205 static inline struct job *job_get()
207 struct job *job = first_job;
208 while (job && job->blocked)
214 * Releases the processed 'job': removes it
215 * from the list of jobs and unblock the first
216 * pending job of the same group if any.
217 * @param job the job to release
219 static inline void job_release(struct job *job)
221 struct job *ijob, **pjob;
224 /* first unqueue the job */
227 while (ijob != job) {
233 /* then unblock jobs of the same group */
237 while (ijob && ijob->group != group)
243 /* recycle the job */
244 job->next = free_jobs;
249 * Monitored cancel callback for a job.
250 * This function is called by the monitor
251 * to cancel the job when the safe environment
253 * @param signum 0 on normal flow or the number
254 * of the signal that interrupted the normal
256 * @param arg the job to run
258 static void job_cancel(int signum, void *arg)
260 struct job *job = arg;
261 job->callback(SIGABRT, job->arg);
265 * Monitored normal callback for events.
266 * This function is called by the monitor
267 * to run the event loop when the safe environment
269 * @param signum 0 on normal flow or the number
270 * of the signal that interrupted the normal
272 * @param arg the events to run
274 static void evloop_run(int signum, void *arg)
278 struct evloop *el = arg;
282 rc = sd_event_prepare(se);
285 ERROR("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
288 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
291 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
294 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT), __ATOMIC_RELAXED);
297 rc = sd_event_dispatch(se);
300 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
305 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT|EVLOOP_STATE_RUN), __ATOMIC_RELAXED);
310 * Main processing loop of threads processing jobs.
311 * The loop must be called with the mutex locked
312 * and it returns with the mutex locked.
313 * @param me the description of the thread to use
314 * TODO: how are timeout handled when reentering?
316 static void thread_run(volatile struct thread *me)
322 /* initialize description of itself and link it in the list */
323 me->tid = pthread_self();
326 me->upper = current_thread;
327 if (!current_thread) {
329 sig_monitor_init_timeouts();
332 threads = (struct thread*)me;
333 current_thread = (struct thread*)me;
335 /* loop until stopped */
337 /* release the event loop */
338 if (current_evloop) {
339 __atomic_sub_fetch(¤t_evloop->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
340 current_evloop = NULL;
344 job = job_get(first_job);
346 /* prepare running the job */
347 remains++; /* increases count of job that can wait */
348 job->blocked = 1; /* mark job as blocked */
349 me->job = job; /* record the job (only for terminate) */
352 pthread_mutex_unlock(&mutex);
353 sig_monitor(job->timeout, job->callback, job->arg);
354 pthread_mutex_lock(&mutex);
356 /* release the run job */
359 /* no job, check events */
361 if (el->sdev && !__atomic_load_n(&el->state, __ATOMIC_RELAXED)) {
363 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
365 pthread_mutex_unlock(&mutex);
366 sig_monitor(0, evloop_run, el);
367 pthread_mutex_lock(&mutex);
369 /* no job and not events */
372 ERROR("Entering job deep sleep! Check your bindings.");
374 pthread_cond_wait(&cond, &mutex);
381 /* release the event loop */
382 if (current_evloop) {
383 __atomic_sub_fetch(¤t_evloop->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
384 current_evloop = NULL;
387 /* unlink the current thread and cleanup */
392 current_thread = me->upper;
393 if (!current_thread) {
394 sig_monitor_clean_timeouts();
400 * Entry point for created threads.
401 * @param data not used
404 static void *thread_main(void *data)
408 pthread_mutex_lock(&mutex);
412 pthread_mutex_unlock(&mutex);
417 * Starts a new thread
418 * @return 0 in case of success or -1 in case of error
420 static int start_one_thread()
425 rc = pthread_create(&tid, NULL, thread_main, NULL);
428 WARNING("not able to start thread: %m");
435 * Queues a new asynchronous job represented by 'callback' and 'arg'
436 * for the 'group' and the 'timeout'.
437 * Jobs are queued FIFO and are possibly executed in parallel
438 * concurrently except for job of the same group that are
439 * executed sequentially in FIFO order.
440 * @param group The group of the job or NULL when no group.
441 * @param timeout The maximum execution time in seconds of the job
442 * or 0 for unlimited time.
443 * @param callback The function to execute for achieving the job.
444 * Its first parameter is either 0 on normal flow
445 * or the signal number that broke the normal flow.
446 * The remaining parameter is the parameter 'arg1'
448 * @param arg The second argument for 'callback'
449 * @return 0 in case of success or -1 in case of error
454 void (*callback)(int, void*),
461 pthread_mutex_lock(&mutex);
463 /* allocates the job */
464 job = job_create(group, timeout, callback, arg);
467 info = "out of memory";
471 /* check availability */
474 info = "too many jobs";
478 /* start a thread if needed */
479 if (running == started && started < allowed) {
480 /* all threads are busy and a new can be started */
481 rc = start_one_thread();
482 if (rc < 0 && started == 0) {
483 info = "can't start first thread";
492 /* signal an existing job */
493 pthread_cond_signal(&cond);
494 pthread_mutex_unlock(&mutex);
498 job->next = free_jobs;
501 ERROR("can't process job with threads: %s, %m", info);
502 pthread_mutex_unlock(&mutex);
507 * Internal helper function for 'jobs_enter'.
508 * @see jobs_enter, jobs_leave
510 static void enter_cb(int signum, void *closure)
512 struct sync *sync = closure;
513 sync->enter(signum, sync->arg, (void*)&sync->thread);
517 * Internal helper function for 'jobs_call'.
520 static void call_cb(int signum, void *closure)
522 struct sync *sync = closure;
523 sync->callback(signum, sync->arg);
524 jobs_leave((void*)&sync->thread);
528 * Internal helper for synchronous jobs. It enters
529 * a new thread loop for evaluating the given job
530 * as recorded by the couple 'sync_cb' and 'sync'.
531 * @see jobs_call, jobs_enter, jobs_leave
536 void (*sync_cb)(int signum, void *closure),
542 pthread_mutex_lock(&mutex);
544 /* allocates the job */
545 job = job_create(group, timeout, sync_cb, sync);
547 ERROR("out of memory");
549 pthread_mutex_unlock(&mutex);
556 /* run until stopped */
557 thread_run(&sync->thread);
558 pthread_mutex_unlock(&mutex);
563 * Enter a synchronisation point: activates the job given by 'callback'
564 * and 'closure' using 'group' and 'timeout' to control sequencing and
566 * @param group the group for sequencing jobs
567 * @param timeout the time in seconds allocated to the job
568 * @param callback the callback that will handle the job.
569 * it receives 3 parameters: 'signum' that will be 0
570 * on normal flow or the catched signal number in case
571 * of interrupted flow, the context 'closure' as given and
572 * a 'jobloop' reference that must be used when the job is
573 * terminated to unlock the current execution flow.
574 * @param arg the argument to the callback
575 * @return 0 on success or -1 in case of error
580 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
586 sync.enter = callback;
588 return do_sync(group, timeout, enter_cb, &sync);
592 * Unlocks the execution flow designed by 'jobloop'.
593 * @param jobloop indication of the flow to unlock
594 * @return 0 in case of success of -1 on error
596 int jobs_leave(struct jobloop *jobloop)
600 pthread_mutex_lock(&mutex);
602 while (t && t != (struct thread*)jobloop)
609 pthread_cond_broadcast(&cond);
611 pthread_mutex_unlock(&mutex);
616 * Calls synchronously the job represented by 'callback' and 'arg1'
617 * for the 'group' and the 'timeout' and waits for its completion.
618 * @param group The group of the job or NULL when no group.
619 * @param timeout The maximum execution time in seconds of the job
620 * or 0 for unlimited time.
621 * @param callback The function to execute for achieving the job.
622 * Its first parameter is either 0 on normal flow
623 * or the signal number that broke the normal flow.
624 * The remaining parameter is the parameter 'arg1'
626 * @param arg The second argument for 'callback'
627 * @return 0 in case of success or -1 in case of error
632 void (*callback)(int, void*),
637 sync.callback = callback;
640 return do_sync(group, timeout, call_cb, &sync);
644 * Internal callback for evloop management.
645 * The effect of this function is hidden: it exits
646 * the waiting poll if any. Then it wakes up a thread
647 * awaiting the evloop using signal.
649 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
652 struct evloop *evloop = userdata;
653 read(evloop->efd, &x, sizeof x);
654 pthread_mutex_lock(&mutex);
655 pthread_cond_broadcast(&evloop->cond);
656 pthread_mutex_unlock(&mutex);
661 * Gets a sd_event item for the current thread.
662 * @return a sd_event or NULL in case of error
664 static struct sd_event *get_sd_event_locked()
670 /* creates the evloop on need */
673 /* start the creation */
675 /* creates the eventfd for waking up polls */
676 el->efd = eventfd(0, EFD_CLOEXEC);
678 ERROR("can't make eventfd for events");
681 /* create the systemd event loop */
682 rc = sd_event_new(&el->sdev);
684 ERROR("can't make new event loop");
687 /* put the eventfd in the event loop */
688 rc = sd_event_add_io(el->sdev, NULL, el->efd, EPOLLIN, on_evloop_efd, el);
690 ERROR("can't register eventfd");
691 sd_event_unref(el->sdev);
700 /* attach the event loop to the current thread */
701 if (current_evloop != el) {
703 __atomic_sub_fetch(¤t_evloop->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
705 __atomic_add_fetch(&el->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
708 /* wait for a modifiable event loop */
709 while (__atomic_load_n(&el->state, __ATOMIC_RELAXED) & EVLOOP_STATE_WAIT) {
711 write(el->efd, &x, sizeof x);
712 pthread_cond_wait(&el->cond, &mutex);
719 * Gets a sd_event item for the current thread.
720 * @return a sd_event or NULL in case of error
722 struct sd_event *jobs_get_sd_event()
724 struct sd_event *result;
726 pthread_mutex_lock(&mutex);
727 result = get_sd_event_locked();
728 pthread_mutex_unlock(&mutex);
734 * Enter the jobs processing loop.
735 * @param allowed_count Maximum count of thread for jobs including this one
736 * @param start_count Count of thread to start now, must be lower.
737 * @param waiter_count Maximum count of jobs that can be waiting.
738 * @param start The start routine to activate (can't be NULL)
739 * @return 0 in case of success or -1 in case of error.
741 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
747 assert(allowed_count >= 1);
748 assert(start_count >= 0);
749 assert(waiter_count > 0);
750 assert(start_count <= allowed_count);
753 pthread_mutex_lock(&mutex);
755 /* check whether already running */
756 if (current_thread || allowed) {
757 ERROR("thread already started");
763 if (sig_monitor_init() < 0) {
764 ERROR("failed to initialise signal handlers");
768 /* records the allowed count */
769 allowed = allowed_count;
772 remains = waiter_count;
775 /* set the watchdog */
776 if (sd_watchdog_enabled(0, NULL))
777 sd_event_set_watchdog(get_sd_event_locked(), 1);
780 /* start at least one thread */
782 while ((launched + 1) < start_count) {
783 if (start_one_thread() != 0) {
784 ERROR("Not all threads can be started");
790 /* queue the start job */
791 job = job_create(NULL, 0, start, arg);
793 ERROR("out of memory");
804 pthread_mutex_unlock(&mutex);
809 * Terminate all the threads and cancel all pending jobs.
811 void jobs_terminate()
813 struct job *job, *head, *tail;
814 pthread_t me, *others;
821 /* request all threads to stop */
822 pthread_mutex_lock(&mutex);
825 /* count the number of threads */
829 if (!t->upper && !pthread_equal(t->tid, me))
834 /* fill the array of threads */
835 others = alloca(count * sizeof *others);
839 if (!t->upper && !pthread_equal(t->tid, me))
840 others[count++] = t->tid;
844 /* stops the threads */
851 /* wait the threads */
852 pthread_cond_broadcast(&cond);
853 pthread_mutex_unlock(&mutex);
855 pthread_join(others[--count], NULL);
856 pthread_mutex_lock(&mutex);
858 /* cancel pending jobs of other threads */
868 /* search if job is stacked for current */
870 while (t && t->job != job)
873 /* yes, relink it at end */
881 /* no cancel the job */
882 pthread_mutex_unlock(&mutex);
883 sig_monitor(0, job_cancel, job);
885 pthread_mutex_lock(&mutex);
888 pthread_mutex_unlock(&mutex);