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>
30 #include "sig-monitor.h"
34 #define _alert_ "do you really want to remove monitoring?"
35 #define sig_monitor_init_timeouts() ((void)0)
36 #define sig_monitor_clean_timeouts() ((void)0)
37 #define sig_monitor(to,cb,arg) (cb(0,arg))
40 /** Internal shortcut for callback */
41 typedef void (*job_cb_t)(int, void*, void *, void*);
43 /** Description of a pending job */
46 struct job *next; /**< link to the next job enqueued */
47 void *group; /**< group of the request */
48 job_cb_t callback; /**< processing callback */
49 void *arg1; /**< first arg */
50 void *arg2; /**< second arg */
51 void *arg3; /**< third arg */
52 int timeout; /**< timeout in second for processing the request */
53 unsigned blocked: 1; /**< is an other request blocking this one ? */
54 unsigned dropped: 1; /**< is removed ? */
57 /** Description of threads */
60 struct thread *next; /**< next thread of the list */
61 struct thread *upper; /**< upper same thread */
62 struct job *job; /**< currently processed job */
63 pthread_t tid; /**< the thread id */
64 unsigned stop: 1; /**< stop requested */
65 unsigned lowered: 1; /**< has a lower same thread */
66 unsigned waits: 1; /**< is waiting? */
69 /* synchronisation of threads */
70 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
71 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
73 /* count allowed, started and waiting threads */
74 static int allowed = 0; /** allowed count of threads */
75 static int started = 0; /** started count of threads */
76 static int waiting = 0; /** waiting count of threads */
77 static int remains = 0; /** allowed count of waiting jobs */
80 static struct thread *threads;
81 static _Thread_local struct thread *current;
83 /* queue of pending jobs */
84 static struct job *first_job;
85 static struct job *first_events;
86 static struct job *free_jobs;
89 * Create a new job with the given parameters
90 * @param group the group of the job
91 * @param timeout the timeout of the job (0 if none)
92 * @param callback the function that achieves the job
93 * @param arg1 the first argument of the callback
94 * @param arg2 the second argument of the callback
95 * @param arg3 the third argument of the callback
96 * @return the created job unblock or NULL when no more memory
98 static struct job *job_create(
108 /* try recyle existing job */
111 free_jobs = job->next;
113 /* allocation without blocking */
114 pthread_mutex_unlock(&mutex);
115 job = malloc(sizeof *job);
116 pthread_mutex_lock(&mutex);
122 /* initialises the job */
124 job->timeout = timeout;
125 job->callback = callback;
136 * Adds 'job1' and 'job2' at the end of the list of jobs, marking it
137 * as blocked if an other job with the same group is pending.
138 * @param job1 the first job to add
139 * @param job2 the second job to add or NULL
141 static void job_add2(struct job *job1, struct job *job2)
143 void *group1, *group2, *group;
144 struct job *ijob, **pjob;
147 group1 = job1->group;
153 group2 = job2->group;
154 if (group2 && group2 == group1)
158 /* search end and blockers */
178 * Get the next job to process or NULL if none.
179 * @param job the head of the list to search.
180 * @return the first job that isn't blocked or NULL
182 static inline struct job *job_get(struct job *job)
184 while (job && job->blocked)
190 * Releases the processed 'job': removes it
191 * from the list of jobs and unblock the first
192 * pending job of the same group if any.
193 * @param job the job to release
195 static inline void job_release(struct job *job)
197 struct job *ijob, **pjob;
200 /* first unqueue the job */
203 while (ijob != job) {
209 /* then unblock jobs of the same group */
213 while (ijob && ijob->group != group)
219 /* recycle the job */
220 job->next = free_jobs;
225 * Releases the events 'job': removes it
226 * from the list of events.
227 * @param job the event to release
229 static inline void events_release(struct job *job)
231 struct job *ijob, **pjob;
233 /* first unqueue the job */
234 pjob = &first_events;
236 while (ijob != job) {
242 /* recycle the job */
243 job->next = free_jobs;
248 * Get the events of 'key' if existing.
249 * @param key the key to search
250 * @return the found events or NULL if none existing has key
252 static inline struct job *events_of_key(void *key)
260 while (job && (job->dropped || job->group != key))
267 * Monitored normal callback for a job.
268 * This function is called by the monitor
269 * to run the job when the safe environment
271 * @param signum 0 on normal flow or the number
272 * of the signal that interrupted the normal
274 * @param arg the job to run
276 static void job_call(int signum, void *arg)
278 struct job *job = arg;
279 job->callback(signum, job->arg1, job->arg2, job->arg3);
283 * Monitored cancel callback for a job.
284 * This function is called by the monitor
285 * to cancel the job when the safe environment
287 * @param signum 0 on normal flow or the number
288 * of the signal that interrupted the normal
290 * @param arg the job to run
292 static void job_cancel(int signum, void *arg)
294 job_call(SIGABRT, arg);
298 * Main processing loop of threads processing jobs.
299 * The loop must be called with the mutex locked
300 * and it returns with the mutex locked.
301 * @param me the description of the thread to use
302 * TODO: how are timeout handled when reentering?
304 static void thread_run(struct thread *me)
309 /* initialize description of itself and link it in the list */
310 me->tid = pthread_self();
316 current->lowered = 1;
318 sig_monitor_init_timeouts();
324 /* loop until stopped */
327 job = job_get(first_job);
329 /* prepare running the job */
330 remains++; /* increases count of job that can wait */
331 job->blocked = 1; /* mark job as blocked */
332 me->job = job; /* record the job (only for terminate) */
335 pthread_mutex_unlock(&mutex);
336 sig_monitor(job->timeout, job_call, job);
337 pthread_mutex_lock(&mutex);
339 /* release the run job */
342 /* no job, check events */
343 job = job_get(first_events);
347 pthread_mutex_unlock(&mutex);
348 sig_monitor(job->timeout, job_call, job);
349 pthread_mutex_lock(&mutex);
354 /* no job and not events */
357 pthread_cond_wait(&cond, &mutex);
364 /* unlink the current thread and cleanup */
372 current->lowered = 0;
374 sig_monitor_clean_timeouts();
378 * Entry point for created threads.
379 * @param data not used
382 static void *thread_main(void *data)
386 pthread_mutex_lock(&mutex);
388 pthread_mutex_unlock(&mutex);
393 * Starts a new thread
394 * @return 0 in case of success or -1 in case of error
396 static int start_one_thread()
401 rc = pthread_create(&tid, NULL, thread_main, NULL);
404 WARNING("not able to start thread: %m");
411 * Queues a new asynchronous job represented by 'callback'
412 * for the 'group' and the 'timeout'.
413 * Jobs are queued FIFO and are possibly executed in parallel
414 * concurrently except for job of the same group that are
415 * executed sequentially in FIFO order.
416 * @param group The group of the job or NULL when no group.
417 * @param timeout The maximum execution time in seconds of the job
418 * or 0 for unlimited time.
419 * @param callback The function to execute for achieving the job.
420 * Its first parameter is either 0 on normal flow
421 * or the signal number that broke the normal flow.
422 * @return 0 in case of success or -1 in case of error
427 void (*callback)(int signum))
429 return jobs_queue3(group, timeout, (job_cb_t)callback, NULL, NULL, NULL);
433 * Queues a new asynchronous job represented by 'callback' and 'arg1'
434 * for the 'group' and the 'timeout'.
435 * Jobs are queued FIFO and are possibly executed in parallel
436 * concurrently except for job of the same group that are
437 * executed sequentially in FIFO order.
438 * @param group The group of the job or NULL when no group.
439 * @param timeout The maximum execution time in seconds of the job
440 * or 0 for unlimited time.
441 * @param callback The function to execute for achieving the job.
442 * Its first parameter is either 0 on normal flow
443 * or the signal number that broke the normal flow.
444 * The remaining parameter is the parameter 'arg1'
446 * @param arg1 The second argument for 'callback'
447 * @return 0 in case of success or -1 in case of error
452 void (*callback)(int, void*),
455 return jobs_queue3(group, timeout, (job_cb_t)callback, arg, NULL, NULL);
459 * Queues a new asynchronous job represented by 'callback' and 'arg[12]'
460 * for the 'group' and the 'timeout'.
461 * Jobs are queued FIFO and are possibly executed in parallel
462 * concurrently except for job of the same group that are
463 * executed sequentially in FIFO order.
464 * @param group The group of the job or NULL when no group.
465 * @param timeout The maximum execution time in seconds of the job
466 * or 0 for unlimited time.
467 * @param callback The function to execute for achieving the job.
468 * Its first parameter is either 0 on normal flow
469 * or the signal number that broke the normal flow.
470 * The remaining parameters are the parameters 'arg[12]'
472 * @param arg1 The second argument for 'callback'
473 * @param arg2 The third argument for 'callback'
474 * @return 0 in case of success or -1 in case of error
479 void (*callback)(int, void*, void*),
483 return jobs_queue3(group, timeout, (job_cb_t)callback, arg1, arg2, NULL);
487 * Queues a new asynchronous job represented by 'callback' and 'arg[123]'
488 * for the 'group' and the 'timeout'.
489 * Jobs are queued FIFO and are possibly executed in parallel
490 * concurrently except for job of the same group that are
491 * executed sequentially in FIFO order.
492 * @param group The group of the job or NULL when no group.
493 * @param timeout The maximum execution time in seconds of the job
494 * or 0 for unlimited time.
495 * @param callback The function to execute for achieving the job.
496 * Its first parameter is either 0 on normal flow
497 * or the signal number that broke the normal flow.
498 * The remaining parameters are the parameters 'arg[123]'
500 * @param arg1 The second argument for 'callback'
501 * @param arg2 The third argument for 'callback'
502 * @param arg3 The forth argument for 'callback'
503 * @return 0 in case of success or -1 in case of error
508 void (*callback)(int, void*, void *, void*),
517 pthread_mutex_lock(&mutex);
519 /* allocates the job */
520 job = job_create(group, timeout, callback, arg1, arg2, arg3);
523 info = "out of memory";
527 /* check availability */
530 info = "too many jobs";
534 /* start a thread if needed */
535 if (waiting == 0 && started < allowed) {
536 /* all threads are busy and a new can be started */
537 rc = start_one_thread();
538 if (rc < 0 && started == 0) {
539 info = "can't start first thread";
548 /* signal an existing job */
549 pthread_cond_signal(&cond);
550 pthread_mutex_unlock(&mutex);
554 job->next = free_jobs;
557 ERROR("can't process job with threads: %s, %m", info);
558 pthread_mutex_unlock(&mutex);
563 * Run a asynchronous job represented by 'callback'
564 * with the 'timeout' but only returns after job completion.
565 * @param timeout The maximum execution time in seconds of the job
566 * or 0 for unlimited time.
567 * @param callback The function to execute for achieving the job.
568 * Its first parameter is either 0 on normal flow
569 * or the signal number that broke the normal flow.
570 * @return 0 in case of success or -1 in case of error
574 void (*callback)(int signum))
576 return jobs_invoke3(timeout, (job_cb_t)callback, NULL, NULL, NULL);
580 * Run a asynchronous job represented by 'callback' and 'arg1'
581 * with the 'timeout' but only returns after job completion.
582 * @param timeout The maximum execution time in seconds of the job
583 * or 0 for unlimited time.
584 * @param callback The function to execute for achieving the job.
585 * Its first parameter is either 0 on normal flow
586 * or the signal number that broke the normal flow.
587 * The remaining parameter is the parameter 'arg1'
589 * @param arg1 The second argument for 'callback'
590 * @return 0 in case of success or -1 in case of error
594 void (*callback)(int, void*),
597 return jobs_invoke3(timeout, (job_cb_t)callback, arg, NULL, NULL);
601 * Run a asynchronous job represented by 'callback' and 'arg[12]'
602 * with the 'timeout' but only returns after job completion.
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 parameters are the parameters 'arg[12]'
610 * @param arg1 The second argument for 'callback'
611 * @param arg2 The third argument for 'callback'
612 * @return 0 in case of success or -1 in case of error
616 void (*callback)(int, void*, void*),
620 return jobs_invoke3(timeout, (job_cb_t)callback, arg1, arg2, NULL);
624 * Stops the thread pointed by 'arg1'. Used with
625 * invoke familly to return to the caller after completion.
626 * @param signum Unused
627 * @param arg1 The thread to stop
631 static void unlock_invoker(int signum, void *arg1, void *arg2, void *arg3)
633 struct thread *t = arg1;
634 pthread_mutex_lock(&mutex);
637 pthread_cond_broadcast(&cond);
638 pthread_mutex_unlock(&mutex);
642 * Run a asynchronous job represented by 'callback' and 'arg[123]'
643 * with the 'timeout' but only returns after job completion.
644 * @param timeout The maximum execution time in seconds of the job
645 * or 0 for unlimited time.
646 * @param callback The function to execute for achieving the job.
647 * Its first parameter is either 0 on normal flow
648 * or the signal number that broke the normal flow.
649 * The remaining parameters are the parameters 'arg[123]'
651 * @param arg1 The second argument for 'callback'
652 * @param arg2 The third argument for 'callback'
653 * @param arg3 The forth argument for 'callback'
654 * @return 0 in case of success or -1 in case of error
658 void (*callback)(int, void*, void *, void*),
663 struct job *job1, *job2;
666 pthread_mutex_lock(&mutex);
668 /* allocates the job */
669 job1 = job_create(&me, timeout, callback, arg1, arg2, arg3);
670 job2 = job_create(&me, 0, unlock_invoker, &me, NULL, NULL);
671 if (!job1 || !job2) {
672 ERROR("out of memory");
675 job1->next = free_jobs;
679 job2->next = free_jobs;
682 pthread_mutex_unlock(&mutex);
687 job_add2(job1, job2);
689 /* run until stopped */
691 pthread_mutex_unlock(&mutex);
696 * Initialise the job stuff.
697 * @param allowed_count Maximum count of thread for jobs (can be 0,
698 * see 'jobs_add_me' for merging new threads)
699 * @param start_count Count of thread to start now, must be lower.
700 * @param waiter_count Maximum count of jobs that can be waiting.
701 * @return 0 in case of success or -1 in case of error.
703 int jobs_init(int allowed_count, int start_count, int waiter_count)
707 assert(allowed_count >= 0);
708 assert(start_count >= 0);
709 assert(waiter_count > 0);
710 assert(start_count <= allowed_count);
712 /* records the allowed count */
713 allowed = allowed_count;
716 remains = waiter_count;
718 /* start at least one thread */
719 pthread_mutex_lock(&mutex);
721 while (launched < start_count && start_one_thread() == 0)
723 rc = -(launched != start_count);
724 pthread_mutex_unlock(&mutex);
728 ERROR("Not all threads can be started");
733 * Terminate all the threads and cancel all pending jobs.
735 void jobs_terminate()
737 struct job *job, *head, *tail;
738 pthread_t me, *others;
745 /* request all threads to stop */
746 pthread_mutex_lock(&mutex);
749 /* count the number of threads */
753 if (!t->upper && !pthread_equal(t->tid, me))
758 /* fill the array of threads */
759 others = alloca(count * sizeof *others);
763 if (!t->upper && !pthread_equal(t->tid, me))
764 others[count++] = t->tid;
768 /* stops the threads */
775 /* wait the threads */
776 pthread_cond_broadcast(&cond);
777 pthread_mutex_unlock(&mutex);
779 pthread_join(others[--count], NULL);
780 pthread_mutex_lock(&mutex);
782 /* cancel pending jobs of other threads */
792 /* search if job is stacked for current */
794 while (t && t->job != job)
797 /* yes, relink it at end */
805 /* no cancel the job */
806 pthread_mutex_unlock(&mutex);
807 sig_monitor(0, job_cancel, job);
809 pthread_mutex_lock(&mutex);
812 pthread_mutex_unlock(&mutex);
816 * Adds the events waiter/dispatcher to the list of events waiters/dispatchers
818 * @param key A key to register the events waiter/dispatcher (see
820 * @param timeout Timeout in second of the function or 0 if none
821 * @param events The callback, the first argument is 0 for normal
822 * flow or the signal number when normal flow failed
823 * @param closure The closure to give to the callback as secondd argument
824 * @return 0 in case of success or -1 in case of error
826 int jobs_add_events(void *key, int timeout, void (*events)(int signum, void*), void *closure)
830 pthread_mutex_lock(&mutex);
832 /* look at an already existsing events for same key */
833 job = events_of_key(key);
835 pthread_mutex_unlock(&mutex);
836 ERROR("events of key %p already exist", key);
841 /* creates the job */
842 job = job_create(key, timeout, (job_cb_t)events, closure, NULL, NULL);
844 pthread_mutex_unlock(&mutex);
845 ERROR("Can't create events, out of memory");
851 job->next = first_events;
854 /* signal the loop */
856 pthread_cond_signal(&cond);
857 pthread_mutex_unlock(&mutex);
862 * Removes the events of 'key'
863 * @param key The key of the events to remove
864 * @return 0 in case of success or -1 in case of error
866 int jobs_del_events(void *key)
870 pthread_mutex_lock(&mutex);
871 job = events_of_key(key);
877 pthread_mutex_unlock(&mutex);
879 ERROR("events of key %p not found", key);
886 * Adds the current thread to the pool of threads
887 * processing the jobs. Returns normally when the threads are
888 * terminated or immediately with an error if the thread is
889 * already in the pool.
890 * @return 0 in case of success or -1 in case of error
896 /* check whether already running */
898 ERROR("thread already running");
904 pthread_mutex_lock(&mutex);
908 pthread_mutex_unlock(&mutex);