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;
71 /** Description of threads */
74 struct thread *next; /**< next thread of the list */
75 struct thread *upper; /**< upper same thread */
76 struct job *job; /**< currently processed job */
77 struct events *events; /**< currently processed job */
78 pthread_t tid; /**< the thread id */
79 unsigned stop: 1; /**< stop requested */
80 unsigned lowered: 1; /**< has a lower same thread */
81 unsigned waits: 1; /**< is waiting? */
85 * Description of synchonous callback
89 struct thread thread; /**< thread loop data */
91 void (*callback)(int, void*); /**< the synchronous callback */
92 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
93 /**< the entering synchronous routine */
95 void *arg; /**< the argument of the callback */
99 /* synchronisation of threads */
100 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
101 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
103 /* count allowed, started and waiting threads */
104 static int allowed = 0; /** allowed count of threads */
105 static int started = 0; /** started count of threads */
106 static int waiting = 0; /** waiting count of threads */
107 static int remains = 0; /** allowed count of waiting jobs */
108 static int nevents = 0; /** count of events */
110 /* list of threads */
111 static struct thread *threads;
112 static _Thread_local struct thread *current;
114 /* queue of pending jobs */
115 static struct job *first_job;
116 static struct events *first_events;
117 static struct job *free_jobs;
120 * Create a new job with the given parameters
121 * @param group the group of the job
122 * @param timeout the timeout of the job (0 if none)
123 * @param callback the function that achieves the job
124 * @param arg the argument of the callback
125 * @return the created job unblock or NULL when no more memory
127 static struct job *job_create(
135 /* try recyle existing job */
138 free_jobs = job->next;
140 /* allocation without blocking */
141 pthread_mutex_unlock(&mutex);
142 job = malloc(sizeof *job);
143 pthread_mutex_lock(&mutex);
149 /* initialises the job */
151 job->timeout = timeout;
152 job->callback = callback;
161 * Adds 'job' at the end of the list of jobs, marking it
162 * as blocked if an other job with the same group is pending.
163 * @param job the job to add
165 static void job_add(struct job *job)
168 struct job *ijob, **pjob;
174 /* search end and blockers */
178 if (group && ijob->group == group)
189 * Get the next job to process or NULL if none.
190 * @return the first job that isn't blocked or NULL
192 static inline struct job *job_get()
194 struct job *job = first_job;
195 while (job && job->blocked)
201 * Get the next events to process or NULL if none.
202 * @return the first events that isn't running or NULL
204 static inline struct events *events_get()
206 struct events *events = first_events;
207 while (events && events->used)
208 events = events->next;
213 * Releases the processed 'job': removes it
214 * from the list of jobs and unblock the first
215 * pending job of the same group if any.
216 * @param job the job to release
218 static inline void job_release(struct job *job)
220 struct job *ijob, **pjob;
223 /* first unqueue the job */
226 while (ijob != job) {
232 /* then unblock jobs of the same group */
236 while (ijob && ijob->group != group)
242 /* recycle the job */
243 job->next = free_jobs;
248 * Monitored cancel callback for a job.
249 * This function is called by the monitor
250 * to cancel the job when the safe environment
252 * @param signum 0 on normal flow or the number
253 * of the signal that interrupted the normal
255 * @param arg the job to run
257 static void job_cancel(int signum, void *arg)
259 struct job *job = arg;
260 job->callback(SIGABRT, job->arg);
264 * Monitored normal callback for events.
265 * This function is called by the monitor
266 * to run the event loop when the safe environment
268 * @param signum 0 on normal flow or the number
269 * of the signal that interrupted the normal
271 * @param arg the events to run
273 static void events_call(int signum, void *arg)
275 struct events *events = arg;
277 sd_event_run(events->event, events->timeout);
281 * Main processing loop of threads processing jobs.
282 * The loop must be called with the mutex locked
283 * and it returns with the mutex locked.
284 * @param me the description of the thread to use
285 * TODO: how are timeout handled when reentering?
287 static void thread_run(volatile struct thread *me)
289 struct thread **prv, *thr;
291 struct events *events;
294 /* initialize description of itself and link it in the list */
295 me->tid = pthread_self();
301 current->lowered = 1;
302 evto = EVENT_TIMEOUT_CHILD;
305 sig_monitor_init_timeouts();
306 evto = EVENT_TIMEOUT_TOP;
309 threads = (struct thread*)me;
310 current = (struct thread*)me;
312 /* loop until stopped */
316 job = job_get(first_job);
318 /* prepare running the job */
319 remains++; /* increases count of job that can wait */
320 job->blocked = 1; /* mark job as blocked */
321 me->job = job; /* record the job (only for terminate) */
324 pthread_mutex_unlock(&mutex);
325 sig_monitor(job->timeout, job->callback, job->arg);
326 pthread_mutex_lock(&mutex);
328 /* release the run job */
331 /* release event if any */
338 /* no job, check events */
339 thr = (struct thread*)me;
341 while (thr && !(events = thr->events))
343 if (events && !events->runs) {
346 events->timeout = evto;
348 pthread_mutex_unlock(&mutex);
349 sig_monitor(0, events_call, events);
350 pthread_mutex_lock(&mutex);
354 /* no owned event, check events */
355 events = events_get();
360 events->timeout = evto;
362 pthread_mutex_unlock(&mutex);
363 sig_monitor(0, events_call, events);
364 pthread_mutex_lock(&mutex);
369 /* no job and not events */
372 pthread_cond_wait(&cond, &mutex);
380 /* unlink the current thread and cleanup */
387 current->lowered = 0;
389 sig_monitor_clean_timeouts();
395 * Entry point for created threads.
396 * @param data not used
399 static void *thread_main(void *data)
403 pthread_mutex_lock(&mutex);
405 pthread_mutex_unlock(&mutex);
410 * Starts a new thread
411 * @return 0 in case of success or -1 in case of error
413 static int start_one_thread()
418 rc = pthread_create(&tid, NULL, thread_main, NULL);
421 WARNING("not able to start thread: %m");
428 * Queues a new asynchronous job represented by 'callback' and 'arg'
429 * for the 'group' and the 'timeout'.
430 * Jobs are queued FIFO and are possibly executed in parallel
431 * concurrently except for job of the same group that are
432 * executed sequentially in FIFO order.
433 * @param group The group of the job or NULL when no group.
434 * @param timeout The maximum execution time in seconds of the job
435 * or 0 for unlimited time.
436 * @param callback The function to execute for achieving the job.
437 * Its first parameter is either 0 on normal flow
438 * or the signal number that broke the normal flow.
439 * The remaining parameter is the parameter 'arg1'
441 * @param arg The second argument for 'callback'
442 * @return 0 in case of success or -1 in case of error
447 void (*callback)(int, void*),
454 pthread_mutex_lock(&mutex);
456 /* allocates the job */
457 job = job_create(group, timeout, callback, arg);
460 info = "out of memory";
464 /* check availability */
467 info = "too many jobs";
471 /* start a thread if needed */
472 if (waiting == 0 && started < allowed) {
473 /* all threads are busy and a new can be started */
474 rc = start_one_thread();
475 if (rc < 0 && started == 0) {
476 info = "can't start first thread";
485 /* signal an existing job */
486 pthread_cond_signal(&cond);
487 pthread_mutex_unlock(&mutex);
491 job->next = free_jobs;
494 ERROR("can't process job with threads: %s, %m", info);
495 pthread_mutex_unlock(&mutex);
500 * Internal helper function for 'jobs_enter'.
501 * @see jobs_enter, jobs_leave
503 static void enter_cb(int signum, void *closure)
505 struct sync *sync = closure;
506 sync->enter(signum, sync->arg, (void*)&sync->thread);
510 * Internal helper function for 'jobs_call'.
513 static void call_cb(int signum, void *closure)
515 struct sync *sync = closure;
516 sync->callback(signum, sync->arg);
517 jobs_leave((void*)&sync->thread);
521 * Internal helper for synchronous jobs. It enters
522 * a new thread loop for evaluating the given job
523 * as recorded by the couple 'sync_cb' and 'sync'.
524 * @see jobs_call, jobs_enter, jobs_leave
529 void (*sync_cb)(int signum, void *closure),
535 pthread_mutex_lock(&mutex);
537 /* allocates the job */
538 job = job_create(group, timeout, sync_cb, sync);
540 ERROR("out of memory");
542 pthread_mutex_unlock(&mutex);
549 /* run until stopped */
550 thread_run(&sync->thread);
551 pthread_mutex_unlock(&mutex);
556 * Enter a synchronisation point: activates the job given by 'callback'
557 * and 'closure' using 'group' and 'timeout' to control sequencing and
559 * @param group the group for sequencing jobs
560 * @param timeout the time in seconds allocated to the job
561 * @param callback the callback that will handle the job.
562 * it receives 3 parameters: 'signum' that will be 0
563 * on normal flow or the catched signal number in case
564 * of interrupted flow, the context 'closure' as given and
565 * a 'jobloop' reference that must be used when the job is
566 * terminated to unlock the current execution flow.
567 * @param arg the argument to the callback
568 * @return 0 on success or -1 in case of error
573 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
579 sync.enter = callback;
581 return do_sync(group, timeout, enter_cb, &sync);
585 * Unlocks the execution flow designed by 'jobloop'.
586 * @param jobloop indication of the flow to unlock
587 * @return 0 in case of success of -1 on error
589 int jobs_leave(struct jobloop *jobloop)
593 pthread_mutex_lock(&mutex);
595 while (t && t != (struct thread*)jobloop)
602 pthread_cond_broadcast(&cond);
604 pthread_mutex_unlock(&mutex);
609 * Calls synchronously the job represented by 'callback' and 'arg1'
610 * for the 'group' and the 'timeout' and waits for its completion.
611 * @param group The group of the job or NULL when no group.
612 * @param timeout The maximum execution time in seconds of the job
613 * or 0 for unlimited time.
614 * @param callback The function to execute for achieving the job.
615 * Its first parameter is either 0 on normal flow
616 * or the signal number that broke the normal flow.
617 * The remaining parameter is the parameter 'arg1'
619 * @param arg The second argument for 'callback'
620 * @return 0 in case of success or -1 in case of error
625 void (*callback)(int, void*),
630 sync.callback = callback;
633 return do_sync(group, timeout, call_cb, &sync);
637 * Gets a sd_event item for the current thread.
638 * @return a sd_event or NULL in case of error
640 struct sd_event *jobs_get_sd_event()
642 struct events *events;
646 pthread_mutex_lock(&mutex);
648 /* search events on stack */
650 while (me && !me->events)
653 /* return the stacked events */
656 /* search an available events */
657 events = events_get();
659 /* not found, check if creation possible */
660 if (nevents >= allowed) {
661 ERROR("not possible to add a new event");
664 events = malloc(sizeof *events);
665 if (events && (rc = sd_event_new(&events->event)) >= 0) {
666 if (nevents < started || start_one_thread() >= 0) {
669 events->next = first_events;
670 first_events = events;
672 ERROR("can't start thread for events");
673 sd_event_unref(events->event);
679 ERROR("out of memory");
683 ERROR("creation of sd_event failed: %m");
696 WARNING("event returned for unknown thread!");
700 pthread_mutex_unlock(&mutex);
701 return events ? events->event : NULL;
705 * Enter the jobs processing loop.
706 * @param allowed_count Maximum count of thread for jobs including this one
707 * @param start_count Count of thread to start now, must be lower.
708 * @param waiter_count Maximum count of jobs that can be waiting.
709 * @param start The start routine to activate (can't be NULL)
710 * @return 0 in case of success or -1 in case of error.
712 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum))
718 assert(allowed_count >= 1);
719 assert(start_count >= 0);
720 assert(waiter_count > 0);
721 assert(start_count <= allowed_count);
724 pthread_mutex_lock(&mutex);
726 /* check whether already running */
727 if (current || allowed) {
728 ERROR("thread already started");
734 if (sig_monitor_init() < 0) {
735 ERROR("failed to initialise signal handlers");
739 /* records the allowed count */
740 allowed = allowed_count;
743 remains = waiter_count;
745 /* start at least one thread */
747 while ((launched + 1) < start_count) {
748 if (start_one_thread() != 0) {
749 ERROR("Not all threads can be started");
755 /* queue the start job */
756 job = job_create(NULL, 0, (job_cb_t)start, NULL);
758 ERROR("out of memory");
769 pthread_mutex_unlock(&mutex);
774 * Terminate all the threads and cancel all pending jobs.
776 void jobs_terminate()
778 struct job *job, *head, *tail;
779 pthread_t me, *others;
786 /* request all threads to stop */
787 pthread_mutex_lock(&mutex);
790 /* count the number of threads */
794 if (!t->upper && !pthread_equal(t->tid, me))
799 /* fill the array of threads */
800 others = alloca(count * sizeof *others);
804 if (!t->upper && !pthread_equal(t->tid, me))
805 others[count++] = t->tid;
809 /* stops the threads */
816 /* wait the threads */
817 pthread_cond_broadcast(&cond);
818 pthread_mutex_unlock(&mutex);
820 pthread_join(others[--count], NULL);
821 pthread_mutex_lock(&mutex);
823 /* cancel pending jobs of other threads */
833 /* search if job is stacked for current */
835 while (t && t->job != job)
838 /* yes, relink it at end */
846 /* no cancel the job */
847 pthread_mutex_unlock(&mutex);
848 sig_monitor(0, job_cancel, job);
850 pthread_mutex_lock(&mutex);
853 pthread_mutex_unlock(&mutex);