2 * Copyright (C) 2016, 2017 "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.
25 #include <sys/syscall.h>
30 #include <systemd/sd-event.h>
33 #include "sig-monitor.h"
37 #define _alert_ "do you really want to remove monitoring?"
38 #define sig_monitor_init_timeouts() ((void)0)
39 #define sig_monitor_clean_timeouts() ((void)0)
40 #define sig_monitor(to,cb,arg) (cb(0,arg))
43 #define EVENT_TIMEOUT_TOP ((uint64_t)-1)
44 #define EVENT_TIMEOUT_CHILD ((uint64_t)10000)
46 /** Internal shortcut for callback */
47 typedef void (*job_cb_t)(int, void*);
49 /** Description of a pending job */
52 struct job *next; /**< link to the next job enqueued */
53 void *group; /**< group of the request */
54 job_cb_t callback; /**< processing callback */
55 void *arg; /**< argument */
56 int timeout; /**< timeout in second for processing the request */
57 unsigned blocked: 1; /**< is an other request blocking this one ? */
58 unsigned dropped: 1; /**< is removed ? */
61 /** Description of handled event loops */
65 struct sd_event *event;
70 /** Description of threads */
73 struct thread *next; /**< next thread of the list */
74 struct thread *upper; /**< upper same thread */
75 struct job *job; /**< currently processed job */
76 struct events *events; /**< currently processed job */
77 pthread_t tid; /**< the thread id */
78 unsigned stop: 1; /**< stop requested */
79 unsigned lowered: 1; /**< has a lower same thread */
80 unsigned waits: 1; /**< is waiting? */
84 * Description of synchonous callback
88 struct thread thread; /**< thread loop data */
90 void (*callback)(int, void*); /**< the synchronous callback */
91 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
92 /**< the entering synchronous routine */
94 void *arg; /**< the argument of the callback */
98 /* synchronisation of threads */
99 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
100 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
102 /* count allowed, started and waiting threads */
103 static int allowed = 0; /** allowed count of threads */
104 static int started = 0; /** started count of threads */
105 static int waiting = 0; /** waiting count of threads */
106 static int remains = 0; /** allowed count of waiting jobs */
107 static int nevents = 0; /** count of events */
109 /* list of threads */
110 static struct thread *threads;
111 static _Thread_local struct thread *current;
113 /* queue of pending jobs */
114 static struct job *first_job;
115 static struct events *first_events;
116 static struct job *free_jobs;
119 * Create a new job with the given parameters
120 * @param group the group of the job
121 * @param timeout the timeout of the job (0 if none)
122 * @param callback the function that achieves the job
123 * @param arg the argument of the callback
124 * @return the created job unblock or NULL when no more memory
126 static struct job *job_create(
134 /* try recyle existing job */
137 free_jobs = job->next;
139 /* allocation without blocking */
140 pthread_mutex_unlock(&mutex);
141 job = malloc(sizeof *job);
142 pthread_mutex_lock(&mutex);
148 /* initialises the job */
150 job->timeout = timeout;
151 job->callback = callback;
160 * Adds 'job' at the end of the list of jobs, marking it
161 * as blocked if an other job with the same group is pending.
162 * @param job the job to add
164 static void job_add(struct job *job)
167 struct job *ijob, **pjob;
173 /* search end and blockers */
177 if (group && ijob->group == group)
188 * Get the next job to process or NULL if none.
189 * @return the first job that isn't blocked or NULL
191 static inline struct job *job_get()
193 struct job *job = first_job;
194 while (job && job->blocked)
200 * Get the next events to process or NULL if none.
201 * @return the first events that isn't running or NULL
203 static inline struct events *events_get()
205 struct events *events = first_events;
206 while (events && events->runs)
207 events = events->next;
212 * Releases the processed 'job': removes it
213 * from the list of jobs and unblock the first
214 * pending job of the same group if any.
215 * @param job the job to release
217 static inline void job_release(struct job *job)
219 struct job *ijob, **pjob;
222 /* first unqueue the job */
225 while (ijob != job) {
231 /* then unblock jobs of the same group */
235 while (ijob && ijob->group != group)
241 /* recycle the job */
242 job->next = free_jobs;
247 * Monitored cancel callback for a job.
248 * This function is called by the monitor
249 * to cancel the job when the safe environment
251 * @param signum 0 on normal flow or the number
252 * of the signal that interrupted the normal
254 * @param arg the job to run
256 static void job_cancel(int signum, void *arg)
258 struct job *job = arg;
259 job->callback(SIGABRT, job->arg);
263 * Monitored normal callback for events.
264 * This function is called by the monitor
265 * to run the event loop when the safe environment
267 * @param signum 0 on normal flow or the number
268 * of the signal that interrupted the normal
270 * @param arg the events to run
272 static void events_call(int signum, void *arg)
274 struct events *events = arg;
276 sd_event_run(events->event, events->timeout);
280 * Main processing loop of threads processing jobs.
281 * The loop must be called with the mutex locked
282 * and it returns with the mutex locked.
283 * @param me the description of the thread to use
284 * TODO: how are timeout handled when reentering?
286 static void thread_run(volatile struct thread *me)
290 struct events *events;
293 /* initialize description of itself and link it in the list */
294 me->tid = pthread_self();
300 current->lowered = 1;
301 evto = EVENT_TIMEOUT_CHILD;
304 sig_monitor_init_timeouts();
305 evto = EVENT_TIMEOUT_TOP;
308 threads = (struct thread*)me;
309 current = (struct thread*)me;
311 /* loop until stopped */
315 job = job_get(first_job);
317 /* prepare running the job */
318 remains++; /* increases count of job that can wait */
319 job->blocked = 1; /* mark job as blocked */
320 me->job = job; /* record the job (only for terminate) */
323 pthread_mutex_unlock(&mutex);
324 sig_monitor(job->timeout, job->callback, job->arg);
325 pthread_mutex_lock(&mutex);
327 /* release the run job */
330 /* release event if any */
337 /* no job, check events */
338 events = events_get();
342 events->timeout = evto;
344 pthread_mutex_unlock(&mutex);
345 sig_monitor(0, events_call, events);
346 pthread_mutex_lock(&mutex);
350 /* no job and not events */
353 pthread_cond_wait(&cond, &mutex);
360 /* unlink the current thread and cleanup */
367 current->lowered = 0;
369 sig_monitor_clean_timeouts();
375 * Entry point for created threads.
376 * @param data not used
379 static void *thread_main(void *data)
383 pthread_mutex_lock(&mutex);
385 pthread_mutex_unlock(&mutex);
390 * Starts a new thread
391 * @return 0 in case of success or -1 in case of error
393 static int start_one_thread()
398 rc = pthread_create(&tid, NULL, thread_main, NULL);
401 WARNING("not able to start thread: %m");
408 * Queues a new asynchronous job represented by 'callback' and 'arg'
409 * for the 'group' and the 'timeout'.
410 * Jobs are queued FIFO and are possibly executed in parallel
411 * concurrently except for job of the same group that are
412 * executed sequentially in FIFO order.
413 * @param group The group of the job or NULL when no group.
414 * @param timeout The maximum execution time in seconds of the job
415 * or 0 for unlimited time.
416 * @param callback The function to execute for achieving the job.
417 * Its first parameter is either 0 on normal flow
418 * or the signal number that broke the normal flow.
419 * The remaining parameter is the parameter 'arg1'
421 * @param arg The second argument for 'callback'
422 * @return 0 in case of success or -1 in case of error
427 void (*callback)(int, void*),
434 pthread_mutex_lock(&mutex);
436 /* allocates the job */
437 job = job_create(group, timeout, callback, arg);
440 info = "out of memory";
444 /* check availability */
447 info = "too many jobs";
451 /* start a thread if needed */
452 if (waiting == 0 && started < allowed) {
453 /* all threads are busy and a new can be started */
454 rc = start_one_thread();
455 if (rc < 0 && started == 0) {
456 info = "can't start first thread";
465 /* signal an existing job */
466 pthread_cond_signal(&cond);
467 pthread_mutex_unlock(&mutex);
471 job->next = free_jobs;
474 ERROR("can't process job with threads: %s, %m", info);
475 pthread_mutex_unlock(&mutex);
480 * Internal helper function for 'jobs_enter'.
481 * @see jobs_enter, jobs_leave
483 static void enter_cb(int signum, void *closure)
485 struct sync *sync = closure;
486 sync->enter(signum, sync->arg, (void*)&sync->thread);
490 * Internal helper function for 'jobs_call'.
493 static void call_cb(int signum, void *closure)
495 struct sync *sync = closure;
496 sync->callback(signum, sync->arg);
497 jobs_leave((void*)&sync->thread);
501 * Internal helper for synchronous jobs. It enters
502 * a new thread loop for evaluating the given job
503 * as recorded by the couple 'sync_cb' and 'sync'.
504 * @see jobs_call, jobs_enter, jobs_leave
509 void (*sync_cb)(int signum, void *closure),
515 pthread_mutex_lock(&mutex);
517 /* allocates the job */
518 job = job_create(group, timeout, sync_cb, sync);
520 ERROR("out of memory");
522 pthread_mutex_unlock(&mutex);
529 /* run until stopped */
530 thread_run(&sync->thread);
531 pthread_mutex_unlock(&mutex);
536 * Enter a synchronisation point: activates the job given by 'callback'
537 * and 'closure' using 'group' and 'timeout' to control sequencing and
539 * @param group the group for sequencing jobs
540 * @param timeout the time in seconds allocated to the job
541 * @param callback the callback that will handle the job.
542 * it receives 3 parameters: 'signum' that will be 0
543 * on normal flow or the catched signal number in case
544 * of interrupted flow, the context 'closure' as given and
545 * a 'jobloop' reference that must be used when the job is
546 * terminated to unlock the current execution flow.
547 * @param arg the argument to the callback
548 * @return 0 on success or -1 in case of error
553 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
559 sync.enter = callback;
561 return do_sync(group, timeout, enter_cb, &sync);
565 * Unlocks the execution flow designed by 'jobloop'.
566 * @param jobloop indication of the flow to unlock
567 * @return 0 in case of success of -1 on error
569 int jobs_leave(struct jobloop *jobloop)
573 pthread_mutex_lock(&mutex);
575 while (t && t != (struct thread*)jobloop)
582 pthread_cond_broadcast(&cond);
584 pthread_mutex_unlock(&mutex);
589 * Calls synchronously the job represented by 'callback' and 'arg1'
590 * for the 'group' and the 'timeout' and waits for its completion.
591 * @param group The group of the job or NULL when no group.
592 * @param timeout The maximum execution time in seconds of the job
593 * or 0 for unlimited time.
594 * @param callback The function to execute for achieving the job.
595 * Its first parameter is either 0 on normal flow
596 * or the signal number that broke the normal flow.
597 * The remaining parameter is the parameter 'arg1'
599 * @param arg The second argument for 'callback'
600 * @return 0 in case of success or -1 in case of error
605 void (*callback)(int, void*),
610 sync.callback = callback;
613 return do_sync(group, timeout, call_cb, &sync);
617 * Gets a sd_event item for the current thread.
618 * @return a sd_event or NULL in case of error
620 struct sd_event *jobs_get_sd_event()
622 struct events *events;
626 pthread_mutex_lock(&mutex);
628 /* search events on stack */
630 while (me && !me->events)
633 /* return the stacked events */
636 /* search an available events */
637 events = events_get();
639 /* not found, check if creation possible */
640 if (nevents >= allowed) {
641 ERROR("not possible to add a new event");
644 events = malloc(sizeof *events);
645 if (events && (rc = sd_event_new(&events->event)) >= 0) {
646 if (nevents < started || start_one_thread() >= 0) {
648 events->next = first_events;
649 first_events = events;
651 ERROR("can't start thread for events");
652 sd_event_unref(events->event);
658 ERROR("out of memory");
662 ERROR("creation of sd_event failed: %m");
676 WARNING("event returned for unknown thread!");
680 pthread_mutex_unlock(&mutex);
681 return events ? events->event : NULL;
685 * Enter the jobs processing loop.
686 * @param allowed_count Maximum count of thread for jobs including this one
687 * @param start_count Count of thread to start now, must be lower.
688 * @param waiter_count Maximum count of jobs that can be waiting.
689 * @param start The start routine to activate (can't be NULL)
690 * @return 0 in case of success or -1 in case of error.
692 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)())
698 assert(allowed_count >= 1);
699 assert(start_count >= 0);
700 assert(waiter_count > 0);
701 assert(start_count <= allowed_count);
704 pthread_mutex_lock(&mutex);
706 /* check whether already running */
707 if (current || allowed) {
708 ERROR("thread already started");
714 if (sig_monitor_init() < 0) {
715 ERROR("failed to initialise signal handlers");
719 /* records the allowed count */
720 allowed = allowed_count;
723 remains = waiter_count;
725 /* start at least one thread */
727 while ((launched + 1) < start_count) {
728 if (start_one_thread() != 0) {
729 ERROR("Not all threads can be started");
735 /* queue the start job */
736 job = job_create(NULL, 0, (job_cb_t)start, NULL);
738 ERROR("out of memory");
749 pthread_mutex_unlock(&mutex);
754 * Terminate all the threads and cancel all pending jobs.
756 void jobs_terminate()
758 struct job *job, *head, *tail;
759 pthread_t me, *others;
766 /* request all threads to stop */
767 pthread_mutex_lock(&mutex);
770 /* count the number of threads */
774 if (!t->upper && !pthread_equal(t->tid, me))
779 /* fill the array of threads */
780 others = alloca(count * sizeof *others);
784 if (!t->upper && !pthread_equal(t->tid, me))
785 others[count++] = t->tid;
789 /* stops the threads */
796 /* wait the threads */
797 pthread_cond_broadcast(&cond);
798 pthread_mutex_unlock(&mutex);
800 pthread_join(others[--count], NULL);
801 pthread_mutex_lock(&mutex);
803 /* cancel pending jobs of other threads */
813 /* search if job is stacked for current */
815 while (t && t->job != job)
818 /* yes, relink it at end */
826 /* no cancel the job */
827 pthread_mutex_unlock(&mutex);
828 sig_monitor(0, job_cancel, job);
830 pthread_mutex_lock(&mutex);
833 pthread_mutex_unlock(&mutex);