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*, void *, 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 *arg1; /**< first arg */
56 void *arg2; /**< second arg */
57 void *arg3; /**< third arg */
58 int timeout; /**< timeout in second for processing the request */
59 unsigned blocked: 1; /**< is an other request blocking this one ? */
60 unsigned dropped: 1; /**< is removed ? */
63 /** Description of handled event loops */
67 struct sd_event *event;
72 /** Description of threads */
75 struct thread *next; /**< next thread of the list */
76 struct thread *upper; /**< upper same thread */
77 struct job *job; /**< currently processed job */
78 struct events *events; /**< currently processed job */
79 pthread_t tid; /**< the thread id */
80 unsigned stop: 1; /**< stop requested */
81 unsigned lowered: 1; /**< has a lower same thread */
82 unsigned waits: 1; /**< is waiting? */
86 * Description of synchonous callback
90 void (*callback)(int, void*); /**< the synchrnous callback */
91 void *arg; /**< the argument of the callback */
94 /* synchronisation of threads */
95 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
96 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
98 /* count allowed, started and waiting threads */
99 static int allowed = 0; /** allowed count of threads */
100 static int started = 0; /** started count of threads */
101 static int waiting = 0; /** waiting count of threads */
102 static int remains = 0; /** allowed count of waiting jobs */
103 static int nevents = 0; /** count of events */
105 /* list of threads */
106 static struct thread *threads;
107 static _Thread_local struct thread *current;
109 /* queue of pending jobs */
110 static struct job *first_job;
111 static struct events *first_events;
112 static struct job *free_jobs;
115 * Create a new job with the given parameters
116 * @param group the group of the job
117 * @param timeout the timeout of the job (0 if none)
118 * @param callback the function that achieves the job
119 * @param arg1 the first argument of the callback
120 * @param arg2 the second argument of the callback
121 * @param arg3 the third argument of the callback
122 * @return the created job unblock or NULL when no more memory
124 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;
162 * Adds 'job' at the end of the list of jobs, marking it
163 * as blocked if an other job with the same group is pending.
164 * @param job the job to add
166 static void job_add(struct job *job)
169 struct job *ijob, **pjob;
175 /* search end and blockers */
179 if (group && ijob->group == group)
190 * Get the next job to process or NULL if none.
191 * @return the first job that isn't blocked or NULL
193 static inline struct job *job_get()
195 struct job *job = first_job;
196 while (job && job->blocked)
202 * Get the next events to process or NULL if none.
203 * @return the first events that isn't running or NULL
205 static inline struct events *events_get()
207 struct events *events = first_events;
208 while (events && events->runs)
209 events = events->next;
214 * Releases the processed 'job': removes it
215 * from the list of jobs and unblock the first
216 * pending job of the same group if any.
217 * @param job the job to release
219 static inline void job_release(struct job *job)
221 struct job *ijob, **pjob;
224 /* first unqueue the job */
227 while (ijob != job) {
233 /* then unblock jobs of the same group */
237 while (ijob && ijob->group != group)
243 /* recycle the job */
244 job->next = free_jobs;
249 * Monitored normal callback for a job.
250 * This function is called by the monitor
251 * to run the job when the safe environment
253 * @param signum 0 on normal flow or the number
254 * of the signal that interrupted the normal
256 * @param arg the job to run
258 static void job_call(int signum, void *arg)
260 struct job *job = arg;
261 job->callback(signum, job->arg1, job->arg2, job->arg3);
265 * Monitored cancel callback for a job.
266 * This function is called by the monitor
267 * to cancel the job when the safe environment
269 * @param signum 0 on normal flow or the number
270 * of the signal that interrupted the normal
272 * @param arg the job to run
274 static void job_cancel(int signum, void *arg)
276 job_call(SIGABRT, arg);
280 * Monitored normal callback for events.
281 * This function is called by the monitor
282 * to run the event loop when the safe environment
284 * @param signum 0 on normal flow or the number
285 * of the signal that interrupted the normal
287 * @param arg the events to run
289 static void events_call(int signum, void *arg)
291 struct events *events = arg;
293 sd_event_run(events->event, events->timeout);
297 * Main processing loop of threads processing jobs.
298 * The loop must be called with the mutex locked
299 * and it returns with the mutex locked.
300 * @param me the description of the thread to use
301 * TODO: how are timeout handled when reentering?
303 static void thread_run(volatile struct thread *me)
307 struct events *events;
310 /* initialize description of itself and link it in the list */
311 me->tid = pthread_self();
317 current->lowered = 1;
318 evto = EVENT_TIMEOUT_CHILD;
321 sig_monitor_init_timeouts();
322 evto = EVENT_TIMEOUT_TOP;
325 threads = (struct thread*)me;
326 current = (struct thread*)me;
328 /* loop until stopped */
332 job = job_get(first_job);
334 /* prepare running the job */
335 remains++; /* increases count of job that can wait */
336 job->blocked = 1; /* mark job as blocked */
337 me->job = job; /* record the job (only for terminate) */
340 pthread_mutex_unlock(&mutex);
341 sig_monitor(job->timeout, job_call, job);
342 pthread_mutex_lock(&mutex);
344 /* release the run job */
347 /* release event if any */
354 /* no job, check events */
355 events = events_get();
359 events->timeout = evto;
361 pthread_mutex_unlock(&mutex);
362 sig_monitor(0, events_call, events);
363 pthread_mutex_lock(&mutex);
367 /* no job and not events */
370 pthread_cond_wait(&cond, &mutex);
377 /* unlink the current thread and cleanup */
384 current->lowered = 0;
386 sig_monitor_clean_timeouts();
392 * Entry point for created threads.
393 * @param data not used
396 static void *thread_main(void *data)
400 pthread_mutex_lock(&mutex);
402 pthread_mutex_unlock(&mutex);
407 * Starts a new thread
408 * @return 0 in case of success or -1 in case of error
410 static int start_one_thread()
415 rc = pthread_create(&tid, NULL, thread_main, NULL);
418 WARNING("not able to start thread: %m");
425 * Queues a new asynchronous job represented by 'callback'
426 * for the 'group' and the 'timeout'.
427 * Jobs are queued FIFO and are possibly executed in parallel
428 * concurrently except for job of the same group that are
429 * executed sequentially in FIFO order.
430 * @param group The group of the job or NULL when no group.
431 * @param timeout The maximum execution time in seconds of the job
432 * or 0 for unlimited time.
433 * @param callback The function to execute for achieving the job.
434 * Its first parameter is either 0 on normal flow
435 * or the signal number that broke the normal flow.
436 * @return 0 in case of success or -1 in case of error
441 void (*callback)(int signum))
443 return jobs_queue3(group, timeout, (job_cb_t)callback, NULL, NULL, NULL);
447 * Queues a new asynchronous job represented by 'callback' and 'arg1'
448 * for the 'group' and the 'timeout'.
449 * Jobs are queued FIFO and are possibly executed in parallel
450 * concurrently except for job of the same group that are
451 * executed sequentially in FIFO order.
452 * @param group The group of the job or NULL when no group.
453 * @param timeout The maximum execution time in seconds of the job
454 * or 0 for unlimited time.
455 * @param callback The function to execute for achieving the job.
456 * Its first parameter is either 0 on normal flow
457 * or the signal number that broke the normal flow.
458 * The remaining parameter is the parameter 'arg1'
460 * @param arg The second argument for 'callback'
461 * @return 0 in case of success or -1 in case of error
466 void (*callback)(int, void*),
469 return jobs_queue3(group, timeout, (job_cb_t)callback, arg, NULL, NULL);
473 * Queues a new asynchronous job represented by 'callback' and 'arg[12]'
474 * for the 'group' and the 'timeout'.
475 * Jobs are queued FIFO and are possibly executed in parallel
476 * concurrently except for job of the same group that are
477 * executed sequentially in FIFO order.
478 * @param group The group of the job or NULL when no group.
479 * @param timeout The maximum execution time in seconds of the job
480 * or 0 for unlimited time.
481 * @param callback The function to execute for achieving the job.
482 * Its first parameter is either 0 on normal flow
483 * or the signal number that broke the normal flow.
484 * The remaining parameters are the parameters 'arg[12]'
486 * @param arg1 The second argument for 'callback'
487 * @param arg2 The third argument for 'callback'
488 * @return 0 in case of success or -1 in case of error
493 void (*callback)(int, void*, void*),
497 return jobs_queue3(group, timeout, (job_cb_t)callback, arg1, arg2, NULL);
501 * Queues a new asynchronous job represented by 'callback' and 'arg[123]'
502 * for the 'group' and the 'timeout'.
503 * Jobs are queued FIFO and are possibly executed in parallel
504 * concurrently except for job of the same group that are
505 * executed sequentially in FIFO order.
506 * @param group The group of the job or NULL when no group.
507 * @param timeout The maximum execution time in seconds of the job
508 * or 0 for unlimited time.
509 * @param callback The function to execute for achieving the job.
510 * Its first parameter is either 0 on normal flow
511 * or the signal number that broke the normal flow.
512 * The remaining parameters are the parameters 'arg[123]'
514 * @param arg1 The second argument for 'callback'
515 * @param arg2 The third argument for 'callback'
516 * @param arg3 The forth argument for 'callback'
517 * @return 0 in case of success or -1 in case of error
522 void (*callback)(int, void*, void *, void*),
531 pthread_mutex_lock(&mutex);
533 /* allocates the job */
534 job = job_create(group, timeout, callback, arg1, arg2, arg3);
537 info = "out of memory";
541 /* check availability */
544 info = "too many jobs";
548 /* start a thread if needed */
549 if (waiting == 0 && started < allowed) {
550 /* all threads are busy and a new can be started */
551 rc = start_one_thread();
552 if (rc < 0 && started == 0) {
553 info = "can't start first thread";
562 /* signal an existing job */
563 pthread_cond_signal(&cond);
564 pthread_mutex_unlock(&mutex);
568 job->next = free_jobs;
571 ERROR("can't process job with threads: %s, %m", info);
572 pthread_mutex_unlock(&mutex);
577 * Enter a synchronisation point: activates the job given by 'callback'
578 * and 'closure' using 'group' and 'timeout' to control sequencing and
580 * @param group the group for sequencing jobs
581 * @param timeout the time in seconds allocated to the job
582 * @param callback the callback that will handle the job.
583 * it receives 3 parameters: 'signum' that will be 0
584 * on normal flow or the catched signal number in case
585 * of interrupted flow, the context 'closure' as given and
586 * a 'jobloop' reference that must be used when the job is
587 * terminated to unlock the current execution flow.
588 * @param closure the context completion closure for the callback
589 * @return 0 on success or -1 in case of error
594 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
602 pthread_mutex_lock(&mutex);
604 /* allocates the job */
605 job = job_create(group, timeout, (job_cb_t)callback, closure, &me, NULL);
607 ERROR("out of memory");
609 pthread_mutex_unlock(&mutex);
616 /* run until stopped */
618 pthread_mutex_unlock(&mutex);
623 * Unlocks the execution flow designed by 'jobloop'.
624 * @param jobloop indication of the flow to unlock
625 * @return 0 in case of success of -1 on error
627 int jobs_leave(struct jobloop *jobloop)
631 pthread_mutex_lock(&mutex);
633 while (t && t != (struct thread*)jobloop)
640 pthread_cond_broadcast(&cond);
642 pthread_mutex_unlock(&mutex);
647 * Internal helper function for 'jobs_call'.
648 * @see jobs_call, jobs_enter, jobs_leave
650 static void call_cb(int signum, void *closure, struct jobloop *jobloop)
652 struct sync *sync = closure;
653 sync->callback(signum, sync->arg);
658 * Calls synchronously the job represented by 'callback' and 'arg1'
659 * for the 'group' and the 'timeout' and waits for its completion.
660 * @param group The group of the job or NULL when no group.
661 * @param timeout The maximum execution time in seconds of the job
662 * or 0 for unlimited time.
663 * @param callback The function to execute for achieving the job.
664 * Its first parameter is either 0 on normal flow
665 * or the signal number that broke the normal flow.
666 * The remaining parameter is the parameter 'arg1'
668 * @param arg The second argument for 'callback'
669 * @return 0 in case of success or -1 in case of error
674 void (*callback)(int, void*),
679 sync.callback = callback;
681 return jobs_enter(group, timeout, call_cb, &sync);
685 * Gets a sd_event item for the current thread.
686 * @return a sd_event or NULL in case of error
688 struct sd_event *jobs_get_sd_event()
690 struct events *events;
694 pthread_mutex_lock(&mutex);
696 /* search events on stack */
698 while (me && !me->events)
701 /* return the stacked events */
704 /* search an available events */
705 events = events_get();
707 /* not found, check if creation possible */
708 if (nevents >= allowed) {
709 ERROR("not possible to add a new event");
712 events = malloc(sizeof *events);
713 if (events && (rc = sd_event_new(&events->event)) >= 0) {
714 if (nevents < started || start_one_thread() >= 0) {
716 events->next = first_events;
717 first_events = events;
719 ERROR("can't start thread for events");
720 sd_event_unref(events->event);
726 ERROR("out of memory");
730 ERROR("creation of sd_event failed: %m");
744 WARNING("event returned for unknown thread!");
748 pthread_mutex_unlock(&mutex);
749 return events ? events->event : NULL;
753 * Enter the jobs processing loop.
754 * @param allowed_count Maximum count of thread for jobs including this one
755 * @param start_count Count of thread to start now, must be lower.
756 * @param waiter_count Maximum count of jobs that can be waiting.
757 * @param start The start routine to activate (can't be NULL)
758 * @return 0 in case of success or -1 in case of error.
760 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)())
766 assert(allowed_count >= 1);
767 assert(start_count >= 0);
768 assert(waiter_count > 0);
769 assert(start_count <= allowed_count);
772 pthread_mutex_lock(&mutex);
774 /* check whether already running */
775 if (current || allowed) {
776 ERROR("thread already started");
782 if (sig_monitor_init() < 0) {
783 ERROR("failed to initialise signal handlers");
787 /* records the allowed count */
788 allowed = allowed_count;
791 remains = waiter_count;
793 /* start at least one thread */
795 while ((launched + 1) < start_count) {
796 if (start_one_thread() != 0) {
797 ERROR("Not all threads can be started");
803 /* queue the start job */
804 job = job_create(NULL, 0, (job_cb_t)start, NULL, NULL, NULL);
806 ERROR("out of memory");
817 pthread_mutex_unlock(&mutex);
822 * Terminate all the threads and cancel all pending jobs.
824 void jobs_terminate()
826 struct job *job, *head, *tail;
827 pthread_t me, *others;
834 /* request all threads to stop */
835 pthread_mutex_lock(&mutex);
838 /* count the number of threads */
842 if (!t->upper && !pthread_equal(t->tid, me))
847 /* fill the array of threads */
848 others = alloca(count * sizeof *others);
852 if (!t->upper && !pthread_equal(t->tid, me))
853 others[count++] = t->tid;
857 /* stops the threads */
864 /* wait the threads */
865 pthread_cond_broadcast(&cond);
866 pthread_mutex_unlock(&mutex);
868 pthread_join(others[--count], NULL);
869 pthread_mutex_lock(&mutex);
871 /* cancel pending jobs of other threads */
881 /* search if job is stacked for current */
883 while (t && t->job != job)
886 /* yes, relink it at end */
894 /* no cancel the job */
895 pthread_mutex_unlock(&mutex);
896 sig_monitor(0, job_cancel, job);
898 pthread_mutex_lock(&mutex);
901 pthread_mutex_unlock(&mutex);