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
32 #include <sys/syscall.h>
36 #include <sys/eventfd.h>
38 #include <systemd/sd-event.h>
41 #include <systemd/sd-daemon.h>
45 #include "sig-monitor.h"
48 #if defined(REMOVE_SYSTEMD_EVENT)
49 #include "fdev-epoll.h"
53 #define _alert_ "do you really want to remove signal monitoring?"
54 #define sig_monitor_init_timeouts() ((void)0)
55 #define sig_monitor_clean_timeouts() ((void)0)
56 #define sig_monitor(to,cb,arg) (cb(0,arg))
59 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
60 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
62 /** Internal shortcut for callback */
63 typedef void (*job_cb_t)(int, void*);
65 /** Description of a pending job */
68 struct job *next; /**< link to the next job enqueued */
69 const void *group; /**< group of the request */
70 job_cb_t callback; /**< processing callback */
71 void *arg; /**< argument */
72 int timeout; /**< timeout in second for processing the request */
73 unsigned blocked: 1; /**< is an other request blocking this one ? */
74 unsigned dropped: 1; /**< is removed ? */
77 /** Description of handled event loops */
80 unsigned state; /**< encoded state */
81 int efd; /**< event notification */
82 struct sd_event *sdev; /**< the systemd event loop */
83 pthread_cond_t cond; /**< condition */
84 struct fdev *fdev; /**< handling of events */
87 #define EVLOOP_STATE_WAIT 1U
88 #define EVLOOP_STATE_RUN 2U
89 #define EVLOOP_STATE_LOCK 4U
91 /** Description of threads */
94 struct thread *next; /**< next thread of the list */
95 struct thread *upper; /**< upper same thread */
96 struct job *job; /**< currently processed job */
97 pthread_t tid; /**< the thread id */
98 volatile unsigned stop: 1; /**< stop requested */
99 volatile unsigned waits: 1; /**< is waiting? */
103 * Description of synchonous callback
107 struct thread thread; /**< thread loop data */
109 void (*callback)(int, void*); /**< the synchronous callback */
110 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
111 /**< the entering synchronous routine */
113 void *arg; /**< the argument of the callback */
117 /* synchronisation of threads */
118 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
119 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
121 /* count allowed, started and running threads */
122 static int allowed = 0; /** allowed count of threads */
123 static int started = 0; /** started count of threads */
124 static int running = 0; /** running count of threads */
125 static int remains = 0; /** allowed count of waiting jobs */
127 /* list of threads */
128 static struct thread *threads;
129 static _Thread_local struct thread *current_thread;
130 static _Thread_local struct evloop *current_evloop;
132 /* queue of pending jobs */
133 static struct job *first_job;
134 static struct job *free_jobs;
137 static struct evloop evloop[1];
139 #if defined(REMOVE_SYSTEMD_EVENT)
140 static struct fdev_epoll *fdevepoll;
145 * Create a new job with the given parameters
146 * @param group the group of the job
147 * @param timeout the timeout of the job (0 if none)
148 * @param callback the function that achieves the job
149 * @param arg the argument of the callback
150 * @return the created job unblock or NULL when no more memory
152 static struct job *job_create(
160 /* try recyle existing job */
163 free_jobs = job->next;
165 /* allocation without blocking */
166 pthread_mutex_unlock(&mutex);
167 job = malloc(sizeof *job);
168 pthread_mutex_lock(&mutex);
174 /* initialises the job */
176 job->timeout = timeout;
177 job->callback = callback;
186 * Adds 'job' at the end of the list of jobs, marking it
187 * as blocked if an other job with the same group is pending.
188 * @param job the job to add
190 static void job_add(struct job *job)
193 struct job *ijob, **pjob;
199 /* search end and blockers */
203 if (group && ijob->group == group)
214 * Get the next job to process or NULL if none.
215 * @return the first job that isn't blocked or NULL
217 static inline struct job *job_get()
219 struct job *job = first_job;
220 while (job && job->blocked)
226 * Releases the processed 'job': removes it
227 * from the list of jobs and unblock the first
228 * pending job of the same group if any.
229 * @param job the job to release
231 static inline void job_release(struct job *job)
233 struct job *ijob, **pjob;
236 /* first unqueue the job */
239 while (ijob != job) {
245 /* then unblock jobs of the same group */
249 while (ijob && ijob->group != group)
255 /* recycle the job */
256 job->next = free_jobs;
261 * Monitored cancel callback for a job.
262 * This function is called by the monitor
263 * to cancel the job when the safe environment
265 * @param signum 0 on normal flow or the number
266 * of the signal that interrupted the normal
268 * @param arg the job to run
270 static void job_cancel(int signum, void *arg)
272 struct job *job = arg;
273 job->callback(SIGABRT, job->arg);
276 #if defined(REMOVE_SYSTEMD_EVENT)
278 * Gets a fdev_epoll item.
279 * @return a fdev_epoll or NULL in case of error
281 static struct fdev_epoll *get_fdevepoll()
283 struct fdev_epoll *result;
287 result = fdevepoll = fdev_epoll_create();
294 * Monitored normal callback for events.
295 * This function is called by the monitor
296 * to run the event loop when the safe environment
298 * @param signum 0 on normal flow or the number
299 * of the signal that interrupted the normal
301 * @param arg the events to run
303 static void evloop_run(int signum, void *arg)
307 struct evloop *el = arg;
311 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
313 rc = sd_event_prepare(se);
316 ERROR("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
319 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
322 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
325 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT), __ATOMIC_RELAXED);
328 rc = sd_event_dispatch(se);
331 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
336 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT|EVLOOP_STATE_RUN), __ATOMIC_RELAXED);
340 #if defined(REMOVE_SYSTEMD_EVENT)
342 * Monitored normal loop for waiting events.
343 * @param signum 0 on normal flow or the number
344 * of the signal that interrupted the normal
346 * @param arg the events to run
348 static void monitored_wait_and_dispatch(int signum, void *arg)
350 struct fdev_epoll *fdev_epoll = arg;
352 fdev_epoll_wait_and_dispatch(fdev_epoll, -1);
358 * Main processing loop of threads processing jobs.
359 * The loop must be called with the mutex locked
360 * and it returns with the mutex locked.
361 * @param me the description of the thread to use
362 * TODO: how are timeout handled when reentering?
364 static void thread_run(volatile struct thread *me)
368 #if !defined(REMOVE_SYSTEMD_EVENT)
372 /* initialize description of itself and link it in the list */
373 me->tid = pthread_self();
376 me->upper = current_thread;
377 if (!current_thread) {
379 sig_monitor_init_timeouts();
382 threads = (struct thread*)me;
383 current_thread = (struct thread*)me;
385 /* loop until stopped */
387 /* release the event loop */
388 if (current_evloop) {
389 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
390 current_evloop = NULL;
396 /* prepare running the job */
397 remains++; /* increases count of job that can wait */
398 job->blocked = 1; /* mark job as blocked */
399 me->job = job; /* record the job (only for terminate) */
402 pthread_mutex_unlock(&mutex);
403 sig_monitor(job->timeout, job->callback, job->arg);
404 pthread_mutex_lock(&mutex);
406 /* release the run job */
408 #if !defined(REMOVE_SYSTEMD_EVENT)
410 /* no job, check events */
412 if (el->sdev && !__atomic_load_n(&el->state, __ATOMIC_RELAXED)) {
414 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
416 pthread_mutex_unlock(&mutex);
417 sig_monitor(0, evloop_run, el);
418 pthread_mutex_lock(&mutex);
420 /* no job and not events */
423 ERROR("Entering job deep sleep! Check your bindings.");
425 pthread_cond_wait(&cond, &mutex);
430 } else if (waitevt) {
431 /* no job and not events */
434 ERROR("Entering job deep sleep! Check your bindings.");
436 pthread_cond_wait(&cond, &mutex);
440 /* wait for events */
442 pthread_mutex_unlock(&mutex);
443 sig_monitor(0, monitored_wait_and_dispatch, get_fdevepoll());
444 pthread_mutex_lock(&mutex);
450 /* release the event loop */
451 if (current_evloop) {
452 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
453 current_evloop = NULL;
456 /* unlink the current thread and cleanup */
461 current_thread = me->upper;
462 if (!current_thread) {
463 sig_monitor_clean_timeouts();
469 * Entry point for created threads.
470 * @param data not used
473 static void *thread_main(void *data)
477 pthread_mutex_lock(&mutex);
481 pthread_mutex_unlock(&mutex);
486 * Starts a new thread
487 * @return 0 in case of success or -1 in case of error
489 static int start_one_thread()
494 rc = pthread_create(&tid, NULL, thread_main, NULL);
497 WARNING("not able to start thread: %m");
504 * Queues a new asynchronous job represented by 'callback' and 'arg'
505 * for the 'group' and the 'timeout'.
506 * Jobs are queued FIFO and are possibly executed in parallel
507 * concurrently except for job of the same group that are
508 * executed sequentially in FIFO order.
509 * @param group The group of the job or NULL when no group.
510 * @param timeout The maximum execution time in seconds of the job
511 * or 0 for unlimited time.
512 * @param callback The function to execute for achieving the job.
513 * Its first parameter is either 0 on normal flow
514 * or the signal number that broke the normal flow.
515 * The remaining parameter is the parameter 'arg1'
517 * @param arg The second argument for 'callback'
518 * @return 0 in case of success or -1 in case of error
523 void (*callback)(int, void*),
530 pthread_mutex_lock(&mutex);
532 /* allocates the job */
533 job = job_create(group, timeout, callback, arg);
536 info = "out of memory";
540 /* check availability */
543 info = "too many jobs";
547 /* start a thread if needed */
548 if (running == started && started < allowed) {
549 /* all threads are busy and a new can be started */
550 rc = start_one_thread();
551 if (rc < 0 && started == 0) {
552 info = "can't start first thread";
561 /* signal an existing job */
562 pthread_cond_signal(&cond);
563 pthread_mutex_unlock(&mutex);
567 job->next = free_jobs;
570 ERROR("can't process job with threads: %s, %m", info);
571 pthread_mutex_unlock(&mutex);
576 * Internal helper function for 'jobs_enter'.
577 * @see jobs_enter, jobs_leave
579 static void enter_cb(int signum, void *closure)
581 struct sync *sync = closure;
582 sync->enter(signum, sync->arg, (void*)&sync->thread);
586 * Internal helper function for 'jobs_call'.
589 static void call_cb(int signum, void *closure)
591 struct sync *sync = closure;
592 sync->callback(signum, sync->arg);
593 jobs_leave((void*)&sync->thread);
597 * Internal helper for synchronous jobs. It enters
598 * a new thread loop for evaluating the given job
599 * as recorded by the couple 'sync_cb' and 'sync'.
600 * @see jobs_call, jobs_enter, jobs_leave
605 void (*sync_cb)(int signum, void *closure),
611 pthread_mutex_lock(&mutex);
613 /* allocates the job */
614 job = job_create(group, timeout, sync_cb, sync);
616 ERROR("out of memory");
618 pthread_mutex_unlock(&mutex);
625 /* run until stopped */
626 thread_run(&sync->thread);
627 pthread_mutex_unlock(&mutex);
632 * Enter a synchronisation point: activates the job given by 'callback'
633 * and 'closure' using 'group' and 'timeout' to control sequencing and
635 * @param group the group for sequencing jobs
636 * @param timeout the time in seconds allocated to the job
637 * @param callback the callback that will handle the job.
638 * it receives 3 parameters: 'signum' that will be 0
639 * on normal flow or the catched signal number in case
640 * of interrupted flow, the context 'closure' as given and
641 * a 'jobloop' reference that must be used when the job is
642 * terminated to unlock the current execution flow.
643 * @param closure the argument to the callback
644 * @return 0 on success or -1 in case of error
649 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
655 sync.enter = callback;
657 return do_sync(group, timeout, enter_cb, &sync);
661 * Unlocks the execution flow designed by 'jobloop'.
662 * @param jobloop indication of the flow to unlock
663 * @return 0 in case of success of -1 on error
665 int jobs_leave(struct jobloop *jobloop)
669 pthread_mutex_lock(&mutex);
671 while (t && t != (struct thread*)jobloop)
678 pthread_cond_broadcast(&cond);
680 pthread_mutex_unlock(&mutex);
685 * Calls synchronously the job represented by 'callback' and 'arg1'
686 * for the 'group' and the 'timeout' and waits for its completion.
687 * @param group The group of the job or NULL when no group.
688 * @param timeout The maximum execution time in seconds of the job
689 * or 0 for unlimited time.
690 * @param callback The function to execute for achieving the job.
691 * Its first parameter is either 0 on normal flow
692 * or the signal number that broke the normal flow.
693 * The remaining parameter is the parameter 'arg1'
695 * @param arg The second argument for 'callback'
696 * @return 0 in case of success or -1 in case of error
701 void (*callback)(int, void*),
706 sync.callback = callback;
709 return do_sync(group, timeout, call_cb, &sync);
713 * Internal callback for evloop management.
714 * The effect of this function is hidden: it exits
715 * the waiting poll if any. Then it wakes up a thread
716 * awaiting the evloop using signal.
718 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
721 struct evloop *evloop = userdata;
722 read(evloop->efd, &x, sizeof x);
723 pthread_mutex_lock(&mutex);
724 pthread_cond_broadcast(&evloop->cond);
725 pthread_mutex_unlock(&mutex);
730 #if !defined(REMOVE_SYSTEMD_EVENT)
731 __attribute__((unused))
733 static void evloop_callback(void *arg, uint32_t event, struct fdev *fdev)
735 sig_monitor(0, evloop_run, arg);
739 * Gets a sd_event item for the current thread.
740 * @return a sd_event or NULL in case of error
742 static struct sd_event *get_sd_event_locked()
748 /* creates the evloop on need */
751 /* start the creation */
753 /* creates the eventfd for waking up polls */
754 el->efd = eventfd(0, EFD_CLOEXEC);
756 ERROR("can't make eventfd for events");
759 /* create the systemd event loop */
760 rc = sd_event_new(&el->sdev);
762 ERROR("can't make new event loop");
765 /* put the eventfd in the event loop */
766 rc = sd_event_add_io(el->sdev, NULL, el->efd, EPOLLIN, on_evloop_efd, el);
768 ERROR("can't register eventfd");
769 #if !defined(REMOVE_SYSTEMD_EVENT)
770 sd_event_unref(el->sdev);
780 /* handle the event loop */
781 el->fdev = fdev_epoll_add(get_fdevepoll(), sd_event_get_fd(el->sdev));
783 ERROR("can't create fdev");
785 sd_event_unref(el->sdev);
789 memset(el, 0, sizeof *el);
792 fdev_set_autoclose(el->fdev, 0);
793 fdev_set_events(el->fdev, EPOLLIN);
794 fdev_set_callback(el->fdev, evloop_callback, el);
798 /* attach the event loop to the current thread */
799 if (current_evloop != el) {
801 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
803 __atomic_or_fetch(&el->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
806 /* wait for a modifiable event loop */
807 while (__atomic_load_n(&el->state, __ATOMIC_RELAXED) & EVLOOP_STATE_WAIT) {
809 write(el->efd, &x, sizeof x);
810 pthread_cond_wait(&el->cond, &mutex);
817 * Gets a sd_event item for the current thread.
818 * @return a sd_event or NULL in case of error
820 struct sd_event *jobs_get_sd_event()
822 struct sd_event *result;
824 pthread_mutex_lock(&mutex);
825 result = get_sd_event_locked();
826 pthread_mutex_unlock(&mutex);
831 #if defined(REMOVE_SYSTEMD_EVENT)
833 * Gets the fdev_epoll item.
834 * @return a fdev_epoll or NULL in case of error
836 struct fdev_epoll *jobs_get_fdev_epoll()
838 struct fdev_epoll *result;
840 pthread_mutex_lock(&mutex);
841 result = get_fdevepoll();
842 pthread_mutex_unlock(&mutex);
849 * Enter the jobs processing loop.
850 * @param allowed_count Maximum count of thread for jobs including this one
851 * @param start_count Count of thread to start now, must be lower.
852 * @param waiter_count Maximum count of jobs that can be waiting.
853 * @param start The start routine to activate (can't be NULL)
854 * @return 0 in case of success or -1 in case of error.
856 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
862 assert(allowed_count >= 1);
863 assert(start_count >= 0);
864 assert(waiter_count > 0);
865 assert(start_count <= allowed_count);
868 pthread_mutex_lock(&mutex);
870 /* check whether already running */
871 if (current_thread || allowed) {
872 ERROR("thread already started");
878 if (sig_monitor_init() < 0) {
879 ERROR("failed to initialise signal handlers");
883 /* records the allowed count */
884 allowed = allowed_count;
887 remains = waiter_count;
890 /* set the watchdog */
891 if (sd_watchdog_enabled(0, NULL))
892 sd_event_set_watchdog(get_sd_event_locked(), 1);
895 /* start at least one thread */
897 while ((launched + 1) < start_count) {
898 if (start_one_thread() != 0) {
899 ERROR("Not all threads can be started");
905 /* queue the start job */
906 job = job_create(NULL, 0, start, arg);
908 ERROR("out of memory");
919 pthread_mutex_unlock(&mutex);
924 * Terminate all the threads and cancel all pending jobs.
926 void jobs_terminate()
928 struct job *job, *head, *tail;
929 pthread_t me, *others;
936 /* request all threads to stop */
937 pthread_mutex_lock(&mutex);
940 /* count the number of threads */
944 if (!t->upper && !pthread_equal(t->tid, me))
949 /* fill the array of threads */
950 others = alloca(count * sizeof *others);
954 if (!t->upper && !pthread_equal(t->tid, me))
955 others[count++] = t->tid;
959 /* stops the threads */
966 /* wait the threads */
967 pthread_cond_broadcast(&cond);
968 pthread_mutex_unlock(&mutex);
970 pthread_join(others[--count], NULL);
971 pthread_mutex_lock(&mutex);
973 /* cancel pending jobs of other threads */
983 /* search if job is stacked for current */
985 while (t && t->job != job)
988 /* yes, relink it at end */
996 /* no cancel the job */
997 pthread_mutex_unlock(&mutex);
998 sig_monitor(0, job_cancel, job);
1000 pthread_mutex_lock(&mutex);
1003 pthread_mutex_unlock(&mutex);