Rtos 1
Rtos 1
10
Real-Time Operating
based Embedded System (RTOS)
System Design
LEARNING OBJECTIVES
e a m the banhs of m operutng system and the neenl for un
leam the mtermals of Rel Tme operating system
Operuting System aned the fundamentals RTOS
of based embedded firmware design
len the bav Aetnel servnes of an
operating system
eatn abut the lassifu afion
of operating systems
about the different real-time kermels and the
lean
features that make a kernel Real-Time
l e a n albout tasks, rO
esses and threads in the operating system context
leam about the structure of a process, the
v
dilferent states of a process, process life cycle and process management
Leam the concept of multithreading,
thread standards and thread scheduling
vUnderstand the difference between multiprocessing and multitasking,
Leam about the different types of multitasking (Co-operative,
Preemptive and Non-preemptive)
Leam about the FCFS/FIFO, LCFS7LIFO, SJF and priority based
Leam about the shortest remaining time (SRT), Round Robin and
task/process scheduling
priority based preemptive task/process scheduling
Learn about the different Inter Process Communication
(1PC) mechanisms used by tasks/process to communicate
and co-operate each other in a multitasking environment
Lean the different types of shared memory techniques (Pipes, memory mapped object, etc.) for IPC
Learn the different types of message passing techniques (Message queue, mailbox, signals, etc.) for IPC
learn the RPC based Inter Process Communication
lean the eed for task synchronisation in a multitasking environment
Lean the different issues related to the accessing
of a shared resource by multiple processes concurrently
Lean about 'Racing, Starvation', Livelock, "Deadlock', "Dining Philosopher's Problem,
ed Buffer Problem', 'Readers-Witers Problem' and Priority Inversion'
'Producer-Consumer/Bound-
Lean about the Prionity Inheritance' and Priority Ceiling' based Priority avoidance mechanisms
Lean the eed for task synchronisation and the different mechamisms for task synchronisation in a multitasking
environment
Lean about mutual exclusion and the dijferent poticies for mutual exclusion implementation
Learn about semaphores, different types ofsemaphores, mutex, critical section objects and events for task synchro-
nisation
Learn about device drivers, their role in an operating system based embedded system design, the structure of a
device driver, and interrupt handling inside device drivers
Understand the different functional and non-functional requirements that need to be addressed in the selection of
a Real-Time Operating System
I e previc oedd Systems
previous
execution. The chapter, we
within the loon super loop discussed about the Super loop based
As the loop. Here every executes the tasks task
execution model
number of task is sequentially
quentially in the order in which model for
firmwareor firmware
of the tasks task
involve increases, therepeated
ed
time int
at the tasks
regular intervals and the task execution
intervals
tasks are
are listed
pushed off in accordancewaiting for external events at which task gets serviced also
a
is
non-real time.
r
De
with vents or /O or increas
reases. If some
executed
ecution. This
is fixed
and is
the wait' time device
consumeddevice usage,
usag the task execution time
determined by the task
type of firmware by the task.
The priority in me also gets
S not time critical. execution issuited
suited
placement within the loop, which a task is to
aelay 1s acceptable Typical
in a
for super
examples are electronic embedded devices where
and it will where
response
loop based ex-
aPpicaions demand time critical not create toys and video
gaming response time for
me tor a task
a task
Device driver
Underlying hardware interface
Fig. 10.1 The Operating System Architecture
updated when a
Windows XP kernel keeps the list different Os Kernels) of the kerna
1S(eg.
across
responsibleThe
for service
handling all /O device related
(Name vary
operations.
may The kernel talks to the IVO device throuol.
ce
'Device Manager'
ne system). The devic
service, called drivers.
deviCe
implemented in a
of low-level systems calls, which are Manager is responsible for
a set of devices. The Device
specific to a device or a class
unvers are
Loading and unloading of device drivers control signals to and from the device
ENChanging information and the system specific
management
deals with managing the
The secondary storage
Secondary Storage Managerment Secondary memory is used as
if connected to the system.
Secondary storage memory devices, any, the main memory is volatile. In most of the systems, the
since
ackup medium tor programs and data storage management
service of kernel
The secondary
SCcondary storage is kept in disks (Hard Disk).
deals with
Disk storage allocation
Disk scheduling (Time interval at which the disk is activated to backup data)
Free Disk space management
a way to support
are designed in such
Protection Systemns Most of the modern operating systems
Windows XP with user permissions like
multiple users with ditferent levels of access permissions (e.g.
'Administrator'. 'Standard', "Restricted', etc.). Protection deals with implementing thesecurity policies
or processes or users.
to restrict the access to both and system resources by different applications
user
to view or modify the whole/
In multiuser supported operating systems, one user may not be allowed
not be granted with
portions of another user's data or profile details. In addition, some application may
is the
permission to make use of some of the system resources. This kind of protection provided by
protection services running within the kernel.
Interrupt Handler Kernel provides handler mechanism for all external/internalinterrupts generated
by the system.
These are some of the important services offered by the kernel of an operating system. It does not
mean that a kernel contains no more than components/services explained above. Depending on the type
of the operating system, a kernel may contain lesser number of components/services or more number
of components/services. In addition to the components/services listed above, many operating systems
offer a number of add-on system components/services to the kernel. Network communication, network
management, user-interface graphics, timer services (delays, timeouts, etc.), error handler, database
management, etc. are examples for such components/services. Kernel exposes the interface to the vari-
ous kernel applications/services, hosted by kernel, to the user applications through a set of standard
Application Programming Interfaces (API). User applications can avail these API calls to access the
various kernel application/services.
10.1.1.1 Kernel Space and User Space As
discussed in the earlier section, the
we
applications/
services are classified into two categories, namely: user applications and kernel applications. The pro
gram code corresponding to the kernel applications/services are kept in a contiguous area (OS de
nendent) of primary (working) memory and is protected from the un-authorised access by user pro
grams/applications. The memory space at which the kernel code is located is known as 'Kernel Space
Similarly, all user applications are log2ded to a specime area of primary memory and this memory area
is referred as"User Space. User space is n e area where user
nemory applications are loaded and ex
ecuted The partitioning memory
of into kernel and user space is purely Operating System dependent.
Real-Time Operating System
(RTos) based Embedded
System Design
ome OS implements this kind of 385
nd user application code partitioning and protection whereas
kern
ciuDDOrt, the
storage into two some OS do
segregate the not
nemory support, user
applications separate areas. In an
are loaded
operating
chnique; Meaning, the entire codeinto its corresponding virtual system with virtual
demand paging tech
mary) memory at once, instead the user for the user memory space witn
main
pagesare oaded into and out of the main
application need
application code is split into not be loadedto the
af the
and out of main memory 1S memory area on a need basis. The
different pages and these
termed as act of
emory and seco condary storage memory. Swapping'. Swapping happens betweenloading
Each the
the code into
allowedaccessingthe memory space process run in its own virtual main (primary)
the process. Each corresponding another processes, unless
process will have certain to memory space and are not
uased on the privilege settings, processesprivilege levels on accessing the explicitly requested
rec by
memory of other
ar share through some other can
request kernel to map another processes
dein main memory and it is not mechanism. Most of the process's memory to its
operating
swapped out into the secondary systems keep the kernel
1011.2 Monolithic Kernel and memory.
application
Microkernel As we know, the kernel
erating svstem. Different approaches are
adopted for building an Operating fornms the heart of an op-
o
nel design, kernels can be classified into System kernel. Based on the
'Monolithic' and 'Micro'.
Monolithic Kernel In monolithic kernel
Here all kemel modules run within the same architecture, all kernel services run in the kernel space.
nal integration of kernel modules in memory space under a single kernel thread.
monolithic kernel architecture allows The tight inter-
low-level features of the underlying system. The the effective utilisation of the
or failure in any one of the kernel major drawback of monolithic kernel is that
modules leads to the
crashing of the entire kernel application.any
error
SOLARIS, MS-DOS kernels
examples
are of monolithic kernel. The architecture LINUX,
monolithic kernel is given in Fig. 10.2. representation of a
Applications
A0.2
A0.2 TYPES OF OPERATING SYSTEMS
Depending on the type of kernel and kernel services, purpose and type of computing systems where the
OS is
deployed and the responsiveness to applications, Operating Systems are classified into different
types
10.2.1 General Purpose Operating System (GPOs)
The operating systems, which are deployed in general computing systems, are
pose Operating Systems (GPOS). The kernel of such referred as General Pur-r
of services required for an OS is more generalised and it contains all kinds
executing generic applications. General-purpose operating systems are often
quite non-deterministic in behaviour. Their services can inject random delays into application software
and may cause slow responsiveness of an
application unexpected times. GPOS are usually deployed
at
incomputing systems where deterministic behaviour is not an
Desktop system is a typical example for a system where GPOSs importantcriterion. Personal Computer/
etc. are examples for General
Purpose Operating Systems.
are
deployed. Windows XP/MS-DOS
ment
conflicts. Windows guide the design of an RTOS. Rules
of Real-T
Operating Systems (RTOs). CE, QNX, VxWorks imple-
examples
task dynamically
Modify the TCB to change the priority ofthe
various tasks/processes. A kernel
Task/Process Scheduling sharing the CPU among
Deals with
scheduling. Scheduler is nothing but an algorithm imple
application called 'Scheduler handles the task deterministic
scheduling of tasks to provide a
efficient and optimal
cnlation, which performs the in a later section of this chapter.
DCnaviour. We will discuss the various types of scheduling
Embedded Sy.
Introduction to
388
the concurrent acces of
Deals with synchronisingbetween various tasks, W reso
Task/Process Synchronisation
which is shared
red across multiple tasks and the
communication
communication in a
Ne will disc
later
SOUrCe
anous synchronisation techniques and intertask
/process
ection of this
chapter.
and handling the errors occurred/e.
Error/Exception Handling Deals with registering deadlocks, deadline ppiuons
raised durin the execution of tasks. Insufficient memory, timeouts, of b
etc. are examples errors/exceptione
error, divide by zero, unknown instruction execution,
task level. DeadioCk 1S an example forE Errors/
CCpuons happen at the kernel level services or at
can
Ifthe Timer tick' interval is I millisecond, the systei. I iac register will reset in
232 * 10-3/(24 * 60 60)= 497 ivays = 49.7 Days =~50 Days
The 'Timer tick' interrupt is handled by the Timer Interrupt' handler of kernel.The Timer tick' interrupt
can be utilised for implementing the following actions.
.Save the current context (Context of the currently executing task).
Increment the System time register by one. Generate timing error and reset the System time regis-
ter if the timer tick count is greater than the maximum range available for System time register.
Update the timers implemented in kernel YIncrement or decrement the timer registers for each
timer depending on the count direction setting for each register. Increment registers with countdi
rection setting = "count up' and decrement registers with count direction setting = 'count down').
>cting mplesequi
are
functions, some RTOS provide
Apart from these basic options for selectir
and network functions). Some RTOS kernel provides
anagement The user can pick
the required functione
tions at the time of building a kernel.
same to generate
the kernel binary. Windows CE i a Om the se
oavailable functions and compile the
ample for such an RTOS. While building the target, the user
can select the required com typicalf e
components
kernel. the
10.2.2.2 Hard Real-Time Real-Time Operating Systemsthat strictly adhere to the ti
Straints for a task is referred as 'Hard Real-Time' systems. A Hard Real-1ime system must
deadlines for a task without any slippage. Missing any deadline may produce catastrophie
phic results
meet the
Hard lose and irrecoverable
Real-Time Systems, including permanent data damagesto thesystem
Hard Real-Time systems emphasise the principle 'A late answer is a wronganswer.Asystem
em can ha
Several such tasks and the key to theircorrect operationlies in scheduling them so that they meet
me constraints. Airbag control systems and Anti-lock Brake Systems (ABS) of vehiclesare h
examples for Hard Real-Time Systems. The Air bag control system should beinto action and deploud typica
air
bags when the vehicle meets a severe accident. Ideally speaking, the time ror
deployment task, when an accident is sensed by the Air bag control triggering the ar o
bags should deployed exactly within the time frame,
be system, should be zero and the ae
Any delay in the deployment of the air bags makeswhich
is
task,
the life
predefined for the air bag deployme
the air
deployment task is triggered, the currently executing of
bag the passengers under threat. When
task must be
deployment task should be brought into execution, and the necessary I/O systemspre-empted, the air bao
task. To meet the strict deadline, the timeshould made read.
ily available for the air bag be
deployment between the air bag
deployment event triggering and start of the air
ally zero. As a rule of thumb, Hard Real-Time bag deployment task execution should be
for handling the Systems does not implement the virtual minimum, ide
memory. This eliminates the delay in memory model
task to and from the swapping in and out the code
primary of Human in the corresponding the
In general, the to
introduces unexpected delays memory. presence
and does not contain a
in the task execution.
Most of the Hard Real-Time loop (HITL) for tasks
'human in the loop. Systems are automatic
10.2.2.3 Soft Real-Time
Real-Time Operating System that
but offer the best effort to meet the does not
deadline referred as Soft Real-Time'guarantee meeting deadlines,
for tasksare
acceptable for a Soft Real-timearesystem if the systems. Missing deadlines
compliance limit
late answer is an
of the Quality of Service (QoS). A Soft frequency of deadline
missing is within the
acceptable answer, it could have done bit Real-Time system emphasises the principle
ten have a
'human in the loop (HITL).butAutomatic faster'. Soft Real-Time systems most or-
Real-Time System. If the ATM Teller Machine (ATM) is a
takes a few seconds more than the typical example for Sott
happens. An audio-video playback ideal
damage arises if a sample comes latesystem is another operation time, nothing tatal
by fraction of a example
for Soft
second, for playback.Real-Time system. No potentia
10.3 TASKS, PROCESS AND
THREADS
The term 'task' refers to
something
execution of a number of tasks.
that needs
to be done. In our
assigned by day-to-day
The
task can be the one life, we are bound ton
orderprofessors/teachers
our or the one related to our our
of priority and managers or the one assigned
personal or family needs.
schedule/timeline for In addition, we
program in execution and executing
is defined as the these tasks. In will have a
the related the operating
information maintained bysystem context, a ta
the operating
ting system
syste
Real-Time Operating System
(RTOS) based Embedded
System Design 391
he program. Task 1S also
known as
'Job' in
also called a
is also
execution is "Process. The terms the operating system context. A
operating syste contex and nmost often *Task', Job' and Process' refer program or part of it
in
they are used to the same
entity
10.3.1 Process
interchangeably. in the
Process
Stack
(Stack pointer)
Working registers
Status registers
Code memory
corresponding to the
Process
A process which inherits all the properties of the CPU can be considered as a virtual processor, await-
When the process gets its turn, its
1ng its turn to have its properties switched into the physical processor.
the physical registers of the CPU. From
registers and the program counter register becomes mapped to
into three regions, namely,
perspective, the memory occudied by the process segregated
is
a memory
Stack memory, Data memory and Code memory (Fig. 10.5).
variables local to the process. Data memory
he Stack' memory holds all temporary data such as cor
nolds all global data for the process. The code memory
contains the program code (instructions)
area of memory 1s
to the On loading a process into the main memory, a specific
TCsponding process.
starts (OS Kernel implementation dependent)
at
a t e d for the process. The stack memory usually
392 Introduction to Embedded Systems
is
temporarily suspended from execution and
does not have immediate access to resources. The
blocked state might be invoked by various condi- Blocked
tions like: the
process enters a wait state for an
event to occur
(e.g. Waiting for user inputs such
as
keyboard input) or waiting for getting access
to a shared resource
Waiting Waifor tiShared
ng for VO
(will be discussed at a later
section of this chapter). A state where the Resource Running
process
completes its execution is known as 'Completed
State. The transition of a
process from one state ExecutionCompletion
to another is known as 'State
transition'. When a
process changes its state from Ready to running
or from
unning to blocked or terminated or from
blocked to running, the CPU allocation for the Completed
process may also change:
It should be noted that the state representation Fig. 10.6 Process states and state transition
for a process/task mentioned here is a generic representation
rep-
Real-Time Operating
System (RT ) based
ntation. The states associated with Embedded Syste Design
res 393
or number states than
of task a
may be known with
Works' kemel. the tasks maythebe one explained here under different name or there a
may be more
hET AY and SUSPEND.
in either
The PEND state one or a specific
different OS kernel For
combination example, under
n for L O or
system resource The DELAYrepresents a state where the of the states READY, PEND,
andnd the SUSPEND state state
represents a state in which the task/process
is blocked on
wait-
represents a state
where
process is ternporarily task/process is sieeping
fson and not
available
for
Under Micro exccution
a task/
Task/Process
Code memory
Data memory
Stack
Stack Stack
If the process is
split into multiple threads, which executes a portion of the
main thread and rest of the threads will be created within process, there will be a
the main thread. Use of
execute a process brings the following advantage. multiple threads to
Better memory utilisation. Multiple threads
of the same process share the address space for data
memory. This also reduces the complexity of inter thread
sharedacross the threads communication since variables can be
Since the process is split into different thréads, when
thread enters a wait state, the CPU
one
be utilised by other threads of the process that do not can
require the event, which the other thread is
waiting,
for processing. This speeds up the execution of the process.
.Efficient CPU utilisation. The CPU is engaged all time
0.3.2.2 Thread Stardards : Thread standards deal with the
different standards
"eation and management. These standards are utilised by the available for thread
read It is
operating systems for thread creation and
management. a set of thread class libraries. 1he
commonly available thread class libraries
explained below.
Real-Time Operating System
(RTOs) based
ased Embed Embedded
ded System Design
IN
POS Threads POSIX
stands for Portable 395 Design
h the
with Real-Time extensions and POSIX 4aOperating System Interface.
ibrary
dard library for
for thread creation standard deals with The POSIX.4
standaru
POSIX thread creation and
and
management is 'Pthreads'. thread extensions. The POSIX dealsstan-
The pnmitive management functions in 'C" Pthreads library defines the set of
langua
guage
snt
pthread create
(pthread t *new thread 1D,
oid start function) const
argument s) ; pthread attr t attribute,
(void *), void
create a new thread for
running the
created thread and function start
function. Here pthread t is the
pthread_attr_t s the data
type for handle to the newly
the functhon the thread is going to execute
and holding
the thread attributes.
'start function'
is
avondin the above On successful arguments is the arguments for
example). 'start
pthread createl) function'
Thread Control Block ereation of a Pthread, (lt is
(mewthread_ID in our(OCB)corresponding associates the
to the
example). newly created thread to the variable of type pthread
The prmitive i
Example 1
Wite a multithreaded application to print "Hello I'm in main
thread" from the main thread and "Hello l'm in
5tames each, using the new thread"
pthread_create) and pthread_join) POSIX primitives.
/Assumes the application is running on an os where PoSIX 1ibrary is
available
include <pthread.h>
include <stdlib.h>
include <stdio.h>
*****
0: 5 j+)
printf(Hello I'm in new thread\n" )
/hait for some time. Do nothing
/2he toliowing line of code can be replaced with
9 s supported delay function 1ike sleep( ) , delay () etC.
fori- 0: i < 10000; i t )
Ieturn NULL;
396 Introduction to Embedaded Systems
* * * ** **** ******
//***************:
/Start of main thread
intmain( void )
int i, j:
pthread_t tcb;
//Cedte the new thread for executing new thread tunction
pthread_create ( &tcb, NULL, new thread, NULI ))
if
(pthread_join (tcb, NULL ))
return 1;
zero indicates that the specified thread is not currently in the suspended mode. if the count is not.
the count is nented by one and if the resulting count value is zero, the thread is resumed
APLSeep (DWORD dwMilliseconds) can be used for suspending a thread for the duration specified The
in
miuiseconds by the Sleep function. The
Sleep call is initiated by the
thread.
specified in
Example 2
write a multithreaded application using Win32 APIs to set up a counter in the main thread and secondary thread to co
rom O to 10 and print the counts from both the threads. Put a delay of 500 ms in between the successive printing incount
hoh
the threads.
#include "windows.h"
#include "stdio.h"
7* * * * * * * * * * * * **** ** * ** * * * * ** ***** *** * * ** t * * * * * * * * * * * * * * * * * * * * * * *
//Child thread
7** ************* ******** ** * **** ** ** *******
***** *****************x**
void ChildThread (void)
char ii
for (i=0; i<=10;++i)
Sleep(500)
return 0;
Real-Time Operating System
(RTOS) based Embedded
System Design 399
To execute this program, create a new
Win32 Con-
sole Application using Microsoft Visual
C+and add
the above piece ot code to it and
compile. The output
D:IVCThreadDebugThread.ex
Mecut ing -E
abtained running this application on a machine with
on Execut ing Main
ChildThread: Counter
Theead: Counter
XOcut ing Main Thread:
Windows XP operating system is given in Fig. 10.9, Execut ing Chi ld Thread: Count
If vou examine the output. you can see the XeCut ing Counte
switching xecuting Main
Child Thread:
Thread: G0unter
hetw cen main and child threads. The Execut ing Child Thread: Counter
output need not be EXecut ing Ma in Counter
the same always. The output is purely
dependent on the xecut ing ChildThread:
The ad:
Counter
EXeCut ing Hain Threads 0Unter
scheduling policies implemented by the windows op- Execut ing Chi ld Thre ad: Counter
Counter
erating system for thread scheduling. You may get the
Execut ing Main Thread: ounter
Execut ing Child Thread: Gounter '
output or a different output cach time Execut ing
Execut ing hain
same Thread C0unter
you run the
application Execut ing Child Thre ad: Counter
Ma in Thread:
Execut ing Main Thread: Counter
Counter
Execut ing Child Thre ad:
Tava Threads Java threads are the threads Executing Main Counter
Execut ing Child Thread
Thre ad: Counter
supported by Java
programming Language. Execut ing Main Thread: Counter
Execut ing Child Thread: Counter
The java thread class Thread' is
defined in the Press any key to cont
inue
package java.lang. This package needs to be
imported for using the thread creation functions
supported by the Java thread class. There are Fig. 10.9 Output of the Win32 Multithreaded
two ways of creating threads in Java: Either application
by
extending the base "Thread class or by
implementing an interface. Extending the thread class allows
inheriting the methods and variables of the parent class
(Thread class) only whereas interface allowssa
way to achieve the requirements for a set of classes. The
following piece of code illustrates the imple-
mentation of Java threads with extending the thread base class Th ead.
import java.lang.*;
public class MyThread extends Thread
The above piece of code creates a new class MyThread by extending the base class Thread. It also
Overrides the run) method inherited from the base class with its own run() method. The run() method
of MyThread implements all the task for the MyThread thread. The method start() moves the thread to
a
pool of threads waiting for their turn to be up for picked
the
execution by scheduler.
The
thread is said
to be in the Ready' state at this stage. The scheduler picks the threads for execution from the pool based
on the thread
priorities.
B.g. MyThread.start();
he output of the above piece of code when executed on Windows XP platform is given in
Fig. 10.10.
400 Introduction to Embedded Systems
C:SYSROOTsystem32cmd.exe
Davationesdrel.5.0 11binjava MyThread
Hello Fron Hyi hreadf
DEdavalloneiret.5.0.11bin)
tarnel/System Level Thread Kermel level threads are individual units of execution, which the
Ke
a s separate threads. The OS interrupts the execution
OS
of the currently running kernel thread
hes the execution to another kernel thread based on the scheduling policies implemented byand
the
OS. In summary kerme level threads are pre-emptive.
ar user level threads, the execution switching (thread context
For
switching) happens only
whencalls
rrently executing user tevel thread is voluntarily blocked. Hence, no OS intervention and system the
curre
are involved in the context switching of user level threads. This makes context switching of user level
threads very fast. On the other hand, kernel level threads involve lots of kernel overhead and involve
sstem calls for context switching. However, kernel threads maintain a clear layer of abstraction and
allow threads to use system calls independently. There are many ways for binding user level threads
with system kermel levelthreads. The following section gives an overview ofvarious thread binding
models,
Many-to-One Model Here many user level threads are mapped to a single kernel thread. In this
model. the kernel treats all user level threads as singlethread and the execution switching among the
user level threads happens whena currentlyexecutinguserlevelthread voluntarilyblocksitself orrelin-
quishes the CPU Solaris Green threadsand GNU Portable Threads are examplesfor this. The PThread
example given under the POSIX thread library section is anillustrative example for application with
Many-to-One thread model.
Thread Process
Thread is a single unit of execution and is part of process.Process is a program in execution and contains one or
more threads.
A thread does not have its own data memory and heapProcess has its own code memory, data memory and stack
memory. It shares the data memory and heap memory with memory.
other threads of the same process.
A thread cannot live independently; it lives within the A process contains at least one thread.
process.
There can be muliple threads ina process. The first thread Threads within a proces share the code, data and heap
unain thread) calls the main function and occupies the memory. Each thread holds.separate memory area for
start of the stack
memory of the process. stack (shares the total stack memory of the process).
402 Introduction to Embedded Systems