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 CRITICAL("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
320 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
323 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
326 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT), __ATOMIC_RELAXED);
329 rc = sd_event_dispatch(se);
332 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
337 __atomic_and_fetch(&el->state, ~(EVLOOP_STATE_WAIT|EVLOOP_STATE_RUN), __ATOMIC_RELAXED);
341 #if defined(REMOVE_SYSTEMD_EVENT)
343 * Monitored normal loop for waiting events.
344 * @param signum 0 on normal flow or the number
345 * of the signal that interrupted the normal
347 * @param arg the events to run
349 static void monitored_wait_and_dispatch(int signum, void *arg)
351 struct fdev_epoll *fdev_epoll = arg;
353 fdev_epoll_wait_and_dispatch(fdev_epoll, -1);
359 * Main processing loop of threads processing jobs.
360 * The loop must be called with the mutex locked
361 * and it returns with the mutex locked.
362 * @param me the description of the thread to use
363 * TODO: how are timeout handled when reentering?
365 static void thread_run(volatile struct thread *me)
369 #if !defined(REMOVE_SYSTEMD_EVENT)
373 /* initialize description of itself and link it in the list */
374 me->tid = pthread_self();
377 me->upper = current_thread;
378 if (!current_thread) {
380 sig_monitor_init_timeouts();
383 threads = (struct thread*)me;
384 current_thread = (struct thread*)me;
386 /* loop until stopped */
388 /* release the event loop */
389 if (current_evloop) {
390 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
391 current_evloop = NULL;
397 /* prepare running the job */
398 remains++; /* increases count of job that can wait */
399 job->blocked = 1; /* mark job as blocked */
400 me->job = job; /* record the job (only for terminate) */
403 pthread_mutex_unlock(&mutex);
404 sig_monitor(job->timeout, job->callback, job->arg);
405 pthread_mutex_lock(&mutex);
407 /* release the run job */
409 #if !defined(REMOVE_SYSTEMD_EVENT)
411 /* no job, check events */
413 if (el->sdev && !__atomic_load_n(&el->state, __ATOMIC_RELAXED)) {
415 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
417 pthread_mutex_unlock(&mutex);
418 sig_monitor(0, evloop_run, el);
419 pthread_mutex_lock(&mutex);
421 /* no job and not events */
424 ERROR("Entering job deep sleep! Check your bindings.");
426 pthread_cond_wait(&cond, &mutex);
431 } else if (waitevt) {
432 /* no job and not events */
435 ERROR("Entering job deep sleep! Check your bindings.");
437 pthread_cond_wait(&cond, &mutex);
441 /* wait for events */
443 pthread_mutex_unlock(&mutex);
444 sig_monitor(0, monitored_wait_and_dispatch, get_fdevepoll());
445 pthread_mutex_lock(&mutex);
451 /* release the event loop */
452 if (current_evloop) {
453 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
454 current_evloop = NULL;
457 /* unlink the current thread and cleanup */
462 current_thread = me->upper;
463 if (!current_thread) {
464 sig_monitor_clean_timeouts();
470 * Entry point for created threads.
471 * @param data not used
474 static void *thread_main(void *data)
478 pthread_mutex_lock(&mutex);
482 pthread_mutex_unlock(&mutex);
487 * Starts a new thread
488 * @return 0 in case of success or -1 in case of error
490 static int start_one_thread()
495 rc = pthread_create(&tid, NULL, thread_main, NULL);
498 WARNING("not able to start thread: %m");
505 * Queues a new asynchronous job represented by 'callback' and 'arg'
506 * for the 'group' and the 'timeout'.
507 * Jobs are queued FIFO and are possibly executed in parallel
508 * concurrently except for job of the same group that are
509 * executed sequentially in FIFO order.
510 * @param group The group of the job or NULL when no group.
511 * @param timeout The maximum execution time in seconds of the job
512 * or 0 for unlimited time.
513 * @param callback The function to execute for achieving the job.
514 * Its first parameter is either 0 on normal flow
515 * or the signal number that broke the normal flow.
516 * The remaining parameter is the parameter 'arg1'
518 * @param arg The second argument for 'callback'
519 * @return 0 in case of success or -1 in case of error
524 void (*callback)(int, void*),
531 pthread_mutex_lock(&mutex);
533 /* allocates the job */
534 job = job_create(group, timeout, callback, arg);
537 info = "out of memory";
541 /* check availability */
544 info = "too many jobs";
548 /* start a thread if needed */
549 if (running == started && started < allowed) {
550 /* all threads are busy and a new can be started */
551 rc = start_one_thread();
552 if (rc < 0 && started == 0) {
553 info = "can't start first thread";
562 /* signal an existing job */
563 pthread_cond_signal(&cond);
564 pthread_mutex_unlock(&mutex);
568 job->next = free_jobs;
571 ERROR("can't process job with threads: %s, %m", info);
572 pthread_mutex_unlock(&mutex);
577 * Internal helper function for 'jobs_enter'.
578 * @see jobs_enter, jobs_leave
580 static void enter_cb(int signum, void *closure)
582 struct sync *sync = closure;
583 sync->enter(signum, sync->arg, (void*)&sync->thread);
587 * Internal helper function for 'jobs_call'.
590 static void call_cb(int signum, void *closure)
592 struct sync *sync = closure;
593 sync->callback(signum, sync->arg);
594 jobs_leave((void*)&sync->thread);
598 * Internal helper for synchronous jobs. It enters
599 * a new thread loop for evaluating the given job
600 * as recorded by the couple 'sync_cb' and 'sync'.
601 * @see jobs_call, jobs_enter, jobs_leave
606 void (*sync_cb)(int signum, void *closure),
612 pthread_mutex_lock(&mutex);
614 /* allocates the job */
615 job = job_create(group, timeout, sync_cb, sync);
617 ERROR("out of memory");
619 pthread_mutex_unlock(&mutex);
626 /* run until stopped */
627 thread_run(&sync->thread);
628 pthread_mutex_unlock(&mutex);
633 * Enter a synchronisation point: activates the job given by 'callback'
634 * and 'closure' using 'group' and 'timeout' to control sequencing and
636 * @param group the group for sequencing jobs
637 * @param timeout the time in seconds allocated to the job
638 * @param callback the callback that will handle the job.
639 * it receives 3 parameters: 'signum' that will be 0
640 * on normal flow or the catched signal number in case
641 * of interrupted flow, the context 'closure' as given and
642 * a 'jobloop' reference that must be used when the job is
643 * terminated to unlock the current execution flow.
644 * @param closure the argument to the callback
645 * @return 0 on success or -1 in case of error
650 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
656 sync.enter = callback;
658 return do_sync(group, timeout, enter_cb, &sync);
662 * Unlocks the execution flow designed by 'jobloop'.
663 * @param jobloop indication of the flow to unlock
664 * @return 0 in case of success of -1 on error
666 int jobs_leave(struct jobloop *jobloop)
670 pthread_mutex_lock(&mutex);
672 while (t && t != (struct thread*)jobloop)
679 pthread_cond_broadcast(&cond);
681 pthread_mutex_unlock(&mutex);
686 * Calls synchronously the job represented by 'callback' and 'arg1'
687 * for the 'group' and the 'timeout' and waits for its completion.
688 * @param group The group of the job or NULL when no group.
689 * @param timeout The maximum execution time in seconds of the job
690 * or 0 for unlimited time.
691 * @param callback The function to execute for achieving the job.
692 * Its first parameter is either 0 on normal flow
693 * or the signal number that broke the normal flow.
694 * The remaining parameter is the parameter 'arg1'
696 * @param arg The second argument for 'callback'
697 * @return 0 in case of success or -1 in case of error
702 void (*callback)(int, void*),
707 sync.callback = callback;
710 return do_sync(group, timeout, call_cb, &sync);
714 * Internal callback for evloop management.
715 * The effect of this function is hidden: it exits
716 * the waiting poll if any. Then it wakes up a thread
717 * awaiting the evloop using signal.
719 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
722 struct evloop *evloop = userdata;
723 read(evloop->efd, &x, sizeof x);
724 pthread_mutex_lock(&mutex);
725 pthread_cond_broadcast(&evloop->cond);
726 pthread_mutex_unlock(&mutex);
731 #if !defined(REMOVE_SYSTEMD_EVENT)
732 __attribute__((unused))
734 static void evloop_callback(void *arg, uint32_t event, struct fdev *fdev)
736 sig_monitor(0, evloop_run, arg);
740 * Gets a sd_event item for the current thread.
741 * @return a sd_event or NULL in case of error
743 static struct sd_event *get_sd_event_locked()
749 /* creates the evloop on need */
752 /* start the creation */
754 /* creates the eventfd for waking up polls */
755 el->efd = eventfd(0, EFD_CLOEXEC);
757 ERROR("can't make eventfd for events");
760 /* create the systemd event loop */
761 rc = sd_event_new(&el->sdev);
763 ERROR("can't make new event loop");
766 /* put the eventfd in the event loop */
767 rc = sd_event_add_io(el->sdev, NULL, el->efd, EPOLLIN, on_evloop_efd, el);
769 ERROR("can't register eventfd");
770 #if !defined(REMOVE_SYSTEMD_EVENT)
771 sd_event_unref(el->sdev);
781 /* handle the event loop */
782 el->fdev = fdev_epoll_add(get_fdevepoll(), sd_event_get_fd(el->sdev));
784 ERROR("can't create fdev");
786 sd_event_unref(el->sdev);
790 memset(el, 0, sizeof *el);
793 fdev_set_autoclose(el->fdev, 0);
794 fdev_set_events(el->fdev, EPOLLIN);
795 fdev_set_callback(el->fdev, evloop_callback, el);
799 /* attach the event loop to the current thread */
800 if (current_evloop != el) {
802 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
804 __atomic_or_fetch(&el->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
807 /* wait for a modifiable event loop */
808 while (__atomic_load_n(&el->state, __ATOMIC_RELAXED) & EVLOOP_STATE_WAIT) {
810 write(el->efd, &x, sizeof x);
811 pthread_cond_wait(&el->cond, &mutex);
818 * Gets a sd_event item for the current thread.
819 * @return a sd_event or NULL in case of error
821 struct sd_event *jobs_get_sd_event()
823 struct sd_event *result;
825 pthread_mutex_lock(&mutex);
826 result = get_sd_event_locked();
827 pthread_mutex_unlock(&mutex);
832 #if defined(REMOVE_SYSTEMD_EVENT)
834 * Gets the fdev_epoll item.
835 * @return a fdev_epoll or NULL in case of error
837 struct fdev_epoll *jobs_get_fdev_epoll()
839 struct fdev_epoll *result;
841 pthread_mutex_lock(&mutex);
842 result = get_fdevepoll();
843 pthread_mutex_unlock(&mutex);
850 * Enter the jobs processing loop.
851 * @param allowed_count Maximum count of thread for jobs including this one
852 * @param start_count Count of thread to start now, must be lower.
853 * @param waiter_count Maximum count of jobs that can be waiting.
854 * @param start The start routine to activate (can't be NULL)
855 * @return 0 in case of success or -1 in case of error.
857 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
863 assert(allowed_count >= 1);
864 assert(start_count >= 0);
865 assert(waiter_count > 0);
866 assert(start_count <= allowed_count);
869 pthread_mutex_lock(&mutex);
871 /* check whether already running */
872 if (current_thread || allowed) {
873 ERROR("thread already started");
879 if (sig_monitor_init() < 0) {
880 ERROR("failed to initialise signal handlers");
884 /* records the allowed count */
885 allowed = allowed_count;
888 remains = waiter_count;
891 /* set the watchdog */
892 if (sd_watchdog_enabled(0, NULL))
893 sd_event_set_watchdog(get_sd_event_locked(), 1);
896 /* start at least one thread */
898 while ((launched + 1) < start_count) {
899 if (start_one_thread() != 0) {
900 ERROR("Not all threads can be started");
906 /* queue the start job */
907 job = job_create(NULL, 0, start, arg);
909 ERROR("out of memory");
920 pthread_mutex_unlock(&mutex);
925 * Terminate all the threads and cancel all pending jobs.
927 void jobs_terminate()
929 struct job *job, *head, *tail;
930 pthread_t me, *others;
937 /* request all threads to stop */
938 pthread_mutex_lock(&mutex);
941 /* count the number of threads */
945 if (!t->upper && !pthread_equal(t->tid, me))
950 /* fill the array of threads */
951 others = alloca(count * sizeof *others);
955 if (!t->upper && !pthread_equal(t->tid, me))
956 others[count++] = t->tid;
960 /* stops the threads */
967 /* wait the threads */
968 pthread_cond_broadcast(&cond);
969 pthread_mutex_unlock(&mutex);
971 pthread_join(others[--count], NULL);
972 pthread_mutex_lock(&mutex);
974 /* cancel pending jobs of other threads */
984 /* search if job is stacked for current */
986 while (t && t->job != job)
989 /* yes, relink it at end */
997 /* no cancel the job */
998 pthread_mutex_unlock(&mutex);
999 sig_monitor(0, job_cancel, job);
1001 pthread_mutex_lock(&mutex);
1004 pthread_mutex_unlock(&mutex);