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"
52 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
53 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
55 /** Internal shortcut for callback */
56 typedef void (*job_cb_t)(int, void*);
58 /** Description of a pending job */
61 struct job *next; /**< link to the next job enqueued */
62 const void *group; /**< group of the request */
63 job_cb_t callback; /**< processing callback */
64 void *arg; /**< argument */
65 int timeout; /**< timeout in second for processing the request */
66 unsigned blocked: 1; /**< is an other request blocking this one ? */
67 unsigned dropped: 1; /**< is removed ? */
70 /** Description of handled event loops */
73 unsigned state; /**< encoded state */
74 int efd; /**< event notification */
75 struct sd_event *sdev; /**< the systemd event loop */
76 pthread_cond_t cond; /**< condition */
77 struct fdev *fdev; /**< handling of events */
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 volatile unsigned stop: 1; /**< stop requested */
92 volatile 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];
132 #if defined(REMOVE_SYSTEMD_EVENT)
133 static struct fdev_epoll *fdevepoll;
138 * Create a new job with the given parameters
139 * @param group the group of the job
140 * @param timeout the timeout of the job (0 if none)
141 * @param callback the function that achieves the job
142 * @param arg the argument of the callback
143 * @return the created job unblock or NULL when no more memory
145 static struct job *job_create(
153 /* try recyle existing job */
156 free_jobs = job->next;
158 /* allocation without blocking */
159 pthread_mutex_unlock(&mutex);
160 job = malloc(sizeof *job);
161 pthread_mutex_lock(&mutex);
167 /* initialises the job */
169 job->timeout = timeout;
170 job->callback = callback;
179 * Adds 'job' at the end of the list of jobs, marking it
180 * as blocked if an other job with the same group is pending.
181 * @param job the job to add
183 static void job_add(struct job *job)
186 struct job *ijob, **pjob;
192 /* search end and blockers */
196 if (group && ijob->group == group)
207 * Get the next job to process or NULL if none.
208 * @return the first job that isn't blocked or NULL
210 static inline struct job *job_get()
212 struct job *job = first_job;
213 while (job && job->blocked)
219 * Releases the processed 'job': removes it
220 * from the list of jobs and unblock the first
221 * pending job of the same group if any.
222 * @param job the job to release
224 static inline void job_release(struct job *job)
226 struct job *ijob, **pjob;
229 /* first unqueue the job */
232 while (ijob != job) {
238 /* then unblock jobs of the same group */
242 while (ijob && ijob->group != group)
248 /* recycle the job */
249 job->next = free_jobs;
254 * Monitored cancel callback for a job.
255 * This function is called by the monitor
256 * to cancel the job when the safe environment
258 * @param signum 0 on normal flow or the number
259 * of the signal that interrupted the normal
261 * @param arg the job to run
263 static void job_cancel(int signum, void *arg)
265 struct job *job = arg;
266 job->callback(SIGABRT, job->arg);
269 #if defined(REMOVE_SYSTEMD_EVENT)
271 * Gets a fdev_epoll item.
272 * @return a fdev_epoll or NULL in case of error
274 static struct fdev_epoll *get_fdevepoll()
276 struct fdev_epoll *result;
280 result = fdevepoll = fdev_epoll_create();
287 * Monitored normal callback for events.
288 * This function is called by the monitor
289 * to run the event loop when the safe environment
291 * @param signum 0 on normal flow or the number
292 * of the signal that interrupted the normal
294 * @param arg the events to run
296 static void evloop_run(int signum, void *arg)
300 struct evloop *el = arg;
304 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
306 rc = sd_event_prepare(se);
309 CRITICAL("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);
334 #if defined(REMOVE_SYSTEMD_EVENT)
336 * Monitored normal loop for waiting events.
337 * @param signum 0 on normal flow or the number
338 * of the signal that interrupted the normal
340 * @param arg the events to run
342 static void monitored_wait_and_dispatch(int signum, void *arg)
344 struct fdev_epoll *fdev_epoll = arg;
346 fdev_epoll_wait_and_dispatch(fdev_epoll, -1);
352 * Main processing loop of threads processing jobs.
353 * The loop must be called with the mutex locked
354 * and it returns with the mutex locked.
355 * @param me the description of the thread to use
356 * TODO: how are timeout handled when reentering?
358 static void thread_run(volatile struct thread *me)
362 #if !defined(REMOVE_SYSTEMD_EVENT)
366 /* initialize description of itself and link it in the list */
367 me->tid = pthread_self();
370 me->upper = current_thread;
371 if (!current_thread) {
373 sig_monitor_init_timeouts();
376 threads = (struct thread*)me;
377 current_thread = (struct thread*)me;
379 /* loop until stopped */
381 /* release the event loop */
382 if (current_evloop) {
383 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
384 current_evloop = NULL;
390 /* prepare running the job */
391 remains++; /* increases count of job that can wait */
392 job->blocked = 1; /* mark job as blocked */
393 me->job = job; /* record the job (only for terminate) */
396 pthread_mutex_unlock(&mutex);
397 sig_monitor(job->timeout, job->callback, job->arg);
398 pthread_mutex_lock(&mutex);
400 /* release the run job */
402 #if !defined(REMOVE_SYSTEMD_EVENT)
404 /* no job, check events */
406 if (el->sdev && !__atomic_load_n(&el->state, __ATOMIC_RELAXED)) {
408 __atomic_store_n(&el->state, EVLOOP_STATE_LOCK|EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT, __ATOMIC_RELAXED);
410 pthread_mutex_unlock(&mutex);
411 sig_monitor(0, evloop_run, el);
412 pthread_mutex_lock(&mutex);
414 /* no job and not events */
417 ERROR("Entering job deep sleep! Check your bindings.");
419 pthread_cond_wait(&cond, &mutex);
424 } else if (waitevt) {
425 /* no job and not events */
428 ERROR("Entering job deep sleep! Check your bindings.");
430 pthread_cond_wait(&cond, &mutex);
434 /* wait for events */
436 pthread_mutex_unlock(&mutex);
437 sig_monitor(0, monitored_wait_and_dispatch, get_fdevepoll());
438 pthread_mutex_lock(&mutex);
444 /* release the event loop */
445 if (current_evloop) {
446 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
447 current_evloop = NULL;
450 /* unlink the current thread and cleanup */
455 current_thread = me->upper;
456 if (!current_thread) {
457 sig_monitor_clean_timeouts();
463 * Entry point for created threads.
464 * @param data not used
467 static void *thread_main(void *data)
471 pthread_mutex_lock(&mutex);
475 pthread_mutex_unlock(&mutex);
480 * Starts a new thread
481 * @return 0 in case of success or -1 in case of error
483 static int start_one_thread()
488 rc = pthread_create(&tid, NULL, thread_main, NULL);
491 WARNING("not able to start thread: %m");
498 * Queues a new asynchronous job represented by 'callback' and 'arg'
499 * for the 'group' and the 'timeout'.
500 * Jobs are queued FIFO and are possibly executed in parallel
501 * concurrently except for job of the same group that are
502 * executed sequentially in FIFO order.
503 * @param group The group of the job or NULL when no group.
504 * @param timeout The maximum execution time in seconds of the job
505 * or 0 for unlimited time.
506 * @param callback The function to execute for achieving the job.
507 * Its first parameter is either 0 on normal flow
508 * or the signal number that broke the normal flow.
509 * The remaining parameter is the parameter 'arg1'
511 * @param arg The second argument for 'callback'
512 * @return 0 in case of success or -1 in case of error
517 void (*callback)(int, void*),
524 pthread_mutex_lock(&mutex);
526 /* allocates the job */
527 job = job_create(group, timeout, callback, arg);
530 info = "out of memory";
534 /* check availability */
537 info = "too many jobs";
541 /* start a thread if needed */
542 if (running == started && started < allowed) {
543 /* all threads are busy and a new can be started */
544 rc = start_one_thread();
545 if (rc < 0 && started == 0) {
546 info = "can't start first thread";
555 /* signal an existing job */
556 pthread_cond_signal(&cond);
557 pthread_mutex_unlock(&mutex);
561 job->next = free_jobs;
564 ERROR("can't process job with threads: %s, %m", info);
565 pthread_mutex_unlock(&mutex);
570 * Internal helper function for 'jobs_enter'.
571 * @see jobs_enter, jobs_leave
573 static void enter_cb(int signum, void *closure)
575 struct sync *sync = closure;
576 sync->enter(signum, sync->arg, (void*)&sync->thread);
580 * Internal helper function for 'jobs_call'.
583 static void call_cb(int signum, void *closure)
585 struct sync *sync = closure;
586 sync->callback(signum, sync->arg);
587 jobs_leave((void*)&sync->thread);
591 * Internal helper for synchronous jobs. It enters
592 * a new thread loop for evaluating the given job
593 * as recorded by the couple 'sync_cb' and 'sync'.
594 * @see jobs_call, jobs_enter, jobs_leave
599 void (*sync_cb)(int signum, void *closure),
605 pthread_mutex_lock(&mutex);
607 /* allocates the job */
608 job = job_create(group, timeout, sync_cb, sync);
610 ERROR("out of memory");
612 pthread_mutex_unlock(&mutex);
619 /* run until stopped */
620 thread_run(&sync->thread);
621 pthread_mutex_unlock(&mutex);
626 * Enter a synchronisation point: activates the job given by 'callback'
627 * and 'closure' using 'group' and 'timeout' to control sequencing and
629 * @param group the group for sequencing jobs
630 * @param timeout the time in seconds allocated to the job
631 * @param callback the callback that will handle the job.
632 * it receives 3 parameters: 'signum' that will be 0
633 * on normal flow or the catched signal number in case
634 * of interrupted flow, the context 'closure' as given and
635 * a 'jobloop' reference that must be used when the job is
636 * terminated to unlock the current execution flow.
637 * @param closure the argument to the callback
638 * @return 0 on success or -1 in case of error
643 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
649 sync.enter = callback;
651 return do_sync(group, timeout, enter_cb, &sync);
655 * Unlocks the execution flow designed by 'jobloop'.
656 * @param jobloop indication of the flow to unlock
657 * @return 0 in case of success of -1 on error
659 int jobs_leave(struct jobloop *jobloop)
663 pthread_mutex_lock(&mutex);
665 while (t && t != (struct thread*)jobloop)
672 pthread_cond_broadcast(&cond);
674 pthread_mutex_unlock(&mutex);
679 * Calls synchronously the job represented by 'callback' and 'arg1'
680 * for the 'group' and the 'timeout' and waits for its completion.
681 * @param group The group of the job or NULL when no group.
682 * @param timeout The maximum execution time in seconds of the job
683 * or 0 for unlimited time.
684 * @param callback The function to execute for achieving the job.
685 * Its first parameter is either 0 on normal flow
686 * or the signal number that broke the normal flow.
687 * The remaining parameter is the parameter 'arg1'
689 * @param arg The second argument for 'callback'
690 * @return 0 in case of success or -1 in case of error
695 void (*callback)(int, void*),
700 sync.callback = callback;
703 return do_sync(group, timeout, call_cb, &sync);
707 * Internal callback for evloop management.
708 * The effect of this function is hidden: it exits
709 * the waiting poll if any. Then it wakes up a thread
710 * awaiting the evloop using signal.
712 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
715 struct evloop *evloop = userdata;
716 read(evloop->efd, &x, sizeof x);
717 pthread_mutex_lock(&mutex);
718 pthread_cond_broadcast(&evloop->cond);
719 pthread_mutex_unlock(&mutex);
724 #if !defined(REMOVE_SYSTEMD_EVENT)
725 __attribute__((unused))
727 static void evloop_callback(void *arg, uint32_t event, struct fdev *fdev)
729 sig_monitor(0, evloop_run, arg);
733 * Gets a sd_event item for the current thread.
734 * @return a sd_event or NULL in case of error
736 static struct sd_event *get_sd_event_locked()
742 /* creates the evloop on need */
745 /* start the creation */
747 /* creates the eventfd for waking up polls */
748 el->efd = eventfd(0, EFD_CLOEXEC);
750 ERROR("can't make eventfd for events");
753 /* create the systemd event loop */
754 rc = sd_event_new(&el->sdev);
756 ERROR("can't make new event loop");
759 /* put the eventfd in the event loop */
760 rc = sd_event_add_io(el->sdev, NULL, el->efd, EPOLLIN, on_evloop_efd, el);
762 ERROR("can't register eventfd");
763 #if !defined(REMOVE_SYSTEMD_EVENT)
764 sd_event_unref(el->sdev);
774 /* handle the event loop */
775 el->fdev = fdev_epoll_add(get_fdevepoll(), sd_event_get_fd(el->sdev));
777 ERROR("can't create fdev");
779 sd_event_unref(el->sdev);
783 memset(el, 0, sizeof *el);
786 fdev_set_autoclose(el->fdev, 0);
787 fdev_set_events(el->fdev, EPOLLIN);
788 fdev_set_callback(el->fdev, evloop_callback, el);
792 /* attach the event loop to the current thread */
793 if (current_evloop != el) {
795 __atomic_and_fetch(¤t_evloop->state, ~EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
797 __atomic_or_fetch(&el->state, EVLOOP_STATE_LOCK, __ATOMIC_RELAXED);
800 /* wait for a modifiable event loop */
801 while (__atomic_load_n(&el->state, __ATOMIC_RELAXED) & EVLOOP_STATE_WAIT) {
803 write(el->efd, &x, sizeof x);
804 pthread_cond_wait(&el->cond, &mutex);
811 * Gets a sd_event item for the current thread.
812 * @return a sd_event or NULL in case of error
814 struct sd_event *jobs_get_sd_event()
816 struct sd_event *result;
818 pthread_mutex_lock(&mutex);
819 result = get_sd_event_locked();
820 pthread_mutex_unlock(&mutex);
825 #if defined(REMOVE_SYSTEMD_EVENT)
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);
843 * Enter the jobs processing loop.
844 * @param allowed_count Maximum count of thread for jobs including this one
845 * @param start_count Count of thread to start now, must be lower.
846 * @param waiter_count Maximum count of jobs that can be waiting.
847 * @param start The start routine to activate (can't be NULL)
848 * @return 0 in case of success or -1 in case of error.
850 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
856 assert(allowed_count >= 1);
857 assert(start_count >= 0);
858 assert(waiter_count > 0);
859 assert(start_count <= allowed_count);
862 pthread_mutex_lock(&mutex);
864 /* check whether already running */
865 if (current_thread || allowed) {
866 ERROR("thread already started");
871 /* records the allowed count */
872 allowed = allowed_count;
875 remains = waiter_count;
878 /* set the watchdog */
879 if (sd_watchdog_enabled(0, NULL))
880 sd_event_set_watchdog(get_sd_event_locked(), 1);
883 /* start at least one thread */
885 while ((launched + 1) < start_count) {
886 if (start_one_thread() != 0) {
887 ERROR("Not all threads can be started");
893 /* queue the start job */
894 job = job_create(NULL, 0, start, arg);
896 ERROR("out of memory");
907 pthread_mutex_unlock(&mutex);
912 * Terminate all the threads and cancel all pending jobs.
914 void jobs_terminate()
916 struct job *job, *head, *tail;
917 pthread_t me, *others;
924 /* request all threads to stop */
925 pthread_mutex_lock(&mutex);
928 /* count the number of threads */
932 if (!t->upper && !pthread_equal(t->tid, me))
937 /* fill the array of threads */
938 others = alloca(count * sizeof *others);
942 if (!t->upper && !pthread_equal(t->tid, me))
943 others[count++] = t->tid;
947 /* stops the threads */
954 /* wait the threads */
955 pthread_cond_broadcast(&cond);
956 pthread_mutex_unlock(&mutex);
958 pthread_join(others[--count], NULL);
959 pthread_mutex_lock(&mutex);
961 /* cancel pending jobs of other threads */
971 /* search if job is stacked for current */
973 while (t && t->job != job)
976 /* yes, relink it at end */
984 /* no cancel the job */
985 pthread_mutex_unlock(&mutex);
986 sig_monitor(0, job_cancel, job);
988 pthread_mutex_lock(&mutex);
991 pthread_mutex_unlock(&mutex);