0% found this document useful (0 votes)
5 views

Unit 5 Embedded software Design-II

The document discusses the design of embedded system software, focusing on OS-based design, real-time kernels, task management, and inter-process communication. It explains multitasking, task states, synchronization methods like mutexes and semaphores, and provides APIs for task management in the RTX kernel. Additionally, it highlights the importance of resource synchronization and the role of tasks in managing CPU time and system resources.

Uploaded by

Raj Hingar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit 5 Embedded software Design-II

The document discusses the design of embedded system software, focusing on OS-based design, real-time kernels, task management, and inter-process communication. It explains multitasking, task states, synchronization methods like mutexes and semaphores, and provides APIs for task management in the RTX kernel. Additionally, it highlights the importance of resource synchronization and the role of tasks in managing CPU time and system resources.

Uploaded by

Raj Hingar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

RV College of

Engineering

Unit 5
Designing Embedded System Software –II
1
Designing Embedded System Software –II
OS based Design, Real Time Kernel, Process& Thread, Inter Process Communications,
Synchronization, Kernel Services, Case Study: RTX-ARM/FreeRTOS

2 MGRJ,ECE,RVCE
OS based Design
 The embedded application which requires execution of several operations
simultaneously, often supported with Kernel(Operating System).
 The kernel provides scheduler to allocate different resources among concurrently
executing operations(tasks).
 The each task is executed for a small portion of CPU processing time and currently
executing task is stopped and other tasks are given a chance to execute. The switching
will happen at very high rate and creates an illusion that execution is parallel.
 The Embedded OS is responsible for scheduling the execution of user tasks and the
allocation of system resources among multiple tasks.
 This is called as multitasking and is supported by creating multiple threads.

3 MGRJ,ECE,RVCE
 A multitasking scenario is illustrated in figure shown
OS based design…
below.
 In this scenario, the kernel multitasks in such a way
that many threads of execution appear to be running
parallel; however, the kernel is actually
interleaving executions sequentially, based on
scheduling algorithm.
 The scheduler must ensure that the appropriate task 1 2

runs at the right time.


 Each task has its own context, which is the state of
the CPU registers required each time it is scheduled
to run.
 A context switch occurs when the scheduler
switches from one task to another.
Source: Qing Li, “Real-Time Concepts for Embedded Systems”, CMP Books
4 MGRJ,ECE,RVCE
Embedded Software Stack up
 A real-time operating system (RTOS) is
a program that schedules execution in a
timely manner, manages system
resources.
 In some applications, an RTOS
comprises only a kernel, which is the
core supervisory software that provides
minimal logic, scheduling, and
resource-management algorithms.

5 MGRJ,ECE,RVCE
Real Time Kernel
 The kernel is the part of a multitasking system responsible for the management of
tasks (that is, for managing the CPU's time) and communication between tasks. The
fundamental service provided by the kernel is context switching.
 A kernel will add overhead, because it requires an extra memory(code space),
additional RAM for the kernel data structures.
 A kernel will also consume CPU time (typically between 2 and 5%).
 A kernel is provided with different objects to be used in an application program by
calling APIs.

6 MGRJ,ECE,RVCE
Real Time Kernel…

Most RTOS kernels contain the following components:


 Scheduler-is contained within each kernel and follows a set of algorithms that
determines which task executes when. Some common examples of scheduling
algorithms include round-robin and pre-emptive scheduling.
 Objects-are special kernel constructs that help developers create applications for
real-time embedded systems. Common kernel objects include tasks, semaphores,
and message queues.
 Services-are operations that the kernel performs on an object or, generally
operations such as timing, interrupt handling, and resource management.

7 MGRJ,ECE,RVCE
Real Time Kernel…

 The figure shows different


objects of a Kernel.

Source: Qing Li, “Real-Time Concepts for Embedded Systems”, CMP Books
8 MGRJ,ECE,RVCE
Task
 A task is an independent thread of execution
that can compete with other concurrent
tasks for processor execution time.
 Developers decompose applications into
multiple concurrent tasks to optimize the
handling of inputs and outputs within set
time constraints.
 A task is defined by its distinct set of
parameters and supporting data structures.
 Upon creation, each task has an associated
name, a unique ID, a priority, a task control
block (TCB), a stack, and a task routine, as
shown in figure.
Source: Qing Li, “Real-Time Concepts for Embedded Systems”, CMP Books
9 MGRJ,ECE,RVCE
Task….
 When the kernel first starts, it creates its own set of system tasks and allocates the
appropriate priority for each from a set of reserved priority levels.
 Examples of system tasks include:
initialization or start up task—initializes the system and creates and starts
system tasks,
logging task—logs system messages,
exception-handling task—handles exceptions
debug agent task—allows debugging with a host debugger.
 As the developer creates new tasks, the developer must assign each a task name,
priority, stack size, and a task routine. The kernel does the rest by assigning each task a
unique ID and creating an associated TCB and stack space in memory for it.

10 MGRJ,ECE,RVCE
Task….
Task States
 Whether it's a system task or an
application task, at any time each task
exists in one of a small number of
states, including ready, running, or
blocked.
 As the real-time embedded system
runs, each task moves from one state to
another, according to the logic of a
simple finite state machine (FSM) as
shown in figure.

Source: Qing Li, “Real-Time Concepts for Embedded Systems”, CMP Books
11 MGRJ,ECE,RVCE
Task States….

 Although kernels can define task-state groupings differently, generally three main states
are used in most typical pre emptive-scheduling kernels, including:
 ready state-the task is ready to run but cannot because a higher priority task is
executing.
 blocked state-the task has requested a resource that is not available, has requested
to wait until some event occurs, or has delayed itself for some duration.
 running state-the task is the highest priority task and is running.
 Note some commercial kernels, such as the VxWorks kernel, define other, more granular
states, such as suspended, pended, and delayed.

12 MGRJ,ECE,RVCE
Task….
 When writing code for tasks, tasks are structured in one of two ways:
Run to completion: Pseudo Code

Endless loop: Pseudo Code

13 MGRJ,ECE,RVCE
Task Management APIs of RL-RTX
 The RTX kernel is an easy to use Real Time eXecutive (RTX) providing a
set of C functions and macros for building real-time applications which are
using tasks running quasi-parallel on the CPU.
 RTX Kernel Library can be used with devices based on:
-ARM7 and ARM9
- Cortex-M0/M1, Cortex-M3, Cortex-M4, and Cortex-R4

14 MGRJ,ECE,RVCE
RL-RTX…
 Technical Data

Source: Keil IDE Help Tab


15 MGRJ,ECE,RVCE
RL-RTX…

 Timing Specification

Source: Keil IDE Help Tab


16 MGRJ,ECE,RVCE
 Task Management APIs

17 MGRJ,ECE,RVCE
void os_sys_init ( void (*task)(void) ); Task Management APIs…

 The os_sys_init function initializes and starts the Real-Time eXecutive (RTX) kernel.
 The task argument points to the task function to start after the kernel is initialized. The
RTX kernel gives the task a default priority of 1.
 The os_sys_init function is in the RL-RTX library.The prototype is defined in rtl.h.
OS_TID os_tsk_create ( void (*task)(void), U8 priority );
 The os_tsk_create function creates the task identified by the task function pointer
argument and then adds the task to the ready queue. It dynamically assigns a task identifier
value (TID) to the new task.
 The priority argument specifies the priority for the task.The default task priority is 1.
void os_tsk_delete_self (void);
 The os_tsk_delete_self function stops and deletes the currently running task. The
program execution continues with the task with the next highest priority in the ready
queue.
18 MGRJ,ECE,RVCE
Process and Thread
 An application consist of one more
process. A process, in the simplest
terms is an executing program.
 One or more threads run in the
context of the process.
 A thread is the basic unit to which
the operating system allocates
processor time.
 The figure shows threads in a
process.

19 MGRJ,ECE,RVCE
Synchronization
 Synchronization is classified into two categories:
- Resource synchronization determines whether access to a shared resource is safe,
and, if not, when it will be safe.
E.g. Mutex, Semaphores can be used for resource synchronization.
- Activity synchronization determines whether the execution of a multithreaded
program has reached a certain state and, if it hasn't, how to wait for and be notified
when this state is reached.
E.g. Signals and Events are used to execution synchronization, Barrier
synchronization.

Source: Qing Li, “Real-Time Concepts for Embedded Systems”, CMP Books

20 MGRJ,ECE,RVCE
Resource Synchronization
 Access by multiple tasks must be synchronized to maintain the integrity of a shared
resource.This process is called resource synchronization.
 Mutual exclusion is a provision by which only one task at a time can access a shared
resource. A critical section is the section of code from which the shared resource is
accessed.
E.g: Consider two tasks trying to access shared memory. One task (the sensor task)
periodically receives data from a sensor and writes the data to shared memory. Meanwhile, a
second task (the display task) periodically reads from shared memory and sends the data to a
display.

21 MGRJ,ECE,RVCE
Resource Synchronization…

Mutex
 A mutual exclusion algorithm ensures that one task's execution of a critical section is not
interrupted by the competing critical sections of other concurrently executing tasks.
RL-RTX Mutex Management APIs:
 void os_mut_init (OS_MUT *mutex );
This function initializes the mutex object identified by the function argument.
 OS_RESULT os_mut_wait (OS_MUT *mutex, U16 timeout);
-This function tries to acquire the mutex identified by the function argument. If the mutex
has not been locked by another task, the calling task acquires and locks the mutex and
might continue immediately.
-If the mutex has been locked by another task, then the RTX kernel puts the calling task to
sleep until the mutex becomes unlocked or until the timeout expires.

22 MGRJ,ECE,RVCE
Mutex…

 OS_RESULT os_mut_release (OS_MUT mutex );


-This function decrements the internal counter of the mutex identified by the
function argument in order to release the mutex.
-Only when the internal counter of the mutex is zero, then the mutex is really free
to be acquired by another task.
-The priority inheritance method is used in mutex management routines to
eliminate priority inversion problems.

23 MGRJ,ECE,RVCE
Semaphore
 A semaphore (sometimes called a semaphore token) is a kernel object that one or more
threads of execution can acquire or release for the purposes of synchronization or
mutual exclusion.
• When a semaphore is first created, the kernel
assigns to it an associated semaphore
control block (SCB), a unique ID, a
value (binary or a count), and a task-
waiting list, as shown in figure.
• The kernel tracks the number of times a
semaphore has been acquired or released by
maintaining a token count, which is
initialized to a value when the semaphore is
created. As a task acquires the semaphore, the
token count is decremented; as a task releases
the semaphore, the count is incremented.
24
Semaphore….
 If the token count reaches 0, the semaphore has no tokens left. A requesting task,
therefore, cannot acquire the semaphore, and the task blocks if it chooses to wait for the
semaphore to become available.
 A kernel can support many different types of semaphores, including binary, counting,
and mutual-exclusion (mutex) semaphores.
 Binary Semaphores: A binary semaphore can have a value of either 0 or 1. When a binary
semaphore’s value is 0, the semaphore is considered unavailable (or empty); when the value
is 1, the binary semaphore is considered available (or full ).
• Binary semaphores are treated as global
resources, which means they are shared
among all tasks that need them. Making
the semaphore a global resource allows
any task to release it, even if the task did
not initially acquire it.
25 MGRJ,ECE,RVCE
Counting Semaphores
 A counting semaphore uses a count to allow it to be acquired or released multiple times.
When creating a counting semaphore, assign the semaphore a count that denotes the
number of semaphore tokens it has initially.
 If the initial count is 0, the counting semaphore is created in the unavailable state. If the
count is greater than 0, the semaphore is created in the available state, and the number of
tokens it has equals its count.
 Counting semaphores are global resources
that can be shared by all tasks that need them.

26 MGRJ,ECE,RVCE
Mutual Exclusion (Mutex) Semaphores
 A mutual exclusion (mutex) semaphore is a special binary semaphore that supports ownership,
recursive access, task deletion safety, and one or more protocols for avoiding problems
inherent to mutual exclusion.
 Ownership: When a task owns the mutex, it is not possible for any other task to lock or
unlock that mutex.
 Recursive Locking: This type of mutex is most useful when a task requiring exclusive
access to a shared resource calls one or more routines that also require access to the same
resource.
 Task Deletion Safety: Enabling this capability
within a mutex ensures that while a task owns
the mutex, the task cannot be deleted.

27 MGRJ,ECE,RVCE
RL-RTX Semaphore management APIs
 void os_sem_init ( OS_SEM semaphore, U16 token_count );
The os_sem_init function initializes the semaphore object identified by the function
argument.
The argument token_count determines the number of tokens stored in the semaphore
initially.
 OS_RESULT os_sem_send ( OS_SEM semaphore );
The os_sem_send function increments the number of tokens in the semaphore object
identified by the function argument.
 OS_RESULT os_sem_wait ( OS_SEM semaphore, U16 timeout );
The os_sem_wait function requests a token from the semaphore identified by the
function argument.

28 MGRJ,ECE,RVCE
Activity synchronization using Signals & Events
 API in RTX ARM to set an event:
void os_evt_set ( U16 event_flags, OS_TID task );
The os_evt_set function sets the event flags for the task identified by the function
argument. The function only sets the event flags whose corresponding bit is set to 1 in the
event_flags argument.
 API in RTX ARM to wait for an event:
OS_RESULT os_evt_wait_and ( U16 wait_flags, U16 timeout );
The os_evt_wait_and function waits for all the events specified in the wait_flags to occur.
The function only waits on events whose corresponding flags have been set to 1 in the
wait_flags parameter.The function can wait on as many as 16 different events.

29 MGRJ,ECE,RVCE
Inter Process Communication(IPC)
 Tasks communicate with one another so that they can pass information to each other and
coordinate their activities in a multithreaded embedded application.
 Communication has several purposes, including the following:
- Transferring data from one task to another.
- Signalling the occurrences of events between tasks.
- Allowing one task to control the execution of other tasks.
- Synchronizing activities.
- Implementing custom synchronization protocols for resource sharing.
 The third purpose of communication is for one task to control the execution of other tasks.
Tasks can have a master/slave relationship.
E.g: In a control system, a master task that has the full knowledge of the entire running
system controls individual subordinate tasks. Each subtask is responsible for a
component, such as various sensors of the control system. The master task sends
commands to the subordinate tasks to enable or disable sensors.
30 MGRJ,ECE,RVCE
IPC…
 The fifth purpose of communication is to implement additional synchronization protocols
for resource sharing. The tasks of a multithreaded program can implement custom, more-
complex resource synchronization protocols on top of the system-supplied
synchronization primitives.
 Two scenarios:

Unidirectional data flow: Loosely Coupled Bidirectional data flow: Tightly Coupled

31 MGRJ,ECE,RVCE
IPC…
Mailbox
 Mailbox is an IPC through a message-block at an OS that can be used only by a single
destined task.
 A task puts into the mailbox only a pointer to a message.
 Kernel services with mailbox: Initialization, Query, Post, Accept
RL-RTX mailbox APIs:
 The following macro creates a mailbox.
#define os_mbx_declare( \
name, \ /* Name of the mailbox */
cnt ) \ /* Number of message entries */
U32 name [4 + cnt]

32 MGRJ,ECE,RVCE
Mailbox…
void os_mbx_init (OS_MBX mailbox, U16 mbx_size);
 The os_mbx_init function initializes the mailbox object identified by the function
argument.The argument mbx_size specifies the size of the mailbox, in bytes.
OS_RESULT os_mbx_send (OS_MBX mailbox, void* message_ptr, U16
timeout);
 The os_mbx_send function puts the pointer to a message, message_ptr, in the
mailbox, if the mailbox is not already full. If the mailbox is full, the RTX kernel puts
the calling task to sleep.
OS_RESULT os_mbx_wait (OS_MBX mailbox, void** message,U16 timeout );
 The os_mbx_wait function gets a pointer to a message from the mailbox if the
mailbox is not empty. The function puts the message pointer from the mailbox into
the location pointed by the message argument. If the mailbox is empty, the RTX
kernel puts the calling task to sleep.

33 MGRJ,ECE,RVCE
Message Queue IPC…
 A message queue is a buffer-like object through which tasks and ISRs send and
receive messages to communicate and synchronize with data.
 It temporarily holds messages from a sender until the intended receiver is ready to
read them.
• When a message queue is first created, it is
assigned an associated queue control block
(QCB), a message queue name, a unique ID,
memory buffers, a queue length, a maximum
message length, and one or more task-waiting
lists, as shown in figure.

MGRJ,ECE,RVCE
34
Message Queue…
 Typical message queue operations include the following:
- Creating and deleting message queues.
- Sending and receiving messages.
-Obtaining message queue information.
 When sending messages, a kernel typically fills a message queue from head to tail in FIFO
order. Each new message is placed at the end of the queue.

35 MGRJ,ECE,RVCE
Message Queue…
 Many message-queue implementations allow urgent messages to go straight to the head
of the queue. If all arriving messages are urgent, they all go to the head of the queue,
and the queuing order effectively becomes last-in/first-out (LIFO).

 At times, messages must be sent without blocking the sender. If a message queue is
already full, the send call returns with an error, and the task or ISR making the call
continues executing.
 Most times, however, the system should be designed so that a task will block if it
attempts to send a message to a queue that is full.
36 MGRJ,ECE,RVCE
Message Queue…
 Messages can be read from the head of a message queue in two different ways:
-Destructive read.
- Non-destructive read.
 In a destructive read, when a task successfully receives a message from a queue, the
task permanently removes the message from the message queue’s storage buffer.
 In a non-destructive read, a receiving task peeks at the message at the head of the
queue without removing it.

37 MGRJ,ECE,RVCE
Message queues in POSIX
#define MSGSZ 128
void* child_thread2()
typedef struct msgbuf {
long mtype;
{
char mtext[MSGSZ]; int msqid;
} message_buf; key_t key;
void* child_thread1(){ message_buf rbuf;
int msqid; key = 1234;
int msgflg = IPC_CREAT | 0666; if ((msqid = msgget(key, IPC_CREAT | 0666)) < 0) {
key_t key; printf("Error: msgget");
message_buf sbuf;
exit(1);
size_t buf_length;
}
key = 1234;
if ((msqid = msgget(key, msgflg )) < 0) {
// Receive a message type 1.
printf("Error:msgget : ID : %d",msqid); if (msgrcv(msqid, &rbuf, MSGSZ, 1, IPC_NOWAIT) < 0) {
exit(-1); } printf("Error: msgrcv");
sbuf.mtype = 1; exit(-1);
strcpy(sbuf.mtext, "ECE,RVCE"); }
buf_length = strlen(sbuf.mtext) + 1 ; printf("\nReceived message:");
if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { printf("%s\n", rbuf.mtext);
printf ("Error: sending");
pthread_exit(0);
exit(-1); }
}
else
printf("message sent successfully");
pthread_exit(0);
}38
Message queues in POSIX
main()
{
pthread_t threadid1,threadid2;
int i;
pthread_create(&threadid1, NULL, child_thread1, NULL);
pthread_join(threadid1, NULL);
pthread_create(&threadid2, NULL, child_thread2, NULL);
pthread_join(threadid2, NULL);
exit(0);
}

39 MGRJ,ECE,RVCE
Response Time
 Time interval between the occurrence of an event and the completion of associated
action.

40 MGR,ECE,RVCE
Response time…
Identify different timing components:
Polled loop: while (1)
{
 The response time consists of if((LPC_GPIO_PORT->PIN[2] & 8)==0 {
while(num<=7)
three components: {
- Hardware delays in the LED_On (num);
delay(50000);
external device to set the num++;
signalling event. }
num=7;
- Time to test flag. while(num>=0)
{
-Time needed to respond to and LED_Off (num);
process the event associated delay(50000);
num--;
with the flag. }
num=0;
}
}
}
41 MGRJ,ECE,RVCE
Source: Ref 1
Response time…

Interrupt Driven Environment


 The response time calculation is often nondeterministic because the events are
asynchronous.
 Several timing components consists of :
- Time taken by hardware to set an event.
-Interrupt generation and acknowledgement to the interrupt.
- Context switch time
- Execution time
-Single interrupt system
-Premptive system(Event with high priority/event with low priority)

42 MGRJ,ECE,RVCE
Interrupt Driven Environment…
Identify the response time in the code given below:
void change_dir()interrupt 0{
dir=~dir;
}
void main()
{

//End of else
//End of while
//End of main
43 MGRJ,ECE,RVCE
Tutorial 1
 A colleague has designed an embedded application that utilize a timer that is supposed to
interrupt every 5 ms. She is debugging the code and claims that she cannot determine
whether the timer is working properly. Suggest a way she can instrument the code to
enable her to determine whether the program is entering the interrupt service routine
and if so at what interval.
 Using C struct, design a probe data type that is inserted as a static variable into a function
to count the number of times the function has been invoked. Demonstrate the probe on
several different functions.

44 MGRJ,ECE,RVCE
Time Loading
 It is the percentage of time that the CPU is doing useful work.
 Useful work(Primary task): Execution of instructions of a program or task.
 Supported Tasks: context switching, setting stack frames, etc.

𝑇𝑖𝑚𝑒 𝑓𝑜𝑟 𝑝𝑟𝑖𝑚𝑎𝑟𝑦 𝑡𝑎𝑠𝑘


𝑇𝑖𝑚𝑒 𝑙𝑜𝑎𝑑𝑖𝑛𝑔 =
𝑇𝑖𝑚𝑒 𝑓𝑜𝑟 (𝑝𝑟𝑖𝑚𝑎𝑟𝑦 +𝑆𝑢𝑝𝑝𝑜𝑟𝑡𝑒𝑑)

45 MGR,ECE,RVCE
Time loading…

 To compute the times, three primary methods are used:


- Instruction Counting
- Simulation and modelling
- Physical measurement

46 MGR,ECE,RVCE
Tutorial 3
Approximate the time loading for the following multitasking program:

47 MGRJ,ECE,RVCE
Tutorial 3
 Design and build 1 millisecond delay block using C language instructions. Build the same
loop using your microprocessor’s assembly language instructions. What is the error for
each implementation? What is the error in the both cases if your delays are used to
implement a 10 ms delay? A 100 ms delay.
 Design and build a 1 millisecond delay block using one of your processor’s timer. What
is the error in the implementation? What is the error if your delay is used to implement
a 10 ms delay? A 100 ms delay.

48 MGRJ,ECE,RVCE
Memory Loading
 It is defined as percentage of usable memory utilized
by an application.
Example: Consider a memory map:
- The system memory is not available for user.
-The firmware memory loading is depends on
memory utilized by an application between 0xE5FF
to 0x68FF.
 Total memory loading will be sum of the individual
loadings for instructions, Stack and RAM.

49 MGR,ECE,RVCE
References
 James K Peckol, “Embedded Systems – A contemporary Design Tool”, John Weily,
2008, ISBN: 0-444-51616-6
 Qing Li, “Real-Time Concepts for Embedded Systems”, CMP Books
 RL-RTX User manual/White Papers

50 MGRJ,ECE,RVCE

You might also like