RTEMS C User’s Guide¶
RTEMS C User’s Guide¶
COPYRIGHT (c) 1988 - 2015.On-Line Applications Research Corporation (OAR).
The authors have used their best efforts in preparing this material. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. No warranty of any kind, expressed or implied, with regard to the software or the material contained in this document is provided. No liability arising out of the application or use of any product described in this document is assumed. The authors reserve the right to revise this material and to make changes from time to time in the content hereof without obligation to notify anyone of such revision or changes.
The RTEMS Project is hosted at http://www.rtems.org/. Any inquiries concerning RTEMS, its related support components, or its documentation should be directed to the Community Project hosted at http://www.rtems.org/.
RTEMS Online Resources
Home | https://www.rtems.org/ |
Developers | https://devel.rtems.org/ |
Documentation | https://docs.rtems.org/ |
Bug Reporting | https://devel.rtems.org/query |
Mailing Lists | https://lists.rtems.org/ |
Git Repositories | https://git.rtems.org/ |
1. Preface¶
In recent years, the cost required to develop a software product has increased significantly while the target hardware costs have decreased. Now a larger portion of money is expended in developing, using, and maintaining software. The trend in computing costs is the complete dominance of software over hardware costs. Because of this, it is necessary that formal disciplines be established to increase the probability that software is characterized by a high degree of correctness, maintainability, and portability. In addition, these disciplines must promote practices that aid in the consistent and orderly development of a software system within schedule and budgetary constraints. To be effective, these disciplines must adopt standards which channel individual software efforts toward a common goal.
The push for standards in the software development field has been met with various degrees of success. The Microprocessor Operating Systems Interfaces (MOSI) effort has experienced only limited success. As popular as the UNIX operating system has grown, the attempt to develop a standard interface definition to allow portable application development has only recently begun to produce the results needed in this area. Unfortunately, very little effort has been expended to provide standards addressing the needs of the real-time community. Several organizations have addressed this need during recent years.
The Real Time Executive Interface Definition (RTEID) was developed by Motorola with technical input from Software Components Group. RTEID was adopted by the VMEbus International Trade Association (VITA) as a baseline draft for their proposed standard multiprocessor, real-time executive interface, Open Real-Time Kernel Interface Definition (ORKID). These two groups are currently working together with the IEEE P1003.4 committee to insure that the functionality of their proposed standards is adopted as the real-time extensions to POSIX.
This emerging standard defines an interface for the development of real-time software to ease the writing of real-time application programs that are directly portable across multiple real-time executive implementations. This interface includes both the source code interfaces and run-time behavior as seen by a real-time application. It does not include the details of how a kernel implements these functions. The standard’s goal is to serve as a complete definition of external interfaces so that application code that conforms to these interfaces will execute properly in all real-time executive environments. With the use of a standards compliant executive, routines that acquire memory blocks, create and manage message queues, establish and use semaphores, and send and receive signals need not be redeveloped for a different real-time environment as long as the new environment is compliant with the standard. Software developers need only concentrate on the hardware dependencies of the real-time system. Furthermore, most hardware dependencies for real-time applications can be localized to the device drivers.
A compliant executive provides simple and flexible real-time multiprocessing. It easily lends itself to both tightly-coupled and loosely-coupled configurations (depending on the system hardware configuration). Objects such as tasks, queues, events, signals, semaphores, and memory blocks can be designated as global objects and accessed by any task regardless of which processor the object and the accessing task reside.
The acceptance of a standard for real-time executives will produce the same advantages enjoyed from the push for UNIX standardization by AT&T’s System V Interface Definition and IEEE’s POSIX efforts. A compliant multiprocessing executive will allow close coupling between UNIX systems and real-time executives to provide the many benefits of the UNIX development environment to be applied to real-time software development. Together they provide the necessary laboratory environment to implement real-time, distributed, embedded systems using a wide variety of computer architectures.
A study was completed in 1988, within the Research, Development, and Engineering Center, U.S. Army Missile Command, which compared the various aspects of the Ada programming language as they related to the application of Ada code in distributed and/or multiple processing systems. Several critical conclusions were derived from the study. These conclusions have a major impact on the way the Army develops application software for embedded applications. These impacts apply to both in-house software development and contractor developed software.
A conclusion of the analysis, which has been previously recognized by other agencies attempting to utilize Ada in a distributed or multiprocessing environment, is that the Ada programming language does not adequately support multiprocessing. Ada does provide a mechanism for multi-tasking, however, this capability exists only for a single processor system. The language also does not have inherent capabilities to access global named variables, flags or program code. These critical features are essential in order for data to be shared between processors. However, these drawbacks do have workarounds which are sometimes awkward and defeat the intent of software maintainability and portability goals.
Another conclusion drawn from the analysis, was that the run time executives being delivered with the Ada compilers were too slow and inefficient to be used in modern missile systems. A run time executive is the core part of the run time system code, or operating system code, that controls task scheduling, input/output management and memory management. Traditionally, whenever efficient executive (also known as kernel) code was required by the application, the user developed in-house software. This software was usually written in assembly language for optimization.
Because of this shortcoming in the Ada programming language, software developers in research and development and contractors for project managed systems, are mandated by technology to purchase and utilize off-the-shelf third party kernel code. The contractor, and eventually the Government, must pay a licensing fee for every copy of the kernel code used in an embedded system.
The main drawback to this development environment is that the Government does not own, nor has the right to modify code contained within the kernel. V&V techniques in this situation are more difficult than if the complete source code were available. Responsibility for system failures due to faulty software is yet another area to be resolved under this environment.
The Guidance and Control Directorate began a software development effort to address these problems. A project to develop an experimental run time kernel was begun that will eliminate the major drawbacks of the Ada programming language mentioned above. The Real Time Executive for Multiprocessor Systems (RTEMS) provides full capabilities for management of tasks, interrupts, time, and multiple processors in addition to those features typical of generic operating systems. The code is Government owned, so no licensing fees are necessary. RTEMS has been implemented in both the Ada and C programming languages. It has been ported to the following processor families:
- Adapteva Epiphany
- Altera NIOS II
- Analog Devices Blackfin
- Atmel AVR
- ARM
- Freescale (formerly Motorola) MC68xxx
- Freescale (formerly Motorola) MC683xx
- Freescale (formerly Motorola) ColdFire
- Intel i386 and above
- Lattice Semiconductor LM32
- NEC V850
- MIPS
- Moxie Processor
- OpenRISC
- PowerPC
- Renesas (formerly Hitachi) SuperH
- Renesas (formerly Hitachi) H8/300
- Renesas M32C
- SPARC v7, v8, and V9
Since almost all of RTEMS is written in a high level language, ports to additional processor families require minimal effort.
RTEMS multiprocessor support is capable of handling either homogeneous or heterogeneous systems. The kernel automatically compensates for architectural differences (byte swapping, etc.) between processors. This allows a much easier transition from one processor family to another without a major system redesign.
Since the proposed standards are still in draft form, RTEMS cannot and does not claim compliance. However, the status of the standard is being carefully monitored to guarantee that RTEMS provides the functionality specified in the standard. Once approved, RTEMS will be made compliant.
This document is a detailed users guide for a functionally compliant real-time multiprocessor executive. It describes the user interface and run-time behavior of Release 4.10.99.0 of the C interface to RTEMS.
2. Overview¶
2.1. Introduction¶
RTEMS, Real-Time Executive for Multiprocessor Systems, is a real-time executive (kernel) which provides a high performance environment for embedded military applications including the following features:
- multitasking capabilities
- homogeneous and heterogeneous multiprocessor systems
- event-driven, priority-based, preemptive scheduling
- optional rate monotonic scheduling
- intertask communication and synchronization
- priority inheritance
- responsive interrupt management
- dynamic memory allocation
- high level of user configurability
This manual describes the usage of RTEMS for applications written in the C programming language. Those implementation details that are processor dependent are provided in the Applications Supplement documents. A supplement document which addresses specific architectural issues that affect RTEMS is provided for each processor type that is supported.
2.2. Real-time Application Systems¶
Real-time application systems are a special class of computer applications. They have a complex set of characteristics that distinguish them from other software problems. Generally, they must adhere to more rigorous requirements. The correctness of the system depends not only on the results of computations, but also on the time at which the results are produced. The most important and complex characteristic of real-time application systems is that they must receive and respond to a set of external stimuli within rigid and critical time constraints referred to as deadlines. Systems can be buried by an avalanche of interdependent, asynchronous or cyclical event streams.
Deadlines can be further characterized as either hard or soft based upon the value of the results when produced after the deadline has passed. A deadline is hard if the results have no value or if their use will result in a catastrophic event. In contrast, results which are produced after a soft deadline may have some value.
Another distinguishing requirement of real-time application systems is the ability to coordinate or manage a large number of concurrent activities. Since software is a synchronous entity, this presents special problems. One instruction follows another in a repeating synchronous cycle. Even though mechanisms have been developed to allow for the processing of external asynchronous events, the software design efforts required to process and manage these events and tasks are growing more complicated.
The design process is complicated further by spreading this activity over a set of processors instead of a single processor. The challenges associated with designing and building real-time application systems become very complex when multiple processors are involved. New requirements such as interprocessor communication channels and global resources that must be shared between competing processors are introduced. The ramifications of multiple processors complicate each and every characteristic of a real-time system.
2.3. Real-time Executive¶
Fortunately, real-time operating systems or real-time executives serve as a cornerstone on which to build the application system. A real-time multitasking executive allows an application to be cast into a set of logical, autonomous processes or tasks which become quite manageable. Each task is internally synchronous, but different tasks execute independently, resulting in an asynchronous processing stream. Tasks can be dynamically paused for many reasons resulting in a different task being allowed to execute for a period of time. The executive also provides an interface to other system components such as interrupt handlers and device drivers. System components may request the executive to allocate and coordinate resources, and to wait for and trigger synchronizing conditions. The executive system calls effectively extend the CPU instruction set to support efficient multitasking. By causing tasks to travel through well-defined state transitions, system calls permit an application to demand-switch between tasks in response to real-time events.
By proper grouping of responses to stimuli into separate tasks, a system can now asynchronously switch between independent streams of execution, directly responding to external stimuli as they occur. This allows the system design to meet critical performance specifications which are typically measured by guaranteed response time and transaction throughput. The multiprocessor extensions of RTEMS provide the features necessary to manage the extra requirements introduced by a system distributed across several processors. It removes the physical barriers of processor boundaries from the world of the system designer, enabling more critical aspects of the system to receive the required attention. Such a system, based on an efficient real-time, multiprocessor executive, is a more realistic model of the outside world or environment for which it is designed. As a result, the system will always be more logical, efficient, and reliable.
By using the directives provided by RTEMS, the real-time applications developer is freed from the problem of controlling and synchronizing multiple tasks and processors. In addition, one need not develop, test, debug, and document routines to manage memory, pass messages, or provide mutual exclusion. The developer is then able to concentrate solely on the application. By using standard software components, the time and cost required to develop sophisticated real-time applications is significantly reduced.
2.4. RTEMS Application Architecture¶
One important design goal of RTEMS was to provide a bridge between two critical layers of typical real-time systems. As shown in the following figure, RTEMS serves as a buffer between the project dependent application code and the target hardware. Most hardware dependencies for real-time applications can be localized to the low level device drivers.
The RTEMS I/O interface manager provides an efficient tool for incorporating these hardware dependencies into the system while simultaneously providing a general mechanism to the application code that accesses them. A well designed real-time system can benefit from this architecture by building a rich library of standard application components which can be used repeatedly in other real-time projects.
2.5. RTEMS Internal Architecture¶
RTEMS can be viewed as a set of layered components that work in harmony to provide a set of services to a real-time application system. The executive interface presented to the application is formed by grouping directives into logical sets called resource managers. Functions utilized by multiple managers such as scheduling, dispatching, and object management are provided in the executive core. The executive core depends on a small set of CPU dependent routines. Together these components provide a powerful run time environment that promotes the development of efficient real-time application systems. The following figure illustrates this organization:
Subsequent chapters present a detailed description of the capabilities provided by each of the following RTEMS managers:
- initialization
- task
- interrupt
- clock
- timer
- semaphore
- message
- event
- signal
- partition
- region
- dual ported memory
- I/O
- fatal error
- rate monotonic
- user extensions
- multiprocessing
2.6. User Customization and Extensibility¶
As thirty-two bit microprocessors have decreased in cost, they have become increasingly common in a variety of embedded systems. A wide range of custom and general-purpose processor boards are based on various thirty-two bit processors. RTEMS was designed to make no assumptions concerning the characteristics of individual microprocessor families or of specific support hardware. In addition, RTEMS allows the system developer a high degree of freedom in customizing and extending its features.
RTEMS assumes the existence of a supported microprocessor and sufficient memory for both RTEMS and the real-time application. Board dependent components such as clocks, interrupt controllers, or I/O devices can be easily integrated with RTEMS. The customization and extensibility features allow RTEMS to efficiently support as many environments as possible.
2.7. Portability¶
The issue of portability was the major factor in the creation of RTEMS. Since RTEMS is designed to isolate the hardware dependencies in the specific board support packages, the real-time application should be easily ported to any other processor. The use of RTEMS allows the development of real-time applications which can be completely independent of a particular microprocessor architecture.
2.8. Memory Requirements¶
Since memory is a critical resource in many real-time embedded systems, RTEMS was specifically designed to automatically leave out all services that are not required from the run-time environment. Features such as networking, various fileystems, and many other features are completely optional. This allows the application designer the flexibility to tailor RTEMS to most efficiently meet system requirements while still satisfying even the most stringent memory constraints. As a result, the size of the RTEMS executive is application dependent.
RTEMS requires RAM to manage each instance of an RTEMS object that is created. Thus the more RTEMS objects an application needs, the more memory that must be reserved. See Chapter 24 - Configuring a System.
RTEMS utilizes memory for both code and data space. Although RTEMS’ data space must be in RAM, its code space can be located in either ROM or RAM.
2.9. Audience¶
This manual was written for experienced real-time software developers. Although some background is provided, it is assumed that the reader is familiar with the concepts of task management as well as intertask communication and synchronization. Since directives, user related data structures, and examples are presented in C, a basic understanding of the C programming language is required to fully understand the material presented. However, because of the similarity of the Ada and C RTEMS implementations, users will find that the use and behavior of the two implementations is very similar. A working knowledge of the target processor is helpful in understanding some of RTEMS’ features. A thorough understanding of the executive cannot be obtained without studying the entire manual because many of RTEMS’ concepts and features are interrelated. Experienced RTEMS users will find that the manual organization facilitates its use as a reference document.
2.10. Conventions¶
The following conventions are used in this manual:
- Significant words or phrases as well as all directive names are printed in bold type.
- Items in bold capital letters are constants defined by RTEMS. Each language interface provided by RTEMS includes a file containing the standard set of constants, data types, and structure definitions which can be incorporated into the user application.
- A number of type definitions are provided by RTEMS and can be found in rtems.h.
- The characters “0x” preceding a number indicates that the number is in hexadecimal format. Any other numbers are assumed to be in decimal format.
2.11. Manual Organization¶
This first chapter has presented the introductory and background material for the RTEMS executive. The remaining chapters of this manual present a detailed description of RTEMS and the environment, including run time behavior, it creates for the user.
A chapter is dedicated to each manager and provides a detailed discussion of each RTEMS manager and the directives which it provides. The presentation format for each directive includes the following sections:
- Calling sequence
- Directive status codes
- Description
- Notes
The following provides an overview of the remainder of this manual:
- Chapter 2:
- Key Concepts: presents an introduction to the ideas which are common across multiple RTEMS managers.
- Chapter 3:
- RTEMS Data Types: describes the fundamental data types shared by the services in the RTEMS Classic API.
- Chapter 4:
- Scheduling Concepts: details the various RTEMS scheduling algorithms and task state transitions.
- Chapter 5:
- Initialization Manager: describes the functionality and directives provided by the Initialization Manager.
- Chapter 6:
- Task Manager: describes the functionality and directives provided by the Task Manager.
- Chapter 7:
- Interrupt Manager: describes the functionality and directives provided by the Interrupt Manager.
- Chapter 8:
- Clock Manager: describes the functionality and directives provided by the Clock Manager.
- Chapter 9:
- Timer Manager: describes the functionality and directives provided by the Timer Manager.
- Chapter 10:
- Rate Monotonic Manager: describes the functionality and directives provided by the Rate Monotonic Manager.
- Chapter 11:
- Semaphore Manager: describes the functionality and directives provided by the Semaphore Manager.
- Chapter 12:
- Barrier Manager: describes the functionality and directives provided by the Barrier Manager.
- Chapter 13:
- Message Manager: describes the functionality and directives provided by the Message Manager.
- Chapter 14:
- Event Manager: describes the functionality and directives provided by the Event Manager.
- Chapter 15:
- Signal Manager: describes the functionality and directives provided by the Signal Manager.
- Chapter 16:
- Partition Manager: describes the functionality and directives provided by the Partition Manager.
- Chapter 17:
- Region Manager: describes the functionality and directives provided by the Region Manager.
- Chapter 18:
- Dual-Ported Memory Manager: describes the functionality and directives provided by the Dual-Ported Memory Manager.
- Chapter 19:
- I/O Manager: describes the functionality and directives provided by the I/O Manager.
- Chapter 20:
- Fatal Error Manager: describes the functionality and directives provided by the Fatal Error Manager.
- Chapter 21:
- Board Support Packages: defines the functionality required of user-supplied board support packages.
- Chapter 22:
- User Extensions: shows the user how to extend RTEMS to incorporate custom features.
- Chapter 23:
- Configuring a System: details the process by which one tailors RTEMS for a particular single-processor or multiprocessor application.
- Chapter 24:
- Multiprocessing Manager: presents a conceptual overview of the multiprocessing capabilities provided by RTEMS as well as describing the Multiprocessing Communications Interface Layer and Multiprocessing Manager directives.
- Chapter 25:
- Stack Bounds Checker: presents the capabilities of the RTEMS task stack checker which can report stack usage as well as detect bounds violations.
- Chapter 26:
- CPU Usage Statistics: presents the capabilities of the CPU Usage statistics gathered on a per task basis along with the mechanisms for reporting and resetting the statistics.
- Chapter 27:
- Object Services: presents a collection of helper services useful when manipulating RTEMS objects. These include methods to assist in obtaining an object’s name in printable form. Additional services are provided to decompose an object Id and determine which API and object class it belongs to.
- Chapter 28:
- Chains: presents the methods provided to build, iterate and manipulate doubly-linked chains. This manager makes the chain implementation used internally by RTEMS to user space applications.
- Chapter 29:
- Timespec Helpers: presents a set of helper services useful when manipulating POSIX
struct timespec
instances. - Chapter 30:
- Constant Bandwidth Server Scheduler API.
- Chapter 31:
- Directive Status Codes: provides a definition of each of the directive status codes referenced in this manual.
- Chapter 32:
- Example Application: provides a template for simple RTEMS applications.
- Chapter 33:
- Glossary: defines terms used throughout this manual.
3. Key Concepts¶
3.1. Introduction¶
The facilities provided by RTEMS are built upon a foundation of very powerful concepts. These concepts must be understood before the application developer can efficiently utilize RTEMS. The purpose of this chapter is to familiarize one with these concepts.
3.2. Objects¶
RTEMS provides directives which can be used to dynamically create, delete, and manipulate a set of predefined object types. These types include tasks, message queues, semaphores, memory regions, memory partitions, timers, ports, and rate monotonic periods. The object-oriented nature of RTEMS encourages the creation of modular applications built upon re-usable “building block” routines.
All objects are created on the local node as required by the application and have an RTEMS assigned ID. All objects have a user-assigned name. Although a relationship exists between an object’s name and its RTEMS assigned ID, the name and ID are not identical. Object names are completely arbitrary and selected by the user as a meaningful “tag” which may commonly reflect the object’s use in the application. Conversely, object IDs are designed to facilitate efficient object manipulation by the executive.
3.2.1. Object Names¶
An object name is an unsigned thirty-two bit entity associated with the object by the user. The data type rtems_name
is used to store object names... index:: rtems_build_name
Although not required by RTEMS, object names are often composed of four ASCII characters which help identify that object. For example, a task which causes a light to blink might be called “LITE”. The rtems_build_name
routine is provided to build an object name from four ASCII characters. The following example illustrates this:
rtems_name my_name;
my_name = rtems_build_name( 'L', 'I', 'T', 'E' );
However, it is not required that the application use ASCII characters to build object names. For example, if an application requires one-hundred tasks, it would be difficult to assign meaningful ASCII names to each task. A more convenient approach would be to name them the binary values one through one-hundred, respectively.
RTEMS provides a helper routine, rtems_object_get_name
, which can be used to obtain the name of any RTEMS object using just its ID. This routine attempts to convert the name into a printable string.
The following example illustrates the use of this method to print an object name:
#include <rtems.h>
#include <rtems/bspIo.h>
void print_name(rtems_id id)
{
char buffer[10]; /* name assumed to be 10 characters or less */
char *result;
result = rtems_object_get_name( id, sizeof(buffer), buffer );
printk( "ID=0x%08x name=%s\n", id, ((result) ? result : "no name") );
}
3.2.2. Object IDs¶
An object ID is a unique unsigned integer value which uniquely identifies an object instance. Object IDs are passed as arguments to many directives in RTEMS and RTEMS translates the ID to an internal object pointer. The efficient manipulation of object IDs is critical to the performance of RTEMS services. Because of this, there are two object Id formats defined. Each target architecture specifies which format it will use. There is a thirty-two bit format which is used for most of the supported architectures and supports multiprocessor configurations. There is also a simpler sixteen bit format which is appropriate for smaller target architectures and does not support multiprocessor configurations.
3.2.2.1. Thirty-Two Object ID Format¶
The thirty-two bit format for an object ID is composed of four parts: API, object class, node, and index. The data type rtems_id
is used to store object IDs.
31 27 26 24 23 16 15 0
+---------+-------+--------------+-------------------------------+
| | | | |
| Class | API | Node | Index |
| | | | |
+---------+-------+--------------+-------------------------------+
The most significant five bits are the object class. The next three bits indicate the API to which the object class belongs. The next eight bits (16-23) are the number of the node on which this object was created. The node number is always one (1) in a single processor system. The least significant sixteen bits form an identifier within a particular object type. This identifier, called the object index, ranges in value from 1 to the maximum number of objects configured for this object type.
3.2.2.2. Sixteen Bit Object ID Format¶
The sixteen bit format for an object ID is composed of three parts: API, object class, and index. The data type rtems_id
is used to store object IDs.
15 11 10 8 7 0
+---------+-------+--------------+
| | | |
| Class | API | Index |
| | | |
+---------+-------+--------------+
The sixteen-bit format is designed to be as similar as possible to the thrity-two bit format. The differences are limited to the eliminatation of the node field and reduction of the index field from sixteen-bits to 8-bits. Thus the sixteen bit format only supports up to 255 object instances per API/Class combination and single processor systems. As this format is typically utilized by sixteen-bit processors with limited address space, this is more than enough object instances.
3.2.3. Object ID Description¶
The components of an object ID make it possible to quickly locate any object in even the most complicated multiprocessor system. Object ID’s are associated with an object by RTEMS when the object is created and the corresponding ID is returned by the appropriate object create directive. The object ID is required as input to all directives involving objects, except those which create an object or obtain the ID of an object.
The object identification directives can be used to dynamically obtain a particular object’s ID given its name. This mapping is accomplished by searching the name table associated with this object type. If the name is non-unique, then the ID associated with the first occurrence of the name will be returned to the application. Since object IDs are returned when the object is created, the object identification directives are not necessary in a properly designed single processor application.
In addition, services are provided to portably examine the subcomponents of an RTEMS ID. These services are described in detail later in this manual but are prototyped as follows:
uint32_t rtems_object_id_get_api( rtems_id );
uint32_t rtems_object_id_get_class( rtems_id );
uint32_t rtems_object_id_get_node( rtems_id );
uint32_t rtems_object_id_get_index( rtems_id );
An object control block is a data structure defined by RTEMS which contains the information necessary to manage a particular object type. For efficiency reasons, the format of each object type’s control block is different. However, many of the fields are similar in function. The number of each type of control block is application dependent and determined by the values specified in the user’s Configuration Table. An object control block is allocated at object create time and freed when the object is deleted. With the exception of user extension routines, object control blocks are not directly manipulated by user applications.
3.3. Communication and Synchronization¶
In real-time multitasking applications, the ability for cooperating execution threads to communicate and synchronize with each other is imperative. A real-time executive should provide an application with the following capabilities:
- Data transfer between cooperating tasks
- Data transfer between tasks and ISRs
- Synchronization of cooperating tasks
- Synchronization of tasks and ISRs
Most RTEMS managers can be used to provide some form of communication and/or synchronization. However, managers dedicated specifically to communication and synchronization provide well established mechanisms which directly map to the application’s varying needs. This level of flexibility allows the application designer to match the features of a particular manager with the complexity of communication and synchronization required. The following managers were specifically designed for communication and synchronization:
- Semaphore
- Message Queue
- Event
- Signal
The semaphore manager supports mutual exclusion involving the synchronization of access to one or more shared user resources. Binary semaphores may utilize the optional priority inheritance algorithm to avoid the problem of priority inversion. The message manager supports both communication and synchronization, while the event manager primarily provides a high performance synchronization mechanism. The signal manager supports only asynchronous communication and is typically used for exception handling.
3.4. Time¶
The development of responsive real-time applications requires an understanding of how RTEMS maintains and supports time-related operations. The basic unit of time in RTEMS is known as a tick. The frequency of clock ticks is completely application dependent and determines the granularity and accuracy of all interval and calendar time operations.
By tracking time in units of ticks, RTEMS is capable of supporting interval timing functions such as task delays, timeouts, timeslicing, the delayed execution of timer service routines, and the rate monotonic scheduling of tasks. An interval is defined as a number of ticks relative to the current time. For example, when a task delays for an interval of ten ticks, it is implied that the task will not execute until ten clock ticks have occurred. All intervals are specified using data type rtems_interval
.
A characteristic of interval timing is that the actual interval period may be a fraction of a tick less than the interval requested. This occurs because the time at which the delay timer is set up occurs at some time between two clock ticks. Therefore, the first countdown tick occurs in less than the complete time interval for a tick. This can be a problem if the clock granularity is large.
The rate monotonic scheduling algorithm is a hard real-time scheduling methodology. This methodology provides rules which allows one to guarantee that a set of independent periodic tasks will always meet their deadlines even under transient overload conditions. The rate monotonic manager provides directives built upon the Clock Manager’s interval timer support routines.
Interval timing is not sufficient for the many applications which require that time be kept in wall time or true calendar form. Consequently, RTEMS maintains the current date and time. This allows selected time operations to be scheduled at an actual calendar date and time. For example, a task could request to delay until midnight on New Year’s Eve before lowering the ball at Times Square. The data type rtems_time_of_day
is used to specify calendar time in RTEMS services. See Chapter 9 Section 2.2 - Time and Date Data Structures.
Obviously, the directives which use intervals or wall time cannot operate without some external mechanism which provides a periodic clock tick. This clock tick is typically provided by a real time clock or counter/timer device.
3.5. Memory Management¶
RTEMS memory management facilities can be grouped into two classes: dynamic memory allocation and address translation. Dynamic memory allocation is required by applications whose memory requirements vary through the application’s course of execution. Address translation is needed by applications which share memory with another CPU or an intelligent Input/Output processor. The following RTEMS managers provide facilities to manage memory:
- Region
- Partition
- Dual Ported Memory
RTEMS memory management features allow an application to create simple memory pools of fixed size buffers and/or more complex memory pools of variable size segments. The partition manager provides directives to manage and maintain pools of fixed size entities such as resource control blocks. Alternatively, the region manager provides a more general purpose memory allocation scheme that supports variable size blocks of memory which are dynamically obtained and freed by the application. The dual-ported memory manager provides executive support for address translation between internal and external dual-ported RAM address space.
4. RTEMS Data Types¶
4.1. Introduction¶
This chapter contains a complete list of the RTEMS primitive data types in alphabetical order. This is intended to be an overview and the user is encouraged to look at the appropriate chapters in the manual for more information about the usage of the various data types.
4.2. List of Data Types¶
The following is a complete list of the RTEMS primitive data types in alphabetical order:
rtems_address
- The data type used to manage addresses. It is equivalent to a
void *
pointer.
rtems_asr
- The return type for an RTEMS ASR.
rtems_asr_entry
- The address of the entry point to an RTEMS ASR.
rtems_attribute
- The data type used to manage the attributes for RTEMS objects. It is primarily used as an argument to object create routines to specify characteristics of the new object.
rtems_boolean
- May only take on the values of
TRUE
andFALSE
. This type is deprecated. Usebool
instead.
rtems_context
- The CPU dependent data structure used to manage the integer and system register portion of each task’s context.
rtems_context_fp
- The CPU dependent data structure used to manage the floating point portion of each task’s context.
rtems_device_driver
- The return type for a RTEMS device driver routine.
rtems_device_driver_entry
- The entry point to a RTEMS device driver routine.
rtems_device_major_number
- The data type used to manage device major numbers.
rtems_device_minor_number
- The data type used to manage device minor numbers.
rtems_double
- The RTEMS data type that corresponds to double precision floating point on the target hardware. This type is deprecated. Use
double
instead.
rtems_event_set
- The data type used to manage and manipulate RTEMS event sets with the Event Manager.
rtems_extension
- The return type for RTEMS user extension routines.
rtems_fatal_extension
- The entry point for a fatal error user extension handler routine.
rtems_id
- The data type used to manage and manipulate RTEMS object IDs.
rtems_interrupt_frame
- The data structure that defines the format of the interrupt stack frame as it appears to a user ISR. This data structure may not be defined on all ports.
rtems_interrupt_level
- The data structure used with the
rtems_interrupt_disable
,rtems_interrupt_enable
, andrtems_interrupt_flash
routines. This data type is CPU dependent and usually corresponds to the contents of the processor register containing the interrupt mask level.
rtems_interval
- The data type used to manage and manipulate time intervals. Intervals are non-negative integers used to measure the length of time in clock ticks.
rtems_isr
- The return type of a function implementing an RTEMS ISR.
rtems_isr_entry
- The address of the entry point to an RTEMS ISR. It is equivalent to the entry point of the function implementing the ISR.
rtems_mp_packet_classes
- The enumerated type which specifies the categories of multiprocessing messages. For example, one of the classes is for messages that must be processed by the Task Manager.
rtems_mode
- The data type used to manage and dynamically manipulate the execution mode of an RTEMS task.
rtems_mpci_entry
- The return type of an RTEMS MPCI routine.
rtems_mpci_get_packet_entry
- The address of the entry point to the get packet routine for an MPCI implementation.
rtems_mpci_initialization_entry
- The address of the entry point to the initialization routine for an MPCI implementation.
rtems_mpci_receive_packet_entry
- The address of the entry point to the receive packet routine for an MPCI implementation.
rtems_mpci_return_packet_entry
- The address of the entry point to the return packet routine for an MPCI implementation.
rtems_mpci_send_packet_entry
- The address of the entry point to the send packet routine for an MPCI implementation.
rtems_mpci_table
- The data structure containing the configuration information for an MPCI.
rtems_name
- The data type used to contain the name of a Classic API object. It is an unsigned thirty-two bit integer which can be treated as a numeric value or initialized using
rtems_build_name
to contain four ASCII characters.
rtems_option
- The data type used to specify which behavioral options the caller desires. It is commonly used with potentially blocking directives to specify whether the caller is willing to block or return immediately with an error indicating that the resource was not available.
rtems_packet_prefix
- The data structure that defines the first bytes in every packet sent between nodes in an RTEMS multiprocessor system. It contains routing information that is expected to be used by the MPCI layer.
rtems_signal_set
- The data type used to manage and manipulate RTEMS signal sets with the Signal Manager.
int8_t
- The C99 data type that corresponds to signed eight bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
int16_t
- The C99 data type that corresponds to signed sixteen bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
int32_t
- The C99 data type that corresponds to signed thirty-two bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
int64_t
- The C99 data type that corresponds to signed sixty-four bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
rtems_single
- The RTEMS data type that corresponds to single precision floating point on the target hardware. This type is deprecated. Use
float
instead.
rtems_status_codes
- The return type for most RTEMS services. This is an enumerated type of approximately twenty-five values. In general, when a service returns a particular status code, it indicates that a very specific error condition has occurred.
rtems_task
- The return type for an RTEMS Task.
rtems_task_argument
- The data type for the argument passed to each RTEMS task. In RTEMS 4.7 and older, this is an unsigned thirty-two bit integer. In RTEMS 4.8 and newer, this is based upon the C99 type
uintptr_t
which is guaranteed to be an integer large enough to hold a pointer on the target architecture.
rtems_task_begin_extension
- The entry point for a task beginning execution user extension handler routine.
rtems_task_create_extension
- The entry point for a task creation execution user extension handler routine.
rtems_task_delete_extension
- The entry point for a task deletion user extension handler routine.
rtems_task_entry
- The address of the entry point to an RTEMS ASR. It is equivalent to the entry point of the function implementing the ASR.
rtems_task_exitted_extension
- The entry point for a task exitted user extension handler routine.
rtems_task_priority
- The data type used to manage and manipulate task priorities.
rtems_task_restart_extension
- The entry point for a task restart user extension handler routine.
rtems_task_start_extension
- The entry point for a task start user extension handler routine.
rtems_task_switch_extension
- The entry point for a task context switch user extension handler routine.
rtems_tcb
- The data structure associated with each task in an RTEMS system.
rtems_time_of_day
- The data structure used to manage and manipulate calendar time in RTEMS.
rtems_timer_service_routine
- The return type for an RTEMS Timer Service Routine.
rtems_timer_service_routine_entry
- The address of the entry point to an RTEMS TSR. It is equivalent to the entry point of the function implementing the TSR.
rtems_vector_number
- The data type used to manage and manipulate interrupt vector numbers.
uint8_t
- The C99 data type that corresponds to unsigned eight bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
uint16_t
- The C99 data type that corresponds to unsigned sixteen bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
uint32_t
- The C99 data type that corresponds to unsigned thirty-two bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
uint64_t
- The C99 data type that corresponds to unsigned sixty-four bit integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
uintptr_t
- The C99 data type that corresponds to the unsigned integer type that is of sufficient size to represent addresses as unsigned integers. This data type is defined by RTEMS in a manner that ensures it is portable across different target processors.
5. Scheduling Concepts¶
5.1. Introduction¶
The concept of scheduling in real-time systems dictates the ability to provide immediate response to specific external events, particularly the necessity of scheduling tasks to run within a specified time limit after the occurrence of an event. For example, software embedded in life-support systems used to monitor hospital patients must take instant action if a change in the patient’s status is detected.
The component of RTEMS responsible for providing this capability is appropriately called the scheduler. The scheduler’s sole purpose is to allocate the all important resource of processor time to the various tasks competing for attention.
5.2. Scheduling Algorithms¶
RTEMS provides a plugin framework which allows it to support multiple scheduling algorithms. RTEMS now includes multiple scheduling algorithms in the SuperCore and the user can select which of these they wish to use in their application. In addition, the user can implement their own scheduling algorithm and configure RTEMS to use it.
Supporting multiple scheduling algorithms gives the end user the option to select the algorithm which is most appropriate to their use case. Most real-time operating systems schedule tasks using a priority based algorithm, possibly with preemption control. The classic RTEMS scheduling algorithm which was the only algorithm available in RTEMS 4.10 and earlier, is a priority based scheduling algorithm. This scheduling algoritm is suitable for single core (e.g. non-SMP) systems and is now known as the Deterministic Priority Scheduler. Unless the user configures another scheduling algorithm, RTEMS will use this on single core systems.
5.2.1. Priority Scheduling¶
When using priority based scheduling, RTEMS allocates the processor using a priority-based, preemptive algorithm augmented to provide round-robin characteristics within individual priority groups. The goal of this algorithm is to guarantee that the task which is executing on the processor at any point in time is the one with the highest priority among all tasks in the ready state.
When a task is added to the ready chain, it is placed behind all other tasks of the same priority. This rule provides a round-robin within priority group scheduling characteristic. This means that in a group of equal priority tasks, tasks will execute in the order they become ready or FIFO order. Even though there are ways to manipulate and adjust task priorities, the most important rule to remember is:
Note
Priority based scheduling algorithms will always select the highest priority task that is ready to run when allocating the processor to a task.
Priority scheduling is the most commonly used scheduling algorithm. It should be used by applications in which multiple tasks contend for CPU time or other resources and there is a need to ensure certain tasks are given priority over other tasks.
There are a few common methods of accomplishing the mechanics of this algorithm. These ways involve a list or chain of tasks in the ready state.
- The least efficient method is to randomly place tasks in the ready chain forcing the scheduler to scan the entire chain to determine which task receives the processor.
- A more efficient method is to schedule the task by placing it in the proper place on the ready chain based on the designated scheduling criteria at the time it enters the ready state. Thus, when the processor is free, the first task on the ready chain is allocated the processor.
- Another mechanism is to maintain a list of FIFOs per priority. When a task is readied, it is placed on the rear of the FIFO for its priority. This method is often used with a bitmap to assist in locating which FIFOs have ready tasks on them.
RTEMS currently includes multiple priority based scheduling algorithms as well as other algorithms which incorporate deadline. Each algorithm is discussed in the following sections.
5.2.2. Deterministic Priority Scheduler¶
This is the scheduler implementation which has always been in RTEMS. After the 4.10 release series, it was factored into pluggable scheduler selection. It schedules tasks using a priority based algorithm which takes into account preemption. It is implemented using an array of FIFOs with a FIFO per priority. It maintains a bitmap which is used to track which priorities have ready tasks.
This algorithm is deterministic (e.g. predictable and fixed) in execution time. This comes at the cost of using slightly over three (3) kilobytes of RAM on a system configured to support 256 priority levels.
This scheduler is only aware of a single core.
5.2.3. Simple Priority Scheduler¶
This scheduler implementation has the same behaviour as the Deterministic Priority Scheduler but uses only one linked list to manage all ready tasks. When a task is readied, a linear search of that linked list is performed to determine where to insert the newly readied task.
This algorithm uses much less RAM than the Deterministic Priority Scheduler but is O(n) where n is the number of ready tasks. In a small system with a small number of tasks, this will not be a performance issue. Reducing RAM consumption is often critical in small systems which are incapable of supporting a large number of tasks.
This scheduler is only aware of a single core.
5.2.4. Simple SMP Priority Scheduler¶
This scheduler is based upon the Simple Priority Scheduler and is designed to have the same behaviour on a single core system. But this scheduler is capable of scheduling threads across multiple cores in an SMP system. When given a choice of replacing one of two threads at equal priority on different cores, this algorithm favors replacing threads which are preemptible and have executed the longest.
This algorithm is non-deterministic. When scheduling, it must consider which tasks are to be executed on each core while avoiding superfluous task migrations.
5.2.5. Earliest Deadline First Scheduler¶
This is an alternative scheduler in RTEMS for single core applications. The primary EDF advantage is high total CPU utilization (theoretically up to 100%). It assumes that tasks have priorities equal to deadlines.
This EDF is initially preemptive, however, individual tasks may be declared not-preemptive. Deadlines are declared using only Rate Monotonic manager which goal is to handle periodic behavior. Period is always equal to deadline. All ready tasks reside in a single ready queue implemented using a red-black tree.
This implementation of EDF schedules two different types of task priority types while each task may switch between the two types within its execution. If a task does have a deadline declared using the Rate Monotonic manager, the task is deadline-driven and its priority is equal to deadline. On the contrary if a task does not have any deadline or the deadline is cancelled using the Rate Monotonic manager, the task is considered a background task with priority equal to that assigned upon initialization in the same manner as for priority scheduler. Each background task is of a lower importance than each deadline-driven one and is scheduled when no deadline-driven task and no higher priority background task is ready to run.
Every deadline-driven scheduling algorithm requires means for tasks to claim a deadline. The Rate Monotonic Manager is responsible for handling periodic execution. In RTEMS periods are equal to deadlines, thus if a task announces a period, it has to be finished until the end of this period. The call of rtems_rate_monotonic_period
passes the scheduler the length of oncoming deadline. Moreover, the rtems_rate_monotonic_cancel
and rtems_rate_monotonic_delete
calls clear the deadlines assigned to the task.
5.2.6. Constant Bandwidth Server Scheduling (CBS)¶
This is an alternative scheduler in RTEMS for single core applications. The CBS is a budget aware extension of EDF scheduler. The main goal of this scheduler is to ensure temporal isolation of tasks meaning that a task’s execution in terms of meeting deadlines must not be influenced by other tasks as if they were run on multiple independent processors.
Each task can be assigned a server (current implementation supports only one task per server). The server is characterized by period (deadline) and computation time (budget). The ratio budget/period yields bandwidth, which is the fraction of CPU to be reserved by the scheduler for each subsequent period.
The CBS is equipped with a set of rules applied to tasks attached to servers ensuring that deadline miss because of another task cannot occur. In case a task breaks one of the rules, its priority is pulled to background until the end of its period and then restored again. The rules are:
- Task cannot exceed its registered budget,
- Task cannot be unblocked when a ratio between remaining budget and remaining deadline is higher than declared bandwidth.
The CBS provides an extensive API. Unlike EDF, the rtems_rate_monotonic_period
does not declare a deadline because it is carried out using CBS API. This call only announces next period.
5.3. Scheduling Modification Mechanisms¶
RTEMS provides four mechanisms which allow the user to alter the task scheduling decisions:
- user-selectable task priority level
- task preemption control
- task timeslicing control
- manual round-robin selection
Each of these methods provides a powerful capability to customize sets of tasks to satisfy the unique and particular requirements encountered in custom real-time applications. Although each mechanism operates independently, there is a precedence relationship which governs the effects of scheduling modifications. The evaluation order for scheduling characteristics is always priority, preemption mode, and timeslicing. When reading the descriptions of timeslicing and manual round-robin it is important to keep in mind that preemption (if enabled) of a task by higher priority tasks will occur as required, overriding the other factors presented in the description.
5.3.1. Task Priority and Scheduling¶
The most significant task scheduling modification mechanism is the ability for the user to assign a priority level to each individual task when it is created and to alter a task’s priority at run-time. RTEMS supports up to 255 priority levels. Level 255 is the lowest priority and level 1 is the highest.
5.3.2. Preemption¶
Another way the user can alter the basic scheduling algorithm is by manipulating the preemption mode flag (RTEMS_PREEMPT_MASK
) of individual tasks. If preemption is disabled for a task (RTEMS_NO_PREEMPT
), then the task will not relinquish control of the processor until it terminates, blocks, or re-enables preemption. Even tasks which become ready to run and possess higher priority levels will not be allowed to execute. Note that the preemption setting has no effect on the manner in which a task is scheduled. It only applies once a task has control of the processor.
5.3.3. Timeslicing¶
Timeslicing or round-robin scheduling is an additional method which can be used to alter the basic scheduling algorithm. Like preemption, timeslicing is specified on a task by task basis using the timeslicing mode flag (RTEMS_TIMESLICE_MASK
). If timeslicing is enabled for a task (RTEMS_TIMESLICE
), then RTEMS will limit the amount of time the task can execute before the processor is allocated to another task. Each tick of the real-time clock reduces the currently running task’s timeslice. When the execution time equals the timeslice, RTEMS will dispatch another task of the same priority to execute. If there are no other tasks of the same priority ready to execute, then the current task is allocated an additional timeslice and continues to run. Remember that a higher priority task will preempt the task (unless preemption is disabled) as soon as it is ready to run, even if the task has not used up its entire timeslice.
5.3.4. Manual Round-Robin¶
The final mechanism for altering the RTEMS scheduling algorithm is called manual round-robin. Manual round-robin is invoked by using the rtems_task_wake_after
directive with a time interval of RTEMS_YIELD_PROCESSOR
. This allows a task to give up the processor and be immediately returned to the ready chain at the end of its priority group. If no other tasks of the same priority are ready to run, then the task does not lose control of the processor.
5.4. Dispatching Tasks¶
The dispatcher is the RTEMS component responsible for allocating the processor to a ready task. In order to allocate the processor to one task, it must be deallocated or retrieved from the task currently using it. This involves a concept called a context switch. To perform a context switch, the dispatcher saves the context of the current task and restores the context of the task which has been allocated to the processor. Saving and restoring a task’s context is the storing/loading of all the essential information about a task to enable it to continue execution without any effects of the interruption. For example, the contents of a task’s register set must be the same when it is given the processor as they were when it was taken away. All of the information that must be saved or restored for a context switch is located either in the TCB or on the task’s stacks.
Tasks that utilize a numeric coprocessor and are created with the RTEMS_FLOATING_POINT
attribute require additional operations during a context switch. These additional operations are necessary to save and restore the floating point context of RTEMS_FLOATING_POINT
tasks. To avoid unnecessary save and restore operations, the state of the numeric coprocessor is only saved when a RTEMS_FLOATING_POINT
task is dispatched and that task was not the last task to utilize the coprocessor.
5.5. Task State Transitions¶
Tasks in an RTEMS system must always be in one of the five allowable task states. These states are: executing, ready, blocked, dormant, and non-existent.
A task occupies the non-existent state before a rtems_task_create
has been issued on its behalf. A task enters the non-existent state from any other state in the system when it is deleted with the rtems_task_delete
directive. While a task occupies this state it does not have a TCB or a task ID assigned to it; therefore, no other tasks in the system may reference this task.
When a task is created via the rtems_task_create
directive it enters the dormant state. This state is not entered through any other means. Although the task exists in the system, it cannot actively compete for system resources. It will remain in the dormant state until it is started via the rtems_task_start
directive, at which time it enters the ready state. The task is now permitted to be scheduled for the processor and to compete for other system resources.
A task occupies the blocked state whenever it is unable to be scheduled to run. A running task may block itself or be blocked by other tasks in the system. The running task blocks itself through voluntary operations that cause the task to wait. The only way a task can block a task other than itself is with the rtems_task_suspend
directive. A task enters the blocked state due to any of the following conditions:
- A task issues a
rtems_task_suspend
directive which blocks either itself or another task in the system. - The running task issues a
rtems_barrier_wait
directive. - The running task issues a
rtems_message_queue_receive
directive with the wait option and the message queue is empty. - The running task issues an
rtems_event_receive
directive with the wait option and the currently pending events do not satisfy the request. - The running task issues a
rtems_semaphore_obtain
directive with the wait option and the requested semaphore is unavailable. - The running task issues a
rtems_task_wake_after
directive which blocks the task for the given time interval. If the time interval specified is zero, the task yields the processor and remains in the ready state. - The running task issues a
rtems_task_wake_when
directive which blocks the task until the requested date and time arrives. - The running task issues a
rtems_rate_monotonic_period
directive and must wait for the specified rate monotonic period to conclude. - The running task issues a
rtems_region_get_segment
directive with the wait option and there is not an available segment large enough to satisfy the task’s request.
A blocked task may also be suspended. Therefore, both the suspension and the blocking condition must be removed before the task becomes ready to run again.
A task occupies the ready state when it is able to be scheduled to run, but currently does not have control of the processor. Tasks of the same or higher priority will yield the processor by either becoming blocked, completing their timeslice, or being deleted. All tasks with the same priority will execute in FIFO order. A task enters the ready state due to any of the following conditions:
- A running task issues a
rtems_task_resume
directive for a task that is suspended and the task is not blocked waiting on any resource. - A running task issues a
rtems_message_queue_send
,rtems_message_queue_broadcast
, or artems_message_queue_urgent
directive which posts a message to the queue on which the blocked task is waiting. - A running task issues an
rtems_event_send
directive which sends an event condition to a task which is blocked waiting on that event condition. - A running task issues a
rtems_semaphore_release
directive which releases the semaphore on which the blocked task is waiting. - A timeout interval expires for a task which was blocked by a call to the
rtems_task_wake_after
directive. - A timeout period expires for a task which blocked by a call to the
rtems_task_wake_when
directive. - A running task issues a
rtems_region_return_segment
directive which releases a segment to the region on which the blocked task is waiting and a resulting segment is large enough to satisfy the task’s request. - A rate monotonic period expires for a task which blocked by a call to the
rtems_rate_monotonic_period
directive. - A timeout interval expires for a task which was blocked waiting on a message, event, semaphore, or segment with a timeout specified.
- A running task issues a directive which deletes a message queue, a semaphore, or a region on which the blocked task is waiting.
- A running task issues a
rtems_task_restart
directive for the blocked task. - The running task, with its preemption mode enabled, may be made ready by issuing any of the directives that may unblock a task with a higher priority. This directive may be issued from the running task itself or from an ISR. A ready task occupies the executing state when it has control of the CPU. A task enters the executing state due to any of the following conditions:
- The task is the highest priority ready task in the system.
- The running task blocks and the task is next in the scheduling queue. The task may be of equal priority as in round-robin scheduling or the task may possess the highest priority of the remaining ready tasks.
- The running task may reenable its preemption mode and a task exists in the ready queue that has a higher priority than the running task.
- The running task lowers its own priority and another task is of higher priority as a result.
- The running task raises the priority of a task above its own and the running task is in preemption mode.
6. Initialization Manager¶
6.1. Introduction¶
The Initialization Manager is responsible for initiating and shutting down RTEMS. Initiating RTEMS involves creating and starting all configured initialization tasks, and for invoking the initialization routine for each user-supplied device driver. In a multiprocessor configuration, this manager also initializes the interprocessor communications layer. The directives provided by the Initialization Manager are:
- rtems_initialize_executive - Initialize RTEMS
- rtems_shutdown_executive - Shutdown RTEMS
6.2. Background¶
6.2.1. Initialization Tasks¶
Initialization task(s) are the mechanism by which RTEMS transfers initial control to the user’s application. Initialization tasks differ from other application tasks in that they are defined in the User Initialization Tasks Table and automatically created and started by RTEMS as part of its initialization sequence. Since the initialization tasks are scheduled using the same algorithm as all other RTEMS tasks, they must be configured at a priority and mode which will ensure that they will complete execution before other application tasks execute. Although there is no upper limit on the number of initialization tasks, an application is required to define at least one.
A typical initialization task will create and start the static set of application tasks. It may also create any other objects used by the application. Initialization tasks which only perform initialization should delete themselves upon completion to free resources for other tasks. Initialization tasks may transform themselves into a “normal” application task. This transformation typically involves changing priority and execution mode. RTEMS does not automatically delete the initialization tasks.
6.2.2. System Initialization¶
System Initialization begins with board reset and continues through RTEMS initialization, initialization of all device drivers, and eventually a context switch to the first user task. Remember, that interrupts are disabled during initialization and the initialization context is not a task in any sense and the user should be very careful during initialization.
The BSP must ensure that the there is enough stack space reserved for the initialization context to successfully execute the initialization routines for all device drivers and, in multiprocessor configurations, the Multiprocessor Communications Interface Layer initialization routine.
6.2.3. The Idle Task¶
The Idle Task is the lowest priority task in a system and executes only when no other task is ready to execute. This default implementation of this task consists of an infinite loop. RTEMS allows the Idle Task body to be replaced by a CPU specific implementation, a BSP specific implementation or an application specific implementation.
The Idle Task is preemptible and WILL be preempted when any other task is made ready to execute. This characteristic is critical to the overall behavior of any application.
6.2.4. Initialization Manager Failure¶
The rtems_fatal_error_occurred
directive will be invoked from rtems_initialize_executive
for any of the following reasons:
- If either the Configuration Table or the CPU Dependent Information Table is not provided.
- If the starting address of the RTEMS RAM Workspace, supplied by the application in the Configuration Table, is NULL or is not aligned on a four-byte boundary.
- If the size of the RTEMS RAM Workspace is not large enough to initialize and configure the system.
- If the interrupt stack size specified is too small.
- If multiprocessing is configured and the node entry in the Multiprocessor Configuration Table is not between one and the maximum_nodes entry.
- If a multiprocessor system is being configured and no Multiprocessor Communications Interface is specified.
- If no user initialization tasks are configured. At least one initialization task must be configured to allow RTEMS to pass control to the application at the end of the executive initialization sequence.
- If any of the user initialization tasks cannot be created or started successfully.
A discussion of RTEMS actions when a fatal error occurs may be found Chapter 21 Section 3.1 - Announcing a Fatal Error.
6.3. Operations¶
6.3.1. Initializing RTEMS¶
The Initialization Manager rtems_initialize_executive
directives is called by the boot_card
routine. The boot_card
routine is invoked by the Board Support Package once a basic C run-time environment is set up. This consists of
- a valid and accessible text section, read-only data, read-write data and zero-initialized data,
- an initialization stack large enough to initialize the rest of the Board Support Package, RTEMS and the device drivers,
- all registers and components mandated by Application Binary Interface, and
- disabled interrupts.
The rtems_initialize_executive
directive uses a system initialization linker set to initialize only those parts of the overall RTEMS feature set that is necessary for a particular application. See Chapter 36 - Linker Sets. Each RTEMS feature used the application may optionally register an initialization handler. The system initialization API is available via``#included <rtems/sysinit.h>``.
A list of all initialization steps follows. Some steps are optional depending on the requested feature set of the application. The initialization steps are execute in the order presented here.
RTEMS_SYSINIT_BSP_WORK_AREAS
- The work areas consisting of C Program Heap and the RTEMS Workspace are initialized by the Board Support Package. This step is mandatory.
RTEMS_SYSINIT_BSP_START
- Basic initialization step provided by the Board Support Package. This step is mandatory.
RTEMS_SYSINIT_DATA_STRUCTURES
- This directive is called when the Board Support Package has completed its basic initialization and allows RTEMS to initialize the application environment based upon the information in the Configuration Table, User Initialization Tasks Table, Device Driver Table, User Extension Table, Multiprocessor Configuration Table, and the Multiprocessor Communications Interface (MPCI) Table.
RTEMS_SYSINIT_BSP_LIBC
- Depending on the application configuration the IO library and root filesystem is initialized. This step is mandatory.
RTEMS_SYSINIT_BEFORE_DRIVERS
- This directive performs initialization that must occur between basis RTEMS data structure initialization and device driver initialization. In particular, in a multiprocessor configuration, this directive will create the MPCI Server Task.
RTEMS_SYSINIT_BSP_PRE_DRIVERS
- Initialization step performed right before device drivers are initialized provided by the Board Support Package. This step is mandatory.
RTEMS_SYSINIT_DEVICE_DRIVERS
- This step initializes all statically configured device drivers and performs all RTEMS initialization which requires device drivers to be initialized. This step is mandatory. In a multiprocessor configuration, this service will initialize the Multiprocessor Communications Interface (MPCI) and synchronize with the other nodes in the system.
RTEMS_SYSINIT_BSP_POST_DRIVERS
- Initialization step performed right after device drivers are initialized provided by the Board Support Package. This step is mandatory.
The final action of the rtems_initialize_executive
directive is to start multitasking. RTEMS does not return to the initialization context and the initialization stack may be re-used for interrupt processing.
Many of RTEMS actions during initialization are based upon the contents of the Configuration Table. For more information regarding the format and contents of this table, please refer to the chapter Chapter 24 - Configuring a System.
The final action in the initialization sequence is the initiation of multitasking. When the scheduler and dispatcher are enabled, the highest priority, ready task will be dispatched to run. Control will not be returned to the Board Support Package after multitasking is enabled. The initialization stack may be re-used for interrupt processing.
6.3.2. Shutting Down RTEMS¶
The rtems_shutdown_executive
directive is invoked by the application to end multitasking and terminate the system.
6.4. Directives¶
This section details the Initialization Manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
6.4.1. INITIALIZE_EXECUTIVE - Initialize RTEMS¶
- CALLING SEQUENCE:
void rtems_initialize_executive(void);
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- Iterates through the system initialization linker set and invokes the registered handlers. The final step is to start multitasking.
- NOTES:
This directive should be called by
boot_card
only.This directive does not return to the caller. Errors in the initialization sequence are usually fatal and lead to a system termination.
6.4.2. SHUTDOWN_EXECUTIVE - Shutdown RTEMS¶
- CALLING SEQUENCE:
void rtems_shutdown_executive( uint32_t result );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive is called when the application wishes to shutdown RTEMS. The system is terminated with a fatal source of
RTEMS_FATAL_SOURCE_EXIT
and the specifiedresult
code. - NOTES:
This directive must be the last RTEMS directive invoked by an application and it does not return to the caller.
This directive may be called any time.
7. Task Manager¶
7.1. Introduction¶
The task manager provides a comprehensive set of directives to create, delete, and administer tasks. The directives provided by the task manager are:
- rtems_task_create - Create a task
- rtems_task_ident - Get ID of a task
- rtems_task_self - Obtain ID of caller
- rtems_task_start - Start a task
- rtems_task_restart - Restart a task
- rtems_task_delete - Delete a task
- rtems_task_suspend - Suspend a task
- rtems_task_resume - Resume a task
- rtems_task_is_suspended - Determine if a task is suspended
- rtems_task_set_priority - Set task priority
- rtems_task_mode - Change current task’s mode
- rtems_task_get_note - Get task notepad entry
- rtems_task_set_note - Set task notepad entry
- rtems_task_wake_after - Wake up after interval
- rtems_task_wake_when - Wake up when specified
- rtems_iterate_over_all_threads - Iterate Over Tasks
- rtems_task_variable_add - Associate per task variable
- rtems_task_variable_get - Obtain value of a a per task variable
- rtems_task_variable_delete - Remove per task variable
7.2. Background¶
7.2.1. Task Definition¶
Many definitions of a task have been proposed in computer literature. Unfortunately, none of these definitions encompasses all facets of the concept in a manner which is operating system independent. Several of the more common definitions are provided to enable each user to select a definition which best matches their own experience and understanding of the task concept:
- a “dispatchable” unit.
- an entity to which the processor is allocated.
- an atomic unit of a real-time, multiprocessor system.
- single threads of execution which concurrently compete for resources.
- a sequence of closely related computations which can execute concurrently with other computational sequences.
From RTEMS’ perspective, a task is the smallest thread of execution which can compete on its own for system resources. A task is manifested by the existence of a task control block (TCB).
7.2.2. Task Control Block¶
The Task Control Block (TCB) is an RTEMS defined data structure which contains all the information that is pertinent to the execution of a task. During system initialization, RTEMS reserves a TCB for each task configured. A TCB is allocated upon creation of the task and is returned to the TCB free list upon deletion of the task.
The TCB’s elements are modified as a result of system calls made by the application in response to external and internal stimuli. TCBs are the only RTEMS internal data structure that can be accessed by an application via user extension routines. The TCB contains a task’s name, ID, current priority, current and starting states, execution mode, TCB user extension pointer, scheduling control structures, as well as data required by a blocked task.
A task’s context is stored in the TCB when a task switch occurs. When the task regains control of the processor, its context is restored from the TCB. When a task is restarted, the initial state of the task is restored from the starting context area in the task’s TCB.
7.2.3. Task States¶
A task may exist in one of the following five states:
- executing - Currently scheduled to the CPU
- ready - May be scheduled to the CPU
- blocked - Unable to be scheduled to the CPU
- dormant - Created task that is not started
- non-existent - Uncreated or deleted task
An active task may occupy the executing, ready, blocked or dormant state, otherwise the task is considered non-existent. One or more tasks may be active in the system simultaneously. Multiple tasks communicate, synchronize, and compete for system resources with each other via system calls. The multiple tasks appear to execute in parallel, but actually each is dispatched to the CPU for periods of time determined by the RTEMS scheduling algorithm. The scheduling of a task is based on its current state and priority.
7.2.4. Task Priority¶
A task’s priority determines its importance in relation to the other tasks executing on the same processor. RTEMS supports 255 levels of priority ranging from 1 to 255. The data type rtems_task_priority
is used to store task priorities.
Tasks of numerically smaller priority values are more important tasks than tasks of numerically larger priority values. For example, a task at priority level 5 is of higher privilege than a task at priority level 10. There is no limit to the number of tasks assigned to the same priority.
Each task has a priority associated with it at all times. The initial value of this priority is assigned at task creation time. The priority of a task may be changed at any subsequent time.
Priorities are used by the scheduler to determine which ready task will be allowed to execute. In general, the higher the logical priority of a task, the more likely it is to receive processor execution time.
7.2.5. Task Mode¶
A task’s execution mode is a combination of the following four components:
- preemption
- ASR processing
- timeslicing
- interrupt level
It is used to modify RTEMS’ scheduling process and to alter the execution environment of the task. The data type rtems_task_mode
is used to manage the task execution mode.
The preemption component allows a task to determine when control of the processor is relinquished. If preemption is disabled (RTEMS_NO_PREEMPT
), the task will retain control of the processor as long as it is in the executing state - even if a higher priority task is made ready. If preemption is enabled (RTEMS_PREEMPT
) and a higher priority task is made ready, then the processor will be taken away from the current task immediately and given to the higher priority task.
The timeslicing component is used by the RTEMS scheduler to determine how the processor is allocated to tasks of equal priority. If timeslicing is enabled (RTEMS_TIMESLICE
), then RTEMS will limit the amount of time the task can execute before the processor is allocated to another ready task of equal priority. The length of the timeslice is application dependent and specified in the Configuration Table. If timeslicing is disabled (RTEMS_NO_TIMESLICE
), then the task will be allowed to execute until a task of higher priority is made ready. If RTEMS_NO_PREEMPT
is selected, then the timeslicing component is ignored by the scheduler.
The asynchronous signal processing component is used to determine when received signals are to be processed by the task. If signal processing is enabled (RTEMS_ASR
), then signals sent to the task will be processed the next time the task executes. If signal processing is disabled (RTEMS_NO_ASR
), then all signals received by the task will remain posted until signal processing is enabled. This component affects only tasks which have established a routine to process asynchronous signals.
The interrupt level component is used to determine which interrupts will be enabled when the task is executing. RTEMS_INTERRUPT_LEVEL(n)
specifies that the task will execute at interrupt level n.
RTEMS_PREEMPT | enable preemption (default) |
RTEMS_NO_PREEMPT | disable preemption |
RTEMS_NO_TIMESLICE | disable timeslicing (default) |
RTEMS_TIMESLICE | enable timeslicing |
RTEMS_ASR | enable ASR processing (default) |
RTEMS_NO_ASR | disable ASR processing |
RTEMS_INTERRUPT_LEVEL(0) | enable all interrupts (default) |
RTEMS_INTERRUPT_LEVEL(n) | execute at interrupt level n |
The set of default modes may be selected by specifying the RTEMS_DEFAULT_MODES
constant.
7.2.6. Accessing Task Arguments¶
All RTEMS tasks are invoked with a single argument which is specified when they are started or restarted. The argument is commonly used to communicate startup information to the task. The simplest manner in which to define a task which accesses it argument is:
rtems_task user_task(
rtems_task_argument argument
);
Application tasks requiring more information may view this single argument as an index into an array of parameter blocks.
7.2.7. Floating Point Considerations¶
Creating a task with the RTEMS_FLOATING_POINT
attribute flag results in additional memory being allocated for the TCB to store the state of the numeric coprocessor during task switches. This additional memory is NOT allocated for RTEMS_NO_FLOATING_POINT
tasks. Saving and restoring the context of a RTEMS_FLOATING_POINT
task takes longer than that of a RTEMS_NO_FLOATING_POINT
task because of the relatively large amount of time required for the numeric coprocessor to save or restore its computational state.
Since RTEMS was designed specifically for embedded military applications which are floating point intensive, the executive is optimized to avoid unnecessarily saving and restoring the state of the numeric coprocessor. The state of the numeric coprocessor is only saved when a RTEMS_FLOATING_POINT
task is dispatched and that task was not the last task to utilize the coprocessor. In a system with only one RTEMS_FLOATING_POINT
task, the state of the numeric coprocessor will never be saved or restored.
Although the overhead imposed by RTEMS_FLOATING_POINT
tasks is minimal, some applications may wish to completely avoid the overhead associated with RTEMS_FLOATING_POINT
tasks and still utilize a numeric coprocessor. By preventing a task from being preempted while performing a sequence of floating point operations, a RTEMS_NO_FLOATING_POINT
task can utilize the numeric coprocessor without incurring the overhead of a RTEMS_FLOATING_POINT
context switch. This approach also avoids the allocation of a floating point context area. However, if this approach is taken by the application designer, NO tasks should be created as RTEMS_FLOATING_POINT
tasks. Otherwise, the floating point context will not be correctly maintained because RTEMS assumes that the state of the numeric coprocessor will not be altered by RTEMS_NO_FLOATING_POINT
tasks.
If the supported processor type does not have hardware floating capabilities or a standard numeric coprocessor, RTEMS will not provide built-in support for hardware floating point on that processor. In this case, all tasks are considered RTEMS_NO_FLOATING_POINT
whether created as RTEMS_FLOATING_POINT
or RTEMS_NO_FLOATING_POINT
tasks. A floating point emulation software library must be utilized for floating point operations.
On some processors, it is possible to disable the floating point unit dynamically. If this capability is supported by the target processor, then RTEMS will utilize this capability to enable the floating point unit only for tasks which are created with the RTEMS_FLOATING_POINT
attribute. The consequence of a RTEMS_NO_FLOATING_POINT
task attempting to access the floating point unit is CPU dependent but will generally result in an exception condition.
7.2.8. Per Task Variables¶
Per task variables are deprecated, see the warning below.
Per task variables are used to support global variables whose value may be unique to a task. After indicating that a variable should be treated as private (i.e. per-task) the task can access and modify the variable, but the modifications will not appear to other tasks, and other tasks’ modifications to that variable will not affect the value seen by the task. This is accomplished by saving and restoring the variable’s value each time a task switch occurs to or from the calling task.
The value seen by other tasks, including those which have not added the variable to their set and are thus accessing the variable as a common location shared among tasks, cannot be affected by a task once it has added a variable to its local set. Changes made to the variable by other tasks will not affect the value seen by a task which has added the variable to its private set.
This feature can be used when a routine is to be spawned repeatedly as several independent tasks. Although each task will have its own stack, and thus separate stack variables, they will all share the same static and global variables. To make a variable not shareable (i.e. a “global” variable that is specific to a single task), the tasks can call rtems_task_variable_add
to make a separate copy of the variable for each task, but all at the same physical address.
Task variables increase the context switch time to and from the tasks that own them so it is desirable to minimize the number of task variables. One efficient method is to have a single task variable that is a pointer to a dynamically allocated structure containing the task’s private “global” data.
A critical point with per-task variables is that each task must separately request that the same global variable is per-task private.
7.2.9. Building a Task Attribute Set¶
In general, an attribute set is built by a bitwise OR of the desired components. The set of valid task attribute components is listed below:
RTEMS_NO_FLOATING_POINT | does not use coprocessor (default) |
RTEMS_FLOATING_POINT | uses numeric coprocessor |
RTEMS_LOCAL | local task (default) |
RTEMS_GLOBAL | global task |
Attribute values are specifically designed to be mutually exclusive, therefore bitwise OR and addition operations are equivalent as long as each attribute appears exactly once in the component list. A component listed as a default is not required to appear in the component list, although it is a good programming practice to specify default components. If all defaults are desired, then RTEMS_DEFAULT_ATTRIBUTES
should be used.
This example demonstrates the attribute_set parameter needed to create a local task which utilizes the numeric coprocessor. The attribute_set parameter could be RTEMS_FLOATING_POINT
or RTEMS_LOCAL | RTEMS_FLOATING_POINT
. The attribute_set parameter can be set to RTEMS_FLOATING_POINT
because RTEMS_LOCAL
is the default for all created tasks. If the task were global and used the numeric coprocessor, then the attribute_set parameter would be RTEMS_GLOBAL | RTEMS_FLOATING_POINT
.
7.2.10. Building a Mode and Mask¶
In general, a mode and its corresponding mask is built by a bitwise OR of the desired components. The set of valid mode constants and each mode’s corresponding mask constant is listed below:
RTEMS_PREEMPT | is masked by RTEMS_PREEMPT_MASK and enables preemption |
RTEMS_NO_PREEMPT | is masked by RTEMS_PREEMPT_MASK and disables preemption |
RTEMS_NO_TIMESLICE | is masked by RTEMS_TIMESLICE_MASK and disables timeslicing |
RTEMS_TIMESLICE | is masked by RTEMS_TIMESLICE_MASK and enables timeslicing |
RTEMS_ASR | is masked by RTEMS_ASR_MASK and enables ASR processing |
RTEMS_NO_ASR | is masked by RTEMS_ASR_MASK and disables ASR processing |
RTEMS_INTERRUPT_LEVEL(0) | is masked by RTEMS_INTERRUPT_MASK and enables all interrupts |
RTEMS_INTERRUPT_LEVEL(n) | is masked by RTEMS_INTERRUPT_MASK and sets interrupts level n |
Mode values are specifically designed to be mutually exclusive, therefore bitwise OR and addition operations are equivalent as long as each mode appears exactly once in the component list. A mode component listed as a default is not required to appear in the mode component list, although it is a good programming practice to specify default components. If all defaults are desired, the mode RTEMS_DEFAULT_MODES
and the mask RTEMS_ALL_MODE_MASKS
should be used.
The following example demonstrates the mode and mask parameters used with the rtems_task_mode
directive to place a task at interrupt level 3 and make it non-preemptible. The mode should be set to RTEMS_INTERRUPT_LEVEL(3) | RTEMS_NO_PREEMPT
to indicate the desired preemption mode and interrupt level, while the mask parameter should be set to RTEMS_INTERRUPT_MASK | RTEMS_NO_PREEMPT_MASK
to indicate that the calling task’s interrupt level and preemption mode are being altered.
7.3. Operations¶
7.3.1. Creating Tasks¶
The rtems_task_create
directive creates a task by allocating a task control block, assigning the task a user-specified name, allocating it a stack and floating point context area, setting a user-specified initial priority, setting a user-specified initial mode, and assigning it a task ID. Newly created tasks are initially placed in the dormant state. All RTEMS tasks execute in the most privileged mode of the processor.
7.3.2. Obtaining Task IDs¶
When a task is created, RTEMS generates a unique task ID and assigns it to the created task until it is deleted. The task ID may be obtained by either of two methods. First, as the result of an invocation of the rtems_task_create
directive, the task ID is stored in a user provided location. Second, the task ID may be obtained later using the rtems_task_ident
directive. The task ID is used by other directives to manipulate this task.
7.3.3. Starting and Restarting Tasks¶
The rtems_task_start
directive is used to place a dormant task in the ready state. This enables the task to compete, based on its current priority, for the processor and other system resources. Any actions, such as suspension or change of priority, performed on a task prior to starting it are nullified when the task is started.
With the rtems_task_start
directive the user specifies the task’s starting address and argument. The argument is used to communicate some startup information to the task. As part of this directive, RTEMS initializes the task’s stack based upon the task’s initial execution mode and start address. The starting argument is passed to the task in accordance with the target processor’s calling convention.
The rtems_task_restart
directive restarts a task at its initial starting address with its original priority and execution mode, but with a possibly different argument. The new argument may be used to distinguish between the original invocation of the task and subsequent invocations. The task’s stack and control block are modified to reflect their original creation values. Although references to resources that have been requested are cleared, resources allocated by the task are NOT automatically returned to RTEMS. A task cannot be restarted unless it has previously been started (i.e. dormant tasks cannot be restarted). All restarted tasks are placed in the ready state.
7.3.4. Suspending and Resuming Tasks¶
The rtems_task_suspend
directive is used to place either the caller or another task into a suspended state. The task remains suspended until a rtems_task_resume
directive is issued. This implies that a task may be suspended as well as blocked waiting either to acquire a resource or for the expiration of a timer.
The rtems_task_resume
directive is used to remove another task from the suspended state. If the task is not also blocked, resuming it will place it in the ready state, allowing it to once again compete for the processor and resources. If the task was blocked as well as suspended, this directive clears the suspension and leaves the task in the blocked state.
Suspending a task which is already suspended or resuming a task which is not suspended is considered an error. The rtems_task_is_suspended
can be used to determine if a task is currently suspended.
7.3.5. Delaying the Currently Executing Task¶
The rtems_task_wake_after
directive creates a sleep timer which allows a task to go to sleep for a specified interval. The task is blocked until the delay interval has elapsed, at which time the task is unblocked. A task calling the rtems_task_wake_after
directive with a delay interval of RTEMS_YIELD_PROCESSOR
ticks will yield the processor to any other ready task of equal or greater priority and remain ready to execute.
The rtems_task_wake_when
directive creates a sleep timer which allows a task to go to sleep until a specified date and time. The calling task is blocked until the specified date and time has occurred, at which time the task is unblocked.
7.3.6. Changing Task Priority¶
The rtems_task_set_priority
directive is used to obtain or change the current priority of either the calling task or another task. If the new priority requested is RTEMS_CURRENT_PRIORITY
or the task’s actual priority, then the current priority will be returned and the task’s priority will remain unchanged. If the task’s priority is altered, then the task will be scheduled according to its new priority.
The rtems_task_restart
directive resets the priority of a task to its original value.
7.3.7. Changing Task Mode¶
The rtems_task_mode
directive is used to obtain or change the current execution mode of the calling task. A task’s execution mode is used to enable preemption, timeslicing, ASR processing, and to set the task’s interrupt level.
The rtems_task_restart
directive resets the mode of a task to its original value.
7.3.8. Notepad Locations¶
RTEMS provides sixteen notepad locations for each task. Each notepad location may contain a note consisting of four bytes of information. RTEMS provides two directives, rtems_task_set_note
and rtems_task_get_note
, that enable a user to access and change the notepad locations. The rtems_task_set_note
directive enables the user to set a task’s notepad entry to a specified note. The rtems_task_get_note
directive allows the user to obtain the note contained in any one of the sixteen notepads of a specified task.
7.3.9. Task Deletion¶
RTEMS provides the rtems_task_delete
directive to allow a task to delete itself or any other task. This directive removes all RTEMS references to the task, frees the task’s control block, removes it from resource wait queues, and deallocates its stack as well as the optional floating point context. The task’s name and ID become inactive at this time, and any subsequent references to either of them is invalid. In fact, RTEMS may reuse the task ID for another task which is created later in the application.
Unexpired delay timers (i.e. those used by rtems_task_wake_after
and rtems_task_wake_when
) and timeout timers associated with the task are automatically deleted, however, other resources dynamically allocated by the task are NOT automatically returned to RTEMS. Therefore, before a task is deleted, all of its dynamically allocated resources should be deallocated by the user. This may be accomplished by instructing the task to delete itself rather than directly deleting the task. Other tasks may instruct a task to delete itself by sending a “delete self” message, event, or signal, or by restarting the task with special arguments which instruct the task to delete itself.
7.3.10. Transition Advice for Obsolete Directives¶
7.3.10.1. Notepads¶
Task notepads and the associated directives rtems_task_get_note
and rtems_task_set_note
were removed after the 4.11 Release Series. These were never thread-safe to access and subject to conflicting use of the notepad index by libraries which were designed independently.
It is recommended that applications be modified to use services which are thread safe and not subject to issues with multiple applications conflicting over the key (e.g. notepad index) selection. For most applications, POSIX Keys should be used. These are available in all RTEMS build configurations. It is also possible that Thread Local Storage is an option for some use cases.
7.4. Directives¶
This section details the task manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
7.4.1. TASK_CREATE - Create a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_create( rtems_name name, rtems_task_priority initial_priority, size_t stack_size, rtems_mode initial_modes, rtems_attribute attribute_set, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task created successfully RTEMS_INVALID_ADDRESS
id
is NULLRTEMS_INVALID_NAME
invalid task name RTEMS_INVALID_PRIORITY
invalid task priority RTEMS_MP_NOT_CONFIGURED
multiprocessing not configured RTEMS_TOO_MANY
too many tasks created RTEMS_UNSATISFIED
not enough memory for stack/FP context RTEMS_TOO_MANY
too many global objects - DESCRIPTION:
- This directive creates a task which resides on the local node. It allocates and initializes a TCB, a stack, and an optional floating point context area. The mode parameter contains values which sets the task’s initial execution mode. The
RTEMS_FLOATING_POINT
attribute should be specified if the created task is to use a numeric coprocessor. For performance reasons, it is recommended that tasks not using the numeric coprocessor should specify theRTEMS_NO_FLOATING_POINT
attribute. If theRTEMS_GLOBAL
attribute is specified, the task can be accessed from remote nodes. The task id, returned in id, is used in other task related directives to access the task. When created, a task is placed in the dormant state and can only be made ready to execute using the directivertems_task_start
. - NOTES:
This directive will not cause the calling task to be preempted.
Valid task priorities range from a high of 1 to a low of 255.
If the requested stack size is less than the configured minimum stack size, then RTEMS will use the configured minimum as the stack size for this task. In addition to being able to specify the task stack size as a integer, there are two constants which may be specified:
RTEMS_MINIMUM_STACK_SIZE
- The minimum stack size RECOMMENDED for use on this processor. This value is selected by the RTEMS developers conservatively to minimize the risk of blown stacks for most user applications. Using this constant when specifying the task stack size, indicates that the stack size will be at least
RTEMS_MINIMUM_STACK_SIZE
bytes in size. If the user configured minimum stack size is larger than the recommended minimum, then it will be used. RTEMS_CONFIGURED_MINIMUM_STACK_SIZE
- Indicates this task is to be created with a stack size of the minimum stack size that was configured by the application. If not explicitly configured by the application, the default configured minimum stack size is the processor dependent value
RTEMS_MINIMUM_STACK_SIZE
. Since this uses the configured minimum stack size value, you may get a stack size that is smaller or larger than the recommended minimum. This can be used to provide large stacks for all tasks on complex applications or small stacks on applications that are trying to conserve memory.
Application developers should consider the stack usage of the device drivers when calculating the stack size required for tasks which utilize the driver.
The following task attribute constants are defined by RTEMS:
RTEMS_NO_FLOATING_POINT
does not use coprocessor (default) RTEMS_FLOATING_POINT
uses numeric coprocessor RTEMS_LOCAL
local task (default) RTEMS_GLOBAL
global task The following task mode constants are defined by RTEMS:
RTEMS_PREEMPT
enable preemption (default) RTEMS_NO_PREEMPT
disable preemption RTEMS_NO_TIMESLICE
disable timeslicing (default) RTEMS_TIMESLICE
enable timeslicing RTEMS_ASR
enable ASR processing (default) RTEMS_NO_ASR
disable ASR processing RTEMS_INTERRUPT_LEVEL(0)
enable all interrupts (default) RTEMS_INTERRUPT_LEVEL(n)
execute at interrupt level n
The interrupt level portion of the task execution mode supports a maximum of 256 interrupt levels. These levels are mapped onto the interrupt levels actually supported by the target processor in a processor dependent fashion.
Tasks should not be made global unless remote tasks must interact with them. This avoids the system overhead incurred by the creation of a global task. When a global task is created, the task’s name and id must be transmitted to every node in the system for insertion in the local copy of the global object table.
The total number of global objects, including tasks, is limited by the maximum_global_objects field in the Configuration Table.
7.4.2. TASK_IDENT - Get ID of a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_ident( rtems_name name, uint32_t node, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task identified successfully RTEMS_INVALID_ADDRESS
id
is NULLRTEMS_INVALID_NAME
invalid task name RTEMS_INVALID_NODE
invalid node id - DESCRIPTION:
- This directive obtains the task id associated with the task name specified in name. A task may obtain its own id by specifying
RTEMS_SELF
or its own task name in name. If the task name is not unique, then the task id returned will match one of the tasks with that name. However, this task id is not guaranteed to correspond to the desired task. The task id, returned in id, is used in other task related directives to access the task. - NOTES:
This directive will not cause the running task to be preempted.
If node is
RTEMS_SEARCH_ALL_NODES
, all nodes are searched with the local node being searched first. All other nodes are searched with the lowest numbered node searched first.If node is a valid node number which does not represent the local node, then only the tasks exported by the designated node are searched.
This directive does not generate activity on remote nodes. It accesses only the local copy of the global object table.
7.4.3. TASK_SELF - Obtain ID of caller¶
- CALLING SEQUENCE:
rtems_id rtems_task_self(void);
- DIRECTIVE STATUS CODES:
- Returns the object Id of the calling task.
- DESCRIPTION:
- This directive returns the Id of the calling task.
- NOTES:
- If called from an interrupt service routine, this directive will return the Id of the interrupted task.
7.4.4. TASK_START - Start a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_start( rtems_id id, rtems_task_entry entry_point, rtems_task_argument argument );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
ask started successfully RTEMS_INVALID_ADDRESS
invalid task entry point RTEMS_INVALID_ID
invalid task id RTEMS_INCORRECT_STATE
task not in the dormant state RTEMS_ILLEGAL_ON_REMOTE_OBJECT
cannot start remote task - DESCRIPTION:
- This directive readies the task, specified by
id
, for execution based on the priority and execution mode specified when the task was created. The starting address of the task is given inentry_point
. The task’s starting argument is contained in argument. This argument can be a single value or used as an index into an array of parameter blocks. The type of this numeric argument is an unsigned integer type with the property that any valid pointer to void can be converted to this type and then converted back to a pointer to void. The result will compare equal to the original pointer. - NOTES:
The calling task will be preempted if its preemption mode is enabled and the task being started has a higher priority.
Any actions performed on a dormant task such as suspension or change of priority are nullified when the task is initiated via the
rtems_task_start
directive.
7.4.5. TASK_RESTART - Restart a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_restart( rtems_id id, rtems_task_argument argument );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task restarted successfully RTEMS_INVALID_ID
task id invalid RTEMS_INCORRECT_STATE
task never started RTEMS_ILLEGAL_ON_REMOTE_OBJECT
cannot restart remote task - DESCRIPTION:
This directive resets the task specified by id to begin execution at its original starting address. The task’s priority and execution mode are set to the original creation values. If the task is currently blocked, RTEMS automatically makes the task ready. A task can be restarted from any state, except the dormant state.
The task’s starting argument is contained in argument. This argument can be a single value or an index into an array of parameter blocks. The type of this numeric argument is an unsigned integer type with the property that any valid pointer to void can be converted to this type and then converted back to a pointer to void. The result will compare equal to the original pointer. This new argument may be used to distinguish between the initial
rtems_task_start
of the task and any ensuing calls tortems_task_restart
of the task. This can be beneficial in deleting a task. Instead of deleting a task using thertems_task_delete
directive, a task can delete another task by restarting that task, and allowing that task to release resources back to RTEMS and then delete itself.- NOTES:
If id is
RTEMS_SELF
, the calling task will be restarted and will not return from this directive.The calling task will be preempted if its preemption mode is enabled and the task being restarted has a higher priority.
The task must reside on the local node, even if the task was created with the
RTEMS_GLOBAL
option.
7.4.6. TASK_DELETE - Delete a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_delete( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task deleted successfully RTEMS_INVALID_ID
task id invalid RTEMS_ILLEGAL_ON_REMOTE_OBJECT
cannot restart remote task - DESCRIPTION:
- This directive deletes a task, either the calling task or another task, as specified by id. RTEMS stops the execution of the task and reclaims the stack memory, any allocated delay or timeout timers, the TCB, and, if the task is
RTEMS_FLOATING_POINT
, its floating point context area. RTEMS does not reclaim the following resources: region segments, partition buffers, semaphores, timers, or rate monotonic periods. - NOTES:
A task is responsible for releasing its resources back to RTEMS before deletion. To insure proper deallocation of resources, a task should not be deleted unless it is unable to execute or does not hold any RTEMS resources. If a task holds RTEMS resources, the task should be allowed to deallocate its resources before deletion. A task can be directed to release its resources and delete itself by restarting it with a special argument or by sending it a message, an event, or a signal.
Deletion of the current task (
RTEMS_SELF
) will force RTEMS to select another task to execute.When a global task is deleted, the task id must be transmitted to every node in the system for deletion from the local copy of the global object table.
The task must reside on the local node, even if the task was created with the
RTEMS_GLOBAL
option.
7.4.7. TASK_SUSPEND - Suspend a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_suspend( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task suspended successfully RTEMS_INVALID_ID
task id invalid RTEMS_ALREADY_SUSPENDED
task already suspended - DESCRIPTION:
- This directive suspends the task specified by id from further execution by placing it in the suspended state. This state is additive to any other blocked state that the task may already be in. The task will not execute again until another task issues the
rtems_task_resume
directive for this task and any blocked state has been removed. - NOTES:
The requesting task can suspend itself by specifying
RTEMS_SELF
as id. In this case, the task will be suspended and a successful return code will be returned when the task is resumed.Suspending a global task which does not reside on the local node will generate a request to the remote node to suspend the specified task.
If the task specified by id is already suspended, then the
RTEMS_ALREADY_SUSPENDED
status code is returned.
7.4.8. TASK_RESUME - Resume a task¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_resume( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task resumed successfully RTEMS_INVALID_ID
task id invalid RTEMS_INCORRECT_STATE
task not suspended - DESCRIPTION:
- This directive removes the task specified by id from the suspended state. If the task is in the ready state after the suspension is removed, then it will be scheduled to run. If the task is still in a blocked state after the suspension is removed, then it will remain in that blocked state.
- NOTES:
The running task may be preempted if its preemption mode is enabled and the local task being resumed has a higher priority.
Resuming a global task which does not reside on the local node will generate a request to the remote node to resume the specified task.
If the task specified by id is not suspended, then the
RTEMS_INCORRECT_STATE
status code is returned.
7.4.9. TASK_IS_SUSPENDED - Determine if a task is Suspended¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_is_suspended( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task is NOT suspended RTEMS_ALREADY_SUSPENDED
task is currently suspended RTEMS_INVALID_ID
task id invalid RTEMS_ILLEGAL_ON_REMOTE_OBJECT
not supported on remote tasks - DESCRIPTION:
- This directive returns a status code indicating whether or not the specified task is currently suspended.
- NOTES:
- This operation is not currently supported on remote tasks.
7.4.10. TASK_SET_PRIORITY - Set task priority¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_set_priority( rtems_id id, rtems_task_priority new_priority, rtems_task_priority *old_priority );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task priority set successfully RTEMS_INVALID_ID
invalid task id RTEMS_INVALID_ADDRESS
invalid return argument pointer RTEMS_INVALID_PRIORITY
invalid task priority - DESCRIPTION:
- This directive manipulates the priority of the task specified by id. An id of
RTEMS_SELF
is used to indicate the calling task. When new_priority is not equal toRTEMS_CURRENT_PRIORITY
, the specified task’s previous priority is returned in old_priority. When new_priority isRTEMS_CURRENT_PRIORITY
, the specified task’s current priority is returned in old_priority. Valid priorities range from a high of 1 to a low of 255. - NOTES:
The calling task may be preempted if its preemption mode is enabled and it lowers its own priority or raises another task’s priority.
In case the new priority equals the current priority of the task, then nothing happens.
Setting the priority of a global task which does not reside on the local node will generate a request to the remote node to change the priority of the specified task.
If the task specified by id is currently holding any binary semaphores which use the priority inheritance algorithm, then the task’s priority cannot be lowered immediately. If the task’s priority were lowered immediately, then priority inversion results. The requested lowering of the task’s priority will occur when the task has released all priority inheritance binary semaphores. The task’s priority can be increased regardless of the task’s use of priority inheritance binary semaphores.
7.4.11. TASK_MODE - Change the current task mode¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_mode( rtems_mode mode_set, rtems_mode mask, rtems_mode *previous_mode_set );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
task mode set successfully RTEMS_INVALID_ADDRESS
previous_mode_set
is NULL- DESCRIPTION:
- This directive manipulates the execution mode of the calling task. A task’s execution mode enables and disables preemption, timeslicing, asynchronous signal processing, as well as specifying the current interrupt level. To modify an execution mode, the mode class(es) to be changed must be specified in the mask parameter and the desired mode(s) must be specified in the mode parameter.
- NOTES:
The calling task will be preempted if it enables preemption and a higher priority task is ready to run.
Enabling timeslicing has no effect if preemption is disabled. For a task to be timesliced, that task must have both preemption and timeslicing enabled.
A task can obtain its current execution mode, without modifying it, by calling this directive with a mask value of
RTEMS_CURRENT_MODE
.To temporarily disable the processing of a valid ASR, a task should call this directive with the
RTEMS_NO_ASR
indicator specified in mode.The set of task mode constants and each mode’s corresponding mask constant is provided in the following table:
RTEMS_PREEMPT
is masked by RTEMS_PREEMPT_MASK
and enables preemptionRTEMS_NO_PREEMPT
is masked by RTEMS_PREEMPT_MASK
and disables preemptionRTEMS_NO_TIMESLICE
is masked by RTEMS_TIMESLICE_MASK
and disables timeslicingRTEMS_TIMESLICE
is masked by RTEMS_TIMESLICE_MASK
and enables timeslicingRTEMS_ASR
is masked by RTEMS_ASR_MASK
and enables ASR processingRTEMS_NO_ASR
is masked by RTEMS_ASR_MASK
and disables ASR processingRTEMS_INTERRUPT_LEVEL(0)
is masked by RTEMS_INTERRUPT_MASK
and enables all interruptsRTEMS_INTERRUPT_LEVEL(n)
is masked by RTEMS_INTERRUPT_MASK
and sets interrupts level n
7.4.12. TASK_GET_NOTE - Get task notepad entry¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_get_note( rtems_id id, uint32_t notepad, uint32_t *note );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
note value obtained successfully RTEMS_INVALID_ADDRESS
note
parameter is NULLRTEMS_INVALID_ID
invalid task id RTEMS_INVALID_NUMBER
invalid notepad location - DESCRIPTION:
- This directive returns the note contained in the notepad location of the task specified by id.
- NOTES:
This directive will not cause the running task to be preempted.
If id is set to
RTEMS_SELF
, the calling task accesses its own notepad.The sixteen notepad locations can be accessed using the constants
RTEMS_NOTEPAD_0
throughRTEMS_NOTEPAD_15
.Getting a note of a global task which does not reside on the local node will generate a request to the remote node to obtain the notepad entry of the specified task.
7.4.13. TASK_SET_NOTE - Set task notepad entry¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_set_note( rtems_id id, uint32_t notepad, uint32_t note );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
note set successfully RTEMS_INVALID_ID
invalid task id RTEMS_INVALID_NUMBER
invalid notepad location - DESCRIPTION:
- This directive sets the notepad entry for the task specified by id to the value note.
- NOTES:
If
id
is set toRTEMS_SELF
, the calling task accesses its own notepad.This directive will not cause the running task to be preempted.
The sixteen notepad locations can be accessed using the constants
RTEMS_NOTEPAD_0
throughRTEMS_NOTEPAD_15
.Setting a note of a global task which does not reside on the local node will generate a request to the remote node to set the notepad entry of the specified task.
7.4.14. TASK_WAKE_AFTER - Wake up after interval¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_wake_after( rtems_interval ticks );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
always successful - DESCRIPTION:
- This directive blocks the calling task for the specified number of system clock ticks. When the requested interval has elapsed, the task is made ready. The clock tick directives automatically updates the delay period.
- NOTES:
Setting the system date and time with the
rtems_clock_set
directive has no effect on artems_task_wake_after
blocked task.A task may give up the processor and remain in the ready state by specifying a value of
RTEMS_YIELD_PROCESSOR
in ticks.The maximum timer interval that can be specified is the maximum value which can be represented by the uint32_t type.
A clock tick is required to support the functionality of this directive.
7.4.15. TASK_WAKE_WHEN - Wake up when specified¶
- CALLING SEQUENCE:
rtems_status_code rtems_task_wake_when( rtems_time_of_day *time_buffer );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
awakened at date/time successfully RTEMS_INVALID_ADDRESS
time_buffer
is NULLRTEMS_INVALID_TIME_OF_DAY
invalid time buffer RTEMS_NOT_DEFINED
system date and time is not set - DESCRIPTION:
- This directive blocks a task until the date and time specified in time_buffer. At the requested date and time, the calling task will be unblocked and made ready to execute.
- NOTES:
The ticks portion of time_buffer structure is ignored. The timing granularity of this directive is a second.
A clock tick is required to support the functionality of this directive.
7.4.16. ITERATE_OVER_ALL_THREADS - Iterate Over Tasks¶
- CALLING SEQUENCE:
typedef void (*rtems_per_thread_routine)(Thread_Control *the_thread); void rtems_iterate_over_all_threads( rtems_per_thread_routine routine );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
This directive iterates over all of the existant threads in the system and invokes
routine
on each of them. The user should be careful in accessing the contents ofthe_thread
.This routine is intended for use in diagnostic utilities and is not intented for routine use in an operational system.
- NOTES:
- There is NO protection while this routine is called. Thus it is possible that
the_thread
could be deleted while this is operating. By not having protection, the user is free to invoke support routines from the C Library which require semaphores for data structures.
7.4.17. TASK_VARIABLE_ADD - Associate per task variable¶
Warning
This directive is deprecated and task variables will be removed.
- CALLING SEQUENCE:
rtems_status_code rtems_task_variable_add( rtems_id tid, void **task_variable, void (*dtor)(void *) );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
per task variable added successfully RTEMS_INVALID_ADDRESS
task_variable
is NULLRTEMS_INVALID_ID
invalid task id RTEMS_NO_MEMORY
invalid task id RTEMS_ILLEGAL_ON_REMOTE_OBJECT
not supported on remote tasks - DESCRIPTION:
- This directive adds the memory location specified by the ptr argument to the context of the given task. The variable will then be private to the task. The task can access and modify the variable, but the modifications will not appear to other tasks, and other tasks’ modifications to that variable will not affect the value seen by the task. This is accomplished by saving and restoring the variable’s value each time a task switch occurs to or from the calling task. If the dtor argument is non-NULL it specifies the address of a ‘destructor’ function which will be called when the task is deleted. The argument passed to the destructor function is the task’s value of the variable.
- NOTES:
Task variables increase the context switch time to and from the tasks that own them so it is desirable to minimize the number of task variables. One efficient method is to have a single task variable that is a pointer to a dynamically allocated structure containing the task’s private ‘global’ data. In this case the destructor function could be ‘free’.
Per-task variables are disabled in SMP configurations and this service is not available.
7.4.18. TASK_VARIABLE_GET - Obtain value of a per task variable¶
Warning
This directive is deprecated and task variables will be removed.
- CALLING SEQUENCE:
rtems_status_code rtems_task_variable_get( rtems_id tid, void **task_variable, void **task_variable_value );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
per task variable obtained successfully RTEMS_INVALID_ADDRESS
task_variable
is NULLRTEMS_INVALID_ADDRESS
task_variable_value
is NULLRTEMS_INVALID_ADDRESS
task_variable
is not foundRTEMS_NO_MEMORY
invalid task id RTEMS_ILLEGAL_ON_REMOTE_OBJECT
not supported on remote tasks - DESCRIPTION:
- This directive looks up the private value of a task variable for a specified task and stores that value in the location pointed to by the result argument. The specified task is usually not the calling task, which can get its private value by directly accessing the variable.
- NOTES:
If you change memory which
task_variable_value
points to, remember to declare that memory as volatile, so that the compiler will optimize it correctly. In this case both the pointertask_variable_value
and data referenced bytask_variable_value
should be considered volatile.Per-task variables are disabled in SMP configurations and this service is not available.
7.4.19. TASK_VARIABLE_DELETE - Remove per task variable¶
Warning
This directive is deprecated and task variables will be removed.
- CALLING SEQUENCE:
rtems_status_code rtems_task_variable_delete( rtems_id id, void **task_variable );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
per task variable deleted successfully RTEMS_INVALID_ID
invalid task id RTEMS_NO_MEMORY
invalid task id RTEMS_INVALID_ADDRESS
task_variable
is NULLRTEMS_ILLEGAL_ON_REMOTE_OBJECT
not supported on remote tasks - DESCRIPTION:
- This directive removes the given location from a task’s context.
- NOTES:
- Per-task variables are disabled in SMP configurations and this service is not available.
8. Interrupt Manager¶
8.1. Introduction¶
Any real-time executive must provide a mechanism for quick response to externally generated interrupts to satisfy the critical time constraints of the application. The interrupt manager provides this mechanism for RTEMS. This manager permits quick interrupt response times by providing the critical ability to alter task execution which allows a task to be preempted upon exit from an ISR. The interrupt manager includes the following directive:
- rtems_interrupt_catch - Establish an ISR
- rtems_interrupt_disable - Disable Interrupts
- rtems_interrupt_enable - Enable Interrupts
- rtems_interrupt_flash - Flash Interrupt
- rtems_interrupt_local_disable - Disable Interrupts on Current Processor
- rtems_interrupt_local_enable - Enable Interrupts on Current Processor
- rtems_interrupt_lock_initialize - Initialize an ISR Lock
- rtems_interrupt_lock_acquire - Acquire an ISR Lock
- rtems_interrupt_lock_release - Release an ISR Lock
- rtems_interrupt_lock_acquire_isr - Acquire an ISR Lock from ISR
- rtems_interrupt_lock_release_isr - Release an ISR Lock from ISR
- rtems_interrupt_is_in_progress - Is an ISR in Progress
8.2. Background¶
8.2.1. Processing an Interrupt¶
The interrupt manager allows the application to connect a function to a hardware interrupt vector. When an interrupt occurs, the processor will automatically vector to RTEMS. RTEMS saves and restores all registers which are not preserved by the normal C calling convention for the target processor and invokes the user’s ISR. The user’s ISR is responsible for processing the interrupt, clearing the interrupt if necessary, and device specific manipulation.
The rtems_interrupt_catch
directive connects a procedure to an interrupt vector. The vector number is managed using the rtems_vector_number
data type.
The interrupt service routine is assumed to abide by these conventions and have a prototype similar to the following:
rtems_isr user_isr(
rtems_vector_number vector
);
The vector number argument is provided by RTEMS to allow the application to identify the interrupt source. This could be used to allow a single routine to service interrupts from multiple instances of the same device. For example, a single routine could service interrupts from multiple serial ports and use the vector number to identify which port requires servicing.
To minimize the masking of lower or equal priority level interrupts, the ISR should perform the minimum actions required to service the interrupt. Other non-essential actions should be handled by application tasks. Once the user’s ISR has completed, it returns control to the RTEMS interrupt manager which will perform task dispatching and restore the registers saved before the ISR was invoked.
The RTEMS interrupt manager guarantees that proper task scheduling and dispatching are performed at the conclusion of an ISR. A system call made by the ISR may have readied a task of higher priority than the interrupted task. Therefore, when the ISR completes, the postponed dispatch processing must be performed. No dispatch processing is performed as part of directives which have been invoked by an ISR.
Applications must adhere to the following rule if proper task scheduling and dispatching is to be performed:
Note
The interrupt manager must be used for all ISRs which may be interrupted by the highest priority ISR which invokes an RTEMS directive.
Consider a processor which allows a numerically low interrupt level to interrupt a numerically greater interrupt level. In this example, if an RTEMS directive is used in a level 4 ISR, then all ISRs which execute at levels 0 through 4 must use the interrupt manager.
Interrupts are nested whenever an interrupt occurs during the execution of another ISR. RTEMS supports efficient interrupt nesting by allowing the nested ISRs to terminate without performing any dispatch processing. Only when the outermost ISR terminates will the postponed dispatching occur.
8.2.2. RTEMS Interrupt Levels¶
Many processors support multiple interrupt levels or priorities. The exact number of interrupt levels is processor dependent. RTEMS internally supports 256 interrupt levels which are mapped to the processor’s interrupt levels. For specific information on the mapping between RTEMS and the target processor’s interrupt levels, refer to the Interrupt Processing chapter of the Applications Supplement document for a specific target processor.
8.2.3. Disabling of Interrupts by RTEMS¶
During the execution of directive calls, critical sections of code may be executed. When these sections are encountered, RTEMS disables all maskable interrupts before the execution of the section and restores them to the previous level upon completion of the section. RTEMS has been optimized to ensure that interrupts are disabled for a minimum length of time. The maximum length of time interrupts are disabled by RTEMS is processor dependent and is detailed in the Timing Specification chapter of the Applications Supplement document for a specific target processor.
Non-maskable interrupts (NMI) cannot be disabled, and ISRs which execute at this level MUST NEVER issue RTEMS system calls. If a directive is invoked, unpredictable results may occur due to the inability of RTEMS to protect its critical sections. However, ISRs that make no system calls may safely execute as non-maskable interrupts.
8.3. Operations¶
8.3.1. Establishing an ISR¶
The rtems_interrupt_catch
directive establishes an ISR for the system. The address of the ISR and its associated CPU vector number are specified to this directive. This directive installs the RTEMS interrupt wrapper in the processor’s Interrupt Vector Table and the address of the user’s ISR in the RTEMS’ Vector Table. This directive returns the previous contents of the specified vector in the RTEMS’ Vector Table.
8.3.2. Directives Allowed from an ISR¶
Using the interrupt manager ensures that RTEMS knows when a directive is being called from an ISR. The ISR may then use system calls to synchronize itself with an application task. The synchronization may involve messages, events or signals being passed by the ISR to the desired task. Directives invoked by an ISR must operate only on objects which reside on the local node. The following is a list of RTEMS system calls that may be made from an ISR:
- Task Management Although it is acceptable to operate on the RTEMS_SELF task (e.g. the currently executing task), while in an ISR, this will refer to the interrupted task. Most of the time, it is an application implementation error to use RTEMS_SELF from an ISR.
- rtems_task_suspend
- rtems_task_resume
- Interrupt Management
- rtems_interrupt_enable
- rtems_interrupt_disable
- rtems_interrupt_flash
- rtems_interrupt_lock_acquire
- rtems_interrupt_lock_release
- rtems_interrupt_lock_acquire_isr
- rtems_interrupt_lock_release_isr
- rtems_interrupt_is_in_progress
- rtems_interrupt_catch
- Clock Management
- rtems_clock_set
- rtems_clock_get
- rtems_clock_get_tod
- rtems_clock_get_tod_timeval
- rtems_clock_get_seconds_since_epoch
- rtems_clock_get_ticks_per_second
- rtems_clock_get_ticks_since_boot
- rtems_clock_get_uptime
- rtems_timecounter_tick
- rtems_timecounter_simple_downcounter_tick
- rtems_timecounter_simple_upcounter_tick
- Timer Management
- rtems_timer_cancel
- rtems_timer_reset
- rtems_timer_fire_after
- rtems_timer_fire_when
- rtems_timer_server_fire_after
- rtems_timer_server_fire_when
- Event Management
- rtems_event_send
- rtems_event_system_send
- rtems_event_transient_send
- Semaphore Management
- rtems_semaphore_release
- Message Management
- rtems_message_queue_send
- rtems_message_queue_urgent
- Signal Management
- rtems_signal_send
- Dual-Ported Memory Management
- rtems_port_external_to_internal
- rtems_port_internal_to_external
- IO Management The following services are safe to call from an ISR if and only if the device driver service invoked is also safe. The IO Manager itself is safe but the invoked driver entry point may or may not be.
- rtems_io_initialize
- rtems_io_open
- rtems_io_close
- rtems_io_read
- rtems_io_write
- rtems_io_control
- Fatal Error Management
- rtems_fatal
- rtems_fatal_error_occurred
- Multiprocessing
- rtems_multiprocessing_announce
8.4. Directives¶
This section details the interrupt manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
8.4.1. INTERRUPT_CATCH - Establish an ISR¶
- CALLING SEQUENCE:
rtems_status_code rtems_interrupt_catch( rtems_isr_entry new_isr_handler, rtems_vector_number vector, rtems_isr_entry *old_isr_handler );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
ISR established successfully RTEMS_INVALID_NUMBER
illegal vector number RTEMS_INVALID_ADDRESS
illegal ISR entry point or invalid old_isr_handler
- DESCRIPTION:
This directive establishes an interrupt service routine (ISR) for the specified interrupt vector number. The
new_isr_handler
parameter specifies the entry point of the ISR. The entry point of the previous ISR for the specified vector is returned inold_isr_handler
.To release an interrupt vector, pass the old handler’s address obtained when the vector was first capture.
- NOTES:
- This directive will not cause the calling task to be preempted.
8.4.2. INTERRUPT_DISABLE - Disable Interrupts¶
- CALLING SEQUENCE:
void rtems_interrupt_disable( rtems_interrupt_level level );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive disables all maskable interrupts and returns the previous
level
. A later invocation of thertems_interrupt_enable
directive should be used to restore the interrupt level.
- NOTES:
This directive will not cause the calling task to be preempted.
This directive is only available on uni-processor configurations. The directive
rtems_interrupt_local_disable
is available on all configurations.
8.4.3. INTERRUPT_ENABLE - Enable Interrupts¶
- CALLING SEQUENCE:
void rtems_interrupt_enable( rtems_interrupt_level level );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive enables maskable interrupts to the
level
which was returned by a previous call tortems_interrupt_disable
. Immediately prior to invoking this directive, maskable interrupts should be disabled by a call tortems_interrupt_disable
and will be enabled when this directive returns to the caller. - NOTES:
This directive will not cause the calling task to be preempted.
This directive is only available on uni-processor configurations. The directive
rtems_interrupt_local_enable
is available on all configurations.
8.4.4. INTERRUPT_FLASH - Flash Interrupts¶
- CALLING SEQUENCE:
void rtems_interrupt_flash( rtems_interrupt_level level );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive temporarily enables maskable interrupts to the
level
which was returned by a previous call tortems_interrupt_disable
. Immediately prior to invoking this directive, maskable interrupts should be disabled by a call tortems_interrupt_disable
and will be redisabled when this directive returns to the caller. - NOTES:
This directive will not cause the calling task to be preempted.
This directive is only available on uni-processor configurations. The directives
rtems_interrupt_local_disable
andrtems_interrupt_local_enable
is available on all configurations.
8.4.5. INTERRUPT_LOCAL_DISABLE - Disable Interrupts on Current Processor¶
- CALLING SEQUENCE:
void rtems_interrupt_local_disable( rtems_interrupt_level level );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive disables all maskable interrupts and returns the previous
level
. A later invocation of thertems_interrupt_local_enable
directive should be used to restore the interrupt level.
- NOTES:
This directive will not cause the calling task to be preempted.
On SMP configurations this will not ensure system wide mutual exclusion. Use interrupt locks instead.
8.4.6. INTERRUPT_LOCAL_ENABLE - Enable Interrupts on Current Processor¶
- CALLING SEQUENCE:
void rtems_interrupt_local_enable( rtems_interrupt_level level );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive enables maskable interrupts to the
level
which was returned by a previous call tortems_interrupt_local_disable
. Immediately prior to invoking this directive, maskable interrupts should be disabled by a call tortems_interrupt_local_disable
and will be enabled when this directive returns to the caller. - NOTES:
- This directive will not cause the calling task to be preempted.
8.4.7. INTERRUPT_LOCK_INITIALIZE - Initialize an ISR Lock¶
- CALLING SEQUENCE:
void rtems_interrupt_lock_initialize( rtems_interrupt_lock *lock, const char *name );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- Initializes an interrupt lock. The name must be persistent throughout the lifetime of the lock.
- NOTES:
- Concurrent initialization leads to unpredictable results.
8.4.8. INTERRUPT_LOCK_ACQUIRE - Acquire an ISR Lock¶
- CALLING SEQUENCE:
void rtems_interrupt_lock_acquire( rtems_interrupt_lock *lock, rtems_interrupt_lock_context *lock_context );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- Interrupts will be disabled. On SMP configurations this directive acquires a SMP lock.
- NOTES:
A separate lock context must be provided for each acquire/release pair, for example an automatic variable.
An attempt to recursively acquire the lock may result in an infinite loop with interrupts disabled.
This directive will not cause the calling thread to be preempted. This directive can be used in thread and interrupt context.
8.4.9. INTERRUPT_LOCK_RELEASE - Release an ISR Lock¶
- CALLING SEQUENCE:
void rtems_interrupt_lock_release( rtems_interrupt_lock *lock, rtems_interrupt_lock_context *lock_context );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- The interrupt status will be restored. On SMP configurations this directive releases a SMP lock.
- NOTES:
The lock context must be the one used to acquire the lock, otherwise the result is unpredictable.
This directive will not cause the calling thread to be preempted. This directive can be used in thread and interrupt context.
8.4.10. INTERRUPT_LOCK_ACQUIRE_ISR - Acquire an ISR Lock from ISR¶
- CALLING SEQUENCE:
void rtems_interrupt_lock_acquire_isr( rtems_interrupt_lock *lock, rtems_interrupt_lock_context *lock_context );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- The interrupt status will remain unchanged. On SMP configurations this directive acquires a SMP lock.
- NOTES:
A separate lock context must be provided for each acquire/release pair, for example an automatic variable.
An attempt to recursively acquire the lock may result in an infinite loop.
This directive is intended for device drivers and should be called from the corresponding interrupt service routine.
In case the corresponding interrupt service routine can be interrupted by higher priority interrupts and these interrupts enter the critical section protected by this lock, then the result is unpredictable.
8.4.11. INTERRUPT_LOCK_RELEASE_ISR - Release an ISR Lock from ISR¶
- CALLING SEQUENCE:
void rtems_interrupt_lock_release_isr( rtems_interrupt_lock *lock, rtems_interrupt_lock_context *lock_context );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- The interrupt status will remain unchanged. In SMP configurations, this directive releases an SMP lock.
- NOTES:
The lock context must be the one used to acquire the lock, otherwise the result is unpredictable.
This directive is intended for device drivers and should be called from the corresponding interrupt service routine.
8.4.12. INTERRUPT_IS_IN_PROGRESS - Is an ISR in Progress¶
- CALLING SEQUENCE:
bool rtems_interrupt_is_in_progress(void);
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive returns
TRUE
if the processor is currently servicing an interrupt andFALSE
otherwise. A return value ofTRUE
indicates that the caller is an interrupt service routine, NOT a task. The directives available to an interrupt service routine are restricted. - NOTES:
- This directive will not cause the calling task to be preempted.
9. Clock Manager¶
9.1. Introduction¶
The clock manager provides support for time of day and other time related capabilities. The directives provided by the clock manager are:
- rtems_clock_set - Set date and time
- rtems_clock_get - Get date and time information
- rtems_clock_get_tod - Get date and time in TOD format
- rtems_clock_get_tod_timeval - Get date and time in timeval format
- rtems_clock_get_seconds_since_epoch - Get seconds since epoch
- rtems_clock_get_ticks_per_second - Get ticks per second
- rtems_clock_get_ticks_since_boot - Get current ticks counter value
- rtems_clock_tick_later - Get tick value in the future
- rtems_clock_tick_later_usec - Get tick value in the future in microseconds
- rtems_clock_tick_before - Is tick value is before a point in time
- rtems_clock_get_uptime - Get time since boot
- rtems_clock_get_uptime_timeval - Get time since boot in timeval format
- rtems_clock_get_uptime_seconds - Get seconds since boot
- rtems_clock_get_uptime_nanoseconds - Get nanoseconds since boot
9.2. Background¶
9.2.1. Required Support¶
For the features provided by the clock manager to be utilized, periodic timer interrupts are required. Therefore, a real-time clock or hardware timer is necessary to create the timer interrupts. The clock tick directive is normally called by the timer ISR to announce to RTEMS that a system clock tick has occurred. Elapsed time is measured in ticks. A tick is defined to be an integral number of microseconds which is specified by the user in the Configuration Table.
9.2.2. Time and Date Data Structures¶
The clock facilities of the clock manager operate upon calendar time. These directives utilize the following date and time structure for the native time and date format:
struct rtems_tod_control {
uint32_t year; /* greater than 1987 */
uint32_t month; /* 1 - 12 */
uint32_t day; /* 1 - 31 */
uint32_t hour; /* 0 - 23 */
uint32_t minute; /* 0 - 59 */
uint32_t second; /* 0 - 59 */
uint32_t ticks; /* elapsed between seconds */
};
typedef struct rtems_tod_control rtems_time_of_day;
The native date and time format is the only format supported when setting the system date and time using the rtems_clock_set
directive. Some applications expect to operate on a UNIX-style date and time data structure. The rtems_clock_get_tod_timeval
always returns the date and time in struct timeval
format. The rtems_clock_get
directive can optionally return the current date and time in this format.
The struct timeval
data structure has two fields: tv_sec
and tv_usec
which are seconds and microseconds, respectively. The tv_sec
field in this data structure is the number of seconds since the POSIX epoch of January 1, 1970 but will never be prior to the RTEMS epoch of January 1, 1988.
9.2.3. Clock Tick and Timeslicing¶
Timeslicing is a task scheduling discipline in which tasks of equal priority are executed for a specific period of time before control of the CPU is passed to another task. It is also sometimes referred to as the automatic round-robin scheduling algorithm. The length of time allocated to each task is known as the quantum or timeslice.
The system’s timeslice is defined as an integral number of ticks, and is specified in the Configuration Table. The timeslice is defined for the entire system of tasks, but timeslicing is enabled and disabled on a per task basis.
The clock tick directives implement timeslicing by decrementing the running task’s time-remaining counter when both timeslicing and preemption are enabled. If the task’s timeslice has expired, then that task will be preempted if there exists a ready task of equal priority.
9.2.4. Delays¶
A sleep timer allows a task to delay for a given interval or up until a given time, and then wake and continue execution. This type of timer is created automatically by the rtems_task_wake_after
and rtems_task_wake_when
directives and, as a result, does not have an RTEMS ID. Once activated, a sleep timer cannot be explicitly deleted. Each task may activate one and only one sleep timer at a time.
9.2.5. Timeouts¶
Timeouts are a special type of timer automatically created when the timeout option is used on the rtems_message_queue_receive
, rtems_event_receive
, rtems_semaphore_obtain
and rtems_region_get_segment
directives. Each task may have one and only one timeout active at a time. When a timeout expires, it unblocks the task with a timeout status code.
9.3. Operations¶
9.3.1. Announcing a Tick¶
RTEMS provides the several clock tick directives which are called from the user’s real-time clock ISR to inform RTEMS that a tick has elapsed. Depending on the timer hardware capabilities the clock driver must choose the most appropriate clock tick directive. The tick frequency value, defined in microseconds, is a configuration parameter found in the Configuration Table. RTEMS divides one million microseconds (one second) by the number of microseconds per tick to determine the number of calls to the clock tick directive per second. The frequency of clock tick calls determines the resolution (granularity) for all time dependent RTEMS actions. For example, calling the clock tick directive ten times per second yields a higher resolution than calling the clock tick two times per second. The clock tick directives are responsible for maintaining both calendar time and the dynamic set of timers.
9.3.2. Setting the Time¶
The rtems_clock_set
directive allows a task or an ISR to set the date and time maintained by RTEMS. If setting the date and time causes any outstanding timers to pass their deadline, then the expired timers will be fired during the invocation of the rtems_clock_set
directive.
9.3.3. Obtaining the Time¶
The rtems_clock_get
directive allows a task or an ISR to obtain the current date and time or date and time related information. The current date and time can be returned in either native or UNIX-style format. Additionally, the application can obtain date and time related information such as the number of seconds since the RTEMS epoch, the number of ticks since the executive was initialized, and the number of ticks per second. The information returned by the rtems_clock_get
directive is dependent on the option selected by the caller. This is specified using one of the following constants associated with the enumerated type rtems_clock_get_options
:
RTEMS_CLOCK_GET_TOD
- obtain native style date and time
RTEMS_CLOCK_GET_TIME_VALUE
- obtain UNIX-style date and time
RTEMS_CLOCK_GET_TICKS_SINCE_BOOT
- obtain number of ticks since RTEMS was initialized
RTEMS_CLOCK_GET_SECONDS_SINCE_EPOCH
- obtain number of seconds since RTEMS epoch
RTEMS_CLOCK_GET_TICKS_PER_SECOND
- obtain number of clock ticks per second
Calendar time operations will return an error code if invoked before the date and time have been set.
9.4. Directives¶
This section details the clock manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
9.4.1. CLOCK_SET - Set date and time¶
- CALLING SEQUENCE:
rtems_status_code rtems_clock_set( rtems_time_of_day *time_buffer );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
date and time set successfully RTEMS_INVALID_ADDRESS
time_buffer
is NULLRTEMS_INVALID_CLOCK
invalid time of day - DESCRIPTION:
- This directive sets the system date and time. The date, time, and ticks in the time_buffer structure are all range-checked, and an error is returned if any one is out of its valid range.
- NOTES:
Years before 1988 are invalid.
The system date and time are based on the configured tick rate (number of microseconds in a tick).
Setting the time forward may cause a higher priority task, blocked waiting on a specific time, to be made ready. In this case, the calling task will be preempted after the next clock tick.
Re-initializing RTEMS causes the system date and time to be reset to an uninitialized state. Another call to
rtems_clock_set
is required to re-initialize the system date and time to application specific specifications.
9.4.2. CLOCK_GET - Get date and time information¶
Warning
This directive is deprecated and will be removed.
- CALLING SEQUENCE:
rtems_status_code rtems_clock_get( rtems_clock_get_options option, void *time_buffer );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
current time obtained successfully RTEMS_NOT_DEFINED
system date and time is not set RTEMS_INVALID_ADDRESS
time_buffer
is NULL- DESCRIPTION:
This directive obtains the system date and time. If the caller is attempting to obtain the date and time (i.e. option is set to either
RTEMS_CLOCK_GET_SECONDS_SINCE_EPOCH
,RTEMS_CLOCK_GET_TOD
, orRTEMS_CLOCK_GET_TIME_VALUE
) and the date and time has not been set with a previous call tortems_clock_set
, then theRTEMS_NOT_DEFINED
status code is returned. The caller can always obtain the number of ticks per second (option isRTEMS_CLOCK_GET_TICKS_PER_SECOND
) and the number of ticks since the executive was initialized option isRTEMS_CLOCK_GET_TICKS_SINCE_BOOT
).The
option
argument may taken on any value of the enumerated typertems_clock_get_options
. The data type expected fortime_buffer
is based on the value ofoption
as indicated below:Option Return type RTEMS_CLOCK_GET_TOD
(rtems_time_of_day *)
RTEMS_CLOCK_GET_SECONDS_SINCE_EPOCH
(rtems_interval *)
RTEMS_CLOCK_GET_TICKS_SINCE_BOOT
(rtems_interval *)
RTEMS_CLOCK_GET_TICKS_PER_SECOND
(rtems_interval *)
RTEMS_CLOCK_GET_TIME_VALUE
(struct timeval *)
- NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted. Re-initializing RTEMS causes the system date and time to be reset to an uninitialized state. Another call to
rtems_clock_set
is required to re-initialize the system date and time to application specific specifications.
9.4.3. CLOCK_GET_TOD - Get date and time in TOD format¶
- CALLING SEQUENCE:
rtems_status_code rtems_clock_get_tod( rtems_time_of_day *time_buffer );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
current time obtained successfully RTEMS_NOT_DEFINED
system date and time is not set RTEMS_INVALID_ADDRESS
time_buffer
is NULL- DESCRIPTION:
- This directive obtains the system date and time. If the date and time has not been set with a previous call to
rtems_clock_set
, then theRTEMS_NOT_DEFINED
status code is returned. - NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted. Re-initializing RTEMS causes the system date and time to be reset to an uninitialized state. Another call to
rtems_clock_set
is required to re-initialize the system date and time to application specific specifications.
9.4.4. CLOCK_GET_TOD_TIMEVAL - Get date and time in timeval format¶
- CALLING SEQUENCE:
rtems_status_code rtems_clock_get_tod_interval( struct timeval *time );
- DIRECTIVE STATUS CODES:
- DESCRIPTION:
- This directive obtains the system date and time in POSIX
struct timeval
format. If the date and time has not been set with a previous call tortems_clock_set
, then theRTEMS_NOT_DEFINED
status code is returned. - NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted. Re-initializing RTEMS causes the system date and time to be reset to an uninitialized state. Another call to
rtems_clock_set
is required to re-initialize the system date and time to application specific specifications.
9.4.5. CLOCK_GET_SECONDS_SINCE_EPOCH - Get seconds since epoch¶
- CALLING SEQUENCE:
rtems_status_code rtems_clock_get_seconds_since_epoch( rtems_interval *the_interval );
- DIRECTIVE STATUS CODES:
- DESCRIPTION:
- This directive returns the number of seconds since the RTEMS epoch and the current system date and time. If the date and time has not been set with a previous call to
rtems_clock_set
, then theRTEMS_NOT_DEFINED
status code is returned. - NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted. Re-initializing RTEMS causes the system date and time to be reset to an uninitialized state. Another call to
rtems_clock_set
is required to re-initialize the system date and time to application specific specifications.
9.4.6. CLOCK_GET_TICKS_PER_SECOND - Get ticks per second¶
- CALLING SEQUENCE:
rtems_interval rtems_clock_get_ticks_per_second(void);
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive returns the number of clock ticks per second. This is strictly based upon the microseconds per clock tick that the application has configured.
- NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted.
9.4.7. CLOCK_GET_TICKS_SINCE_BOOT - Get current ticks counter value¶
- CALLING SEQUENCE:
rtems_interval rtems_clock_get_ticks_since_boot(void);
- DIRECTIVE STATUS CODES:
- NONE
DESCRIPTION:
This directive returns the current tick counter value. With a 1ms clock tick, this counter overflows after 50 days since boot. This is the historical measure of uptime in an RTEMS system. The newer servicertems_clock_get_uptime
is another and potentially more accurate way of obtaining similar information.
NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted.
9.4.8. CLOCK_TICK_LATER - Get tick value in the future¶
- CALLING SEQUENCE:
rtems_interval rtems_clock_tick_later( rtems_interval delta );
- DESCRIPTION:
- Returns the ticks counter value delta ticks in the future.
- NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted.
9.4.9. CLOCK_TICK_LATER_USEC - Get tick value in the future in microseconds¶
- CALLING SEQUENCE:
rtems_interval rtems_clock_tick_later_usec( rtems_interval delta_in_usec );
- DESCRIPTION:
- Returns the ticks counter value at least delta microseconds in the future.
- NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted.
9.4.10. CLOCK_TICK_BEFORE - Is tick value is before a point in time¶
- CALLING SEQUENCE:
rtems_interval rtems_clock_tick_before( rtems_interval tick );
- DESCRIPTION:
- Returns true if the current ticks counter value indicates a time before the time specified by the tick value and false otherwise.
- NOTES:
This directive is callable from an ISR.
This directive will not cause the running task to be preempted.
- EXAMPLE:
status busy( void ) { rtems_interval timeout = rtems_clock_tick_later_usec( 10000 ); do { if ( ok() ) { return success; } } while ( rtems_clock_tick_before( timeout ) ); return timeout; }
9.4.11. CLOCK_GET_UPTIME - Get the time since boot¶
- CALLING SEQUENCE:
rtems_status_code rtems_clock_get_uptime( struct timespec *uptime );
- DIRECTIVE STATUS CODES:
- DESCRIPTION:
- This directive returns the seconds and nanoseconds since the system was booted. If the BSP supports nanosecond clock accuracy, the time reported will probably be different on every call.
- NOTES:
- This directive may be called from an ISR.
9.4.12. CLOCK_GET_UPTIME_TIMEVAL - Get the time since boot in timeval format¶
- CALLING SEQUENCE:
void rtems_clock_get_uptime_timeval( struct timeval *uptime );
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive returns the seconds and microseconds since the system was booted. If the BSP supports nanosecond clock accuracy, the time reported will probably be different on every call.
- NOTES:
- This directive may be called from an ISR.
9.4.13. CLOCK_GET_UPTIME_SECONDS - Get the seconds since boot¶
- CALLING SEQUENCE:
time_t rtems_clock_get_uptime_seconds(void);
- DIRECTIVE STATUS CODES:
- The system uptime in seconds.
- DESCRIPTION:
- This directive returns the seconds since the system was booted.
- NOTES:
- This directive may be called from an ISR.
9.4.14. CLOCK_GET_UPTIME_NANOSECONDS - Get the nanoseconds since boot¶
- CALLING SEQUENCE:
uint64_t rtems_clock_get_uptime_nanoseconds(void);
- DIRECTIVE STATUS CODES:
- The system uptime in nanoseconds.
- DESCRIPTION:
- This directive returns the nanoseconds since the system was booted.
- NOTES:
- This directive may be called from an ISR.
10. Timer Manager¶
10.1. Introduction¶
The timer manager provides support for timer facilities. The directives provided by the timer manager are:
- rtems_timer_create - Create a timer
- rtems_timer_ident - Get ID of a timer
- rtems_timer_cancel - Cancel a timer
- rtems_timer_delete - Delete a timer
- rtems_timer_fire_after - Fire timer after interval
- rtems_timer_fire_when - Fire timer when specified
- rtems_timer_initiate_server - Initiate server for task-based timers
- rtems_timer_server_fire_after - Fire task-based timer after interval
- rtems_timer_server_fire_when - Fire task-based timer when specified
- rtems_timer_reset - Reset an interval timer
10.2. Background¶
10.2.1. Required Support¶
A clock tick is required to support the functionality provided by this manager.
10.2.2. Timers¶
A timer is an RTEMS object which allows the application to schedule operations to occur at specific times in the future. User supplied timer service routines are invoked by either a clock tick directive or a special Timer Server task when the timer fires. Timer service routines may perform any operations or directives which normally would be performed by the application code which invoked a clock tick directive.
The timer can be used to implement watchdog routines which only fire to denote that an application error has occurred. The timer is reset at specific points in the application to ensure that the watchdog does not fire. Thus, if the application does not reset the watchdog timer, then the timer service routine will fire to indicate that the application has failed to reach a reset point. This use of a timer is sometimes referred to as a “keep alive” or a “deadman” timer.
10.2.3. Timer Server¶
The Timer Server task is responsible for executing the timer service routines associated with all task-based timers. This task executes at a priority higher than any RTEMS application task, and is created non-preemptible, and thus can be viewed logically as the lowest priority interrupt.
By providing a mechanism where timer service routines execute in task rather than interrupt space, the application is allowed a bit more flexibility in what operations a timer service routine can perform. For example, the Timer Server can be configured to have a floating point context in which case it would be safe to perform floating point operations from a task-based timer. Most of the time, executing floating point instructions from an interrupt service routine is not considered safe. However, since the Timer Server task is non-preemptible, only directives allowed from an ISR can be called in the timer service routine.
The Timer Server is designed to remain blocked until a task-based timer fires. This reduces the execution overhead of the Timer Server.
10.2.4. Timer Service Routines¶
The timer service routine should adhere to C calling conventions and have a prototype similar to the following:
rtems_timer_service_routine user_routine(
rtems_id timer_id,
void *user_data
);
Where the timer_id parameter is the RTEMS object ID of the timer which is being fired and user_data is a pointer to user-defined information which may be utilized by the timer service routine. The argument user_data may be NULL.
10.3. Operations¶
10.3.1. Creating a Timer¶
The rtems_timer_create
directive creates a timer by allocating a Timer Control Block (TMCB), assigning the timer a user-specified name, and assigning it a timer ID. Newly created timers do not have a timer service routine associated with them and are not active.
10.3.2. Obtaining Timer IDs¶
When a timer is created, RTEMS generates a unique timer ID and assigns it to the created timer until it is deleted. The timer ID may be obtained by either of two methods. First, as the result of an invocation of the rtems_timer_create
directive, the timer ID is stored in a user provided location. Second, the timer ID may be obtained later using the rtems_timer_ident
directive. The timer ID is used by other directives to manipulate this timer.
10.3.3. Initiating an Interval Timer¶
The rtems_timer_fire_after
and rtems_timer_server_fire_after
directives initiate a timer to fire a user provided timer service routine after the specified number of clock ticks have elapsed. When the interval has elapsed, the timer service routine will be invoked from a clock tick directive if it was initiated by the rtems_timer_fire_after
directive and from the Timer Server task if initiated by the rtems_timer_server_fire_after
directive.
10.3.4. Initiating a Time of Day Timer¶
The rtems_timer_fire_when
and rtems_timer_server_fire_when
directive initiate a timer to fire a user provided timer service routine when the specified time of day has been reached. When the interval has elapsed, the timer service routine will be invoked from a clock tick directive by the rtems_timer_fire_when
directive and from the Timer Server task if initiated by the rtems_timer_server_fire_when
directive.
10.3.5. Canceling a Timer¶
The rtems_timer_cancel
directive is used to halt the specified timer. Once canceled, the timer service routine will not fire unless the timer is reinitiated. The timer can be reinitiated using the rtems_timer_reset
, rtems_timer_fire_after
, and rtems_timer_fire_when
directives.
10.3.6. Resetting a Timer¶
The rtems_timer_reset
directive is used to restore an interval timer initiated by a previous invocation of rtems_timer_fire_after
or rtems_timer_server_fire_after
to its original interval length. If the timer has not been used or the last usage of this timer was by the rtems_timer_fire_when
or rtems_timer_server_fire_when
directive, then an error is returned. The timer service routine is not changed or fired by this directive.
10.3.7. Initiating the Timer Server¶
The rtems_timer_initiate_server
directive is used to allocate and start the execution of the Timer Server task. The application can specify both the stack size and attributes of the Timer Server. The Timer Server executes at a priority higher than any application task and thus the user can expect to be preempted as the result of executing the rtems_timer_initiate_server
directive.
10.3.8. Deleting a Timer¶
The rtems_timer_delete
directive is used to delete a timer. If the timer is running and has not expired, the timer is automatically canceled. The timer’s control block is returned to the TMCB free list when it is deleted. A timer can be deleted by a task other than the task which created the timer. Any subsequent references to the timer’s name and ID are invalid.
10.4. Directives¶
This section details the timer manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
10.4.1. TIMER_CREATE - Create a timer¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_create( rtems_name name, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer created successfully RTEMS_INVALID_ADDRESS
id
is NULLRTEMS_INVALID_NAME
invalid timer name RTEMS_TOO_MANY
too many timers created - DESCRIPTION:
- This directive creates a timer. The assigned timer id is returned in id. This id is used to access the timer with other timer manager directives. For control and maintenance of the timer, RTEMS allocates a TMCB from the local TMCB free pool and initializes it.
- NOTES:
- This directive will not cause the calling task to be preempted.
10.4.2. TIMER_IDENT - Get ID of a timer¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_ident( rtems_name name, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer identified successfully RTEMS_INVALID_ADDRESS
id
is NULLRTEMS_INVALID_NAME
timer name not found - DESCRIPTION:
- This directive obtains the timer id associated with the timer name to be acquired. If the timer name is not unique, then the timer id will match one of the timers with that name. However, this timer id is not guaranteed to correspond to the desired timer. The timer id is used to access this timer in other timer related directives.
- NOTES:
- This directive will not cause the running task to be preempted.
10.4.3. TIMER_CANCEL - Cancel a timer¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_cancel( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer canceled successfully RTEMS_INVALID_ID
invalid timer id - DESCRIPTION:
- This directive cancels the timer id. This timer will be reinitiated by the next invocation of
rtems_timer_reset
,rtems_timer_fire_after
, orrtems_timer_fire_when
with this id. - NOTES:
- This directive will not cause the running task to be preempted.
10.4.4. TIMER_DELETE - Delete a timer¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_delete( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer deleted successfully RTEMS_INVALID_ID
invalid timer id - DESCRIPTION:
- This directive deletes the timer specified by id. If the timer is running, it is automatically canceled. The TMCB for the deleted timer is reclaimed by RTEMS.
- NOTES:
This directive will not cause the running task to be preempted.
A timer can be deleted by a task other than the task which created the timer.
10.4.5. TIMER_FIRE_AFTER - Fire timer after interval¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_fire_after( rtems_id id, rtems_interval ticks, rtems_timer_service_routine_entry routine, void *user_data );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer initiated successfully RTEMS_INVALID_ADDRESS
routine
is NULLRTEMS_INVALID_ID
invalid timer id RTEMS_INVALID_NUMBER
invalid interval - DESCRIPTION:
- This directive initiates the timer specified by id. If the timer is running, it is automatically canceled before being initiated. The timer is scheduled to fire after an interval ticks clock ticks has passed. When the timer fires, the timer service routine routine will be invoked with the argument user_data.
- NOTES:
- This directive will not cause the running task to be preempted.
10.4.6. TIMER_FIRE_WHEN - Fire timer when specified¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_fire_when( rtems_id id, rtems_time_of_day *wall_time, rtems_timer_service_routine_entry routine, void *user_data );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer initiated successfully RTEMS_INVALID_ADDRESS
routine
is NULLRTEMS_INVALID_ADDRESS
wall_time
is NULLRTEMS_INVALID_ID
invalid timer id RTEMS_NOT_DEFINED
system date and time is not set RTEMS_INVALID_CLOCK
invalid time of day - DESCRIPTION:
- This directive initiates the timer specified by id. If the timer is running, it is automatically canceled before being initiated. The timer is scheduled to fire at the time of day specified by wall_time. When the timer fires, the timer service routine routine will be invoked with the argument user_data.
- NOTES:
- This directive will not cause the running task to be preempted.
10.4.7. TIMER_INITIATE_SERVER - Initiate server for task-based timers¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_initiate_server( uint32_t priority, uint32_t stack_size, rtems_attribute attribute_set );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
Timer Server initiated successfully RTEMS_TOO_MANY
too many tasks created - DESCRIPTION:
- This directive initiates the Timer Server task. This task is responsible for executing all timers initiated via the
rtems_timer_server_fire_after
orrtems_timer_server_fire_when
directives. - NOTES:
This directive could cause the calling task to be preempted.
The Timer Server task is created using the
rtems_task_create
service and must be accounted for when configuring the system.Even through this directive invokes the
rtems_task_create
andrtems_task_start
directives, it should only fail due to resource allocation problems.
10.4.8. TIMER_SERVER_FIRE_AFTER - Fire task-based timer after interval¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_server_fire_after( rtems_id id, rtems_interval ticks, rtems_timer_service_routine_entry routine, void *user_data );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer initiated successfully RTEMS_INVALID_ADDRESS
routine
is NULLRTEMS_INVALID_ID
invalid timer id RTEMS_INVALID_NUMBER
invalid interval RTEMS_INCORRECT_STATE
Timer Server not initiated - DESCRIPTION:
This directive initiates the timer specified by id and specifies that when it fires it will be executed by the Timer Server.
If the timer is running, it is automatically canceled before being initiated. The timer is scheduled to fire after an interval ticks clock ticks has passed. When the timer fires, the timer service routine routine will be invoked with the argument user_data.
- NOTES:
- This directive will not cause the running task to be preempted.
10.4.9. TIMER_SERVER_FIRE_WHEN - Fire task-based timer when specified¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_server_fire_when( rtems_id id, rtems_time_of_day *wall_time, rtems_timer_service_routine_entry routine, void *user_data );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer initiated successfully RTEMS_INVALID_ADDRESS
routine
is NULLRTEMS_INVALID_ADDRESS
wall_time
is NULLRTEMS_INVALID_ID
invalid timer id RTEMS_NOT_DEFINED
system date and time is not set RTEMS_INVALID_CLOCK
invalid time of day RTEMS_INCORRECT_STATE
Timer Server not initiated - DESCRIPTION:
This directive initiates the timer specified by id and specifies that when it fires it will be executed by the Timer Server.
If the timer is running, it is automatically canceled before being initiated. The timer is scheduled to fire at the time of day specified by wall_time. When the timer fires, the timer service routine routine will be invoked with the argument user_data.
- NOTES:
- This directive will not cause the running task to be preempted.
10.4.10. TIMER_RESET - Reset an interval timer¶
- CALLING SEQUENCE:
rtems_status_code rtems_timer_reset( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
timer reset successfully RTEMS_INVALID_ID
invalid timer id RTEMS_NOT_DEFINED
attempted to reset a when or newly created timer - DESCRIPTION:
- This directive resets the timer associated with id. This timer must have been previously initiated with either the
rtems_timer_fire_after
orrtems_timer_server_fire_after
directive. If active the timer is canceled, after which the timer is reinitiated using the same interval and timer service routine which the originalrtems_timer_fire_after
orrtems_timer_server_fire_after
directive used. - NOTES:
If the timer has not been used or the last usage of this timer was by a
rtems_timer_fire_when
orrtems_timer_server_fire_when
directive, then theRTEMS_NOT_DEFINED
error is returned.Restarting a cancelled after timer results in the timer being reinitiated with its previous timer service routine and interval.
This directive will not cause the running task to be preempted.
11. Rate Monotonic Manager¶
11.1. Introduction¶
The rate monotonic manager provides facilities to implement tasks which execute in a periodic fashion. Critically, it also gathers information about the execution of those periods and can provide important statistics to the user which can be used to analyze and tune the application. The directives provided by the rate monotonic manager are:
- rtems_rate_monotonic_create - Create a rate monotonic period
- rtems_rate_monotonic_ident - Get ID of a period
- rtems_rate_monotonic_cancel - Cancel a period
- rtems_rate_monotonic_delete - Delete a rate monotonic period
- rtems_rate_monotonic_period - Conclude current/Start next period
- rtems_rate_monotonic_get_status - Obtain status from a period
- rtems_rate_monotonic_get_statistics - Obtain statistics from a period
- rtems_rate_monotonic_reset_statistics - Reset statistics for a period
- rtems_rate_monotonic_reset_all_statistics - Reset statistics for all periods
- rtems_rate_monotonic_report_statistics - Print period statistics report
11.2. Background¶
The rate monotonic manager provides facilities to manage the execution of periodic tasks. This manager was designed to support application designers who utilize the Rate Monotonic Scheduling Algorithm (RMS) to ensure that their periodic tasks will meet their deadlines, even under transient overload conditions. Although designed for hard real-time systems, the services provided by the rate monotonic manager may be used by any application which requires periodic tasks.
11.2.1. Rate Monotonic Manager Required Support¶
A clock tick is required to support the functionality provided by this manager.
11.2.2. Period Statistics¶
This manager maintains a set of statistics on each period object. These statistics are reset implictly at period creation time and may be reset or obtained at any time by the application. The following is a list of the information kept:
owner
- is the id of the thread that owns this period.
count
- is the total number of periods executed.
missed_count
- is the number of periods that were missed.
min_cpu_time
- is the minimum amount of CPU execution time consumed on any execution of the periodic loop.
max_cpu_time
- is the maximum amount of CPU execution time consumed on any execution of the periodic loop.
total_cpu_time
- is the total amount of CPU execution time consumed by executions of the periodic loop.
min_wall_time
- is the minimum amount of wall time that passed on any execution of the periodic loop.
max_wall_time
- is the maximum amount of wall time that passed on any execution of the periodic loop.
total_wall_time
- is the total amount of wall time that passed during executions of the periodic loop.
Each period is divided into two consecutive phases. The period starts with the active phase of the task and is followed by the inactive phase of the task. In the inactive phase the task is blocked and waits for the start of the next period. The inactive phase is skipped in case of a period miss. The wall time includes the time during the active phase of the task on which the task is not executing on a processor. The task is either blocked (for example it waits for a resource) or a higher priority tasks executes, thus preventing it from executing. In case the wall time exceeds the period time, then this is a period miss. The gap between the wall time and the period time is the margin between a period miss or success.
The period statistics information is inexpensive to maintain and can provide very useful insights into the execution characteristics of a periodic task loop. But it is just information. The period statistics reported must be analyzed by the user in terms of what the applications is. For example, in an application where priorities are assigned by the Rate Monotonic Algorithm, it would be very undesirable for high priority (i.e. frequency) tasks to miss their period. Similarly, in nearly any application, if a task were supposed to execute its periodic loop every 10 milliseconds and it averaged 11 milliseconds, then application requirements are not being met.
The information reported can be used to determine the “hot spots” in the application. Given a period’s id, the user can determine the length of that period. From that information and the CPU usage, the user can calculate the percentage of CPU time consumed by that periodic task. For example, a task executing for 20 milliseconds every 200 milliseconds is consuming 10 percent of the processor’s execution time. This is usually enough to make it a good candidate for optimization.
However, execution time alone is not enough to gauge the value of optimizing a particular task. It is more important to optimize a task executing 2 millisecond every 10 milliseconds (20 percent of the CPU) than one executing 10 milliseconds every 100 (10 percent of the CPU). As a general rule of thumb, the higher frequency at which a task executes, the more important it is to optimize that task.
11.2.3. Rate Monotonic Manager Definitions¶
A periodic task is one which must be executed at a regular interval. The interval between successive iterations of the task is referred to as its period. Periodic tasks can be characterized by the length of their period and execution time. The period and execution time of a task can be used to determine the processor utilization for that task. Processor utilization is the percentage of processor time used and can be calculated on a per-task or system-wide basis. Typically, the task’s worst-case execution time will be less than its period. For example, a periodic task’s requirements may state that it should execute for 10 milliseconds every 100 milliseconds. Although the execution time may be the average, worst, or best case, the worst-case execution time is more appropriate for use when analyzing system behavior under transient overload conditions... index:: aperiodic task, definition
In contrast, an aperiodic task executes at irregular intervals and has only a soft deadline. In other words, the deadlines for aperiodic tasks are not rigid, but adequate response times are desirable. For example, an aperiodic task may process user input from a terminal.
Finally, a sporadic task is an aperiodic task with a hard deadline and minimum interarrival time. The minimum interarrival time is the minimum period of time which exists between successive iterations of the task. For example, a sporadic task could be used to process the pressing of a fire button on a joystick. The mechanical action of the fire button ensures a minimum time period between successive activations, but the missile must be launched by a hard deadline.
11.2.4. Rate Monotonic Scheduling Algorithm¶
The Rate Monotonic Scheduling Algorithm (RMS) is important to real-time systems designers because it allows one to guarantee that a set of tasks is schedulable. A set of tasks is said to be schedulable if all of the tasks can meet their deadlines. RMS provides a set of rules which can be used to perform a guaranteed schedulability analysis for a task set. This analysis determines whether a task set is schedulable under worst-case conditions and emphasizes the predictability of the system’s behavior. It has been proven that:
RMS is optimal in the sense that if a set of tasks can be scheduled by any static priority algorithm, then RMS will be able to schedule that task set. RMS bases it schedulability analysis on the processor utilization level below which all deadlines can be met.
RMS calls for the static assignment of task priorities based upon their period. The shorter a task’s period, the higher its priority. For example, a task with a 1 millisecond period has higher priority than a task with a 100 millisecond period. If two tasks have the same period, then RMS does not distinguish between the tasks. However, RTEMS specifies that when given tasks of equal priority, the task which has been ready longest will execute first. RMS’s priority assignment scheme does not provide one with exact numeric values for task priorities. For example, consider the following task set and priority assignments:
Task | Period (in milliseconds) | Priority |
---|---|---|
1 | 100 | Low |
2 | 50 | Medium |
3 | 50 | Medium |
4 | 25 | High |
RMS only calls for task 1 to have the lowest priority, task 4 to have the highest priority, and tasks 2 and 3 to have an equal priority between that of tasks 1 and 4. The actual RTEMS priorities assigned to the tasks must only adhere to those guidelines.
Many applications have tasks with both hard and soft deadlines. The tasks with hard deadlines are typically referred to as the critical task set, with the soft deadline tasks being the non-critical task set. The critical task set can be scheduled using RMS, with the non-critical tasks not executing under transient overload, by simply assigning priorities such that the lowest priority critical task (i.e. longest period) has a higher priority than the highest priority non-critical task. Although RMS may be used to assign priorities to the non-critical tasks, it is not necessary. In this instance, schedulability is only guaranteed for the critical task set.
11.2.5. Schedulability Analysis¶
RMS allows application designers to ensure that tasks can meet all deadlines, even under transient overload, without knowing exactly when any given task will execute by applying proven schedulability analysis rules.
11.2.5.1. Assumptions¶
The schedulability analysis rules for RMS were developed based on the following assumptions:
- The requests for all tasks for which hard deadlines exist are periodic, with a constant interval between requests.
- Each task must complete before the next request for it occurs.
- The tasks are independent in that a task does not depend on the initiation or completion of requests for other tasks.
- The execution time for each task without preemption or interruption is constant and does not vary.
- Any non-periodic tasks in the system are special. These tasks displace periodic tasks while executing and do not have hard, critical deadlines.
Once the basic schedulability analysis is understood, some of the above assumptions can be relaxed and the side-effects accounted for.
11.2.5.2. Processor Utilization Rule¶
The Processor Utilization Rule requires that processor utilization be calculated based upon the period and execution time of each task. The fraction of processor time spent executing task index is Time(index) / Period(index)
. The processor utilization can be calculated as follows:
Utilization = 0
for index = 1 to maximum_tasks
Utilization = Utilization + (Time(index)/Period(index))
To ensure schedulability even under transient overload, the processor utilization must adhere to the following rule:
Utilization = maximum_tasks * (2**(1/maximum_tasks) - 1)
As the number of tasks increases, the above formula approaches ln(2) for a worst-case utilization factor of approximately 0.693. Many tasks sets can be scheduled with a greater utilization factor. In fact, the average processor utilization threshold for a randomly generated task set is approximately 0.88.
11.2.5.3. Processor Utilization Rule Example¶
This example illustrates the application of the Processor Utilization Rule to an application with three critical periodic tasks. The following table details the RMS priority, period, execution time, and processor utilization for each task:
Task | RMS Priority | Period | Execution Time | Processor Utilization |
---|---|---|---|---|
1 | High | 100 | 15 | 0.15 |
2 | Medium | 200 | 50 | 0.25 |
3 | Low | 300 | 100 | 0.33 |
The total processor utilization for this task set is 0.73 which is below the upper bound of 3 * (2**(1/3) - 1), or 0.779, imposed by the Processor Utilization Rule. Therefore, this task set is guaranteed to be schedulable using RMS.
11.2.5.4. First Deadline Rule¶
If a given set of tasks do exceed the processor utilization upper limit imposed by the Processor Utilization Rule, they can still be guaranteed to meet all their deadlines by application of the First Deadline Rule. This rule can be stated as follows:
For a given set of independent periodic tasks, if each task meets its first deadline when all tasks are started at the same time, then the deadlines will always be met for any combination of start times.
A key point with this rule is that ALL periodic tasks are assumed to start at the exact same instant in time. Although this assumption may seem to be invalid, RTEMS makes it quite easy to ensure. By having a non-preemptible user initialization task, all application tasks, regardless of priority, can be created and started before the initialization deletes itself. This technique ensures that all tasks begin to compete for execution time at the same instant - when the user initialization task deletes itself.
11.2.5.5. First Deadline Rule Example¶
The First Deadline Rule can ensure schedulability even when the Processor Utilization Rule fails. The example below is a modification of the Processor Utilization Rule example where task execution time has been increased from 15 to 25 units. The following table details the RMS priority, period, execution time, and processor utilization for each task:
Task | RMS Priority | Period | Execution Time | Processor Utilization |
---|---|---|---|---|
1 | High | 100 | 25 | 0.25 |
2 | Medium | 200 | 50 | 0.25 |
3 | Low | 300 | 100 | 0.33 |
The total processor utilization for the modified task set is 0.83 which is above the upper bound of 3 * (2**(1/3) - 1), or 0.779, imposed by the Processor Utilization Rule. Therefore, this task set is not guaranteed to be schedulable using RMS. However, the First Deadline Rule can guarantee the schedulability of this task set. This rule calls for one to examine each occurrence of deadline until either all tasks have met their deadline or one task failed to meet its first deadline. The following table details the time of each deadline occurrence, the maximum number of times each task may have run, the total execution time, and whether all the deadlines have been met:
Deadline Time | Task 1 | Task 2 | Task 3 | Total Execution Time | All Deadlines Met? |
---|---|---|---|---|---|
100 | 1 | 1 | 1 | 25 + 50 + 100 = 175 | NO |
200 | 2 | 1 | 1 | 50 + 50 + 100 = 200 | YES |
The key to this analysis is to recognize when each task will execute. For example at time 100, task 1 must have met its first deadline, but tasks 2 and 3 may also have begun execution. In this example, at time 100 tasks 1 and 2 have completed execution and thus have met their first deadline. Tasks 1 and 2 have used (25 + 50) = 75 time units, leaving (100 - 75) = 25 time units for task 3 to begin. Because task 3 takes 100 ticks to execute, it will not have completed execution at time 100. Thus at time 100, all of the tasks except task 3 have met their first deadline.
At time 200, task 1 must have met its second deadline and task 2 its first deadline. As a result, of the first 200 time units, task 1 uses (2 * 25) = 50 and task 2 uses 50, leaving (200 - 100) time units for task 3. Task 3 requires 100 time units to execute, thus it will have completed execution at time 200. Thus, all of the tasks have met their first deadlines at time 200, and the task set is schedulable using the First Deadline Rule.
11.2.5.6. Relaxation of Assumptions¶
The assumptions used to develop the RMS schedulability rules are uncommon in most real-time systems. For example, it was assumed that tasks have constant unvarying execution time. It is possible to relax this assumption, simply by using the worst-case execution time of each task.
Another assumption is that the tasks are independent. This means that the tasks do not wait for one another or contend for resources. This assumption can be relaxed by accounting for the amount of time a task spends waiting to acquire resources. Similarly, each task’s execution time must account for any I/O performed and any RTEMS directive calls.
In addition, the assumptions did not account for the time spent executing interrupt service routines. This can be accounted for by including all the processor utilization by interrupt service routines in the utilization calculation. Similarly, one should also account for the impact of delays in accessing local memory caused by direct memory access and other processors accessing local dual-ported memory.
The assumption that nonperiodic tasks are used only for initialization or failure-recovery can be relaxed by placing all periodic tasks in the critical task set. This task set can be scheduled and analyzed using RMS. All nonperiodic tasks are placed in the non-critical task set. Although the critical task set can be guaranteed to execute even under transient overload, the non-critical task set is not guaranteed to execute.
In conclusion, the application designer must be fully cognizant of the system and its run-time behavior when performing schedulability analysis for a system using RMS. Every hardware and software factor which impacts the execution time of each task must be accounted for in the schedulability analysis.
11.2.5.7. Further Reading¶
For more information on Rate Monotonic Scheduling and its schedulability analysis, the reader is referred to the following:
- C. L. Liu and J. W. Layland. “Scheduling Algorithms for Multiprogramming in a Hard Real Time Environment.” Journal of the Association of Computing Machinery. January 1973. pp. 46-61.
- John Lehoczky, Lui Sha, and Ye Ding. “The Rate Monotonic Scheduling Algorithm: Exact Characterization and Average Case Behavior.” IEEE Real-Time Systems Symposium. 1989. pp. 166-171.
- Lui Sha and John Goodenough. “Real-Time Scheduling theory and Ada.” IEEE Computer. April 1990. pp. 53-62.
- Alan Burns. “Scheduling hard real-time systems: a review.” Software Engineering Journal. May 1991. pp. 116-128.
11.3. Operations¶
11.3.1. Creating a Rate Monotonic Period¶
The rtems_rate_monotonic_create
directive creates a rate monotonic period which is to be used by the calling task to delineate a period. RTEMS allocates a Period Control Block (PCB) from the PCB free list. This data structure is used by RTEMS to manage the newly created rate monotonic period. RTEMS returns a unique period ID to the application which is used by other rate monotonic manager directives to access this rate monotonic period.
11.3.2. Manipulating a Period¶
The rtems_rate_monotonic_period
directive is used to establish and maintain periodic execution utilizing a previously created rate monotonic period. Once initiated by the rtems_rate_monotonic_period
directive, the period is said to run until it either expires or is reinitiated. The state of the rate monotonic period results in one of the following scenarios:
- If the rate monotonic period is running, the calling task will be blocked for the remainder of the outstanding period and, upon completion of that period, the period will be reinitiated with the specified period.
- If the rate monotonic period is not currently running and has not expired, it is initiated with a length of period ticks and the calling task returns immediately.
- If the rate monotonic period has expired before the task invokes the
rtems_rate_monotonic_period
directive, the period will be initiated with a length of period ticks and the calling task returns immediately with a timeout error status.
11.3.3. Obtaining the Status of a Period¶
If the rtems_rate_monotonic_period
directive is invoked with a period of RTEMS_PERIOD_STATUS
ticks, the current state of the specified rate monotonic period will be returned. The following table details the relationship between the period’s status and the directive status code returned by the rtems_rate_monotonic_period
directive:
RTEMS_SUCCESSFUL | period is running |
RTEMS_TIMEOUT | period has expired |
RTEMS_NOT_DEFINED | period has never been initiated |
Obtaining the status of a rate monotonic period does not alter the state or length of that period.
11.3.4. Canceling a Period¶
The rtems_rate_monotonic_cancel
directive is used to stop the period maintained by the specified rate monotonic period. The period is stopped and the rate monotonic period can be reinitiated using the rtems_rate_monotonic_period
directive.
11.3.5. Deleting a Rate Monotonic Period¶
The rtems_rate_monotonic_delete
directive is used to delete a rate monotonic period. If the period is running and has not expired, the period is automatically canceled. The rate monotonic period’s control block is returned to the PCB free list when it is deleted. A rate monotonic period can be deleted by a task other than the task which created the period.
11.3.6. Examples¶
The following sections illustrate common uses of rate monotonic periods to construct periodic tasks.
11.3.7. Simple Periodic Task¶
This example consists of a single periodic task which, after initialization, executes every 100 clock ticks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | rtems_task Periodic_task(rtems_task_argument arg)
{
rtems_name name;
rtems_id period;
rtems_status_code status;
name = rtems_build_name( 'P', 'E', 'R', 'D' );
status = rtems_rate_monotonic_create( name, &period );
if ( status != RTEMS_STATUS_SUCCESSFUL ) {
printf( "rtems_monotonic_create failed with status of %d.\n", rc );
exit( 1 );
}
while ( 1 ) {
if ( rtems_rate_monotonic_period( period, 100 ) == RTEMS_TIMEOUT )
break;
/* Perform some periodic actions */
}
/* missed period so delete period and SELF */
status = rtems_rate_monotonic_delete( period );
if ( status != RTEMS_STATUS_SUCCESSFUL ) {
printf( "rtems_rate_monotonic_delete failed with status of %d.\n", status );
exit( 1 );
}
status = rtems_task_delete( SELF ); /* should not return */
printf( "rtems_task_delete returned with status of %d.\n", status );
exit( 1 );
}
|
The above task creates a rate monotonic period as part of its initialization. The first time the loop is executed, the rtems_rate_monotonic_period
directive will initiate the period for 100 ticks and return immediately. Subsequent invocations of the rtems_rate_monotonic_period
directive will result in the task blocking for the remainder of the 100 tick period. If, for any reason, the body of the loop takes more than 100 ticks to execute, the rtems_rate_monotonic_period
directive will return the RTEMS_TIMEOUT
status. If the above task misses its deadline, it will delete the rate monotonic period and itself.
11.3.8. Task with Multiple Periods¶
This example consists of a single periodic task which, after initialization, performs two sets of actions every 100 clock ticks. The first set of actions is performed in the first forty clock ticks of every 100 clock ticks, while the second set of actions is performed between the fortieth and seventieth clock ticks. The last thirty clock ticks are not used by this task.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | rtems_task Periodic_task(rtems_task_argument arg)
{
rtems_name name_1, name_2;
rtems_id period_1, period_2;
rtems_status_code status;
name_1 = rtems_build_name( 'P', 'E', 'R', '1' );
name_2 = rtems_build_name( 'P', 'E', 'R', '2' );
(void ) rtems_rate_monotonic_create( name_1, &period_1 );
(void ) rtems_rate_monotonic_create( name_2, &period_2 );
while ( 1 ) {
if ( rtems_rate_monotonic_period( period_1, 100 ) == TIMEOUT )
break;
if ( rtems_rate_monotonic_period( period_2, 40 ) == TIMEOUT )
break;
/*
* Perform first set of actions between clock
* ticks 0 and 39 of every 100 ticks.
*/
if ( rtems_rate_monotonic_period( period_2, 30 ) == TIMEOUT )
break;
/*
* Perform second set of actions between clock 40 and 69
* of every 100 ticks. THEN ...
*
* Check to make sure we didn't miss the period_2 period.
*/
if ( rtems_rate_monotonic_period( period_2, STATUS ) == TIMEOUT )
break;
(void) rtems_rate_monotonic_cancel( period_2 );
}
/* missed period so delete period and SELF */
(void ) rtems_rate_monotonic_delete( period_1 );
(void ) rtems_rate_monotonic_delete( period_2 );
(void ) task_delete( SELF );
}
|
The above task creates two rate monotonic periods as part of its initialization. The first time the loop is executed, the rtems_rate_monotonic_period
directive will initiate the period_1 period for 100 ticks and return immediately. Subsequent invocations of the rtems_rate_monotonic_period
directive for period_1 will result in the task blocking for the remainder of the 100 tick period. The period_2 period is used to control the execution time of the two sets of actions within each 100 tick period established by period_1. The rtems_rate_monotonic_cancel( period_2 )
call is performed to ensure that the period_2 period does not expire while the task is blocked on the period_1 period. If this cancel operation were not performed, every time the rtems_rate_monotonic_period( period_2, 40 )
call is executed, except for the initial one, a directive status of RTEMS_TIMEOUT
is returned. It is important to note that every time this call is made, the period_2 period will be initiated immediately and the task will not block.
If, for any reason, the task misses any deadline, the rtems_rate_monotonic_period
directive will return the RTEMS_TIMEOUT
directive status. If the above task misses its deadline, it will delete the rate monotonic periods and itself.
11.4. Directives¶
This section details the rate monotonic manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
11.4.1. RATE_MONOTONIC_CREATE - Create a rate monotonic period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_create( rtems_name name, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
rate monotonic period created successfully RTEMS_INVALID_NAME
invalid period name RTEMS_TOO_MANY
too many periods created - DESCRIPTION:
- This directive creates a rate monotonic period. The assigned rate monotonic id is returned in id. This id is used to access the period with other rate monotonic manager directives. For control and maintenance of the rate monotonic period, RTEMS allocates a PCB from the local PCB free pool and initializes it.
- NOTES:
- This directive will not cause the calling task to be preempted.
11.4.2. RATE_MONOTONIC_IDENT - Get ID of a period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_ident( rtems_name name, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period identified successfully RTEMS_INVALID_NAME
period name not found - DESCRIPTION:
- This directive obtains the period id associated with the period name to be acquired. If the period name is not unique, then the period id will match one of the periods with that name. However, this period id is not guaranteed to correspond to the desired period. The period id is used to access this period in other rate monotonic manager directives.
- NOTES:
- This directive will not cause the running task to be preempted.
11.4.3. RATE_MONOTONIC_CANCEL - Cancel a period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_cancel( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period canceled successfully RTEMS_INVALID_ID
invalid rate monotonic period id RTEMS_NOT_OWNER_OF_RESOURCE
rate monotonic period not created by calling task
DESCRIPTION:
This directive cancels the rate monotonic period id. This period will be reinitiated by the next invocation ofrtems_rate_monotonic_period
with id.
- NOTES:
This directive will not cause the running task to be preempted.
The rate monotonic period specified by id must have been created by the calling task.
11.4.4. RATE_MONOTONIC_DELETE - Delete a rate monotonic period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_delete( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period deleted successfully RTEMS_INVALID_ID
invalid rate monotonic period id
DESCRIPTION:
This directive deletes the rate monotonic period specified by id. If the period is running, it is automatically canceled. The PCB for the deleted period is reclaimed by RTEMS.
- NOTES:
This directive will not cause the running task to be preempted.
A rate monotonic period can be deleted by a task other than the task which created the period.
11.4.5. RATE_MONOTONIC_PERIOD - Conclude current/Start next period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_period( rtems_id id, rtems_interval length );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period initiated successfully RTEMS_INVALID_ID
invalid rate monotonic period id RTEMS_NOT_OWNER_OF_RESOURCE
period not created by calling task RTEMS_NOT_DEFINED
period has never been initiated (only possible when period is set to PERIOD_STATUS) RTEMS_TIMEOUT
period has expired - DESCRIPTION:
This directive initiates the rate monotonic period id with a length of period ticks. If id is running, then the calling task will block for the remainder of the period before reinitiating the period with the specified period. If id was not running (either expired or never initiated), the period is immediately initiated and the directive returns immediately.
If invoked with a period of
RTEMS_PERIOD_STATUS
ticks, the current state of id will be returned. The directive status indicates the current state of the period. This does not alter the state or period of the period.- NOTES:
- This directive will not cause the running task to be preempted.
11.4.6. RATE_MONOTONIC_GET_STATUS - Obtain status from a period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_get_status( rtems_id id, rtems_rate_monotonic_period_status *status );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period initiated successfully RTEMS_INVALID_ID
invalid rate monotonic period id RTEMS_INVALID_ADDRESS
invalid address of status - *DESCRIPTION:
This directive returns status information associated with the rate monotonic period id in the following data structure:
typedef struct { rtems_id owner; rtems_rate_monotonic_period_states state; rtems_rate_monotonic_period_time_t since_last_period; rtems_thread_cpu_usage_t executed_since_last_period; } rtems_rate_monotonic_period_status;
A configure time option can be used to select whether the time information is given in ticks or seconds and nanoseconds. The default is seconds and nanoseconds. If the period’s state is
RATE_MONOTONIC_INACTIVE
, both time values will be set to 0. Otherwise, both time values will contain time information since the last invocation of thertems_rate_monotonic_period
directive. More specifically, the ticks_since_last_period value contains the elapsed time which has occurred since the last invocation of thertems_rate_monotonic_period
directive and theticks_executed_since_last_period
contains how much processor time the owning task has consumed since the invocation of thertems_rate_monotonic_period
directive.- NOTES:
- This directive will not cause the running task to be preempted.
11.4.7. RATE_MONOTONIC_GET_STATISTICS - Obtain statistics from a period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_get_statistics( rtems_id id, rtems_rate_monotonic_period_statistics *statistics );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period initiated successfully RTEMS_INVALID_ID
invalid rate monotonic period id RTEMS_INVALID_ADDRESS
invalid address of statistics - DESCRIPTION:
This directive returns statistics information associated with the rate monotonic period id in the following data structure:
typedef struct { uint32_t count; uint32_t missed_count; #ifdef RTEMS_ENABLE_NANOSECOND_CPU_USAGE_STATISTICS struct timespec min_cpu_time; struct timespec max_cpu_time; struct timespec total_cpu_time; #else uint32_t min_cpu_time; uint32_t max_cpu_time; uint32_t total_cpu_time; #endif #ifdef RTEMS_ENABLE_NANOSECOND_RATE_MONOTONIC_STATISTICS struct timespec min_wall_time; struct timespec max_wall_time; struct timespec total_wall_time; #else uint32_t min_wall_time; uint32_t max_wall_time; uint32_t total_wall_time; #endif } rtems_rate_monotonic_period_statistics;
This directive returns the current statistics information for the period instance assocaited with
id
. The information returned is indicated by the structure above.- NOTES:
- This directive will not cause the running task to be preempted.
11.4.8. RATE_MONOTONIC_RESET_STATISTICS - Reset statistics for a period¶
- CALLING SEQUENCE:
rtems_status_code rtems_rate_monotonic_reset_statistics( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
period initiated successfully RTEMS_INVALID_ID
invalid rate monotonic period id - DESCRIPTION:
- This directive resets the statistics information associated with this rate monotonic period instance.
- NOTES:
- This directive will not cause the running task to be preempted.
11.4.9. RATE_MONOTONIC_RESET_ALL_STATISTICS - Reset statistics for all periods¶
- CALLING SEQUENCE:
void rtems_rate_monotonic_reset_all_statistics(void);
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
- This directive resets the statistics information associated with all rate monotonic period instances.
- NOTES:
- This directive will not cause the running task to be preempted.
11.4.10. RATE_MONOTONIC_REPORT_STATISTICS - Print period statistics report¶
- CALLING SEQUENCE:
void rtems_rate_monotonic_report_statistics(void);
- DIRECTIVE STATUS CODES:
- NONE
- DESCRIPTION:
This directive prints a report on all active periods which have executed at least one period. The following is an example of the output generated by this directive.
ID OWNER PERIODS MISSED CPU TIME WALL TIME MIN/MAX/AVG MIN/MAX/AVG 0x42010001 TA1 502 0 0/1/0.99 0/0/0.00 0x42010002 TA2 502 0 0/1/0.99 0/0/0.00 0x42010003 TA3 501 0 0/1/0.99 0/0/0.00 0x42010004 TA4 501 0 0/1/0.99 0/0/0.00 0x42010005 TA5 10 0 0/1/0.90 0/0/0.00
- NOTES:
- This directive will not cause the running task to be preempted.
12. Semaphore Manager¶
12.1. Introduction¶
The semaphore manager utilizes standard Dijkstra counting semaphores to provide synchronization and mutual exclusion capabilities. The directives provided by the semaphore manager are:
- rtems_semaphore_create - Create a semaphore
- rtems_semaphore_ident - Get ID of a semaphore
- rtems_semaphore_delete - Delete a semaphore
- rtems_semaphore_obtain - Acquire a semaphore
- rtems_semaphore_release - Release a semaphore
- rtems_semaphore_flush - Unblock all tasks waiting on a semaphore
- rtems_semaphore_set_priority - Set priority by scheduler for a semaphore
12.2. Background¶
A semaphore can be viewed as a protected variable whose value can be modified only with the rtems_semaphore_create
, rtems_semaphore_obtain
, and rtems_semaphore_release
directives. RTEMS supports both binary and counting semaphores. A binary semaphore is restricted to values of zero or one, while a counting semaphore can assume any non-negative integer value.
A binary semaphore can be used to control access to a single resource. In particular, it can be used to enforce mutual exclusion for a critical section in user code. In this instance, the semaphore would be created with an initial count of one to indicate that no task is executing the critical section of code. Upon entry to the critical section, a task must issue the rtems_semaphore_obtain
directive to prevent other tasks from entering the critical section. Upon exit from the critical section, the task must issue the rtems_semaphore_release
directive to allow another task to execute the critical section.
A counting semaphore can be used to control access to a pool of two or more resources. For example, access to three printers could be administered by a semaphore created with an initial count of three. When a task requires access to one of the printers, it issues the rtems_semaphore_obtain
directive to obtain access to a printer. If a printer is not currently available, the task can wait for a printer to become available or return immediately. When the task has completed printing, it should issue the rtems_semaphore_release
directive to allow other tasks access to the printer.
Task synchronization may be achieved by creating a semaphore with an initial count of zero. One task waits for the arrival of another task by issuing a rtems_semaphore_obtain
directive when it reaches a synchronization point. The other task performs a corresponding rtems_semaphore_release
operation when it reaches its synchronization point, thus unblocking the pending task.
12.2.1. Nested Resource Access¶
Deadlock occurs when a task owning a binary semaphore attempts to acquire that same semaphore and blocks as result. Since the semaphore is allocated to a task, it cannot be deleted. Therefore, the task that currently holds the semaphore and is also blocked waiting for that semaphore will never execute again.
RTEMS addresses this problem by allowing the task holding the binary semaphore to obtain the same binary semaphore multiple times in a nested manner. Each rtems_semaphore_obtain
must be accompanied with a rtems_semaphore_release
. The semaphore will only be made available for acquisition by other tasks when the outermost rtems_semaphore_obtain
is matched with a rtems_semaphore_release
.
Simple binary semaphores do not allow nested access and so can be used for task synchronization.
12.2.2. Priority Inversion¶
Priority inversion is a form of indefinite postponement which is common in multitasking, preemptive executives with shared resources. Priority inversion occurs when a high priority tasks requests access to shared resource which is currently allocated to low priority task. The high priority task must block until the low priority task releases the resource. This problem is exacerbated when the low priority task is prevented from executing by one or more medium priority tasks. Because the low priority task is not executing, it cannot complete its interaction with the resource and release that resource. The high priority task is effectively prevented from executing by lower priority tasks.
12.2.3. Priority Inheritance¶
Priority inheritance is an algorithm that calls for the lower priority task holding a resource to have its priority increased to that of the highest priority task blocked waiting for that resource. Each time a task blocks attempting to obtain the resource, the task holding the resource may have its priority increased.
On SMP configurations, in case the task holding the resource and the task that blocks attempting to obtain the resource are in different scheduler instances, the priority of the holder is raised to the pseudo-interrupt priority (priority boosting). The pseudo-interrupt priority is the highest priority.
RTEMS supports priority inheritance for local, binary semaphores that use the priority task wait queue blocking discipline. When a task of higher priority than the task holding the semaphore blocks, the priority of the task holding the semaphore is increased to that of the blocking task. When the task holding the task completely releases the binary semaphore (i.e. not for a nested release), the holder’s priority is restored to the value it had before any higher priority was inherited.
The RTEMS implementation of the priority inheritance algorithm takes into account the scenario in which a task holds more than one binary semaphore. The holding task will execute at the priority of the higher of the highest ceiling priority or at the priority of the highest priority task blocked waiting for any of the semaphores the task holds. Only when the task releases ALL of the binary semaphores it holds will its priority be restored to the normal value.
12.2.4. Priority Ceiling¶
Priority ceiling is an algorithm that calls for the lower priority task holding a resource to have its priority increased to that of the highest priority task which will EVER block waiting for that resource. This algorithm addresses the problem of priority inversion although it avoids the possibility of changing the priority of the task holding the resource multiple times. The priority ceiling algorithm will only change the priority of the task holding the resource a maximum of one time. The ceiling priority is set at creation time and must be the priority of the highest priority task which will ever attempt to acquire that semaphore.
RTEMS supports priority ceiling for local, binary semaphores that use the priority task wait queue blocking discipline. When a task of lower priority than the ceiling priority successfully obtains the semaphore, its priority is raised to the ceiling priority. When the task holding the task completely releases the binary semaphore (i.e. not for a nested release), the holder’s priority is restored to the value it had before any higher priority was put into effect.
The need to identify the highest priority task which will attempt to obtain a particular semaphore can be a difficult task in a large, complicated system. Although the priority ceiling algorithm is more efficient than the priority inheritance algorithm with respect to the maximum number of task priority changes which may occur while a task holds a particular semaphore, the priority inheritance algorithm is more forgiving in that it does not require this apriori information.
The RTEMS implementation of the priority ceiling algorithm takes into account the scenario in which a task holds more than one binary semaphore. The holding task will execute at the priority of the higher of the highest ceiling priority or at the priority of the highest priority task blocked waiting for any of the semaphores the task holds. Only when the task releases ALL of the binary semaphores it holds will its priority be restored to the normal value.
12.2.5. Multiprocessor Resource Sharing Protocol¶
The Multiprocessor Resource Sharing Protocol (MrsP) is defined in A. Burns and A.J. Wellings, A Schedulability Compatible Multiprocessor Resource Sharing Protocol - MrsP, Proceedings of the 25th Euromicro Conference on Real-Time Systems (ECRTS 2013), July 2013. It is a generalization of the Priority Ceiling Protocol to SMP systems. Each MrsP semaphore uses a ceiling priority per scheduler instance. These ceiling priorities can be specified with rtems_semaphore_set_priority()
. A task obtaining or owning a MrsP semaphore will execute with the ceiling priority for its scheduler instance as specified by the MrsP semaphore object. Tasks waiting to get ownership of a MrsP semaphore will not relinquish the processor voluntarily. In case the owner of a MrsP semaphore gets preempted it can ask all tasks waiting for this semaphore to help out and temporarily borrow the right to execute on one of their assigned processors.
12.2.6. Building a Semaphore Attribute Set¶
In general, an attribute set is built by a bitwise OR of the desired attribute components. The following table lists the set of valid semaphore attributes:
RTEMS_FIFO | tasks wait by FIFO (default) |
RTEMS_PRIORITY | tasks wait by priority |
RTEMS_BINARY_SEMAPHORE | restrict values to 0 and 1 |
RTEMS_COUNTING_SEMAPHORE | no restriction on values (default) |
RTEMS_SIMPLE_BINARY_SEMAPHORE | restrict values to 0 and 1, do not allow nested access, allow deletion of locked semaphore. |
RTEMS_NO_INHERIT_PRIORITY | do not use priority inheritance (default) |
RTEMS_INHERIT_PRIORITY | use priority inheritance |
RTEMS_NO_PRIORITY_CEILING | do not use priority ceiling (default) |
RTEMS_PRIORITY_CEILING | use priority ceiling |
RTEMS_NO_MULTIPROCESSOR_RESOURCE_SHARING | do not use Multiprocessor Resource Sharing Protocol (default) |
RTEMS_MULTIPROCESSOR_RESOURCE_SHARING | use Multiprocessor Resource Sharing Protocol |
RTEMS_LOCAL | local semaphore (default) |
RTEMS_GLOBAL | global semaphore |
Attribute values are specifically designed to be mutually exclusive, therefore bitwise OR and addition operations are equivalent as long as each attribute appears exactly once in the component list. An attribute listed as a default is not required to appear in the attribute list, although it is a good programming practice to specify default attributes. If all defaults are desired, the attribute RTEMS_DEFAULT_ATTRIBUTES
should be specified on this call.
This example demonstrates the attribute_set parameter needed to create a local semaphore with the task priority waiting queue discipline. The attribute_set parameter passed to the rtems_semaphore_create
directive could be either RTEMS_PRIORITY
or RTEMS_LOCAL | RTEMS_PRIORITY
. The attribute_set parameter can be set to RTEMS_PRIORITY
because RTEMS_LOCAL
is the default for all created tasks. If a similar semaphore were to be known globally, then the attribute_set parameter would be RTEMS_GLOBAL | RTEMS_PRIORITY
.
Some combinatinos of these attributes are invalid. For example, priority ordered blocking discipline must be applied to a binary semaphore in order to use either the priority inheritance or priority ceiling functionality. The following tree figure illustrates the valid combinations.
12.2.7. Building a SEMAPHORE_OBTAIN Option Set¶
In general, an option is built by a bitwise OR of the desired option components. The set of valid options for the rtems_semaphore_obtain
directive are listed in the following table:
RTEMS_WAIT | task will wait for semaphore (default) |
RTEMS_NO_WAIT | task should not wait |
Option values are specifically designed to be mutually exclusive, therefore bitwise OR and addition operations are equivalent as long as each attribute appears exactly once in the component list. An option listed as a default is not required to appear in the list, although it is a good programming practice to specify default options. If all defaults are desired, the option RTEMS_DEFAULT_OPTIONS
should be specified on this call.
This example demonstrates the option parameter needed to poll for a semaphore. The option parameter passed to the rtems_semaphore_obtain
directive should be RTEMS_NO_WAIT
.
12.3. Operations¶
12.3.1. Creating a Semaphore¶
The rtems_semaphore_create
directive creates a binary or counting semaphore with a user-specified name as well as an initial count. If a binary semaphore is created with a count of zero (0) to indicate that it has been allocated, then the task creating the semaphore is considered the current holder of the semaphore. At create time the method for ordering waiting tasks in the semaphore’s task wait queue (by FIFO or task priority) is specified. Additionally, the priority inheritance or priority ceiling algorithm may be selected for local, binary semaphores that use the priority task wait queue blocking discipline. If the priority ceiling algorithm is selected, then the highest priority of any task which will attempt to obtain this semaphore must be specified. RTEMS allocates a Semaphore Control Block (SMCB) from the SMCB free list. This data structure is used by RTEMS to manage the newly created semaphore. Also, a unique semaphore ID is generated and returned to the calling task.
12.3.2. Obtaining Semaphore IDs¶
When a semaphore is created, RTEMS generates a unique semaphore ID and assigns it to the created semaphore until it is deleted. The semaphore ID may be obtained by either of two methods. First, as the result of an invocation of the rtems_semaphore_create
directive, the semaphore ID is stored in a user provided location. Second, the semaphore ID may be obtained later using the rtems_semaphore_ident
directive. The semaphore ID is used by other semaphore manager directives to access this semaphore.
12.3.3. Acquiring a Semaphore¶
The rtems_semaphore_obtain
directive is used to acquire the specified semaphore. A simplified version of the rtems_semaphore_obtain
directive can be described as follows:
If the semaphore’s count is greater than zero then decrement the semaphore’s count else wait for release of semaphore then return SUCCESSFUL.
When the semaphore cannot be immediately acquired, one of the following situations applies:
- By default, the calling task will wait forever to acquire the semaphore.
- Specifying
RTEMS_NO_WAIT
forces an immediate return with an error status code. - Specifying a timeout limits the interval the task will wait before returning with an error status code.
If the task waits to acquire the semaphore, then it is placed in the semaphore’s task wait queue in either FIFO or task priority order. If the task blocked waiting for a binary semaphore using priority inheritance and the task’s priority is greater than that of the task currently holding the semaphore, then the holding task will inherit the priority of the blocking task. All tasks waiting on a semaphore are returned an error code when the semaphore is deleted.
When a task successfully obtains a semaphore using priority ceiling and the priority ceiling for this semaphore is greater than that of the holder, then the holder’s priority will be elevated.
12.3.4. Releasing a Semaphore¶
The rtems_semaphore_release
directive is used to release the specified semaphore. A simplified version of the rtems_semaphore_release
directive can be described as follows:
If there sre no tasks are waiting on this semaphore then increment the semaphore’s count else assign semaphore to a waiting task and return SUCCESSFUL.
If this is the outermost release of a binary semaphore that uses priority inheritance or priority ceiling and the task does not currently hold any other binary semaphores, then the task performing the rtems_semaphore_release
will have its priority restored to its normal value.
12.3.5. Deleting a Semaphore¶
The rtems_semaphore_delete
directive removes a semaphore from the system and frees its control block. A semaphore can be deleted by any local task that knows the semaphore’s ID. As a result of this directive, all tasks blocked waiting to acquire the semaphore will be readied and returned a status code which indicates that the semaphore was deleted. Any subsequent references to the semaphore’s name and ID are invalid.
12.4. Directives¶
This section details the semaphore manager’s directives. A subsection is dedicated to each of this manager’s directives and describes the calling sequence, related constants, usage, and status codes.
12.4.1. SEMAPHORE_CREATE - Create a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_create( rtems_name name, uint32_t count, rtems_attribute attribute_set, rtems_task_priority priority_ceiling, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
semaphore created successfully RTEMS_INVALID_NAME
invalid semaphore name RTEMS_INVALID_ADDRESS
id
is NULLRTEMS_TOO_MANY
too many semaphores created RTEMS_NOT_DEFINED
invalid attribute set RTEMS_INVALID_NUMBER
invalid starting count for binary semaphore RTEMS_MP_NOT_CONFIGURED
multiprocessing not configured RTEMS_TOO_MANY
too many global objects - DESCRIPTION:
This directive creates a semaphore which resides on the local node. The created semaphore has the user-defined name specified in name and the initial count specified in count. For control and maintenance of the semaphore, RTEMS allocates and initializes a SMCB. The RTEMS-assigned semaphore id is returned in id. This semaphore id is used with other semaphore related directives to access the semaphore.
Specifying PRIORITY in attribute_set causes tasks waiting for a semaphore to be serviced according to task priority. When FIFO is selected, tasks are serviced in First In-First Out order.
- NOTES:
This directive will not cause the calling task to be preempted.
The priority inheritance and priority ceiling algorithms are only supported for local, binary semaphores that use the priority task wait queue blocking discipline.
The following semaphore attribute constants are defined by RTEMS:
RTEMS_FIFO
tasks wait by FIFO (default) RTEMS_PRIORITY
tasks wait by priority RTEMS_BINARY_SEMAPHORE
restrict values to 0 and 1 RTEMS_COUNTING_SEMAPHORE
no restriction on values (default) RTEMS_SIMPLE_BINARY_SEMAPHORE
restrict values to 0 and 1, block on nested access, allow deletion of locked semaphore. RTEMS_NO_INHERIT_PRIORITY
do not use priority inheritance (default) RTEMS_INHERIT_PRIORITY
use priority inheritance RTEMS_NO_PRIORITY_CEILING
do not use priority ceiling (default) RTEMS_PRIORITY_CEILING
use priority ceiling RTEMS_NO_MULTIPROCESSOR_RESOURCE_SHARING
do not use Multiprocessor Resource Sharing Protocol (default) RTEMS_MULTIPROCESSOR_RESOURCE_SHARING
use Multiprocessor Resource Sharing Protocol RTEMS_LOCAL
local semaphore (default) RTEMS_GLOBAL
global semaphore Semaphores should not be made global unless remote tasks must interact with the created semaphore. This is to avoid the system overhead incurred by the creation of a global semaphore. When a global semaphore is created, the semaphore’s name and id must be transmitted to every node in the system for insertion in the local copy of the global object table.
Note, some combinations of attributes are not valid. See the earlier discussion on this.
The total number of global objects, including semaphores, is limited by the maximum_global_objects field in the Configuration Table.
It is not allowed to create an initially locked MrsP semaphore and the
RTEMS_INVALID_NUMBER
status code will be returned on SMP configurations in this case. This prevents lock order reversal problems with the allocator mutex.
12.4.2. SEMAPHORE_IDENT - Get ID of a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_ident( rtems_name name, uint32_t node, rtems_id *id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
semaphore identified successfully RTEMS_INVALID_NAME
semaphore name not found RTEMS_INVALID_NODE
invalid node id - DESCRIPTION:
- This directive obtains the semaphore id associated with the semaphore name. If the semaphore name is not unique, then the semaphore id will match one of the semaphores with that name. However, this semaphore id is not guaranteed to correspond to the desired semaphore. The semaphore id is used by other semaphore related directives to access the semaphore.
- NOTES:
This directive will not cause the running task to be preempted.
If node is
RTEMS_SEARCH_ALL_NODES
, all nodes are searched with the local node being searched first. All other nodes are searched with the lowest numbered node searched first.If node is a valid node number which does not represent the local node, then only the semaphores exported by the designated node are searched.
This directive does not generate activity on remote nodes. It accesses only the local copy of the global object table.
12.4.3. SEMAPHORE_DELETE - Delete a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_delete( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
semaphore deleted successfully RTEMS_INVALID_ID
invalid semaphore id RTEMS_RESOURCE_IN_USE
binary semaphore is in use RTEMS_ILLEGAL_ON_REMOTE_OBJECT
cannot delete remote semaphore - DESCRIPTION:
- This directive deletes the semaphore specified by
id
. All tasks blocked waiting to acquire the semaphore will be readied and returned a status code which indicates that the semaphore was deleted. The SMCB for this semaphore is reclaimed by RTEMS. - NOTES:
The calling task will be preempted if it is enabled by the task’s execution mode and a higher priority local task is waiting on the deleted semaphore. The calling task will NOT be preempted if all of the tasks that are waiting on the semaphore are remote tasks.
The calling task does not have to be the task that created the semaphore. Any local task that knows the semaphore id can delete the semaphore.
When a global semaphore is deleted, the semaphore id must be transmitted to every node in the system for deletion from the local copy of the global object table.
The semaphore must reside on the local node, even if the semaphore was created with the
RTEMS_GLOBAL
option.Proxies, used to represent remote tasks, are reclaimed when the semaphore is deleted.
12.4.4. SEMAPHORE_OBTAIN - Acquire a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_obtain( rtems_id id, rtems_option option_set, rtems_interval timeout );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
semaphore obtained successfully RTEMS_UNSATISFIED
semaphore not available RTEMS_TIMEOUT
timed out waiting for semaphore RTEMS_OBJECT_WAS_DELETED
semaphore deleted while waiting RTEMS_INVALID_ID
invalid semaphore id - DESCRIPTION:
This directive acquires the semaphore specified by id. The
RTEMS_WAIT
andRTEMS_NO_WAIT
components of the options parameter indicate whether the calling task wants to wait for the semaphore to become available or return immediately if the semaphore is not currently available. With eitherRTEMS_WAIT
orRTEMS_NO_WAIT
, if the current semaphore count is positive, then it is decremented by one and the semaphore is successfully acquired by returning immediately with a successful return code.If the calling task chooses to return immediately and the current semaphore count is zero or negative, then a status code is returned indicating that the semaphore is not available. If the calling task chooses to wait for a semaphore and the current semaphore count is zero or negative, then it is decremented by one and the calling task is placed on the semaphore’s wait queue and blocked. If the semaphore was created with the
RTEMS_PRIORITY
attribute, then the calling task is inserted into the queue according to its priority. However, if the semaphore was created with theRTEMS_FIFO
attribute, then the calling task is placed at the rear of the wait queue. If the binary semaphore was created with theRTEMS_INHERIT_PRIORITY
attribute, then the priority of the task currently holding the binary semaphore is guaranteed to be greater than or equal to that of the blocking task. If the binary semaphore was created with theRTEMS_PRIORITY_CEILING
attribute, a task successfully obtains the semaphore, and the priority of that task is greater than the ceiling priority for this semaphore, then the priority of the task obtaining the semaphore is elevated to that of the ceiling.The timeout parameter specifies the maximum interval the calling task is willing to be blocked waiting for the semaphore. If it is set to
RTEMS_NO_TIMEOUT
, then the calling task will wait forever. If the semaphore is available or theRTEMS_NO_WAIT
option component is set, then timeout is ignored.Deadlock situations are detected for MrsP semaphores and the
RTEMS_UNSATISFIED
status code will be returned on SMP configurations in this case.- NOTES:
The following semaphore acquisition option constants are defined by RTEMS:
RTEMS_WAIT
task will wait for semaphore (default) RTEMS_NO_WAIT
task should not wait Attempting to obtain a global semaphore which does not reside on the local node will generate a request to the remote node to access the semaphore. If the semaphore is not available and
RTEMS_NO_WAIT
was not specified, then the task must be blocked until the semaphore is released. A proxy is allocated on the remote node to represent the task until the semaphore is released.A clock tick is required to support the timeout functionality of this directive.
It is not allowed to obtain a MrsP semaphore more than once by one task at a time (nested access) and the
RTEMS_UNSATISFIED
status code will be returned on SMP configurations in this case.
12.4.5. SEMAPHORE_RELEASE - Release a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_release( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
semaphore released successfully RTEMS_INVALID_ID
invalid semaphore id RTEMS_NOT_OWNER_OF_RESOURCE
calling task does not own semaphore RTEMS_INCORRECT_STATE
invalid unlock order - DESCRIPTION:
- This directive releases the semaphore specified by id. The semaphore count is incremented by one. If the count is zero or negative, then the first task on this semaphore’s wait queue is removed and unblocked. The unblocked task may preempt the running task if the running task’s preemption mode is enabled and the unblocked task has a higher priority than the running task.
- NOTES:
The calling task may be preempted if it causes a higher priority task to be made ready for execution.
Releasing a global semaphore which does not reside on the local node will generate a request telling the remote node to release the semaphore.
If the task to be unblocked resides on a different node from the semaphore, then the semaphore allocation is forwarded to the appropriate node, the waiting task is unblocked, and the proxy used to represent the task is reclaimed.
The outermost release of a local, binary, priority inheritance or priority ceiling semaphore may result in the calling task having its priority lowered. This will occur if the calling task holds no other binary semaphores and it has inherited a higher priority.
The MrsP semaphores must be released in the reversed obtain order, otherwise the
RTEMS_INCORRECT_STATE
status code will be returned on SMP configurations in this case.
12.4.6. SEMAPHORE_FLUSH - Unblock all tasks waiting on a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_flush( rtems_id id );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
semaphore released successfully RTEMS_INVALID_ID
invalid semaphore id RTEMS_NOT_DEFINED
operation not defined for the protocol ofthe semaphore RTEMS_ILLEGAL_ON_REMOTE_OBJECT
not supported for remote semaphores - DESCRIPTION:
This directive unblocks all tasks waiting on the semaphore specified by id. Since there are tasks blocked on the semaphore, the semaphore’s count is not changed by this directive and thus is zero before and after this directive is executed. Tasks which are unblocked as the result of this directive will return from the
rtems_semaphore_obtain
directive with a status code ofRTEMS_UNSATISFIED
to indicate that the semaphore was not obtained.This directive may unblock any number of tasks. Any of the unblocked tasks may preempt the running task if the running task’s preemption mode is enabled and an unblocked task has a higher priority than the running task.
- NOTES:
The calling task may be preempted if it causes a higher priority task to be made ready for execution.
If the task to be unblocked resides on a different node from the semaphore, then the waiting task is unblocked, and the proxy used to represent the task is reclaimed.
It is not allowed to flush a MrsP semaphore and the
RTEMS_NOT_DEFINED
status code will be returned on SMP configurations in this case.
12.4.7. SEMAPHORE_SET_PRIORITY - Set priority by scheduler for a semaphore¶
- CALLING SEQUENCE:
rtems_status_code rtems_semaphore_set_priority( rtems_id semaphore_id, rtems_id scheduler_id, rtems_task_priority new_priority, rtems_task_priority *old_priority );
- DIRECTIVE STATUS CODES:
RTEMS_SUCCESSFUL
successful operation RTEMS_INVALID_ID
invalid semaphore or scheduler id RTEMS_INVALID_ADDRESS
old_priority
is NULLRTEMS_INVALID_PRIORITY
invalid new priority value RTEMS_NOT_DEFINED
operation not defined for the protocol ofthe semaphore RTEMS_ILLEGAL_ON_REMOTE_OBJECT
not supported for remote semaphores - DESCRIPTION:
This directive sets the priority value with respect to the specified scheduler of a semaphore.
The special priority value
RTEMS_CURRENT_PRIORITY
can be used to get the current priority value without changing it.The interpretation of the priority value depends on the protocol of the semaphore object.
- The Multiprocessor Resource Sharing Protocol needs a ceiling priority per scheduler instance. This operation can be used to specify these priority values.
- For the Priority Ceiling Protocol the ceiling priority is used with this operation.
- For other protocols this operation is not defined.
- EXAMPLE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
#include <assert.h> #include <stdlib.h> #include <rtems.h> #define SCHED_A rtems_build_name(' ', ' ', ' ', 'A') #define SCHED_B rtems_build_name(' ', ' ', ' ', 'B') static void Init(rtems_task_argument arg) { rtems_status_code sc; rtems_id semaphore_id; rtems_id scheduler_a_id; rtems_id scheduler_b_id; rtems_task_priority prio; /* Get the scheduler identifiers */ sc = rtems_scheduler_ident(SCHED_A, &scheduler_a_id); assert(sc == RTEMS_SUCCESSFUL); sc = rtems_scheduler_ident(SCHED_B, &scheduler_b_id); assert(sc == RTEMS_SUCCESSFUL); /* Create a MrsP semaphore object */ sc = rtems_semaphore_create( rtems_build_name('M', 'R', 'S', 'P'), 1, RTEMS_MULTIPROCESSOR_RESOURCE_SHARING | RTEMS_BINARY_SEMAPHORE, 1, &semaphore_id ); assert(sc == RTEMS_SUCCESSFUL); /* * The ceiling priority values per scheduler are equal to the value specified * for object creation. */ prio = RTEMS_CURRENT_PRIORITY; sc = rtems_semaphore_set_priority(semaphore_id, scheduler_a_id, prio, &prio); assert(sc == RTEMS_SUCCESSFUL); assert(prio == 1); /* Check the old value and set a new ceiling priority for scheduler B */ prio = 2; sc = rtems_semaphore_set_priority(semaphore_id, scheduler_b_id, prio, &prio); assert(sc == RTEMS_SUCCESSFUL); assert(prio == 1); /* Check the ceiling priority values */ prio = RTEMS_CURRENT_PRIORITY; sc = rtems_semaphore_set_priority(semaphore_id, scheduler_a_id, prio, &prio); assert(sc == RTEMS_SUCCESSFUL); assert(prio == 1); prio = RTEMS_CURRENT_PRIORITY; sc = rtems_semaphore_set_priority(semaphore_id, scheduler_b_id, prio, &prio); assert(sc == RTEMS_SUCCESSFUL); assert(prio == 2); sc = rtems_semaphore_delete(semaphore_id); assert(sc == RTEMS_SUCCESSFUL); exit(0);