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)
57 /** Internal shortcut for callback */
58 typedef void (*job_cb_t)(int, void*);
60 /** Description of a pending job */
63 struct job *next; /**< link to the next job enqueued */
64 const void *group; /**< group of the request */
65 job_cb_t callback; /**< processing callback */
66 void *arg; /**< argument */
67 int timeout; /**< timeout in second for processing the request */
68 unsigned blocked: 1; /**< is an other request blocking this one ? */
69 unsigned dropped: 1; /**< is removed ? */
72 /** Description of handled event loops */
75 unsigned state; /**< encoded state */
76 int efd; /**< event notification */
77 struct sd_event *sdev; /**< the systemd event loop */
78 struct fdev *fdev; /**< handling of events */
79 struct thread *holder; /**< holder of the evloop */
82 #define EVLOOP_STATE_WAIT 1U
83 #define EVLOOP_STATE_RUN 2U
85 /** Description of threads */
88 struct thread *next; /**< next thread of the list */
89 struct thread *upper; /**< upper same thread */
90 struct thread *nholder;/**< next holder for evloop */
91 pthread_cond_t *cwhold;/**< condition wait for holding */
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 synchronous 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;
127 /* queue of pending jobs */
128 static struct job *first_job;
129 static struct job *free_jobs;
132 static struct evloop evloop;
134 #if defined(REMOVE_SYSTEMD_EVENT)
135 static struct fdev_epoll *fdevepoll;
140 * Create a new job with the given parameters
141 * @param group the group of the job
142 * @param timeout the timeout of the job (0 if none)
143 * @param callback the function that achieves the job
144 * @param arg the argument of the callback
145 * @return the created job unblock or NULL when no more memory
147 static struct job *job_create(
155 /* try recyle existing job */
158 free_jobs = job->next;
160 /* allocation without blocking */
161 pthread_mutex_unlock(&mutex);
162 job = malloc(sizeof *job);
163 pthread_mutex_lock(&mutex);
169 /* initialises the job */
171 job->timeout = timeout;
172 job->callback = callback;
181 * Adds 'job' at the end of the list of jobs, marking it
182 * as blocked if an other job with the same group is pending.
183 * @param job the job to add
185 static void job_add(struct job *job)
188 struct job *ijob, **pjob;
194 /* search end and blockers */
198 if (group && ijob->group == group)
209 * Get the next job to process or NULL if none.
210 * @return the first job that isn't blocked or NULL
212 static inline struct job *job_get()
214 struct job *job = first_job;
215 while (job && job->blocked)
221 * Releases the processed 'job': removes it
222 * from the list of jobs and unblock the first
223 * pending job of the same group if any.
224 * @param job the job to release
226 static inline void job_release(struct job *job)
228 struct job *ijob, **pjob;
231 /* first unqueue the job */
234 while (ijob != job) {
240 /* then unblock jobs of the same group */
244 while (ijob && ijob->group != group)
250 /* recycle the job */
251 job->next = free_jobs;
256 * Monitored cancel callback for a job.
257 * This function is called by the monitor
258 * to cancel the job when the safe environment
260 * @param signum 0 on normal flow or the number
261 * of the signal that interrupted the normal
263 * @param arg the job to run
265 static void job_cancel(int signum, void *arg)
267 struct job *job = arg;
268 job->callback(SIGABRT, job->arg);
271 #if defined(REMOVE_SYSTEMD_EVENT)
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();
289 * Monitored normal callback for events.
290 * This function is called by the monitor
291 * to run the event loop when the safe environment
293 * @param signum 0 on normal flow or the number
294 * of the signal that interrupted the normal
296 * @param arg the events to run
298 static void evloop_run(int signum, void *arg)
305 rc = sd_event_prepare(se);
308 CRITICAL("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
312 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
315 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
318 evloop.state = EVLOOP_STATE_RUN;
320 rc = sd_event_dispatch(se);
323 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
331 * Internal callback for evloop management.
332 * The effect of this function is hidden: it exits
333 * the waiting poll if any.
335 static void evloop_on_efd_event()
338 read(evloop.efd, &x, sizeof x);
342 * wakeup the event loop if needed by sending
345 static void evloop_wakeup()
349 if (evloop.state & EVLOOP_STATE_WAIT) {
351 write(evloop.efd, &x, sizeof x);
356 * Release the currently held event loop
358 static void evloop_release()
360 struct thread *nh, *ct = current_thread;
362 if (evloop.holder == ct) {
366 pthread_cond_signal(nh->cwhold);
371 * get the eventloop for the current thread
373 static int evloop_get()
375 struct thread *ct = current_thread;
378 return evloop.holder == ct;
386 * acquire the eventloop for the current thread
388 static void evloop_acquire()
390 struct thread **pwait, *ct;
393 /* try to get the evloop */
395 /* failed, init waiting state */
399 pthread_cond_init(&cond, NULL);
401 /* queue current thread in holder list */
402 pwait = &evloop.holder;
404 pwait = &(*pwait)->nholder;
407 /* wake up the evloop */
410 /* wait to acquire the evloop */
411 pthread_cond_wait(&cond, &mutex);
412 pthread_cond_destroy(&cond);
416 #if defined(REMOVE_SYSTEMD_EVENT)
418 * Monitored normal loop for waiting events.
419 * @param signum 0 on normal flow or the number
420 * of the signal that interrupted the normal
422 * @param arg the events to run
424 static void monitored_wait_and_dispatch(int signum, void *arg)
426 struct fdev_epoll *fdev_epoll = arg;
428 fdev_epoll_wait_and_dispatch(fdev_epoll, -1);
434 * Main processing loop of threads processing jobs.
435 * The loop must be called with the mutex locked
436 * and it returns with the mutex locked.
437 * @param me the description of the thread to use
438 * TODO: how are timeout handled when reentering?
440 static void thread_run(volatile struct thread *me)
445 /* initialize description of itself and link it in the list */
446 me->tid = pthread_self();
449 me->upper = current_thread;
450 if (!current_thread) {
452 sig_monitor_init_timeouts();
455 threads = (struct thread*)me;
456 current_thread = (struct thread*)me;
458 /* loop until stopped */
460 /* release the current event loop */
466 /* prepare running the job */
467 remains++; /* increases count of job that can wait */
468 job->blocked = 1; /* mark job as blocked */
469 me->job = job; /* record the job (only for terminate) */
472 pthread_mutex_unlock(&mutex);
473 sig_monitor(job->timeout, job->callback, job->arg);
474 pthread_mutex_lock(&mutex);
476 /* release the run job */
478 #if !defined(REMOVE_SYSTEMD_EVENT)
482 /* no job, check event loop wait */
483 } else if (evloop_get()) {
484 if (evloop.state != 0) {
486 CRITICAL("Can't enter dispatch while in dispatch!");
490 evloop.state = EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT;
491 pthread_mutex_unlock(&mutex);
492 sig_monitor(0, evloop_run, NULL);
493 pthread_mutex_lock(&mutex);
496 /* no job and no event loop */
499 ERROR("Entering job deep sleep! Check your bindings.");
501 pthread_cond_wait(&cond, &mutex);
505 } else if (waitevt) {
506 /* no job and not events */
509 ERROR("Entering job deep sleep! Check your bindings.");
511 pthread_cond_wait(&cond, &mutex);
515 /* wait for events */
517 pthread_mutex_unlock(&mutex);
518 sig_monitor(0, monitored_wait_and_dispatch, get_fdevepoll());
519 pthread_mutex_lock(&mutex);
525 /* release the event loop */
528 /* unlink the current thread and cleanup */
533 current_thread = me->upper;
534 if (!current_thread) {
535 sig_monitor_clean_timeouts();
541 * Entry point for created threads.
542 * @param data not used
545 static void *thread_main(void *data)
549 pthread_mutex_lock(&mutex);
553 pthread_mutex_unlock(&mutex);
558 * Starts a new thread
559 * @return 0 in case of success or -1 in case of error
561 static int start_one_thread()
566 rc = pthread_create(&tid, NULL, thread_main, NULL);
569 WARNING("not able to start thread: %m");
576 * Queues a new asynchronous job represented by 'callback' and 'arg'
577 * for the 'group' and the 'timeout'.
578 * Jobs are queued FIFO and are possibly executed in parallel
579 * concurrently except for job of the same group that are
580 * executed sequentially in FIFO order.
581 * @param group The group of the job or NULL when no group.
582 * @param timeout The maximum execution time in seconds of the job
583 * or 0 for unlimited time.
584 * @param callback The function to execute for achieving the job.
585 * Its first parameter is either 0 on normal flow
586 * or the signal number that broke the normal flow.
587 * The remaining parameter is the parameter 'arg1'
589 * @param arg The second argument for 'callback'
590 * @return 0 in case of success or -1 in case of error
595 void (*callback)(int, void*),
602 pthread_mutex_lock(&mutex);
604 /* allocates the job */
605 job = job_create(group, timeout, callback, arg);
608 info = "out of memory";
612 /* check availability */
615 info = "too many jobs";
619 /* start a thread if needed */
620 if (running == started && started < allowed) {
621 /* all threads are busy and a new can be started */
622 rc = start_one_thread();
623 if (rc < 0 && started == 0) {
624 info = "can't start first thread";
633 /* signal an existing job */
634 pthread_cond_signal(&cond);
635 pthread_mutex_unlock(&mutex);
639 job->next = free_jobs;
642 ERROR("can't process job with threads: %s, %m", info);
643 pthread_mutex_unlock(&mutex);
648 * Internal helper function for 'jobs_enter'.
649 * @see jobs_enter, jobs_leave
651 static void enter_cb(int signum, void *closure)
653 struct sync *sync = closure;
654 sync->enter(signum, sync->arg, (void*)&sync->thread);
658 * Internal helper function for 'jobs_call'.
661 static void call_cb(int signum, void *closure)
663 struct sync *sync = closure;
664 sync->callback(signum, sync->arg);
665 jobs_leave((void*)&sync->thread);
669 * Internal helper for synchronous jobs. It enters
670 * a new thread loop for evaluating the given job
671 * as recorded by the couple 'sync_cb' and 'sync'.
672 * @see jobs_call, jobs_enter, jobs_leave
677 void (*sync_cb)(int signum, void *closure),
683 pthread_mutex_lock(&mutex);
685 /* allocates the job */
686 job = job_create(group, timeout, sync_cb, sync);
688 ERROR("out of memory");
690 pthread_mutex_unlock(&mutex);
697 /* run until stopped */
698 thread_run(&sync->thread);
699 pthread_mutex_unlock(&mutex);
704 * Enter a synchronisation point: activates the job given by 'callback'
705 * and 'closure' using 'group' and 'timeout' to control sequencing and
707 * @param group the group for sequencing jobs
708 * @param timeout the time in seconds allocated to the job
709 * @param callback the callback that will handle the job.
710 * it receives 3 parameters: 'signum' that will be 0
711 * on normal flow or the catched signal number in case
712 * of interrupted flow, the context 'closure' as given and
713 * a 'jobloop' reference that must be used when the job is
714 * terminated to unlock the current execution flow.
715 * @param closure the argument to the callback
716 * @return 0 on success or -1 in case of error
721 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
727 sync.enter = callback;
729 return do_sync(group, timeout, enter_cb, &sync);
733 * Unlocks the execution flow designed by 'jobloop'.
734 * @param jobloop indication of the flow to unlock
735 * @return 0 in case of success of -1 on error
737 int jobs_leave(struct jobloop *jobloop)
741 pthread_mutex_lock(&mutex);
743 while (t && t != (struct thread*)jobloop)
750 pthread_cond_broadcast(&cond);
754 pthread_mutex_unlock(&mutex);
759 * Calls synchronously the job represented by 'callback' and 'arg1'
760 * for the 'group' and the 'timeout' and waits for its completion.
761 * @param group The group of the job or NULL when no group.
762 * @param timeout The maximum execution time in seconds of the job
763 * or 0 for unlimited time.
764 * @param callback The function to execute for achieving the job.
765 * Its first parameter is either 0 on normal flow
766 * or the signal number that broke the normal flow.
767 * The remaining parameter is the parameter 'arg1'
769 * @param arg The second argument for 'callback'
770 * @return 0 in case of success or -1 in case of error
775 void (*callback)(int, void*),
780 sync.callback = callback;
783 return do_sync(group, timeout, call_cb, &sync);
787 * Internal callback for evloop management.
788 * The effect of this function is hidden: it exits
789 * the waiting poll if any. Then it wakes up a thread
790 * awaiting the evloop using signal.
792 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
794 evloop_on_efd_event();
799 #if !defined(REMOVE_SYSTEMD_EVENT)
800 __attribute__((unused))
802 static void evloop_callback(void *arg, uint32_t event, struct fdev *fdev)
804 sig_monitor(0, evloop_run, arg);
808 * Gets a sd_event item for the current thread.
809 * @return a sd_event or NULL in case of error
811 static struct sd_event *get_sd_event_locked()
815 /* creates the evloop on need */
817 /* start the creation */
819 /* creates the eventfd for waking up polls */
820 evloop.efd = eventfd(0, EFD_CLOEXEC|EFD_SEMAPHORE);
821 if (evloop.efd < 0) {
822 ERROR("can't make eventfd for events");
825 /* create the systemd event loop */
826 rc = sd_event_new(&evloop.sdev);
828 ERROR("can't make new event loop");
831 /* put the eventfd in the event loop */
832 rc = sd_event_add_io(evloop.sdev, NULL, evloop.efd, EPOLLIN, on_evloop_efd, NULL);
834 ERROR("can't register eventfd");
835 #if !defined(REMOVE_SYSTEMD_EVENT)
836 sd_event_unref(evloop.sdev);
846 /* handle the event loop */
847 evloop.fdev = fdev_epoll_add(get_fdevepoll(), sd_event_get_fd(evloop.sdev));
849 ERROR("can't create fdev");
851 sd_event_unref(evloop.sdev);
855 memset(&evloop, 0, sizeof evloop);
858 fdev_set_autoclose(evloop.fdev, 0);
859 fdev_set_events(evloop.fdev, EPOLLIN);
860 fdev_set_callback(evloop.fdev, evloop_callback, NULL);
864 /* acquire the event loop */
871 * Gets a sd_event item for the current thread.
872 * @return a sd_event or NULL in case of error
874 struct sd_event *jobs_get_sd_event()
876 struct sd_event *result;
879 /* ensure an existing thread environment */
880 if (!current_thread) {
881 memset(<, 0, sizeof lt);
882 current_thread = <
886 pthread_mutex_lock(&mutex);
887 result = get_sd_event_locked();
888 pthread_mutex_unlock(&mutex);
890 /* release the faked thread environment if needed */
891 if (current_thread == <) {
893 * Releasing it is needed because there is no way to guess
894 * when it has to be released really. But here is where it is
895 * hazardous: if the caller modifies the eventloop when it
896 * is waiting, there is no way to make the change effective.
897 * A workaround to achieve that goal is for the caller to
898 * require the event loop a second time after having modified it.
900 NOTICE("Requiring sd_event loop out of binder callbacks is hazardous!");
901 if (verbose_wants(Log_Level_Info))
902 sig_monitor_dumpstack();
904 current_thread = NULL;
910 #if defined(REMOVE_SYSTEMD_EVENT)
912 * Gets the fdev_epoll item.
913 * @return a fdev_epoll or NULL in case of error
915 struct fdev_epoll *jobs_get_fdev_epoll()
917 struct fdev_epoll *result;
919 pthread_mutex_lock(&mutex);
920 result = get_fdevepoll();
921 pthread_mutex_unlock(&mutex);
928 * Enter the jobs processing loop.
929 * @param allowed_count Maximum count of thread for jobs including this one
930 * @param start_count Count of thread to start now, must be lower.
931 * @param waiter_count Maximum count of jobs that can be waiting.
932 * @param start The start routine to activate (can't be NULL)
933 * @return 0 in case of success or -1 in case of error.
935 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
941 assert(allowed_count >= 1);
942 assert(start_count >= 0);
943 assert(waiter_count > 0);
944 assert(start_count <= allowed_count);
947 pthread_mutex_lock(&mutex);
949 /* check whether already running */
950 if (current_thread || allowed) {
951 ERROR("thread already started");
956 /* records the allowed count */
957 allowed = allowed_count;
960 remains = waiter_count;
963 /* set the watchdog */
964 if (sd_watchdog_enabled(0, NULL))
965 sd_event_set_watchdog(get_sd_event_locked(), 1);
968 /* start at least one thread */
970 while ((launched + 1) < start_count) {
971 if (start_one_thread() != 0) {
972 ERROR("Not all threads can be started");
978 /* queue the start job */
979 job = job_create(NULL, 0, start, arg);
981 ERROR("out of memory");
994 pthread_mutex_unlock(&mutex);
999 * Terminate all the threads and cancel all pending jobs.
1001 void jobs_terminate()
1003 struct job *job, *head, *tail;
1004 pthread_t me, *others;
1009 me = pthread_self();
1011 /* request all threads to stop */
1012 pthread_mutex_lock(&mutex);
1015 /* count the number of threads */
1019 if (!t->upper && !pthread_equal(t->tid, me))
1024 /* fill the array of threads */
1025 others = alloca(count * sizeof *others);
1029 if (!t->upper && !pthread_equal(t->tid, me))
1030 others[count++] = t->tid;
1034 /* stops the threads */
1041 /* wait the threads */
1042 pthread_cond_broadcast(&cond);
1043 pthread_mutex_unlock(&mutex);
1045 pthread_join(others[--count], NULL);
1046 pthread_mutex_lock(&mutex);
1048 /* cancel pending jobs of other threads */
1054 /* unlink the job */
1058 /* search if job is stacked for current */
1060 while (t && t->job != job)
1063 /* yes, relink it at end */
1071 /* no cancel the job */
1072 pthread_mutex_unlock(&mutex);
1073 sig_monitor(0, job_cancel, job);
1075 pthread_mutex_lock(&mutex);
1078 pthread_mutex_unlock(&mutex);