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"
47 #include "fdev-epoll.h"
49 #define _alert_ "do you really want to remove signal monitoring?"
50 #define sig_monitor_init_timeouts() ((void)0)
51 #define sig_monitor_clean_timeouts() ((void)0)
52 #define sig_monitor(to,cb,arg) (cb(0,arg))
55 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
56 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
58 /** Internal shortcut for callback */
59 typedef void (*job_cb_t)(int, void*);
61 /** Description of a pending job */
64 struct job *next; /**< link to the next job enqueued */
65 const void *group; /**< group of the request */
66 job_cb_t callback; /**< processing callback */
67 void *arg; /**< argument */
68 int timeout; /**< timeout in second for processing the request */
69 unsigned blocked: 1; /**< is an other request blocking this one ? */
70 unsigned dropped: 1; /**< is removed ? */
73 /** Description of handled event loops */
76 unsigned state; /**< encoded state */
77 int efd; /**< event notification */
78 struct sd_event *sdev; /**< the systemd event loop */
79 pthread_cond_t cond; /**< condition */
80 struct fdev *fdev; /**< handling of events */
83 #define EVLOOP_STATE_WAIT 1U
84 #define EVLOOP_STATE_RUN 2U
85 #define EVLOOP_STATE_LOCK 4U
87 /** Description of threads */
90 struct thread *next; /**< next thread of the list */
91 struct thread *upper; /**< upper same thread */
92 struct job *job; /**< currently processed job */
93 pthread_t tid; /**< the thread id */
94 volatile unsigned stop: 1; /**< stop requested */
95 volatile unsigned waits: 1; /**< is waiting? */
99 * Description of synchonous callback
103 struct thread thread; /**< thread loop data */
105 void (*callback)(int, void*); /**< the synchronous callback */
106 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
107 /**< the entering synchronous routine */
109 void *arg; /**< the argument of the callback */
113 /* synchronisation of threads */
114 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
115 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
117 /* count allowed, started and running threads */
118 static int allowed = 0; /** allowed count of threads */
119 static int started = 0; /** started count of threads */
120 static int running = 0; /** running count of threads */
121 static int remains = 0; /** allowed count of waiting jobs */
123 /* list of threads */
124 static struct thread *threads;
125 static _Thread_local struct thread *current_thread;
126 static _Thread_local struct evloop *current_evloop;
128 /* queue of pending jobs */
129 static struct job *first_job;
130 static struct job *free_jobs;
133 static struct evloop evloop[1];
134 static struct fdev_epoll *fdevepoll;
135 #if !defined(REMOVE_SYSTEMD_EVENT)
136 __attribute__((unused))
141 * Create a new job with the given parameters
142 * @param group the group of the job
143 * @param timeout the timeout of the job (0 if none)
144 * @param callback the function that achieves the job
145 * @param arg the argument of the callback
146 * @return the created job unblock or NULL when no more memory
148 static struct job *job_create(
156 /* try recyle existing job */
159 free_jobs = job->next;
161 /* allocation without blocking */
162 pthread_mutex_unlock(&mutex);
163 job = malloc(sizeof *job);
164 pthread_mutex_lock(&mutex);
170 /* initialises the job */
172 job->timeout = timeout;
173 job->callback = callback;
182 * Adds 'job' at the end of the list of jobs, marking it
183 * as blocked if an other job with the same group is pending.
184 * @param job the job to add
186 static void job_add(struct job *job)
189 struct job *ijob, **pjob;
195 /* search end and blockers */
199 if (group && ijob->group == group)
210 * Get the next job to process or NULL if none.
211 * @return the first job that isn't blocked or NULL
213 static inline struct job *job_get()
215 struct job *job = first_job;
216 while (job && job->blocked)
222 * Releases the processed 'job': removes it
223 * from the list of jobs and unblock the first
224 * pending job of the same group if any.
225 * @param job the job to release
227 static inline void job_release(struct job *job)
229 struct job *ijob, **pjob;
232 /* first unqueue the job */
235 while (ijob != job) {
241 /* then unblock jobs of the same group */
245 while (ijob && ijob->group != group)
251 /* recycle the job */
252 job->next = free_jobs;
257 * Monitored cancel callback for a job.
258 * This function is called by the monitor
259 * to cancel the job when the safe environment
261 * @param signum 0 on normal flow or the number
262 * of the signal that interrupted the normal
264 * @param arg the job to run
266 static void job_cancel(int signum, void *arg)
268 struct job *job = arg;
269 job->callback(SIGABRT, job->arg);
273 * Gets a fdev_epoll item.
274 * @return a fdev_epoll or NULL in case of error
276 static struct fdev_epoll *get_fdevepoll()
278 struct fdev_epoll *result;
282 result = fdevepoll = fdev_epoll_create();
288 * Monitored normal callback for events.
289 * This function is called by the monitor
290 * to run the event loop when the safe environment
292 * @param signum 0 on normal flow or the number
293 * of the signal that interrupted the normal
295 * @param arg the events to run
297 static void evloop_run(int signum, void *arg)
301 struct evloop *el = arg;
305 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
307 rc = sd_event_prepare(se);
310 ERROR("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
313 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
316 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
319 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT), __ATOMIC_RELAXED);
322 rc = sd_event_dispatch(se);
325 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
330 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT|EVLOOP_STATE_RUN), __ATOMIC_RELAXED);
335 * Monitored normal loop for waiting events.
336 * @param signum 0 on normal flow or the number
337 * of the signal that interrupted the normal
339 * @param arg the events to run
341 #if !defined(REMOVE_SYSTEMD_EVENT)
342 __attribute__((unused))
344 static void monitored_wait_and_dispatch(int signum, void *arg)
346 struct fdev_epoll *fdev_epoll = arg;
348 fdev_epoll_wait_and_dispatch(fdev_epoll, -1);
353 * Main processing loop of threads processing jobs.
354 * The loop must be called with the mutex locked
355 * and it returns with the mutex locked.
356 * @param me the description of the thread to use
357 * TODO: how are timeout handled when reentering?
359 static void thread_run(volatile struct thread *me)
363 #if !defined(REMOVE_SYSTEMD_EVENT)
367 /* initialize description of itself and link it in the list */
368 me->tid = pthread_self();
371 me->upper = current_thread;
372 if (!current_thread) {
374 sig_monitor_init_timeouts();
377 threads = (struct thread*)me;
378 current_thread = (struct thread*)me;
380 /* loop until stopped */
382 /* release the event loop */
383 if (current_evloop) {
384 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
385 current_evloop = NULL;
391 /* prepare running the job */
392 remains++; /* increases count of job that can wait */
393 job->blocked = 1; /* mark job as blocked */
394 me->job = job; /* record the job (only for terminate) */
397 pthread_mutex_unlock(&mutex);
398 sig_monitor(job->timeout, job->callback, job->arg);
399 pthread_mutex_lock(&mutex);
401 /* release the run job */
403 #if !defined(REMOVE_SYSTEMD_EVENT)
405 /* no job, check events */
407 if (el->sdev && !__atomic_load_n(&el->state, __ATOMIC_RELAXED)) {
409 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
411 pthread_mutex_unlock(&mutex);
412 sig_monitor(0, evloop_run, el);
413 pthread_mutex_lock(&mutex);
415 /* no job and not events */
418 ERROR("Entering job deep sleep! Check your bindings.");
420 pthread_cond_wait(&cond, &mutex);
425 } else if (waitevt) {
426 /* no job and not events */
429 ERROR("Entering job deep sleep! Check your bindings.");
431 pthread_cond_wait(&cond, &mutex);
435 /* wait for events */
437 pthread_mutex_unlock(&mutex);
438 sig_monitor(0, monitored_wait_and_dispatch, get_fdevepoll());
439 pthread_mutex_lock(&mutex);
445 /* release the event loop */
446 if (current_evloop) {
447 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
448 current_evloop = NULL;
451 /* unlink the current thread and cleanup */
456 current_thread = me->upper;
457 if (!current_thread) {
458 sig_monitor_clean_timeouts();
464 * Entry point for created threads.
465 * @param data not used
468 static void *thread_main(void *data)
472 pthread_mutex_lock(&mutex);
476 pthread_mutex_unlock(&mutex);
481 * Starts a new thread
482 * @return 0 in case of success or -1 in case of error
484 static int start_one_thread()
489 rc = pthread_create(&tid, NULL, thread_main, NULL);
492 WARNING("not able to start thread: %m");
499 * Queues a new asynchronous job represented by 'callback' and 'arg'
500 * for the 'group' and the 'timeout'.
501 * Jobs are queued FIFO and are possibly executed in parallel
502 * concurrently except for job of the same group that are
503 * executed sequentially in FIFO order.
504 * @param group The group of the job or NULL when no group.
505 * @param timeout The maximum execution time in seconds of the job
506 * or 0 for unlimited time.
507 * @param callback The function to execute for achieving the job.
508 * Its first parameter is either 0 on normal flow
509 * or the signal number that broke the normal flow.
510 * The remaining parameter is the parameter 'arg1'
512 * @param arg The second argument for 'callback'
513 * @return 0 in case of success or -1 in case of error
518 void (*callback)(int, void*),
525 pthread_mutex_lock(&mutex);
527 /* allocates the job */
528 job = job_create(group, timeout, callback, arg);
531 info = "out of memory";
535 /* check availability */
538 info = "too many jobs";
542 /* start a thread if needed */
543 if (running == started && started < allowed) {
544 /* all threads are busy and a new can be started */
545 rc = start_one_thread();
546 if (rc < 0 && started == 0) {
547 info = "can't start first thread";
556 /* signal an existing job */
557 pthread_cond_signal(&cond);
558 pthread_mutex_unlock(&mutex);
562 job->next = free_jobs;
565 ERROR("can't process job with threads: %s, %m", info);
566 pthread_mutex_unlock(&mutex);
571 * Internal helper function for 'jobs_enter'.
572 * @see jobs_enter, jobs_leave
574 static void enter_cb(int signum, void *closure)
576 struct sync *sync = closure;
577 sync->enter(signum, sync->arg, (void*)&sync->thread);
581 * Internal helper function for 'jobs_call'.
584 static void call_cb(int signum, void *closure)
586 struct sync *sync = closure;
587 sync->callback(signum, sync->arg);
588 jobs_leave((void*)&sync->thread);
592 * Internal helper for synchronous jobs. It enters
593 * a new thread loop for evaluating the given job
594 * as recorded by the couple 'sync_cb' and 'sync'.
595 * @see jobs_call, jobs_enter, jobs_leave
600 void (*sync_cb)(int signum, void *closure),
606 pthread_mutex_lock(&mutex);
608 /* allocates the job */
609 job = job_create(group, timeout, sync_cb, sync);
611 ERROR("out of memory");
613 pthread_mutex_unlock(&mutex);
620 /* run until stopped */
621 thread_run(&sync->thread);
622 pthread_mutex_unlock(&mutex);
627 * Enter a synchronisation point: activates the job given by 'callback'
628 * and 'closure' using 'group' and 'timeout' to control sequencing and
630 * @param group the group for sequencing jobs
631 * @param timeout the time in seconds allocated to the job
632 * @param callback the callback that will handle the job.
633 * it receives 3 parameters: 'signum' that will be 0
634 * on normal flow or the catched signal number in case
635 * of interrupted flow, the context 'closure' as given and
636 * a 'jobloop' reference that must be used when the job is
637 * terminated to unlock the current execution flow.
638 * @param closure the argument to the callback
639 * @return 0 on success or -1 in case of error
644 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
650 sync.enter = callback;
652 return do_sync(group, timeout, enter_cb, &sync);
656 * Unlocks the execution flow designed by 'jobloop'.
657 * @param jobloop indication of the flow to unlock
658 * @return 0 in case of success of -1 on error
660 int jobs_leave(struct jobloop *jobloop)
664 pthread_mutex_lock(&mutex);
666 while (t && t != (struct thread*)jobloop)
673 pthread_cond_broadcast(&cond);
675 pthread_mutex_unlock(&mutex);
680 * Calls synchronously the job represented by 'callback' and 'arg1'
681 * for the 'group' and the 'timeout' and waits for its completion.
682 * @param group The group of the job or NULL when no group.
683 * @param timeout The maximum execution time in seconds of the job
684 * or 0 for unlimited time.
685 * @param callback The function to execute for achieving the job.
686 * Its first parameter is either 0 on normal flow
687 * or the signal number that broke the normal flow.
688 * The remaining parameter is the parameter 'arg1'
690 * @param arg The second argument for 'callback'
691 * @return 0 in case of success or -1 in case of error
696 void (*callback)(int, void*),
701 sync.callback = callback;
704 return do_sync(group, timeout, call_cb, &sync);
708 * Internal callback for evloop management.
709 * The effect of this function is hidden: it exits
710 * the waiting poll if any. Then it wakes up a thread
711 * awaiting the evloop using signal.
713 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
716 struct evloop *evloop = userdata;
717 read(evloop->efd, &x, sizeof x);
718 pthread_mutex_lock(&mutex);
719 pthread_cond_broadcast(&evloop->cond);
720 pthread_mutex_unlock(&mutex);
725 #if !defined(REMOVE_SYSTEMD_EVENT)
726 __attribute__((unused))
728 static void evloop_callback(void *arg, uint32_t event, struct fdev *fdev)
730 sig_monitor(0, evloop_run, arg);
734 * Gets a sd_event item for the current thread.
735 * @return a sd_event or NULL in case of error
737 static struct sd_event *get_sd_event_locked()
743 /* creates the evloop on need */
746 /* start the creation */
748 /* creates the eventfd for waking up polls */
749 el->efd = eventfd(0, EFD_CLOEXEC);
751 ERROR("can't make eventfd for events");
754 /* create the systemd event loop */
755 rc = sd_event_new(&el->sdev);
757 ERROR("can't make new event loop");
760 /* put the eventfd in the event loop */
761 rc = sd_event_add_io(el->sdev, NULL, el->efd, EPOLLIN, on_evloop_efd, el);
763 ERROR("can't register eventfd");
764 #if !defined(REMOVE_SYSTEMD_EVENT)
765 sd_event_unref(el->sdev);
775 /* handle the event loop */
776 el->fdev = fdev_epoll_add(get_fdevepoll(), sd_event_get_fd(el->sdev));
778 ERROR("can't create fdev");
780 sd_event_unref(el->sdev);
784 memset(el, 0, sizeof *el);
787 fdev_set_autoclose(el->fdev, 0);
788 fdev_set_events(el->fdev, EPOLLIN);
789 fdev_set_callback(el->fdev, evloop_callback, el);
793 /* attach the event loop to the current thread */
794 if (current_evloop != el) {
796 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
798 __atomic_or_fetch(&el->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
801 /* wait for a modifiable event loop */
802 while (__atomic_load_n(&el->state, __ATOMIC_RELAXED) & EVLOOP_STATE_WAIT) {
804 write(el->efd, &x, sizeof x);
805 pthread_cond_wait(&el->cond, &mutex);
812 * Gets a sd_event item for the current thread.
813 * @return a sd_event or NULL in case of error
815 struct sd_event *jobs_get_sd_event()
817 struct sd_event *result;
819 pthread_mutex_lock(&mutex);
820 result = get_sd_event_locked();
821 pthread_mutex_unlock(&mutex);
827 * Gets the fdev_epoll item.
828 * @return a fdev_epoll or NULL in case of error
830 struct fdev_epoll *jobs_get_fdev_epoll()
832 struct fdev_epoll *result;
834 pthread_mutex_lock(&mutex);
835 result = get_fdevepoll();
836 pthread_mutex_unlock(&mutex);
842 * Enter the jobs processing loop.
843 * @param allowed_count Maximum count of thread for jobs including this one
844 * @param start_count Count of thread to start now, must be lower.
845 * @param waiter_count Maximum count of jobs that can be waiting.
846 * @param start The start routine to activate (can't be NULL)
847 * @return 0 in case of success or -1 in case of error.
849 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
855 assert(allowed_count >= 1);
856 assert(start_count >= 0);
857 assert(waiter_count > 0);
858 assert(start_count <= allowed_count);
861 pthread_mutex_lock(&mutex);
863 /* check whether already running */
864 if (current_thread || allowed) {
865 ERROR("thread already started");
871 if (sig_monitor_init() < 0) {
872 ERROR("failed to initialise signal handlers");
876 /* records the allowed count */
877 allowed = allowed_count;
880 remains = waiter_count;
883 /* set the watchdog */
884 if (sd_watchdog_enabled(0, NULL))
885 sd_event_set_watchdog(get_sd_event_locked(), 1);
888 /* start at least one thread */
890 while ((launched + 1) < start_count) {
891 if (start_one_thread() != 0) {
892 ERROR("Not all threads can be started");
898 /* queue the start job */
899 job = job_create(NULL, 0, start, arg);
901 ERROR("out of memory");
912 pthread_mutex_unlock(&mutex);
917 * Terminate all the threads and cancel all pending jobs.
919 void jobs_terminate()
921 struct job *job, *head, *tail;
922 pthread_t me, *others;
929 /* request all threads to stop */
930 pthread_mutex_lock(&mutex);
933 /* count the number of threads */
937 if (!t->upper && !pthread_equal(t->tid, me))
942 /* fill the array of threads */
943 others = alloca(count * sizeof *others);
947 if (!t->upper && !pthread_equal(t->tid, me))
948 others[count++] = t->tid;
952 /* stops the threads */
959 /* wait the threads */
960 pthread_cond_broadcast(&cond);
961 pthread_mutex_unlock(&mutex);
963 pthread_join(others[--count], NULL);
964 pthread_mutex_lock(&mutex);
966 /* cancel pending jobs of other threads */
976 /* search if job is stacked for current */
978 while (t && t->job != job)
981 /* yes, relink it at end */
989 /* no cancel the job */
990 pthread_mutex_unlock(&mutex);
991 sig_monitor(0, job_cancel, job);
993 pthread_mutex_lock(&mutex);
996 pthread_mutex_unlock(&mutex);