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? */
85 /* synchronisation of threads */
86 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
87 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
89 /* count allowed, started and waiting threads */
90 static int allowed = 0; /** allowed count of threads */
91 static int started = 0; /** started count of threads */
92 static int waiting = 0; /** waiting count of threads */
93 static int remains = 0; /** allowed count of waiting jobs */
94 static int nevents = 0; /** count of events */
97 static struct thread *threads;
98 static _Thread_local struct thread *current;
100 /* queue of pending jobs */
101 static struct job *first_job;
102 static struct events *first_events;
103 static struct job *free_jobs;
106 * Create a new job with the given parameters
107 * @param group the group of the job
108 * @param timeout the timeout of the job (0 if none)
109 * @param callback the function that achieves the job
110 * @param arg1 the first argument of the callback
111 * @param arg2 the second argument of the callback
112 * @param arg3 the third argument of the callback
113 * @return the created job unblock or NULL when no more memory
115 static struct job *job_create(
125 /* try recyle existing job */
128 free_jobs = job->next;
130 /* allocation without blocking */
131 pthread_mutex_unlock(&mutex);
132 job = malloc(sizeof *job);
133 pthread_mutex_lock(&mutex);
139 /* initialises the job */
141 job->timeout = timeout;
142 job->callback = callback;
153 * Adds 'job' at the end of the list of jobs, marking it
154 * as blocked if an other job with the same group is pending.
155 * @param job the job to add
157 static void job_add(struct job *job)
160 struct job *ijob, **pjob;
166 /* search end and blockers */
170 if (group && ijob->group == group)
181 * Get the next job to process or NULL if none.
182 * @return the first job that isn't blocked or NULL
184 static inline struct job *job_get()
186 struct job *job = first_job;
187 while (job && job->blocked)
193 * Get the next events to process or NULL if none.
194 * @return the first events that isn't running or NULL
196 static inline struct events *events_get()
198 struct events *events = first_events;
199 while (events && events->runs)
200 events = events->next;
205 * Releases the processed 'job': removes it
206 * from the list of jobs and unblock the first
207 * pending job of the same group if any.
208 * @param job the job to release
210 static inline void job_release(struct job *job)
212 struct job *ijob, **pjob;
215 /* first unqueue the job */
218 while (ijob != job) {
224 /* then unblock jobs of the same group */
228 while (ijob && ijob->group != group)
234 /* recycle the job */
235 job->next = free_jobs;
240 * Monitored normal callback for a job.
241 * This function is called by the monitor
242 * to run the job when the safe environment
244 * @param signum 0 on normal flow or the number
245 * of the signal that interrupted the normal
247 * @param arg the job to run
249 static void job_call(int signum, void *arg)
251 struct job *job = arg;
252 job->callback(signum, job->arg1, job->arg2, job->arg3);
256 * Monitored cancel callback for a job.
257 * This function is called by the monitor
258 * to cancel the job when the safe environment
260 * @param signum 0 on normal flow or the number
261 * of the signal that interrupted the normal
263 * @param arg the job to run
265 static void job_cancel(int signum, void *arg)
267 job_call(SIGABRT, arg);
271 * Monitored normal callback for events.
272 * This function is called by the monitor
273 * to run the event loop when the safe environment
275 * @param signum 0 on normal flow or the number
276 * of the signal that interrupted the normal
278 * @param arg the events to run
280 static void events_call(int signum, void *arg)
282 struct events *events = arg;
284 sd_event_run(events->event, events->timeout);
288 * Main processing loop of threads processing jobs.
289 * The loop must be called with the mutex locked
290 * and it returns with the mutex locked.
291 * @param me the description of the thread to use
292 * TODO: how are timeout handled when reentering?
294 static void thread_run(volatile struct thread *me)
298 struct events *events;
301 /* initialize description of itself and link it in the list */
302 me->tid = pthread_self();
308 current->lowered = 1;
309 evto = EVENT_TIMEOUT_CHILD;
312 sig_monitor_init_timeouts();
313 evto = EVENT_TIMEOUT_TOP;
316 threads = (struct thread*)me;
317 current = (struct thread*)me;
319 NOTICE("job thread starting %d(/%d) %s", started, allowed, me->upper ? "child" : "parent");
321 /* loop until stopped */
325 job = job_get(first_job);
327 /* prepare running the job */
328 remains++; /* increases count of job that can wait */
329 job->blocked = 1; /* mark job as blocked */
330 me->job = job; /* record the job (only for terminate) */
333 pthread_mutex_unlock(&mutex);
334 sig_monitor(job->timeout, job_call, job);
335 pthread_mutex_lock(&mutex);
337 /* release the run job */
340 /* release event if any */
347 /* no job, check events */
348 events = events_get();
352 events->timeout = evto;
354 pthread_mutex_unlock(&mutex);
355 sig_monitor(0, events_call, events);
356 pthread_mutex_lock(&mutex);
360 /* no job and not events */
363 pthread_cond_wait(&cond, &mutex);
369 NOTICE("job thread stoping %d(/%d) %s", started, allowed, me->upper ? "child" : "parent");
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'
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 * @return 0 in case of success or -1 in case of error
435 void (*callback)(int signum))
437 return jobs_queue3(group, timeout, (job_cb_t)callback, NULL, NULL, NULL);
441 * Queues a new asynchronous job represented by 'callback' and 'arg1'
442 * for the 'group' and the 'timeout'.
443 * Jobs are queued FIFO and are possibly executed in parallel
444 * concurrently except for job of the same group that are
445 * executed sequentially in FIFO order.
446 * @param group The group of the job or NULL when no group.
447 * @param timeout The maximum execution time in seconds of the job
448 * or 0 for unlimited time.
449 * @param callback The function to execute for achieving the job.
450 * Its first parameter is either 0 on normal flow
451 * or the signal number that broke the normal flow.
452 * The remaining parameter is the parameter 'arg1'
454 * @param arg1 The second argument for 'callback'
455 * @return 0 in case of success or -1 in case of error
460 void (*callback)(int, void*),
463 return jobs_queue3(group, timeout, (job_cb_t)callback, arg, NULL, NULL);
467 * Queues a new asynchronous job represented by 'callback' and 'arg[12]'
468 * for the 'group' and the 'timeout'.
469 * Jobs are queued FIFO and are possibly executed in parallel
470 * concurrently except for job of the same group that are
471 * executed sequentially in FIFO order.
472 * @param group The group of the job or NULL when no group.
473 * @param timeout The maximum execution time in seconds of the job
474 * or 0 for unlimited time.
475 * @param callback The function to execute for achieving the job.
476 * Its first parameter is either 0 on normal flow
477 * or the signal number that broke the normal flow.
478 * The remaining parameters are the parameters 'arg[12]'
480 * @param arg1 The second argument for 'callback'
481 * @param arg2 The third argument for 'callback'
482 * @return 0 in case of success or -1 in case of error
487 void (*callback)(int, void*, void*),
491 return jobs_queue3(group, timeout, (job_cb_t)callback, arg1, arg2, NULL);
495 * Queues a new asynchronous job represented by 'callback' and 'arg[123]'
496 * for the 'group' and the 'timeout'.
497 * Jobs are queued FIFO and are possibly executed in parallel
498 * concurrently except for job of the same group that are
499 * executed sequentially in FIFO order.
500 * @param group The group of the job or NULL when no group.
501 * @param timeout The maximum execution time in seconds of the job
502 * or 0 for unlimited time.
503 * @param callback The function to execute for achieving the job.
504 * Its first parameter is either 0 on normal flow
505 * or the signal number that broke the normal flow.
506 * The remaining parameters are the parameters 'arg[123]'
508 * @param arg1 The second argument for 'callback'
509 * @param arg2 The third argument for 'callback'
510 * @param arg3 The forth argument for 'callback'
511 * @return 0 in case of success or -1 in case of error
516 void (*callback)(int, void*, void *, void*),
525 pthread_mutex_lock(&mutex);
527 /* allocates the job */
528 job = job_create(group, timeout, callback, arg1, arg2, arg3);
531 info = "out of memory";
535 /* check availability */
538 info = "too many jobs";
542 /* start a thread if needed */
543 if (waiting == 0 && started < allowed) {
544 /* all threads are busy and a new can be started */
545 rc = start_one_thread();
546 if (rc < 0 && started == 0) {
547 info = "can't start first thread";
556 /* signal an existing job */
557 pthread_cond_signal(&cond);
558 pthread_mutex_unlock(&mutex);
562 job->next = free_jobs;
565 ERROR("can't process job with threads: %s, %m", info);
566 pthread_mutex_unlock(&mutex);
571 * Enter a synchronisation point: activates the job given by 'callback'
572 * @param group the gro
577 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
584 pthread_mutex_lock(&mutex);
586 /* allocates the job */
587 job = job_create(group, timeout, (job_cb_t)callback, closure, &me, NULL);
589 ERROR("out of memory");
591 pthread_mutex_unlock(&mutex);
598 /* run until stopped */
600 pthread_mutex_unlock(&mutex);
604 int jobs_leave(struct jobloop *jobloop)
607 pthread_mutex_lock(&mutex);
610 while (t && t != (struct thread*)jobloop)
617 pthread_cond_broadcast(&cond);
619 pthread_mutex_unlock(&mutex);
624 * Gets a sd_event item for the current thread.
625 * @return a sd_event or NULL in case of error
627 struct sd_event *jobs_get_sd_event()
629 struct events *events;
633 pthread_mutex_lock(&mutex);
635 /* search events on stack */
637 while (me && !me->events)
640 /* return the stacked events */
643 /* search an available events */
644 events = events_get();
646 /* not found, check if creation possible */
647 if (nevents >= allowed) {
648 ERROR("not possible to add a new event");
651 events = malloc(sizeof *events);
652 if (events && (rc = sd_event_new(&events->event)) >= 0) {
653 if (nevents < started || start_one_thread() >= 0) {
655 events->next = first_events;
656 first_events = events;
658 ERROR("can't start thread for events");
659 sd_event_unref(events->event);
665 ERROR("out of memory");
669 ERROR("creation of sd_event failed: %m");
683 WARNING("event returned for unknown thread!");
687 pthread_mutex_unlock(&mutex);
688 return events ? events->event : NULL;
692 * Enter the jobs processing loop.
693 * @param allowed_count Maximum count of thread for jobs including this one
694 * @param start_count Count of thread to start now, must be lower.
695 * @param waiter_count Maximum count of jobs that can be waiting.
696 * @param start The start routine to activate (can't be NULL)
697 * @return 0 in case of success or -1 in case of error.
699 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)())
705 assert(allowed_count >= 1);
706 assert(start_count >= 0);
707 assert(waiter_count > 0);
708 assert(start_count <= allowed_count);
711 pthread_mutex_lock(&mutex);
713 /* check whether already running */
714 if (current || allowed) {
715 ERROR("thread already started");
721 if (sig_monitor_init() < 0) {
722 ERROR("failed to initialise signal handlers");
726 /* records the allowed count */
727 allowed = allowed_count;
730 remains = waiter_count;
732 /* start at least one thread */
734 while ((launched + 1) < start_count) {
735 if (start_one_thread() != 0) {
736 ERROR("Not all threads can be started");
742 /* queue the start job */
743 job = job_create(NULL, 0, (job_cb_t)start, NULL, NULL, NULL);
745 ERROR("out of memory");
756 pthread_mutex_unlock(&mutex);
761 * Terminate all the threads and cancel all pending jobs.
763 void jobs_terminate()
765 struct job *job, *head, *tail;
766 pthread_t me, *others;
773 /* request all threads to stop */
774 pthread_mutex_lock(&mutex);
777 /* count the number of threads */
781 if (!t->upper && !pthread_equal(t->tid, me))
786 /* fill the array of threads */
787 others = alloca(count * sizeof *others);
791 if (!t->upper && !pthread_equal(t->tid, me))
792 others[count++] = t->tid;
796 /* stops the threads */
803 /* wait the threads */
804 pthread_cond_broadcast(&cond);
805 pthread_mutex_unlock(&mutex);
807 pthread_join(others[--count], NULL);
808 pthread_mutex_lock(&mutex);
810 /* cancel pending jobs of other threads */
820 /* search if job is stacked for current */
822 while (t && t->job != job)
825 /* yes, relink it at end */
833 /* no cancel the job */
834 pthread_mutex_unlock(&mutex);
835 sig_monitor(0, job_cancel, job);
837 pthread_mutex_lock(&mutex);
840 pthread_mutex_unlock(&mutex);