CMSIS-RTOS2  
Real-Time Operating System API
 
Loading...
Searching...
No Matches
Using CMSIS-RTOS2 Interface

This sections explains concepts for using CMSIS-RTOS2 interface. They are recommeded to follow for best reusability of the software across different platforms.

  • Functionality overview lists the OS services supported by CMSIS-RTOS2 API.
  • cmsis_os2.h API header file explains how CMSIS-RTOS2 interface is defined and can be used along with the RTOS-specific files as well as part of CMSIS pack.
  • System Startup shows the flow for kernel initialization.
  • Lifecycle of RTOS Objects explains the approach to creating and using RTOS Objects.
  • Memory Management provides information about options for memory management with CMSIS-RTOS2.
  • Process Isolation describes the CMSIS-RTOS2 concepts for protecting execution of critical software tasks against potential flaws in other parts of a program.

Note

Functionality overview

The CMSIS-RTOS2 defines APIs for common RTOS services as listed below:

The referenced pages contain theory of operation for corresponding services as well as detailed API description with example code.

cmsis_os2.h API header file

The CMSIS-RTOS2 interface is provided in cmsis_os2.h file - a standard C header file that user applications and middleware components need to include to access CMSIS-RTOS2 API. It contains all the function declarations, as well as type and macro definitions.

An implementation specific header file (rtos.h in the picture below) provides access to such definitions. Using the cmsis_os2.h along with dynamic object allocation allows to create source code or libraries that require no modifications when using on a different CMSIS-RTOS2 implementation.

CMSIS-RTOS File Structure

Once the files are added to a project, the user can start working with the CMSIS-RTOS functions.

CMSIS-RTOS2 is especially easy use to integrate in projects that support CMSIS-Pack format. CMSIS-RTOS2 is provided in the CMSIS 6 Software Pack as a software component in form of a central API defintion It is part of component class CMSIS and belongs to component group RTOS2.

Coding Rules

CMSIS-RTOS2 follows the general CMSIS coding rules. Additionally following Namespace prefixes are used in CMSIS-RTOS2 API:

System Startup

When program execution reaches main() function there is a recommended order to initialize the hardware and start the kernel.

Your application's main() should implement at least the following in the given order:

  1. Initialize and configure hardware including peripherals, memory, pins, clocks and the interrupt system.
  2. Update the system core clock using the respective CMSIS-Core (Cortex-M) or CMSIS-Core (Cortex-A) function.
  3. Initialize the RTOS kernel using osKernelInitialize.
  4. Optionally, create one thread (for example app_main) using osThreadNew, which will be used as a main thread . This thread should take care of creating and starting objects, once it is run by the scheduler. Alternatively, threads can be created directly in main().
  5. Start the RTOS scheduler using osKernelStart which also configures the system tick timer and initializes RTOS specific interrupts. This function does not return in case of successful execution. Therefore, any application code after osKernelStart will not be executed.

Note

  • Modifying priorities and groupings in the NVIC by the application after the above sequence is not recommended.
  • Before executing osKernelStart, only the functions osKernelGetInfo, osKernelGetState, and object creation functions (osXxxNew) may be called.

Code Example

/*----------------------------------------------------------------------------
* CMSIS-RTOS 'main' function template
*---------------------------------------------------------------------------*/
#include "RTE_Components.h"
#include CMSIS_device_header
#include "cmsis_os2.h"
/*----------------------------------------------------------------------------
* Application main thread
*---------------------------------------------------------------------------*/
void app_main (void *argument) {
// ...
for (;;) {}
}
int main (void) {
// System Initialization
SystemCoreClockUpdate();
// ...
osKernelInitialize(); // Initialize CMSIS-RTOS
osThreadNew(app_main, NULL, NULL); // Create application main thread
osKernelStart(); // Start thread execution
for (;;) {}
}

Lifecycle of RTOS Objects

All RTOS objects share a common design concept. The overall life-cycle of an object can be summarized as created -> in use -> destroyed.

Create Objects

An RTOS object (thread, timer, flags, mutex, etc.) is created by calling its osXxxNew function (for example osThreadNew, osTimerNew, osEventFlagsNew, etc). The new function returns a numeric identifier that can be used to operate with the new object.

The actual state of an object is typically stored in an object specific control block. The memory layout (and size needed) for the control block is implementation specific. One should not make any specific assumptions about the control block. The control block layout might change and hence should be seen as an implementation internal detail.

In order to expose control about object specific options all osXxxNew functions provide an optional attr argument, which can be left as NULL by default. It takes a pointer to an object specific attribute structure, commonly containing the fields:

  • name to attach a human readable name to the object for identification,
  • attr_bits to control object-specific options,
  • cb_mem to provide memory for the control block manually, and
  • cb_size to quantify the memory size provided for the control block.

The name attribute is only used for object identification, e.g. using RTOS-aware debugging. The attached string is not used for any other purposes internally.

The cb_mem and cb_size attributes can be used to provide memory for the control block manually instead of relying on the implementation internal memory allocation. One has to assure that the amount of memory pointed to by cb_mem is sufficient for the objects control block structure. If the size given as cb_size is not sufficient the osXxxNew function returns with an error, i.e. returning NULL. Furthermore providing control block memory manually is less portable. Thus one has to take care about implementation specific alignment and placement requirements for instance. Refer to Memory Management for further details.

Object Usage

After an object has been created successfully it can be used until it is destroyed. The actions defined for an object depends on its type. Commonly all the osXxxDoSomething access function require the reference to the object to work with as the first xxx_id parameter.

The access function can be assumed to apply some sort of sanity checking on the id parameter. So that it is assured one cannot accidentally call an access function with a NULL object reference. Furthermore the concrete object type is verified, i.e. one cannot call access functions of one object type with a reference to another object type.

All further parameter checks applied are either object and action specific or may even be implementation specific. Thus one should always check action function return values for osErrorParameter to assure the provided arguments were accepted.

As a rule of thumb only non-blocking access function can be used from Interrupt Service Routines (ISR). This incorporates osXxxWait functions (and similar) limited to be called with parameter timeout set to 0, i.e. usage of try-semantics.

Object Destruction

Objects that are not needed anymore can be destructed on demand to free the control block memory. Objects are not destructed implicitly. Thus one can assume an object id to be valid until osXxxDelete is called explicitly. The delete function finally frees the control block memory. In case of user provided control block memory, see above, the memory must be freed manually as well.

The only exception one has to take care of are Threads which do not have an explicit osThreadDelete function. Threads can either be detached or joinable. Detached threads are automatically destroyed on termination, i.e. call to osThreadTerminate or osThreadExit or return from thread function. On the other hand joinable threads are kept alive until one explicitly calls osThreadJoin.

Timeout Values

Timeout value is an argument in many API functions that allows to set the maximum time delay for resolving a request. The timeout value specifies the number of timer ticks until the time delay elapses. The value is an upper bound and depends on the actual time elapsed since the last timer tick.

Examples:

  • timeout value 0 : the system does not wait, even when no resource is available the RTOS function returns instantly.
  • timeout value 1 : the system waits until the next timer tick occurs; depending on the previous timer tick, it may be a very short wait time.
  • timeout value 2 : actual wait time is between 1 and 2 timer ticks.
  • timeout value osWaitForever : system waits infinite until a resource becomes available. Or one forces the thread to resume using osThreadResume which is discouraged.
Example of timeout using osDelay()
  • CPU time can be scheduled with the following functionalities:
    • A timeout parameter is incorporated in many CMSIS-RTOS2 functions to avoid system lockup. When a timeout is specified, the system waits until a resource is available or an event occurs. While waiting, other threads are scheduled.
    • The osDelay and osDelayUntil functions put a thread into the WAITING state for a specified period of time.
    • The osThreadYield provides co-operative thread switching and passes execution to another thread of the same priority.

Calls from Interrupt Service Routines

The following CMSIS-RTOS2 functions can be called from threads and Interrupt Service Routines (ISR):

Functions that cannot be called from an ISR are verifying the interrupt status and return the status code osErrorISR, in case they are called from an ISR context. In some implementations, this condition might be caught using the HARD_FAULT

Memory Management

The CMSIS-RTOS2 API offers two options for memory management the user can choose. For object storage one can either use

In order to affect the memory allocation scheme all RTOS objects that can be created on request, i.e. those having a osXxxNew function, accept an optional osXxxAttr_t attr argument on creation. As a rule of thumb the object attributes at least have members to assign custom control block memory, i.e. cb_mem and cb_size members. By default, i.e. attr is NULL or cb_mem is NULL, Automatic Dynamic Allocation is used. Providing a pointer to user memory in cb_mem switches to Manual User-defined Allocation.

Automatic Dynamic Allocation

The automatic allocation is the default and viable for many use-cases. Moreover it is fully portable across different implementations of the CMSIS-RTOS2 API. The common drawback of dynamic memory allocation is the possibility of memory fragmentation and exhaustion. Given that all needed objects are created once upon system initialization and never deleted at runtime this class of runtime failures can be prevented, though.

The actual allocation strategy used is implementation specific, i.e. whether global heap or preallocated memory pools are used.

Code Example:

#include "cmsis_os2.h" // CMSIS-RTOS2 API header
osMutexId_t mutex_id;
osMutexId_t mutex2_id;
const osMutexAttr_t Thread_Mutex_attr = {
"myThreadMutex", // human readable mutex name
NULL, // memory for control block (default)
0U // size for control block (default)
};
void CreateMutex (void) {
mutex_id = osMutexNew(NULL); // use default values for all attributes
mutex2_id = osMutexNew(&Thread_Mutex_attr); // use attributes from defined structure
:
}

The Mutexes in this example are created using automatic memory allocation.

Manual User-defined Allocation

One can get fine grained control over memory allocation by providing user-defined memory. The actual requirements such user-defined memory are kernel-specific. Thus one needs to carefully refer to the size and alignment rules of the implementation used.

Code Example:

#include "cmsis_os2.h" // CMSIS-RTOS2 API header
#include "rtx_os.h" // kernel include file
osMutexId_t mutex_id;
static osRtxMutex_t mutex_cb __attribute__((section(".bss.os.mutex.cb"))); // Placed on .bss.os.mutex.cb section for RTX5 aware debugging
const osMutexAttr_t Thread_Mutex_attr = {
"myThreadMutex", // human readable mutex name
&mutex_cb, // memory for control block (user-defined)
sizeof(mutex_cb) // size for control block (user-defined)
};
void CreateMutex (void) {
mutex_id = osMutexNew(&Thread_Mutex_attr); // use attributes from defined structure
:
}

The above example uses user-defined memory for the mutex control block. For this mutex_cb is defined with the control block type provided by the kernel header file rtx_os.h from CMSIS-RTX RTOS kernel.