1 // -----------------------------------------------------------------------
2 // Copyright (C) 2006 - 2007 FRESCOR consortium partners:
4 // Universidad de Cantabria, SPAIN
5 // University of York, UK
6 // Scuola Superiore Sant'Anna, ITALY
7 // Kaiserslautern University, GERMANY
8 // Univ. Politecnica Valencia, SPAIN
9 // Czech Technical University in Prague, CZECH REPUBLIC
11 // Thales Communication S.A. FRANCE
12 // Visual Tools S.A. SPAIN
13 // Rapita Systems Ltd UK
16 // See http://www.frescor.org for a link to partners' websites
18 // FRESCOR project (FP6/2005/IST/5-034026) is funded
19 // in part by the European Union Sixth Framework Programme
20 // The European Union is not liable of any use that may be
23 // This file is part of the FRSH implementation
25 // FRSH is free software; you can redistribute it and/or modify
26 // it under the terms of the GNU General Public License as published by
27 // the Free Software Foundation; either version 2, or (at your option)
30 // FRSH is distributed in the hope that it will be useful, but
31 // WITHOUT ANY WARRANTY; without even the implied warranty of
32 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
33 // General Public License for more details.
35 // You should have received a copy of the GNU General Public License
36 // distributed with FRSH; see file COPYING. If not, write to the
37 // Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
40 // As a special exception, if you include this header file into source
41 // files to be compiled, this header file does not by itself cause
42 // the resulting executable to be covered by the GNU General Public
43 // License. This exception does not however invalidate any other
44 // reasons why the executable file might be covered by the GNU General
46 // -----------------------------------------------------------------------
47 //==============================================
48 // ******** ****** ******** **********
49 // **///// /** ** **////// /** /**
50 // ** /** ** /** /** /**
51 // ******* /** ** /********* /**********
52 // **//// /** ** ////////** /**//////**
53 // ** /** ** /** /** /**
54 // ** /** ** ******** /** /**
55 // // /******/ //////// // //
57 // FOSA(Frescor Operating System Adaptation layer)
58 //================================================
60 #include "fosa_time.h"
61 #include "fosa_configuration_parameters.h"
62 #include "fosa_threads_and_signals.h"
64 /*************************
65 * Storage of thread-specific keys
66 *************************/
68 static pthread_key_t key_list[FOSA_MAX_KEYS];
69 static bool key_in_use[FOSA_MAX_KEYS];
70 static pthread_mutex_t key_lock;
73 /* Initialize the keys data structure */
77 pthread_mutexattr_t attr;
79 for(i = 0; i < FOSA_MAX_KEYS; i++)
80 key_in_use[i] = false;
82 ret = pthread_mutexattr_init(&attr);
83 if (ret) return errno;
85 ret = pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
86 if (ret) return errno;
88 ret = pthread_mutex_init(&key_lock,&attr);
89 if (ret) return errno;
94 /*************************
95 * Thread identification
96 *************************/
101 * Compare two thread identifiers to determine if they refer to the
104 bool fosa_thread_equal(fosa_thread_id_t t1, fosa_thread_id_t t2)
106 return t1.linux_pid == t2.linux_pid &&
107 t1.linux_tid == t2.linux_tid &&
108 pthread_equal(t1.pthread_id, t2.pthread_id);
114 * Return the thread id of the calling thread
116 fosa_thread_id_t fosa_thread_self()
118 fosa_thread_id_t thread_self;
121 * fosa_thread_id_t => struct {
122 * pthread_t pthread_id;
127 thread_self.pthread_id = pthread_self();
128 thread_self.linux_pid = getpid();
129 thread_self.linux_tid = syscall(__NR_gettid); /* gettid() */
134 /*************************
136 *************************/
138 static inline int __fosa_check_thread(const fosa_thread_id_t *tid)
140 if (tid->linux_pid == tid->linux_tid)
147 * fosa_thread_attr_init()
149 * Initialize a thread attributes object
151 * This function initializes the object pointed to by attr to all
152 * the default values defined by FRSH
154 * return 0 if successful; otherwise it returns
155 * FOSA_ENOMEM: insufficient memory exists to initialize the thread
158 int fosa_thread_attr_init(fosa_thread_attr_t *attr)
160 return pthread_attr_init(attr);
164 * fosa_thread_attr_destroy()
166 * Destroy a thread attributes object
168 * This function is used to destroy the thread attributes object,
169 * pointed to by attr, and deallocate any system resources allocated for it
173 int fosa_thread_attr_destroy(fosa_thread_attr_t *attr)
175 return pthread_attr_destroy(attr);
179 * fosa_thread_attr_set_stacksize()
181 * Set the thread minimum stack size in a thread attributes object
183 * This function sets the minimum stack size of the thread attributes
184 * object attr to the value given by stacksize, in bytes. This
185 * function has no runtime effect on the stack size, except when the
186 * attributes object is used to create a thread, when it will be
187 * created with the specified minimum stack size
189 * return 0 if successful, or the following error code:
190 * FOSA_EINVAL: the specified stacksize value is not supported in
191 * this implementation
193 int fosa_thread_attr_set_stacksize(fosa_thread_attr_t *attr,
196 return pthread_attr_setstacksize(attr, stacksize);
200 * fosa_thread_attr_get_stacksize()
202 * Get the thread minimum stack size from a thread attributes object
204 * This function sets the variable pointed to by stacksize to the
205 * minimum stack size stored in the thread attributes object attr.
209 int fosa_thread_attr_get_stacksize(const fosa_thread_attr_t *attr,
212 return pthread_attr_getstacksize(attr, stacksize);
215 /*************************
216 * Thread creation and termination
217 *************************/
220 * fosa_thread_create()
222 * This function creates a new thread using the attributes specified
223 * in attr. If attr is NULL, default attributes are used. The new
224 * thread starts running immediately, executing the function specified
225 * by code, with an argument equal to arg. Upon successful return, the
226 * variable pointed to by tid will contain the identifier of the newly
227 * created thread. The set of signals that may be synchronously
228 * accepted is inherited from the parent thread.
230 * Returns 0 if successful; otherwise it returs a code error:
232 * EAGAIN: the system lacks the necessary resources to create a
233 * new thread or the maximum number of threads has been
236 * EINVAL: the value specified by attr is invalid (for instance,
237 * it has not been correctly initialized)
239 * EREJECT: the cretion of the thread was rejected by the frsh scheduler
240 * possibly because of incorrect attributes, or because the
241 * requested minimum capacity cannot be guaranteed
243 int fosa_thread_create(fosa_thread_id_t *tid,
244 const fosa_thread_attr_t *attr,
245 fosa_thread_code_t code,
248 return pthread_create(&tid->pthread_id, attr, code, arg);
252 * Note: no thread termination primitive is provided. The termination
253 * of a thread will be notified by the system to the FRSH scheduler
254 * through the scheduler API
257 /**************************************************
258 * Thread-specific data
259 * (extended with access from a different thread)
261 * Several data items (pointers) may be associated with each thread
262 * Each item is identified through a key, an integer value between 0
263 * and FOSA_MAX_KEYS-1. The caller is responsible of allocating and
264 * deallocating the memory area pointed to by the pointer
265 **************************************************/
270 * Create a new key for thread specific data.
272 * Prior to setting data in a key, we need ask the system to create
275 * return 0 if successful \n
276 * FOSA_EINVAL If we already have reached the FOSA_MAX_KEYS limit.
277 * FOSA_ENOMEM If there are no enough memory resources to
280 int fosa_key_create(int *key)
285 ret = pthread_mutex_lock(&key_lock);
288 /* find an unused key */
289 for (i = 0; i < FOSA_MAX_KEYS; i++) {
290 if (!key_in_use[i]) {
291 ret = pthread_key_create(&(key_list[i]), NULL);
295 key_in_use[i] = true;
302 ret = pthread_mutex_unlock(&key_lock);
305 return (!found ? FOSA_EINVAL : ret);
313 * This destroys the key and isables its use in the system
315 * return 0 if successful
316 * FOSA_EINVAL The key is not initialised or is not in FOSA key range.
318 int fosa_key_destroy(int key)
322 ret = pthread_mutex_lock(&key_lock);
325 ret = pthread_key_delete(key_list[key]);
328 key_in_use[key]=false;
330 ret = pthread_mutex_unlock(&key_lock);
338 * fosa_thread_set_specific_data()
340 * Set thread-specific data
342 * For the thread identified by tid, the thread-specifid data field
343 * identified by key will be set to the value specified by value
345 * In this implementation, according to POSIX, the accessed data field
346 * is the one of the calling thread, not the one specified via tid.
348 * Returns 0 if successful; otherwise, an error code is returned
349 * EINVAL: the value of key is not between 0 and FOSA_MAX_KEYS-1
351 int fosa_thread_set_specific_data(int key,
352 fosa_thread_id_t tid,
357 /* only POSIX threads can have specific data */
358 if (!__fosa_check_thread(&tid))
361 ret = pthread_setspecific(key_list[key], value);
363 return ret ? ret : 0;
367 * fosa_thread_get_specific_data()
369 * Get thread-specific data
371 * For the thread identified by tid, the thread-specifid data field
372 * identified by key will be copied to the variable pointed to by value
374 * In this implementation, according to POSIX, the accessed data field
375 * is the one of the calling thread, not the one specified via tid.
377 * Returns 0 if successful; otherwise, an error code is returned
378 * EINVAL: the value of key is not between 0 and FOSA_MAX_KEYS-1
380 int fosa_thread_get_specific_data(int key,
381 fosa_thread_id_t tid,
384 /* only POSIX threads can have specific data */
385 if (!__fosa_check_thread(&tid))
388 value = pthread_getspecific(key_list[key]);
390 return !value ? FOSA_EINVAL : 0;
393 /******************************************************************
396 * This implementation of FRSH assumes an underlying fixed priority
397 * scheduler with priorities in a range, with a minimum and a
398 * maximumm, a number of priority levels with at least 31
399 * priorities. A larger number implies a larger priority. In systems
400 * in which the underlying scheduler uses the opposite convention, a
401 * mapping is automatically provided by the OS adaptation layer.
402 *******************************************************************/
405 * fosa_get_priority_max()
407 * Return the maximum priority value used in this implementation
409 int fosa_get_priority_max()
413 ret = sched_get_priority_max(SCHED_RR);
415 return ret ? errno : 0;
419 * fosa_get_priority_min()
421 * Return the minimum priority value used in this implementation
423 int fosa_get_priority_min()
427 ret = sched_get_priority_min(SCHED_RR);
429 return ret ? errno : 0;
433 * fosa_thread_attr_set_prio()
435 * Change the priority of a thread attributes object
437 * The priority of the thread attriutes object specified by attr is
438 * set to the value specified by prio. This function has no runtime
439 * effect on the priority, except when the attributes object is used
440 * to create a thread, when it will be created with the specified
443 * Returns 0 if successful, or the following error code:
444 * EINVAL: the specified priority value is not between the
445 * minimum and the maximum priorities defined in this
446 * FRSH implementation
448 int fosa_thread_attr_set_prio(fosa_thread_attr_t *attr, int prio)
451 struct sched_param param;
453 param.sched_priority = prio;
454 ret = pthread_attr_setschedpolicy(attr, SCHED_RR);
457 return pthread_attr_setschedparam(attr, ¶m);
461 * fosa_thread_attr_get_prio()
463 * Get the priority from a thread attributes object
465 * This function sets the variable pointed to by prio to the
466 * priority stored in the thread attributes object attr.
470 int fosa_thread_attr_get_prio(const fosa_thread_attr_t *attr, int *prio)
473 struct sched_param param;
475 ret = pthread_attr_getschedparam(attr, ¶m);
478 *prio = param.sched_priority;
484 * fosa_thread_set_prio()
486 * Dynamically change the priority of a thread
488 * The priority of the thread identified by tid is
489 * set to the value specified by prio.
491 * Returns 0 if successful, or the following error code:
492 * EINVAL: the specified priority value is not between the
493 * minimum and the maximum priorities defined in this
494 * FRSH implementation
496 int fosa_thread_set_prio(fosa_thread_id_t tid, int prio)
499 struct sched_param param;
501 param.sched_priority = prio;
503 ret = sched_setscheduler(0, SCHED_RR, ¶m);
505 return ret ? errno : 0;
509 * fosa_thread_get_prio()
511 * Dynamically get the priority of a thread
513 * This function sets the variable pointed to by prio to the
514 * priority of the thread identified by tid
518 int fosa_thread_get_prio(fosa_thread_id_t tid, int *prio)
520 struct sched_param param;
523 ret = sched_getparam(0, ¶m);
524 *prio = param.sched_priority;
526 return ret ? errno : 0;
529 /*******************************************************************
532 * Signals represent events that may be notified by the system, or
533 * sent explicitly by the application, and for which a thread may
534 * synchronously wait. Signals carry an associated piece of
535 * information (an integer or a pointer) and are queued until they are
536 * accepted. Signals are identified by an integer signal number (of
537 * the type fosa_signal_t) in the range FOSA_SIGNAL_MIN,
538 * FOSA_SIGNAL_MAX. This range is required to have at least <tbd>
540 *******************************************************************/
543 * fosa_set_accepted_signals()
545 * Establish the set of signals that may be synchronously accepted
546 * by the calling thread
548 * The function uses the array of signal numbers specified by set,
549 * which must be of size equal to size
551 * Returns 0 if successful; otherwise it returns an error code:
552 * EINVAL: the array contains one or more values which are not
553 * between FOSA_SIGNAL_MIN and FOSA_SIGNAL_MAX, or size
556 * Alternatively, in case of error the implementation is allowed to
557 * notify it to the system console and then terminate the FRSH
558 * implementation and dependant applications
560 int fosa_set_accepted_signals(fosa_signal_t set[], int size)
563 fosa_thread_id_t self;
565 struct sigaction action;
567 ret = sigemptyset(&sigset);
570 action.sa_handler = SIG_DFL;
571 action.sa_mask = sigset;
572 action.sa_flags = SA_SIGINFO;
573 action.sa_sigaction = NULL;
575 for (i = 0; i < size; i++) {
576 ret = sigaddset(&sigset, set[i]);
578 ret = sigaction(set[i], &action, NULL);
582 self = fosa_thread_self();
583 if (__fosa_check_thread(&self)) {
584 ret = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
587 ret = sigprocmask(SIG_BLOCK, &sigset, NULL);
597 * fosa_signal_queue()
601 * This function is used to explicitly send a signal with a specified
604 * The signal number specified by signal is sent together with the
605 * information specified by info, to the thread identified by
606 * receiver. In those implementations that do not support queueing a
607 * signal with information to a thread (such as POSIX), the signal may
608 * be sent to any thread that is waiting for this signal via
609 * fosa_signal_wait(). Portability can be ensured by having the receiver
610 * thread be the one who is waiting for the signal.
612 * In this implementation, this limitation has been overcome by means
613 * of the Linux specific capability of sending a timer event directly
614 * to a specific thread. Thus, we program a fake timer to fire immediately
615 * and notify such event to the requested receiver thread.
617 * Returns 0 if successful; otherwise it returns an error code:
618 * EINVAL: the signal specified by signal is not
619 * between FOSA_SIGNAL_MIN and FOSA_SIGNAL_MAX
621 * EAGAIN: no resources are available to queue the signal; the
622 * maximum number of queued signals has been reached, or a
623 * systemwide resource limit has been exceeded
625 * Alternatively, in case of error the implementation is allowed to
626 * notify it to the system console and then terminate the FRSH
627 * implementation and dependant applications
629 int fosa_signal_queue(fosa_signal_t signal,
630 fosa_signal_info_t info,
631 fosa_thread_id_t receiver)
635 struct itimerspec fake_time;
636 struct sigevent fake_event;
638 ret = timer_create(FOSA_CLOCK_REALTIME, &fake_event, &fake_timer);
641 fake_time.it_value.tv_sec = fake_time.it_value.tv_nsec = 0;
642 fake_time.it_interval.tv_sec = fake_time.it_interval.tv_nsec = 0;
643 fake_event.sigev_notify = SIGEV_THREAD_ID | SIGEV_SIGNAL;
644 fake_event.sigev_signo = SIGRTMIN;
645 fake_event.sigev_value.sival_int = info.sival_int;
646 fake_event._sigev_un._tid = receiver.linux_tid;
648 ret = timer_settime(fake_timer, TIMER_ABSTIME, &fake_time, NULL);
650 timer_delete(fake_timer);
654 ret = timer_delete(fake_timer);
667 * The function waits for the arrival of one of the signals in the
668 * array of signal numbers specified by set, which must be of size
669 * equal to size. If there is a signal already queued, the function
670 * returns immediately. If there is no signal of the specified set
671 * queued, the calling thread is suspended until a signal from that
672 * set arrives. Upon return, if signal_received is not NULL the number
673 * of the signal received is stored in the variable pointed to by
674 * signal_received; and if info is not NULL the associated information
675 * is stored in the variable pointed to by info.
677 * Returns 0 if successful; otherwise it returns an error code:
678 * EINVAL: the array contains one or more values which are not
679 * between FOSA_SIGNAL_MIN and FOSA_SIGNAL_MAX, or size
682 * Alternatively, in case of error the implementation is allowed to
683 * notify it to the system console and then terminate the FRSH
684 * implementation and dependant applications
686 int fosa_signal_wait(fosa_signal_t set[], int size,
687 fosa_signal_t *signal_received,
688 fosa_signal_info_t *info)
694 ret = sigemptyset(&sigset);
697 for (i = 0; i < size; i++) {
698 ret = sigaddset(&sigset,set[i]);
702 ret = sigwaitinfo(&sigset, &siginfo);
705 if (info != NULL && signal_received != NULL)
706 *signal_received = siginfo.si_signo;
708 *info = (fosa_signal_info_t) siginfo.si_value.sival_int;
716 * fosa_signal_timedwait()
718 * Timed wait for a signal
720 * This function behaves the same as fosa_signal_wait(), except that
721 * the suspension time is limited to the time interval specified in
722 * the timespec structure referenced by timeout.
724 * Returns 0 if successful; otherwise it returns an error code:
725 * EINVAL: the array contains one or more values which are not
726 * between FOSA_SIGNAL_MIN and FOSA_SIGNAL_MAX, or size
727 * is less than 0, or timeout is invalid
728 * EAGAIN: The timeout expired
730 * Alternatively, in case of error the implementation is allowed to
731 * notify it to the system console and then terminate the FRSH
732 * implementation and dependant applications
734 int fosa_signal_timedwait(fosa_signal_t set[], int size,
735 fosa_signal_t *signal_received,
736 fosa_signal_info_t *info,
737 const struct timespec *timeout)
743 ret = sigemptyset(&signalset);
746 for (i = 0; i < size; i++) {
747 ret = sigaddset(&signalset,set[i]);
751 ret = sigtimedwait(&signalset,&siginfo,timeout);
754 if (signal_received != NULL)
755 *signal_received = siginfo.si_signo;
757 *info = (fosa_signal_info_t) siginfo.si_value.sival_int;