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.
24 #include <sys/syscall.h>
29 #include <systemd/sd-event.h>
32 #include "sig-monitor.h"
36 #define _alert_ "do you really want to remove monitoring?"
37 #define sig_monitor_init_timeouts() ((void)0)
38 #define sig_monitor_clean_timeouts() ((void)0)
39 #define sig_monitor(to,cb,arg) (cb(0,arg))
42 /** Internal shortcut for callback */
43 typedef void (*job_cb_t)(int, void*, void *, void*);
45 /** Description of a pending job */
48 struct job *next; /**< link to the next job enqueued */
49 void *group; /**< group of the request */
50 job_cb_t callback; /**< processing callback */
51 void *arg1; /**< first arg */
52 void *arg2; /**< second arg */
53 void *arg3; /**< third arg */
54 int timeout; /**< timeout in second for processing the request */
55 unsigned blocked: 1; /**< is an other request blocking this one ? */
56 unsigned dropped: 1; /**< is removed ? */
59 /** Description of handled event loops */
63 struct sd_event *event;
67 /** Description of threads */
70 struct thread *next; /**< next thread of the list */
71 struct thread *upper; /**< upper same thread */
72 struct job *job; /**< currently processed job */
73 struct events *events; /**< currently processed job */
74 pthread_t tid; /**< the thread id */
75 unsigned stop: 1; /**< stop requested */
76 unsigned lowered: 1; /**< has a lower same thread */
77 unsigned waits: 1; /**< is waiting? */
80 /* synchronisation of threads */
81 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
82 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
84 /* count allowed, started and waiting threads */
85 static int allowed = 0; /** allowed count of threads */
86 static int started = 0; /** started count of threads */
87 static int waiting = 0; /** waiting count of threads */
88 static int remains = 0; /** allowed count of waiting jobs */
89 static int nevents = 0; /** count of events */
92 static struct thread *threads;
93 static _Thread_local struct thread *current;
95 /* queue of pending jobs */
96 static struct job *first_job;
97 static struct events *first_events;
98 static struct job *free_jobs;
101 * Create a new job with the given parameters
102 * @param group the group of the job
103 * @param timeout the timeout of the job (0 if none)
104 * @param callback the function that achieves the job
105 * @param arg1 the first argument of the callback
106 * @param arg2 the second argument of the callback
107 * @param arg3 the third argument of the callback
108 * @return the created job unblock or NULL when no more memory
110 static struct job *job_create(
120 /* try recyle existing job */
123 free_jobs = job->next;
125 /* allocation without blocking */
126 pthread_mutex_unlock(&mutex);
127 job = malloc(sizeof *job);
128 pthread_mutex_lock(&mutex);
134 /* initialises the job */
136 job->timeout = timeout;
137 job->callback = callback;
148 * Adds 'job' at the end of the list of jobs, marking it
149 * as blocked if an other job with the same group is pending.
150 * @param job the job to add
152 static void job_add(struct job *job)
155 struct job *ijob, **pjob;
161 /* search end and blockers */
165 if (group && ijob->group == group)
176 * Get the next job to process or NULL if none.
177 * @return the first job that isn't blocked or NULL
179 static inline struct job *job_get()
181 struct job *job = first_job;
182 while (job && job->blocked)
188 * Get the next events to process or NULL if none.
189 * @return the first events that isn't running or NULL
191 static inline struct events *events_get()
193 struct events *events = first_events;
194 while (events && events->runs)
195 events = events->next;
200 * Releases the processed 'job': removes it
201 * from the list of jobs and unblock the first
202 * pending job of the same group if any.
203 * @param job the job to release
205 static inline void job_release(struct job *job)
207 struct job *ijob, **pjob;
210 /* first unqueue the job */
213 while (ijob != job) {
219 /* then unblock jobs of the same group */
223 while (ijob && ijob->group != group)
229 /* recycle the job */
230 job->next = free_jobs;
235 * Monitored normal callback for a job.
236 * This function is called by the monitor
237 * to run the job when the safe environment
239 * @param signum 0 on normal flow or the number
240 * of the signal that interrupted the normal
242 * @param arg the job to run
244 static void job_call(int signum, void *arg)
246 struct job *job = arg;
247 job->callback(signum, job->arg1, job->arg2, job->arg3);
251 * Monitored cancel callback for a job.
252 * This function is called by the monitor
253 * to cancel the job when the safe environment
255 * @param signum 0 on normal flow or the number
256 * of the signal that interrupted the normal
258 * @param arg the job to run
260 static void job_cancel(int signum, void *arg)
262 job_call(SIGABRT, arg);
266 * Monitored normal callback for events.
267 * This function is called by the monitor
268 * to run the event loop when the safe environment
270 * @param signum 0 on normal flow or the number
271 * of the signal that interrupted the normal
273 * @param arg the events to run
275 static void events_call(int signum, void *arg)
277 struct events *events = arg;
279 sd_event_run(events->event, (uint64_t) -1);
283 * Main processing loop of threads processing jobs.
284 * The loop must be called with the mutex locked
285 * and it returns with the mutex locked.
286 * @param me the description of the thread to use
287 * TODO: how are timeout handled when reentering?
289 static void thread_run(volatile struct thread *me)
293 struct events *events;
295 /* initialize description of itself and link it in the list */
296 me->tid = pthread_self();
302 current->lowered = 1;
305 sig_monitor_init_timeouts();
308 threads = (struct thread*)me;
309 current = (struct thread*)me;
311 NOTICE("job thread starting %d(/%d) %s", started, allowed, me->upper ? "child" : "parent");
313 /* 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_call, job);
327 pthread_mutex_lock(&mutex);
329 /* release the run job */
332 /* release event if any */
339 /* no job, check events */
340 events = events_get();
345 pthread_mutex_unlock(&mutex);
346 sig_monitor(0, events_call, events);
347 pthread_mutex_lock(&mutex);
351 /* no job and not events */
354 pthread_cond_wait(&cond, &mutex);
360 NOTICE("job thread stoping %d(/%d) %s", started, allowed, me->upper ? "child" : "parent");
362 /* unlink the current thread and cleanup */
369 current->lowered = 0;
371 sig_monitor_clean_timeouts();
377 * Entry point for created threads.
378 * @param data not used
381 static void *thread_main(void *data)
385 pthread_mutex_lock(&mutex);
387 pthread_mutex_unlock(&mutex);
392 * Starts a new thread
393 * @return 0 in case of success or -1 in case of error
395 static int start_one_thread()
400 rc = pthread_create(&tid, NULL, thread_main, NULL);
403 WARNING("not able to start thread: %m");
410 * Queues a new asynchronous job represented by 'callback'
411 * for the 'group' and the 'timeout'.
412 * Jobs are queued FIFO and are possibly executed in parallel
413 * concurrently except for job of the same group that are
414 * executed sequentially in FIFO order.
415 * @param group The group of the job or NULL when no group.
416 * @param timeout The maximum execution time in seconds of the job
417 * or 0 for unlimited time.
418 * @param callback The function to execute for achieving the job.
419 * Its first parameter is either 0 on normal flow
420 * or the signal number that broke the normal flow.
421 * @return 0 in case of success or -1 in case of error
426 void (*callback)(int signum))
428 return jobs_queue3(group, timeout, (job_cb_t)callback, NULL, NULL, NULL);
432 * Queues a new asynchronous job represented by 'callback' and 'arg1'
433 * for the 'group' and the 'timeout'.
434 * Jobs are queued FIFO and are possibly executed in parallel
435 * concurrently except for job of the same group that are
436 * executed sequentially in FIFO order.
437 * @param group The group of the job or NULL when no group.
438 * @param timeout The maximum execution time in seconds of the job
439 * or 0 for unlimited time.
440 * @param callback The function to execute for achieving the job.
441 * Its first parameter is either 0 on normal flow
442 * or the signal number that broke the normal flow.
443 * The remaining parameter is the parameter 'arg1'
445 * @param arg1 The second argument for 'callback'
446 * @return 0 in case of success or -1 in case of error
451 void (*callback)(int, void*),
454 return jobs_queue3(group, timeout, (job_cb_t)callback, arg, NULL, NULL);
458 * Queues a new asynchronous job represented by 'callback' and 'arg[12]'
459 * for the 'group' and the 'timeout'.
460 * Jobs are queued FIFO and are possibly executed in parallel
461 * concurrently except for job of the same group that are
462 * executed sequentially in FIFO order.
463 * @param group The group of the job or NULL when no group.
464 * @param timeout The maximum execution time in seconds of the job
465 * or 0 for unlimited time.
466 * @param callback The function to execute for achieving the job.
467 * Its first parameter is either 0 on normal flow
468 * or the signal number that broke the normal flow.
469 * The remaining parameters are the parameters 'arg[12]'
471 * @param arg1 The second argument for 'callback'
472 * @param arg2 The third argument for 'callback'
473 * @return 0 in case of success or -1 in case of error
478 void (*callback)(int, void*, void*),
482 return jobs_queue3(group, timeout, (job_cb_t)callback, arg1, arg2, NULL);
486 * Queues a new asynchronous job represented by 'callback' and 'arg[123]'
487 * for the 'group' and the 'timeout'.
488 * Jobs are queued FIFO and are possibly executed in parallel
489 * concurrently except for job of the same group that are
490 * executed sequentially in FIFO order.
491 * @param group The group of the job or NULL when no group.
492 * @param timeout The maximum execution time in seconds of the job
493 * or 0 for unlimited time.
494 * @param callback The function to execute for achieving the job.
495 * Its first parameter is either 0 on normal flow
496 * or the signal number that broke the normal flow.
497 * The remaining parameters are the parameters 'arg[123]'
499 * @param arg1 The second argument for 'callback'
500 * @param arg2 The third argument for 'callback'
501 * @param arg3 The forth argument for 'callback'
502 * @return 0 in case of success or -1 in case of error
507 void (*callback)(int, void*, void *, void*),
516 pthread_mutex_lock(&mutex);
518 /* allocates the job */
519 job = job_create(group, timeout, callback, arg1, arg2, arg3);
522 info = "out of memory";
526 /* check availability */
529 info = "too many jobs";
533 /* start a thread if needed */
534 if (waiting == 0 && started < allowed) {
535 /* all threads are busy and a new can be started */
536 rc = start_one_thread();
537 if (rc < 0 && started == 0) {
538 info = "can't start first thread";
547 /* signal an existing job */
548 pthread_cond_signal(&cond);
549 pthread_mutex_unlock(&mutex);
553 job->next = free_jobs;
556 ERROR("can't process job with threads: %s, %m", info);
557 pthread_mutex_unlock(&mutex);
562 * Enter a synchronisation point: activates the job given by 'callback'
563 * @param group the gro
568 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
575 pthread_mutex_lock(&mutex);
577 /* allocates the job */
578 job = job_create(group, timeout, (job_cb_t)callback, closure, &me, NULL);
580 ERROR("out of memory");
582 pthread_mutex_unlock(&mutex);
589 /* run until stopped */
591 pthread_mutex_unlock(&mutex);
595 int jobs_leave(struct jobloop *jobloop)
598 pthread_mutex_lock(&mutex);
601 while (t && t != (struct thread*)jobloop)
608 pthread_cond_broadcast(&cond);
610 pthread_mutex_unlock(&mutex);
615 * Gets a sd_event item for the current thread.
616 * @return a sd_event or NULL in case of error
618 struct sd_event *jobs_get_sd_event()
620 struct events *events;
624 pthread_mutex_lock(&mutex);
626 /* search events on stack */
628 while (me && !me->events)
631 /* return the stacked events */
634 /* search an available events */
635 events = events_get();
637 /* not found, check if creation possible */
638 if (nevents >= allowed) {
639 ERROR("not possible to add a new event");
642 events = malloc(sizeof *events);
643 if (events && (rc = sd_event_new(&events->event)) >= 0) {
644 if (nevents < started || start_one_thread() >= 0) {
646 events->next = first_events;
647 first_events = events;
649 ERROR("can't start thread for events");
650 sd_event_unref(events->event);
656 ERROR("out of memory");
660 ERROR("creation of sd_event failed: %m");
674 WARNING("event returned for unknown thread!");
678 pthread_mutex_unlock(&mutex);
679 return events ? events->event : NULL;
683 * Enter the jobs processing loop.
684 * @param allowed_count Maximum count of thread for jobs including this one
685 * @param start_count Count of thread to start now, must be lower.
686 * @param waiter_count Maximum count of jobs that can be waiting.
687 * @param start The start routine to activate (can't be NULL)
688 * @return 0 in case of success or -1 in case of error.
690 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)())
696 assert(allowed_count >= 1);
697 assert(start_count >= 0);
698 assert(waiter_count > 0);
699 assert(start_count <= allowed_count);
702 pthread_mutex_lock(&mutex);
704 /* check whether already running */
705 if (current || allowed) {
706 ERROR("thread already started");
712 if (sig_monitor_init() < 0) {
713 ERROR("failed to initialise signal handlers");
717 /* records the allowed count */
718 allowed = allowed_count;
721 remains = waiter_count;
723 /* start at least one thread */
725 while ((launched + 1) < start_count) {
726 if (start_one_thread() != 0) {
727 ERROR("Not all threads can be started");
733 /* queue the start job */
734 job = job_create(NULL, 0, (job_cb_t)start, NULL, NULL, NULL);
736 ERROR("out of memory");
747 pthread_mutex_unlock(&mutex);
752 * Terminate all the threads and cancel all pending jobs.
754 void jobs_terminate()
756 struct job *job, *head, *tail;
757 pthread_t me, *others;
764 /* request all threads to stop */
765 pthread_mutex_lock(&mutex);
768 /* count the number of threads */
772 if (!t->upper && !pthread_equal(t->tid, me))
777 /* fill the array of threads */
778 others = alloca(count * sizeof *others);
782 if (!t->upper && !pthread_equal(t->tid, me))
783 others[count++] = t->tid;
787 /* stops the threads */
794 /* wait the threads */
795 pthread_cond_broadcast(&cond);
796 pthread_mutex_unlock(&mutex);
798 pthread_join(others[--count], NULL);
799 pthread_mutex_lock(&mutex);
801 /* cancel pending jobs of other threads */
811 /* search if job is stacked for current */
813 while (t && t->job != job)
816 /* yes, relink it at end */
824 /* no cancel the job */
825 pthread_mutex_unlock(&mutex);
826 sig_monitor(0, job_cancel, job);
828 pthread_mutex_lock(&mutex);
831 pthread_mutex_unlock(&mutex);