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;
303 me->events = current->events;
306 sig_monitor_init_timeouts();
307 evto = EVENT_TIMEOUT_TOP;
311 threads = (struct thread*)me;
312 current = (struct thread*)me;
314 /* loop until stopped */
317 job = job_get(first_job);
319 /* prepare running the job */
320 remains++; /* increases count of job that can wait */
321 job->blocked = 1; /* mark job as blocked */
322 me->job = job; /* record the job (only for terminate) */
325 pthread_mutex_unlock(&mutex);
326 sig_monitor(job->timeout, job->callback, job->arg);
327 pthread_mutex_lock(&mutex);
329 /* release the run job */
332 /* release event if any */
339 /* no job, check events */
341 if (!events || events->runs)
342 events = events_get();
347 events->timeout = evto;
349 pthread_mutex_unlock(&mutex);
350 sig_monitor(0, events_call, events);
351 pthread_mutex_lock(&mutex);
356 while (thr && thr->events == events) {
361 /* no job and not events */
364 pthread_cond_wait(&cond, &mutex);
371 /* unlink the current thread and cleanup */
378 current->lowered = 0;
380 sig_monitor_clean_timeouts();
386 * Entry point for created threads.
387 * @param data not used
390 static void *thread_main(void *data)
394 pthread_mutex_lock(&mutex);
396 pthread_mutex_unlock(&mutex);
401 * Starts a new thread
402 * @return 0 in case of success or -1 in case of error
404 static int start_one_thread()
409 rc = pthread_create(&tid, NULL, thread_main, NULL);
412 WARNING("not able to start thread: %m");
419 * Queues a new asynchronous job represented by 'callback' and 'arg'
420 * for the 'group' and the 'timeout'.
421 * Jobs are queued FIFO and are possibly executed in parallel
422 * concurrently except for job of the same group that are
423 * executed sequentially in FIFO order.
424 * @param group The group of the job or NULL when no group.
425 * @param timeout The maximum execution time in seconds of the job
426 * or 0 for unlimited time.
427 * @param callback The function to execute for achieving the job.
428 * Its first parameter is either 0 on normal flow
429 * or the signal number that broke the normal flow.
430 * The remaining parameter is the parameter 'arg1'
432 * @param arg The second argument for 'callback'
433 * @return 0 in case of success or -1 in case of error
438 void (*callback)(int, void*),
445 pthread_mutex_lock(&mutex);
447 /* allocates the job */
448 job = job_create(group, timeout, callback, arg);
451 info = "out of memory";
455 /* check availability */
458 info = "too many jobs";
462 /* start a thread if needed */
463 if (waiting == 0 && started < allowed) {
464 /* all threads are busy and a new can be started */
465 rc = start_one_thread();
466 if (rc < 0 && started == 0) {
467 info = "can't start first thread";
476 /* signal an existing job */
477 pthread_cond_signal(&cond);
478 pthread_mutex_unlock(&mutex);
482 job->next = free_jobs;
485 ERROR("can't process job with threads: %s, %m", info);
486 pthread_mutex_unlock(&mutex);
491 * Internal helper function for 'jobs_enter'.
492 * @see jobs_enter, jobs_leave
494 static void enter_cb(int signum, void *closure)
496 struct sync *sync = closure;
497 sync->enter(signum, sync->arg, (void*)&sync->thread);
501 * Internal helper function for 'jobs_call'.
504 static void call_cb(int signum, void *closure)
506 struct sync *sync = closure;
507 sync->callback(signum, sync->arg);
508 jobs_leave((void*)&sync->thread);
512 * Internal helper for synchronous jobs. It enters
513 * a new thread loop for evaluating the given job
514 * as recorded by the couple 'sync_cb' and 'sync'.
515 * @see jobs_call, jobs_enter, jobs_leave
520 void (*sync_cb)(int signum, void *closure),
526 pthread_mutex_lock(&mutex);
528 /* allocates the job */
529 job = job_create(group, timeout, sync_cb, sync);
531 ERROR("out of memory");
533 pthread_mutex_unlock(&mutex);
540 /* run until stopped */
541 thread_run(&sync->thread);
542 pthread_mutex_unlock(&mutex);
547 * Enter a synchronisation point: activates the job given by 'callback'
548 * and 'closure' using 'group' and 'timeout' to control sequencing and
550 * @param group the group for sequencing jobs
551 * @param timeout the time in seconds allocated to the job
552 * @param callback the callback that will handle the job.
553 * it receives 3 parameters: 'signum' that will be 0
554 * on normal flow or the catched signal number in case
555 * of interrupted flow, the context 'closure' as given and
556 * a 'jobloop' reference that must be used when the job is
557 * terminated to unlock the current execution flow.
558 * @param arg the argument to the callback
559 * @return 0 on success or -1 in case of error
564 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
570 sync.enter = callback;
572 return do_sync(group, timeout, enter_cb, &sync);
576 * Unlocks the execution flow designed by 'jobloop'.
577 * @param jobloop indication of the flow to unlock
578 * @return 0 in case of success of -1 on error
580 int jobs_leave(struct jobloop *jobloop)
584 pthread_mutex_lock(&mutex);
586 while (t && t != (struct thread*)jobloop)
593 pthread_cond_broadcast(&cond);
595 pthread_mutex_unlock(&mutex);
600 * Calls synchronously the job represented by 'callback' and 'arg1'
601 * for the 'group' and the 'timeout' and waits for its completion.
602 * @param group The group of the job or NULL when no group.
603 * @param timeout The maximum execution time in seconds of the job
604 * or 0 for unlimited time.
605 * @param callback The function to execute for achieving the job.
606 * Its first parameter is either 0 on normal flow
607 * or the signal number that broke the normal flow.
608 * The remaining parameter is the parameter 'arg1'
610 * @param arg The second argument for 'callback'
611 * @return 0 in case of success or -1 in case of error
616 void (*callback)(int, void*),
621 sync.callback = callback;
624 return do_sync(group, timeout, call_cb, &sync);
628 * Gets a sd_event item for the current thread.
629 * @return a sd_event or NULL in case of error
631 struct sd_event *jobs_get_sd_event()
633 struct events *events;
637 pthread_mutex_lock(&mutex);
639 /* search events on stack */
641 while (me && !me->events)
644 /* return the stacked events */
647 /* search an available events */
648 events = events_get();
650 /* not found, check if creation possible */
651 if (nevents >= allowed) {
652 ERROR("not possible to add a new event");
655 events = malloc(sizeof *events);
656 if (events && (rc = sd_event_new(&events->event)) >= 0) {
657 if (nevents < started || start_one_thread() >= 0) {
660 events->next = first_events;
661 first_events = events;
663 ERROR("can't start thread for events");
664 sd_event_unref(events->event);
670 ERROR("out of memory");
674 ERROR("creation of sd_event failed: %m");
687 WARNING("event returned for unknown thread!");
691 pthread_mutex_unlock(&mutex);
692 return events ? events->event : NULL;
696 * Enter the jobs processing loop.
697 * @param allowed_count Maximum count of thread for jobs including this one
698 * @param start_count Count of thread to start now, must be lower.
699 * @param waiter_count Maximum count of jobs that can be waiting.
700 * @param start The start routine to activate (can't be NULL)
701 * @return 0 in case of success or -1 in case of error.
703 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum))
709 assert(allowed_count >= 1);
710 assert(start_count >= 0);
711 assert(waiter_count > 0);
712 assert(start_count <= allowed_count);
715 pthread_mutex_lock(&mutex);
717 /* check whether already running */
718 if (current || allowed) {
719 ERROR("thread already started");
725 if (sig_monitor_init() < 0) {
726 ERROR("failed to initialise signal handlers");
730 /* records the allowed count */
731 allowed = allowed_count;
734 remains = waiter_count;
736 /* start at least one thread */
738 while ((launched + 1) < start_count) {
739 if (start_one_thread() != 0) {
740 ERROR("Not all threads can be started");
746 /* queue the start job */
747 job = job_create(NULL, 0, (job_cb_t)start, NULL);
749 ERROR("out of memory");
760 pthread_mutex_unlock(&mutex);
765 * Terminate all the threads and cancel all pending jobs.
767 void jobs_terminate()
769 struct job *job, *head, *tail;
770 pthread_t me, *others;
777 /* request all threads to stop */
778 pthread_mutex_lock(&mutex);
781 /* count the number of threads */
785 if (!t->upper && !pthread_equal(t->tid, me))
790 /* fill the array of threads */
791 others = alloca(count * sizeof *others);
795 if (!t->upper && !pthread_equal(t->tid, me))
796 others[count++] = t->tid;
800 /* stops the threads */
807 /* wait the threads */
808 pthread_cond_broadcast(&cond);
809 pthread_mutex_unlock(&mutex);
811 pthread_join(others[--count], NULL);
812 pthread_mutex_lock(&mutex);
814 /* cancel pending jobs of other threads */
824 /* search if job is stacked for current */
826 while (t && t->job != job)
829 /* yes, relink it at end */
837 /* no cancel the job */
838 pthread_mutex_unlock(&mutex);
839 sig_monitor(0, job_cancel, job);
841 pthread_mutex_lock(&mutex);
844 pthread_mutex_unlock(&mutex);