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 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
49 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
53 /** Internal shortcut for callback */
54 typedef void (*job_cb_t)(int, void*);
56 /** Description of a pending job */
59 struct job *next; /**< link to the next job enqueued */
60 const void *group; /**< group of the request */
61 job_cb_t callback; /**< processing callback */
62 void *arg; /**< argument */
63 int timeout; /**< timeout in second for processing the request */
64 unsigned blocked: 1; /**< is an other request blocking this one ? */
65 unsigned dropped: 1; /**< is removed ? */
68 /** Description of handled event loops */
71 unsigned state; /**< encoded state */
72 int efd; /**< event notification */
73 struct sd_event *sdev; /**< the systemd event loop */
74 struct fdev *fdev; /**< handling of events */
75 struct thread *holder; /**< holder of the evloop */
78 #define EVLOOP_STATE_WAIT 1U
79 #define EVLOOP_STATE_RUN 2U
81 /** Description of threads */
84 struct thread *next; /**< next thread of the list */
85 struct thread *upper; /**< upper same thread */
86 struct thread *nholder;/**< next holder for evloop */
87 pthread_cond_t *cwhold;/**< condition wait for holding */
88 struct job *job; /**< currently processed job */
89 pthread_t tid; /**< the thread id */
90 volatile unsigned stop: 1; /**< stop requested */
91 volatile unsigned waits: 1; /**< is waiting? */
95 * Description of synchronous callback
99 struct thread thread; /**< thread loop data */
101 void (*callback)(int, void*); /**< the synchronous callback */
102 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
103 /**< the entering synchronous routine */
105 void *arg; /**< the argument of the callback */
109 /* synchronisation of threads */
110 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
111 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
113 /* count allowed, started and running threads */
114 static int allowed = 0; /** allowed count of threads */
115 static int started = 0; /** started count of threads */
116 static int running = 0; /** running count of threads */
117 static int remains = 0; /** allowed count of waiting jobs */
119 /* list of threads */
120 static struct thread *threads;
121 static _Thread_local struct thread *current_thread;
123 /* queue of pending jobs */
124 static struct job *first_job;
125 static struct job *free_jobs;
128 static struct evloop evloop;
131 * Create a new job with the given parameters
132 * @param group the group of the job
133 * @param timeout the timeout of the job (0 if none)
134 * @param callback the function that achieves the job
135 * @param arg the argument of the callback
136 * @return the created job unblock or NULL when no more memory
138 static struct job *job_create(
146 /* try recyle existing job */
149 free_jobs = job->next;
151 /* allocation without blocking */
152 pthread_mutex_unlock(&mutex);
153 job = malloc(sizeof *job);
154 pthread_mutex_lock(&mutex);
156 ERROR("out of memory");
161 /* initialises the job */
163 job->timeout = timeout;
164 job->callback = callback;
173 * Adds 'job' at the end of the list of jobs, marking it
174 * as blocked if an other job with the same group is pending.
175 * @param job the job to add
177 static void job_add(struct job *job)
180 struct job *ijob, **pjob;
186 /* search end and blockers */
190 if (group && ijob->group == group)
202 * Get the next job to process or NULL if none.
203 * @return the first job that isn't blocked or NULL
205 static inline struct job *job_get()
207 struct job *job = first_job;
208 while (job && job->blocked)
216 * Releases the processed 'job': removes it
217 * from the list of jobs and unblock the first
218 * pending job of the same group if any.
219 * @param job the job to release
221 static inline void job_release(struct job *job)
223 struct job *ijob, **pjob;
226 /* first unqueue the job */
229 while (ijob != job) {
235 /* then unblock jobs of the same group */
239 while (ijob && ijob->group != group)
245 /* recycle the job */
246 job->next = free_jobs;
251 * Monitored cancel callback for a job.
252 * This function is called by the monitor
253 * to cancel the job when the safe environment
255 * @param signum 0 on normal flow or the number
256 * of the signal that interrupted the normal
258 * @param arg the job to run
260 static void job_cancel(int signum, void *arg)
262 struct job *job = arg;
263 job->callback(SIGABRT, job->arg);
267 * Monitored normal callback for events.
268 * This function is called by the monitor
269 * to run the event loop when the safe environment
271 * @param signum 0 on normal flow or the number
272 * of the signal that interrupted the normal
274 * @param arg the events to run
276 static void evloop_run(int signum, void *arg)
283 rc = sd_event_prepare(se);
286 CRITICAL("sd_event_prepare returned an error (state: %d): %m", sd_event_get_state(se));
290 rc = sd_event_wait(se, (uint64_t)(int64_t)-1);
293 ERROR("sd_event_wait returned an error (state: %d): %m", sd_event_get_state(se));
296 evloop.state = EVLOOP_STATE_RUN;
298 rc = sd_event_dispatch(se);
301 ERROR("sd_event_dispatch returned an error (state: %d): %m", sd_event_get_state(se));
309 * Internal callback for evloop management.
310 * The effect of this function is hidden: it exits
311 * the waiting poll if any.
313 static void evloop_on_efd_event()
316 read(evloop.efd, &x, sizeof x);
320 * wakeup the event loop if needed by sending
323 static void evloop_wakeup()
327 if (evloop.state & EVLOOP_STATE_WAIT) {
329 write(evloop.efd, &x, sizeof x);
334 * Release the currently held event loop
336 static void evloop_release()
338 struct thread *nh, *ct = current_thread;
340 if (evloop.holder == ct) {
344 pthread_cond_signal(nh->cwhold);
349 * get the eventloop for the current thread
351 static int evloop_get()
353 struct thread *ct = current_thread;
356 return evloop.holder == ct;
364 * acquire the eventloop for the current thread
366 static void evloop_acquire()
368 struct thread **pwait, *ct;
371 /* try to get the evloop */
373 /* failed, init waiting state */
377 pthread_cond_init(&cond, NULL);
379 /* queue current thread in holder list */
380 pwait = &evloop.holder;
382 pwait = &(*pwait)->nholder;
385 /* wake up the evloop */
388 /* wait to acquire the evloop */
389 pthread_cond_wait(&cond, &mutex);
390 pthread_cond_destroy(&cond);
396 * @param me the description of the thread to enter
398 static void thread_enter(volatile struct thread *me)
400 /* initialize description of itself and link it in the list */
401 me->tid = pthread_self();
404 me->upper = current_thread;
406 threads = (struct thread*)me;
407 current_thread = (struct thread*)me;
412 * @param me the description of the thread to leave
414 static void thread_leave()
416 struct thread **prv, *me;
418 /* unlink the current thread and cleanup */
425 current_thread = me->upper;
429 * Main processing loop of internal threads with processing jobs.
430 * The loop must be called with the mutex locked
431 * and it returns with the mutex locked.
432 * @param me the description of the thread to use
433 * TODO: how are timeout handled when reentering?
435 static void thread_run_internal(volatile struct thread *me)
442 /* loop until stopped */
444 /* release the current event loop */
450 /* prepare running the job */
451 job->blocked = 1; /* mark job as blocked */
452 me->job = job; /* record the job (only for terminate) */
455 pthread_mutex_unlock(&mutex);
456 sig_monitor(job->timeout, job->callback, job->arg);
457 pthread_mutex_lock(&mutex);
459 /* release the run job */
461 /* no job, check event loop wait */
462 } else if (evloop_get()) {
463 if (evloop.state != 0) {
465 CRITICAL("Can't enter dispatch while in dispatch!");
469 evloop.state = EVLOOP_STATE_RUN|EVLOOP_STATE_WAIT;
470 pthread_mutex_unlock(&mutex);
471 sig_monitor(0, evloop_run, NULL);
472 pthread_mutex_lock(&mutex);
475 /* no job and no event loop */
478 ERROR("Entering job deep sleep! Check your bindings.");
480 pthread_cond_wait(&cond, &mutex);
491 * Main processing loop of external threads.
492 * The loop must be called with the mutex locked
493 * and it returns with the mutex locked.
494 * @param me the description of the thread to use
496 static void thread_run_external(volatile struct thread *me)
501 /* loop until stopped */
504 pthread_cond_wait(&cond, &mutex);
510 * Root for created threads.
512 static void thread_main()
518 sig_monitor_init_timeouts();
519 thread_run_internal(&me);
520 sig_monitor_clean_timeouts();
526 * Entry point for created threads.
527 * @param data not used
530 static void *thread_starter(void *data)
532 pthread_mutex_lock(&mutex);
534 pthread_mutex_unlock(&mutex);
539 * Starts a new thread
540 * @return 0 in case of success or -1 in case of error
542 static int start_one_thread()
547 rc = pthread_create(&tid, NULL, thread_starter, NULL);
550 WARNING("not able to start thread: %m");
557 * Queues a new asynchronous job represented by 'callback' and 'arg'
558 * for the 'group' and the 'timeout'.
559 * Jobs are queued FIFO and are possibly executed in parallel
560 * concurrently except for job of the same group that are
561 * executed sequentially in FIFO order.
562 * @param group The group of the job or NULL when no group.
563 * @param timeout The maximum execution time in seconds of the job
564 * or 0 for unlimited time.
565 * @param callback The function to execute for achieving the job.
566 * Its first parameter is either 0 on normal flow
567 * or the signal number that broke the normal flow.
568 * The remaining parameter is the parameter 'arg1'
570 * @param arg The second argument for 'callback'
571 * @return 0 in case of success or -1 in case of error
576 void (*callback)(int, void*),
582 pthread_mutex_lock(&mutex);
584 /* allocates the job */
585 job = job_create(group, timeout, callback, arg);
589 /* check availability */
591 ERROR("can't process job with threads: too many jobs");
596 /* start a thread if needed */
597 if (running == started && started < allowed) {
598 /* all threads are busy and a new can be started */
599 rc = start_one_thread();
600 if (rc < 0 && started == 0) {
601 ERROR("can't start initial thread: %m");
609 /* signal an existing job */
610 pthread_cond_signal(&cond);
611 pthread_mutex_unlock(&mutex);
615 job->next = free_jobs;
618 pthread_mutex_unlock(&mutex);
623 * Internal helper function for 'jobs_enter'.
624 * @see jobs_enter, jobs_leave
626 static void enter_cb(int signum, void *closure)
628 struct sync *sync = closure;
629 sync->enter(signum, sync->arg, (void*)&sync->thread);
633 * Internal helper function for 'jobs_call'.
636 static void call_cb(int signum, void *closure)
638 struct sync *sync = closure;
639 sync->callback(signum, sync->arg);
640 jobs_leave((void*)&sync->thread);
644 * Internal helper for synchronous jobs. It enters
645 * a new thread loop for evaluating the given job
646 * as recorded by the couple 'sync_cb' and 'sync'.
647 * @see jobs_call, jobs_enter, jobs_leave
652 void (*sync_cb)(int signum, void *closure),
658 pthread_mutex_lock(&mutex);
660 /* allocates the job */
661 job = job_create(group, timeout, sync_cb, sync);
663 pthread_mutex_unlock(&mutex);
670 /* run until stopped */
672 thread_run_internal(&sync->thread);
674 thread_run_external(&sync->thread);
675 pthread_mutex_unlock(&mutex);
680 * Enter a synchronisation point: activates the job given by 'callback'
681 * and 'closure' using 'group' and 'timeout' to control sequencing and
683 * @param group the group for sequencing jobs
684 * @param timeout the time in seconds allocated to the job
685 * @param callback the callback that will handle the job.
686 * it receives 3 parameters: 'signum' that will be 0
687 * on normal flow or the catched signal number in case
688 * of interrupted flow, the context 'closure' as given and
689 * a 'jobloop' reference that must be used when the job is
690 * terminated to unlock the current execution flow.
691 * @param closure the argument to the callback
692 * @return 0 on success or -1 in case of error
697 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
703 sync.enter = callback;
705 return do_sync(group, timeout, enter_cb, &sync);
709 * Unlocks the execution flow designed by 'jobloop'.
710 * @param jobloop indication of the flow to unlock
711 * @return 0 in case of success of -1 on error
713 int jobs_leave(struct jobloop *jobloop)
717 pthread_mutex_lock(&mutex);
719 while (t && t != (struct thread*)jobloop)
726 pthread_cond_broadcast(&cond);
730 pthread_mutex_unlock(&mutex);
735 * Calls synchronously the job represented by 'callback' and 'arg1'
736 * for the 'group' and the 'timeout' and waits for its completion.
737 * @param group The group of the job or NULL when no group.
738 * @param timeout The maximum execution time in seconds of the job
739 * or 0 for unlimited time.
740 * @param callback The function to execute for achieving the job.
741 * Its first parameter is either 0 on normal flow
742 * or the signal number that broke the normal flow.
743 * The remaining parameter is the parameter 'arg1'
745 * @param arg The second argument for 'callback'
746 * @return 0 in case of success or -1 in case of error
751 void (*callback)(int, void*),
756 sync.callback = callback;
759 return do_sync(group, timeout, call_cb, &sync);
763 * Internal callback for evloop management.
764 * The effect of this function is hidden: it exits
765 * the waiting poll if any. Then it wakes up a thread
766 * awaiting the evloop using signal.
768 static int on_evloop_efd(sd_event_source *s, int fd, uint32_t revents, void *userdata)
770 evloop_on_efd_event();
775 * Gets a sd_event item for the current thread.
776 * @return a sd_event or NULL in case of error
778 static struct sd_event *get_sd_event_locked()
782 /* creates the evloop on need */
784 /* start the creation */
786 /* creates the eventfd for waking up polls */
787 evloop.efd = eventfd(0, EFD_CLOEXEC|EFD_SEMAPHORE);
788 if (evloop.efd < 0) {
789 ERROR("can't make eventfd for events");
792 /* create the systemd event loop */
793 rc = sd_event_new(&evloop.sdev);
795 ERROR("can't make new event loop");
798 /* put the eventfd in the event loop */
799 rc = sd_event_add_io(evloop.sdev, NULL, evloop.efd, EPOLLIN, on_evloop_efd, NULL);
801 ERROR("can't register eventfd");
802 sd_event_unref(evloop.sdev);
811 /* acquire the event loop */
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;
826 /* ensure an existing thread environment */
827 if (!current_thread) {
828 memset(<, 0, sizeof lt);
829 current_thread = <
833 pthread_mutex_lock(&mutex);
834 result = get_sd_event_locked();
835 pthread_mutex_unlock(&mutex);
837 /* release the faked thread environment if needed */
838 if (current_thread == <) {
840 * Releasing it is needed because there is no way to guess
841 * when it has to be released really. But here is where it is
842 * hazardous: if the caller modifies the eventloop when it
843 * is waiting, there is no way to make the change effective.
844 * A workaround to achieve that goal is for the caller to
845 * require the event loop a second time after having modified it.
847 NOTICE("Requiring sd_event loop out of binder callbacks is hazardous!");
848 if (verbose_wants(Log_Level_Info))
849 sig_monitor_dumpstack();
851 current_thread = NULL;
858 * Enter the jobs processing loop.
859 * @param allowed_count Maximum count of thread for jobs including this one
860 * @param start_count Count of thread to start now, must be lower.
861 * @param waiter_count Maximum count of jobs that can be waiting.
862 * @param start The start routine to activate (can't be NULL)
863 * @return 0 in case of success or -1 in case of error.
865 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
870 assert(allowed_count >= 1);
871 assert(start_count >= 0);
872 assert(waiter_count > 0);
873 assert(start_count <= allowed_count);
876 pthread_mutex_lock(&mutex);
878 /* check whether already running */
879 if (current_thread || allowed) {
880 ERROR("thread already started");
885 /* records the allowed count */
886 allowed = allowed_count;
889 remains = waiter_count;
892 /* set the watchdog */
893 if (sd_watchdog_enabled(0, NULL))
894 sd_event_set_watchdog(get_sd_event_locked(), 1);
897 /* start at least one thread: the current one */
899 while (launched < start_count) {
900 if (start_one_thread() != 0) {
901 ERROR("Not all threads can be started");
907 /* queue the start job */
908 job = job_create(NULL, 0, start, arg);
917 pthread_mutex_unlock(&mutex);
922 * Terminate all the threads and cancel all pending jobs.
924 void jobs_terminate()
926 struct job *job, *head, *tail;
927 pthread_t me, *others;
934 /* request all threads to stop */
935 pthread_mutex_lock(&mutex);
938 /* count the number of threads */
942 if (!t->upper && !pthread_equal(t->tid, me))
947 /* fill the array of threads */
948 others = alloca(count * sizeof *others);
952 if (!t->upper && !pthread_equal(t->tid, me))
953 others[count++] = t->tid;
957 /* stops the threads */
964 /* wait the threads */
965 pthread_cond_broadcast(&cond);
966 pthread_mutex_unlock(&mutex);
968 pthread_join(others[--count], NULL);
969 pthread_mutex_lock(&mutex);
971 /* cancel pending jobs of other threads */
981 /* search if job is stacked for current */
983 while (t && t->job != job)
986 /* yes, relink it at end */
994 /* no cancel the job */
995 pthread_mutex_unlock(&mutex);
996 sig_monitor(0, job_cancel, job);
998 pthread_mutex_lock(&mutex);
1001 pthread_mutex_unlock(&mutex);