C 5.
1 Syllabus: Architecture of kernel, task scheduler, ISR, Semaphores,
mailbox, message queues, pipes, events, timers, memory management,
RTOS services in contrast with traditional OS, introduction to μcosII.
C 5.2 MCQ & Assignment Question
C 5.3 About Title of the Chapter – RTOS concepts
Real Time : Execution time must be defined
Operating System: OS is set of code written to drive the computer HW
Eg: Windows 2010 or Ubuntu
C 5.4 Central Idea of the chapter :. The Chapter Contains the Introduction to the
real time operating system its parameter working. It also introduce the µcos-II Operating
System
C 5.5 Importance of the Chapter
C 5.6 Outcomes of Chapter
Definition: The operating system (OS) is the most important
program that runs on a computer Or A S/W code written to
manage computer H/W
A real-time operating system (RTOS) is an operating system (OS)
in which the result produced is equally important along with the
physical instant (Time Interval) at which results are produced.
RTOS is an operating system (OS) intended to serve real-time
applications that process data as it comes in, typically without
buffering time delays.
Processing time requirements (including any OS delay) are
measured in tenths of seconds or shorter increments of time.
Hard, Soft & Firm RTOS
Example RTOS: Nucleus Palm,Symbain,VxWorks, pSOS, Nucleus,
RTLinux…
Comparison
Structure of a RTOS
A Real Time Operating System (RTOS) generally contains a real-time kernel and other
higher-level services such as file management, protocol stacks, a Graphical User Interface
(GUI), and other components. Most additional services revolve around I/O devices.
Application Program Interface (API)
RTOS-kernel
BSP
Custom-Hardware Or USER
The Role of an RTOS in an Embedded System
An embedded system is a special computer system that is
designed to perform dedicated functions with real
time computing constraints.
It contains software, memory, and a processor that may
be 8051micro-controller memory ROM or Pentium-
IV processor memory RAM.
It also contains different types of inputs and outputs.
Inputs are in the form of probes and sensors, buttons,
control knobs and communication signals.
Outputs are changes made to the physical world,
communication signals, and displays.
Components of RTOS
The most important component of RTOS is its kernel (Monolithic & Microkernel).
Kernel is HEART of OS
KERNEL Objects
(It‟s a processor specific code onto (processor) which we like to have our RTOS
running).
Kernel is continuous all time running program on OS
Two types
Soft real-time
Tasks are performed as fast as possible
Late completion of jobs is undesirable but not fatal.
System performance degrades as more & more jobs miss deadlines
Example:
Online Databases
Hard real-time
Tasks have to be performed on time
Failure to meet deadlines is fatal
Example :
Flight Control System
Hard Real Time System
Validation by probably correct procedures or extensive simulation that the
system always meets the timings constraints
Soft Real Time System
Demonstration of jobs meeting some statistical constraints suffices.
An embedded system is a computer built into a system but not seen by
users as being a computer
Examples
FAX machines
Copiers
Printers
Scanners
Routers
Robots
Features/Services of RTOS or Kernel
RTOS KERNEL
The "kernel" of a real-time operating system ("RTOS") provides an "abstraction layer" that
hides from application software the hardware details of the processor (or set of processors)
upon which the application software will run.
The kernel is part of the operating system that offers core services to application software
that runs on a processor.
The Kernel is the part of the operating system that is responsible for task management, and
intertask communication and synchronization. ... Specifically, the Real Time Scheduler is the
part of the RTOS kernel that is responsible for deciding which task should be executing.
Task Management
Inter-task Communication and Synchronization
Dynamic Memory Allocation Services
Device I/O Supervisor
Interrupt handler,
Task scheduler,
Resource sharing flags and
Memory management.
Event & Timing management
The primary function of the kernel is to process interrupts that external and internal events
cause.
For embedded applications Kernel size should be small and it should fit into the ROM
Msg
Event
RTOS KERNEL Mail
box
Queue
Reg
Signals
ISR
Scheduler
Pipes
Timer
Sema
phore
Tasks
Mutex
• System software that offers primitive I/O and a little more than threading is referred to as a
tiny kernel. Widely used commercial tiny kernels include wind kernel and Nucleus.
• Operating systems operate applications in processes whereby the operating system
monitors errors in processes, prevents the processes from destroying anything but
themselves, and later recovers smoothly once the process terminates unexpectedly.
Commonly used real-time operating systems include QNX, LynxOS, and OS-9.
Architecture of kernel Continued …….
Kernel is a heart of Operating System which provides
different services to RTOS.
Its Continuously running Program on RTOS
The Kernel Provides different type of services through
API to user by its Kernel Objects.
The Kernel objects consists of different type of
Communication objects such as Pipes, mailbox,
Message Box & Signals.
Along with Controlling block semaphores & mutex.
Tasks State & Task management:
A task is basic unit of execution in RTOS.
RTOS scheduler needs to be deterministic ~ O(1).
Scheduling policies that are available in a RTOS are:
Clock driven
Priority driven (RMS & EDF)
In Real Time Applications the Process is called as Task which takes
execution time and occupies memory. The task management is the
process of managing tasks through its life cycle.
Task will have different states. The states of task are Pended, Ready,
Delayed, Suspended, and Run.
Each Task/ process will be in any one of the states. The states are
pended, ready, suspended, delayed and run.
The scheduler will operate the process which is in ready state. At any
time only one process is in run state. Transitions to and from the Ready
queue are affected as a part of the execution of the RTOS services or as a
result of timing events.
Task State
• Running : Task having control on processor/CPU. Or Currently task carrying by
CPU
• Ready : Task which ready to run on CPU or task want control of CPU
• Blocked : The LPT which is blocked by the CPU
• ISR: When HPT task is interrupted the CPU goes to ISR and execute the that
task and returns to main program/address.
Architecture of kernel Continued …….
Scheduler:
It‟s the object which manages the control of CPU from
different tasks.
a) Pre-emptive scheduler
b) Non-Pre-emptive Scheduler
c) Round Robin with time slicing
Architecture of kernel Continued …….
Semaphore and mutex (Mutual Exclusion):
Its Like a token or key depends upon the task
having semaphore that is going to be executed & after
completion. It releases the semaphore & its acquired by
the other task.
Timer : It Provides time delay for different task.
Event Register: It consist of sequence of task that is to be
executed when event occur.
ISR (Interrupt Service Routine) : The ISR mangos task
to be executed when interrupt occur without time delay.
Message Queue, Pipes, Mailbox, Signals : These are
used for interprocess communication and inter task
communication in RTOS.
TCB (Task Control Block)
TASK ID
Function of TCB CONTEXT SWITCHING
• Create Task()
• Queue Task() PROGRAM COUNTER
• Change Priority Task()
• Delete Task() STACK POINTER
• Suspend Task()
CPU REGISTER
PROCESSOR STATUS
REGISTER
PRIORITY
TCB (Task Control Block) Continued…
It‟s the data structure having in function using which it
controls task state, stores protected the memory area of
kernel.
TCB Consist of following functional about task Task ID,
Memory map , PC, SP,CPU Reg., Priority.
The Task control block data Structure can vary from one
task to another.
The Function of Task Control Block :
a) Create Task
b) Delete Task
c) Suspend Task
d) Query Task
e) Resume Task
TCB (Task Control Block) Continued…
Consider the embedded system Consist of Task 1,2,3.
The function of these task is to read the data from
serial port & Convert it into packets & send it to
Ethernet.
a) Task 1 : Reading the data on Serial Port.
b) Task 2: Convert the data into packet & Store in
buffer
c) Task 3: Read the data from buffer & send it to the
Ethernet.
TCB (Task Control Block) Continued…
When Task 1 is running at the same time task 3 wants the
control of CPU, then task 3 is going to be blocked because
task 1 & 2 not completed.
The task either in three states depending upon its priority
as shown below in the diagram.
Task, Task State & TCB (Task Control Block)
HP task in queue
HP
indicates
Highest Running State Ready To Run
Priority
ISR
HP task is
ISR running
Exit
Task is waiting
ISR for external
event to occur
Waiting or
Blocked State
Running State- The task is said to be in running state
when that task has control over CPU.
Ready to Run state – The task which is in the queue &
want the access of processor is kept in the ready to run
state. N-number of task are in ready to run state.
Blocked or Waiting- When high priority task (HPT) &
LPT want access of CPU that time LPT is kept in Blocked
state.
Dormand-Task is created but not used. Task from
block state can be move to ready to run stage when
external event is occur.
the block task cannot directly put in running state.
ISR : When HPT is interrupted the process suspends
the current task & execute the ISR after completion of
ISR it resume to be interrupted task.
Schedular
Schedular is an object which keeps track of task
and among which task have the control of CPU
assigned by the schedular.
Schedular helps in minimum CPU time utilization
for multiple task.
Most Commonly used Schedular are
a) Pre-emptive scheduler
b) Non-Pre-emptive Scheduler
c) Round Robin with time slicing
Pre-emptive scheduler
(Non- Cooperative Scheduling)
Completed
T3
Highest
Priority Preemption Next HPT
T4
Completed Completed
T1 T2 T1 T1 T2 Resume
LP LP LP
Time
Pre-emptive scheduler
(Non- Cooperative Scheduling)
In Preemptive Scheduling the control of CPU is
given to always HPT.
Consider the four task as 1,2,3,4 with their priority
LP,LP,HP,MP.
The task 2 is under running condition & Know the
preemption occurred from ISR for Task 3 . Due to
this CPU Suspends the Task 2 and task 2 goes to
resume state.
Task 3 is executed as it having Highest Priority
Pre-emptive scheduler
(Non- Cooperative Scheduling) Continued….
Once task 3 is completed. The CPU Processes next
highest priority task in queue & goes for its execution
(i.e. Task 4)
After Completion of this task processor resumes to
the interrupted Task 2 & its Executed. That‟s why its
called as “Non Co-Operative Scheduling”.
Limitation : LPT have to wait for longer time.
Non-Pre-emptive scheduler
(Cooperative Scheduling) Continued….
T3
Highest
Priority
Completed
T1 T2 T4 Completed
LP LP MP
Time
Non-Pre-emptive scheduler
(Cooperative Scheduling) Continued….
In order to have a control on CPU each task cooperate
with the other task.
From the diagram the type of Scheduling is called as
Cooperative Scheduling.
Consider the Four task as 1,2,3,4 with their priority LP,
LP,HP,MP.
When the task 2 is going to execute & preemption
(Interrupt) occur from ISR for tasks (HP). The processor
keeps tasks 3 in queue unless the task 2 not completed
though it has high priority .
E.g. Person A goes for telephone booth for making 100
phone call & other person are waiting in queue . A person
makes a single call & handover telephone to the person
in queue.
Round Robin with time Slicing
T
Slice
Highest
Priority T3
HP
T
Slice
Lowest
T1 T2 T4
Priority
LP LP MP
T T T Time
Slice Slice Slice
Round Robin with time Slicing
Continued….
In Round robin time slicing each task is assigned in
fixed interval for execution in that interval only the
task has control of CPU.
In the given time for each task is calculated depends
upon time available (T Cycle) & no. of Task (N).
t Slice = T Cycle/N = Time available /No of task
If task is not completed it must wait for next time slot
in a queue. When time slot comes its executed.
E.g. Consider an embedded system from port A for
every 20msec & decrypted & retransmitted to the port
B. Consider 5 tasks t1-t5 Corresponds to above
process.
Round Robin with time Slicing
Continued….
Task 1 : Check continuously port A for data.
Task 2: Read the data.
Task 3 : Decrypted it & keep in the better
Task 4 : Reads from the buffer.
Task 5 : Sends to the port B
Time Task Context T1 T2 T3 T4 T5
Interval Saving
(ms)
0-4 ms T1
4-8 ms T2
8-12 ms T3 T2
12-16 ms T4 T2,T3
16-20 ms T5 T2,T3,T
5
Initialization
Running
Completed
Not -Completed
Timer :
Timer is a device which is used for measurement
of elapsed time or providing the time delays. We have
seen the RRTS assign a fixed time interval for execution
of task & this action is monitored by timer .
Certain task kept in blocked state for external
event to be occur , if external not occurs the appropriate
action is to be taken i.e. Monitored by again Timer.
Timer Functions: Following functions calls are
provided to manage the timer
1) Get time
2) Set Time
3) Time Delay (in system Clock Ticks )
4) Time Delay ( in Seconds )
5) Reset Timer
Semaphore
• Its one of the kernel object.
• Semaphore act like a key or token so as to access or execute
a task.
• That task must acquire the semaphore.
• Single device
- Task Synchronizer
- Resource Synchronizer
3
TEMP 40 ° C
2
Display
TASK 1 TASK 2
4
1
a) Resource Synchronizer
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.
This is useful for when two or more task accessing same
resource. A binary semaphore used for synchronization does
not need to be ‘given’ back after it has been successfully
‘taken’ (obtained).
Semaphore is a technique for synchronizing two/more
task competing for the same resources. When a task
wants to use a resource, it requests for the semaphore
and will be allocated if the semaphore is available. If the
semaphore is not available then the requesting task will
go to blocked state till the semaphore becomes free.
Ex:- Consider a situation where there are two persons who
want to share a bike. At one time only one person can use the
bike. The one who has the bike key will get the chance to use
it. And when this person gives the key to the 2nd person, then
the 2nd person can use the bike.
Semaphore is just like this Key and the bike is the shared
resource.
Whenever a task wants access to the shared resource, it
must acquire the semaphore first.
The task should release the semaphore after it is done with
the shared resource.
Until this time all other tasks have to wait if they need access
to shared resource as semaphore is not available.
Even if the task trying to acquire the semaphore is of higher
priority than the task acquiring the semaphore, it will be in the
wait state until the semaphore is released by the lower priority
task.
Semaphore Continued….
TASK 2 READ
ADC TASK 1
WRITE DATA DATA DAC
MEMORY
b) Task Synchronizer
Semaphore Continued….
TASK 1 TASK 1 TASK 2 TASK 2 TASK 2
TASK 1 USE
ACQUIRE RELEASE ACQUIRE DISPLAY RELEASE
DISPLAY SEMAPHORE SEMAPHORE SEMAPHORE
SEMAPHORE MESSAGE
RESOURCE SYNCHRONIZATION
The Semaphore can be used for to access the resource between
multiple task. The task having semaphore. Its executed by
processor and the other task is requesting the semaphore kept in
the queue unless the semaphore release the first task.
E.g. Consider a example task1 want to display message TEMP 40
degree 40 °C & task 2 is humidity 25 %
-if they don‟t have semaphore the wrong message may be displayed.
So as to acquire a display for two task they must use semaphore .
Task Synchronization :
Consider a example writing the data into memory from ADC
o/p . This is done by task 1. The other task2 reads data from memory
& gives to DAC .While executing task 1 by the Processor Task 2
Tries to access the control of CPU at the same time.Task 2 kept in
blocked state. So as to avoid this Task 1 & 2 kept must use
semaphore for synchronization .
Type of Semaphores :
1) binary Semaphore
2) Counting Semaphore
Semaphore acquire Count = 0
Available Unavailable
Initial
Count = 0
Semaphore Release (Count =1)
Fig a) Binary Semaphore
Semaphore acquire Count = 0
Available Unavailable
Initial
Count = 0
Semaphore Release (Count =1)
Binary Semaphores
• Binary Semaphores has count value either 0 or 1
Its initial count always going to 1 in available state , when
semaphore is acquired by task its count = 0 & it moves
from available state to unavailable state & vice versa.
Counting Semaphores
When semaphore has its count > 0 its said to be counting
semaphores
The count value is 2,4,16,32,64…. & that count depends
upon kernel size.
MUTEX (Mutual Exclusion)
Mutex is a special kind of Semaphore that support the ownership in
recursive manner for execution of the task.
Mutex can be acquired using four method
1) Disable Scheduler
2) Disable interrupts
3) By the test & set Operation
MUTEX
4) By using Semaphores Acquired
UNLOCKED LOCKED
Initial Count = 1
Initial Count = 0
MUTEX
Released
Disable Scheduler
•When LPT is Running & the same time HPT wants access of
CPU in the scheduler.
•LPT is Going to suspends & HPT is executed once finished HPT
resume to the LPT.
•But when the LPT acquire mutex. This task kept in Blocked
state irrespective of Occurrence of HPT
•The LPT is executed by the processor by disciplined
scheduler & HPT kept in queue.
•Once task is finished it release the mutex & kept in
unblocked state.
Disable interrupts
When task aquire a mutex & its running condition while
processor.
At a same time ISR occurs. The processor disables the interrupt
& currently running task is completed.
After Completion of task , it released the mutex then interrupt is
enabled
By the test & set Operation
In this type of function of task . It create the global
variable x.
If x= 0 its Used by the task
x=1 its available for the task
By using Semaphores
In this task can be executed by acquiring the Semaphores.
Inter task / Process Communication (IPC/ITC)
The Inter task communication involves sharing of data
between one or more task or between ISR.
This can be done through kernel objects
1) Mailbox
2) Message Queue
3) Signals, Timer, Counters , Semaphores.
4) Pipes
When data is taken from keyboard/Mouse, Its going to the
Operating System through the above kernel objects .
Mail box
Task 3 ISR
Task 1 Mail box Task 2
Post the message Message read from
in Mailbox Mailbox
Mail box
When data taken from keyboard/Mouse its going to the
Operating System Through above kernel Objects.
The mail box is very similar to the postal box services in
which one can deposit the message and other can take it
out. And Perform the communication
Functions of mailbox :
1) Post message mailbox
2) Create the mailbox
3) Delete the mailbox
4) Queue can be mailbox
Message Queues
Queue
Control Memory
Block
T1 T2 T3 Max T1 T2 T3
Queue
length
Element
of data
TX END QUEU RX END
NAME
E ID
Message queue
It‟s the kernel object . Message Queue is array of mailbox in which two or
more task can send the message at a time. The incoming message the task
ID/name & Priority assigned by (Queue control block) The transmitting
message can received by other task at receiving end.
In the Message Queue has internal buffer memory which stores incoming
message
Functions of message Queue :
a) Durability: Message can be kept in memory if the need for reliability
indicates a more intensive solution
b) Security Policies : Which application should have access to these
message
c) Message Filtering : Some system Support s Filtering data so that a
subscriber may only see messages matching some prespecified criteria
of interest
d) Receipt Notification : A Publisher may need to know when some or all
subscriber have received a message.
Pipe ISR
TASK 1 TASK 2
Message Sent
TASK 1 TASK 2
Acknowledge
Pipe
The task can write the message into the pipe other task or ISR can read
the message from the pipe
After reception message from task 1 & Task 2 give acknowledge to the
task 1.
Functions of PCB:
The main role of PCB is central in process management
a) The process Scheduling state : The state of process in terms of
ready suspend etc.
b) Process Structuring information : Processors ids of other
process related to the current one in some functional way.
c) Process Privileges : Interms of allowed/ Disallowed access to the
system Resources
d) CPU Scheduling information : It Indicate the information of
process with which it uses the CPU time through Scheduling .
Event Register
1 0 1 1 0 1 1 0 1 0 1 1 1 0 1 0
TASK 4 TASK 6 TASK 5 ISR # 01
Event Register is used for occurrence of certain task at defined
interval .
It‟s the Combination of 16 bit value out of which 4 bit are assigned
for each task so that it consist of 3 task & 1 ISR
4bit are stored in event register is usefull for when the particular
task is running and gives idea of a event flag.
Functions of Event Register :
1) Event Register are typically used for unidirectional activity
synchronization
2) Pending event in the register don‟t change the execution state
of receiving task
Memory management in RTOS
Pool
Memory
Buffer
Count
1
Buffer Size 0
The Important Services Provided by the RTOS is memory management
In certain Embedded system after initialization of Operating system, code.
The part of Memory RAM, ROM , Stack is used fro Communication of kernel
object.
The Process of assigning this physical memory to the other device called
Dynamic Allocation
This memory allocation can be done through two memory function used :
1) malloc(): This function is used for memory allocation to the device.
2) mfree(): To deallocate the memory
3) P_Memory (): It‟s the combination of two or more memory block
or buffer count
Two type of Memory Management in RTOS
1) Stack Management
2) Heap management
1) Stack management : In multitasking RTOS , Each task needs to be
allocated with an amount of memory for Storing their context for
context switching .
This allocation of memory done by using Task Control Block
This set of memory commonly known as kernel stack & management
Process called as Stack Management
Heap management
The remaining physical memory is called as Heap
The heap memory typically used by kernel for dynamic memory
allocation of data space for tasks.
The memory divided into Fixed size blocks which can be
represented by tasks .
When task finishes using memory block it must return to the Pool
This process of management is called as Heap management
RTOS Services in contrast with traditional Operating
Service
Difference between in GPOS and RTOS
Here are important differences between GPOS and RTOS:
General-Purpose Operating System Real-Time Operating System (RTOS)
(GPOS)
It used for desktop PC and laptop. It is only applied to the embedded
application.
Process-based Scheduling. Time-based scheduling used like round-
robin scheduling.
Interrupt latency is not considered as Interrupt lag is minimal, which is
important as in RTOS. measured in a few microseconds.
No priority inversion mechanism is The priority inversion mechanism is
present in the system. current. So it can not modify by the
system.
Kernel's operation may or may not be Kernel's operation can be preempted.
preempted.
Priority inversion remain unnoticed No predictability guarantees
Introduction to µCOS-II
The features of the µC/OS kernels include:
Preemptive multitasking real-time kernel with optional round robin
scheduling
Delivered with complete, clean, consistent source code with in-depth
documentation.
Highly scalable: Unlimited number of tasks, priorities and kernel
objects
Resource-efficient: 6K to 24K bytes code space, 1K+ bytes data space)
Very low interrupt disable time
Extensive performance measurement metrics (configurable)
Certifiable for safety-critical applications
Key Values
Portable. Offering unprecedented ease-of-use, μC/OS kernels are
delivered with complete source code and in-depth documentation. The
μC/OS kernels run on huge number of processor architectures, with ports
available for download.
Scalable. The μC/OS kernels allow for unlimited tasks and kernel
objects. The kernels' memory footprint can be scaled down to contain
only the features required for your application, typically 6–24 KBytes of
code space and 1 KByte of data space.
Reliable. The μC/OS kernels include debugging feature that reduce
development time. The kernels provide extensive range checking,
including checks for pointers passed in API calls, task level services
from ISRs, arguments within allowable range, and for valid specified
options.
Efficient. Micrium's kernels also include valuable runtime statistics,
making the internals of your application observable. Identify
performance bottlenecks, and optimize power usage, early in your
development cycle.
Micro C/OS-II/ μC/OS-II Tasks
Tasks Control Block
TID
• Function of TCB
• Create Task() SAVED_TASK_STATE
• Queue Task()
• Change Priority Task() Resource 1 (signals)
• Delete Task()
• Suspend Task() Resource 2 (events)
Resource 3 (shared memory)
• Because of the complexities of the OS/360 and
successors control program dispatcher, a TCB .
does not strictly perform all the functions of a .
Process control block, although it performs
most of these. System Variables
• Rather, a TCB provides an anchor for a linked
list of other, related request control blocks Task Control Block
(RBs), the composite of which (i.e., the TCB
plus the top-linked RB) performs the function
of a Process control block.
SEMAPHORE
Invented by Edgser Dijkstra in the mid-1960s
It Is like Key or Token acquired by any task to have control of CPU & releases after
execution
send (a message) by semaphore or by signals resembling semaphore.
A semaphore is a key that your code acquires in order to continue execution
If the key is already in use, the requesting task is suspended until the key is released
• There are two types
Binary semaphores
0 or 1
Counting semaphores
>= 0
• Two types : 1)Binary ( value 0 or 1) 2) Counting (Value 8,16,32,64…..2n based
on kernel size)
Binary Semaphore
Counting Semaphore
Semaphore Operations Function of Semaphore
Initialize (or create)
•Initialize or Create
Value must be provided •Wait or pend
Waiting list is initially empty •Signal or post
•Delete
Wait (or pend)
Used for acquiring the semaphore
If the semaphore is available (the semaphore value is positive), the value is
decremented, and the task is not blocked
Otherwise, the task is blocked and placed in the waiting list
Most kernels allow you to specify a timeout
If the timeout occurs, the task will be unblocked and an error code will be
returned to the task
Signal (or post)
Used for releasing the semaphore
If no task is waiting, the semaphore value is incremented
Otherwise, make one of the waiting tasks ready to run but the value is not
incremented
Which waiting task to receive the key?
Highest-priority waiting task
First waiting task
SEMAPHORE
Offered by most multitasking kernels
Used for:
Resource Synchronization
Signaling the occurrence of an event
Task Synchronizing
Semaphores as task synchronization
Display msg as ‘Temperature is 40ºc
Display
Suppose task 1/A wants prints “Display msg as As
Resource
„Temperature is 40ºc!” and Task 2/B prints
“Display msg as „Humidity is 35%”
Semaphore as key
If they were allowed to print at the same time, it
could result in:
Display msg as ”Humidity 40ºcTemperature
is!” is 35%
Solution: Display msg as ‘Humidity is 35%
Binary semaphore
1) Resource Synchronization
Voice signal
2)
Inter process communication (IPC)
Tasks must be able to communicate with one another to
coordinate their activities or to share data
Most of the time tasks cannot run in isolation. They
require to talk to each other.
Synchronization, Protection and Sharing are goals of IPC.
Semaphores (Binary, Counting)
Mutual
Message Queues
Pipes/Named Pipes
Shared Memory
Signals/Slots
Mailbox
Sockets/XTI …
1.IPC by Mailbox • In general, mailboxes are much like
queues. It is like postal box where we
put msg.
• The typical RTOS has functions to
ISR
create, to write to, and to read from
mailboxes, and perhaps functions to
Mailbox Task check whether the mailbox contains
2
Task 1 any messages and to destroy the
mailbox if it is no longer needed
Function of
Mailbox
•Create mailbox
•Delete mailbox
•Query mailbox
•Read mailbox
•Write mailbox
•Post mailbox
2. IPC by Msg Queue • Queues are the primary form of inter
task communications. They can be
used to send messages between two or
more tasks, and between interrupts and
tasks. In most cases they are used as
thread safe FIFO (First In First Out)
buffers with new data being sent to the
back of the queue, although data can
also be sent to the front
Function of Msg Queue
•Create Queue
•Delete Queue
•Flush Queue
•Read msg from Queue
•Post/write msg in Queue
3. Inter process communication (IPC) by pipes
Pipes are also much
like queues. The
RTOS can create
them, write to them,
read from them, and
so on
Function of Pipes
•Create Pipe
•Delete Pipe
•Open Pipe
•Close pipe
•Read Pipe
•Write Pipe
Scheduling: It keeps record of state of task &
assigns CPU to Ready to Run task.
The scheduler is the part of the kernel responsible for
deciding which task should be executing at any
particular time. The kernel can suspend and later resume
a task many times during the task lifetime.
The scheduling policy is the algorithm used by the
scheduler to decide which task to execute at any point
in time.
The primary objective of the job scheduler is to provide
a balanced mix of jobs, such as I/O bound and processor
bound. ...
Time-sharing operating systems have no long term
scheduler.
Also called “dispatchers” , Schedulers are parts of the
kernel responsible for determining which task runs next.
In order to schedule task, information about the task must
be known. The information of task are the number of
tasks, resource requirements, execution time and
deadlines. Based on the system, if it is deterministic,
better scheduling algorithms can be devised
The scheduling algorithms are broadly classified into
priority based and non priority based scheduling. The
Priority based scheduling is based on Greedy / List /
Event Driven. The non priority based are based on first
come first served.
Most real-time kernels use priority-based scheduling
Each task is assigned a priority based on its importance
The priority is application-specific
1.Non Preemptive Scheduling
2.Preemptive Scheduling
3.Round Robin Time Slicing
1.Non Preemptive Scheduling
Perform “cooperative
multitasking”
Each task must explicitly
give up control of the CPU
This must be done
frequently to maintain the
illusion of concurrency
Asynchronous events are still
handled by ISRs
ISRs can make a higher-
priority task ready to run
But ISRs always return to
the interrupted tasks
Advantages :
• Interrupt latency is typically low
Can use non-reentrant functions without fear of
corruption by another task
-Because each task can run to completion before
it relinquishes the CPU
-However, non-reentrant functions should not
be allowed to give up control of the CPU
• Task-response is now given by the time of the
longest task
-much lower than with F/B systems
• Less need to guard shared data through
the use of semaphores
Example : A person making 1000
Disadvantages
call on telephone boot.
• Responsiveness
He do one call & give others
A higher priority task might have to wait
to make like wise one by one.
for a long time
Response time is nondeterministic
• Very few commercial kernels are non-
preemptive
2.Preemptive Scheduling
• The highest-priority task ready to run is always given control of
the CPU
• If an ISR makes a higher-priority task ready, the higher-priority
task is resumed (instead of the interrupted task)
• Most commercial real-time kernels are preemptive
• Advantages :
- Execution of the highest-
priority task is deterministic
- Task-level response time is
minimized
Disadvantages:
- LPT has wait for Long Time
(nested preemptive)
- Should not use non-reentrant
functions unless exclusive
access to these functions is
ensured
3.Round Robin Time Slicing
Round robin means that each
ready task runs turn by in turn
only in a cyclic queue for a limited
time slice.
Widely used model in traditional OS.
Round robin is a hybrid model of
clock-driven model (for example
cyclic model) as well as event
driven (for example, preemptive)
A real time system responds to
the event within a bound time limit
and within an explicit time
Consider serial data from port A & sending it port B by enconding.
Following task is assigned to it.
C1= is checking from port A , C2 = putting msg in queue, C3 = decrypt msg from
queue, C4 = Encode msg,
C5 = X-mit encoded msg to port B
Preemptive Scheduling Non-Preemptive Scheduling
Resources are allocated according to the Resources are used and then held by the
cycles for a limited time. process until it gets terminated.
The process can be interrupted, even before The process is not interrupted until its life
the completion. HPT always run on cpu cycle is complete. All task runs side by side
Starvation may be caused, due to the Starvation can occur when a process with large
insertion of priority process in the queue. burst time occupies the system.
Maintaining queue and remaining time needs No such overheads are required.
storage overhead.
ISR
AN ISR also known as an interrupt service routine (ISR), is a callback subroutine
in an RTOS or device driver whose execution is triggered by the reception of an
interrupt . It saves CPU reg contents On Stack & goes to ISR ,after completion
come back to where it was interrupted.
An interrupt service routine (ISR) is a software routine that hardware invokes
in response to an interrupt. ISR examines an interrupt and determines how to
handle it executes the handling, and then returns a logical interrupt value. If no
further handling is required the ISR notifies the kernel with a return value.
Task 1 CPU ISR CPU Task 1
running context running context running
saving saving
ISR request
Event register
•This register, called an event
register, is an object belonging to a
task and consists of a group of
binary event flags used to track the
occurrence of specific events.
•Depending on a given kernel‟s implementation of this mechanism, an event
register can be 8-, 16-, or 32-bits wide, maybe even more. Each bit in the
event register is treated like a binary flag (also called an event flag) and can
be either set or cleared.
•Through the event register, a task can check for the presence of particular
events that can control its execution. An external source, such as another
task or an ISR, can set bits in the event register to inform the task that a
particular event has occurred.
•Applications define the event associated with an event flag. This definition
must be agreed upon between the event sender and receiver using the event
Mutex (Mutual Exclusion)
• The easiest way for tasks to communicate is through shared data structures
Global variables, pointers, buffers, linked lists, and ring buffers
• Must ensure that each task has exclusive access to the data to avoid data
corruption
• Mutual exclusion (widely known as Mutex) is used in various operating
systems for resource management. ... Mutexes are used to protect access to a
shared resource. A mutex is created and then passed between the threads
(they can acquire and release the mutex). CMSIS-RTOS Mutex. A mutex is a
special version of a semaphore.
The most common methods are:
•Disabling interrupts
•Performing test-and-set operations
•Disabling scheduling
•Using semaphores
Disabling and Enabling Interrupts
The easiest and fastest way to gain exclusive access
Example:
Disable interrupts;
Access the resource;
Enable interrupts;
This is the only way that a task can share variables with an
ISR
However, do not disable interrupts for too long
• A Mutex is different than a semaphore as it is a locking mechanism while a
semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex
but a Mutex can never be used as a semaphore.
Memory Management in RTOS
The part of the operating system that manages the memory
hierarchy is called the memory manager.
Its job is to keep track of which parts of memory are in use and
which parts are not in use, to allocate memory to processes when
they need it and de-allocate it when they are done, and to manage
swapping between main memory and disk when main memory is
too small to hold all the processes.
Memory is premium in environments where RTOS work.
Kernel uses available physical program memory to other I/O
devices after Initialization of code(Dynamic memoery allocation)
mfree() & malloc()
User space and Kernel space memory.
RTOS KERNEL: Memory(3)
The simplest possible memory management scheme is to run just one program at a time,
sharing the memory between that program and the operating system.
Three variations on this theme are shown in Fig. 4-1. The operating system may be at the
bottom of memory in RAM (Random Access Memory), as shown in Fig. 4-1(a), or it
may be in ROM (Read-Only Memory) at the top of memory, as shown in Fig. 4-1(b), or
the device drivers may be at the top of memory in a ROM and the rest of the system in
RAM down below, as shown in Fig. 4-1(c).
The first model was formerly used on mainframes and minicomputers but is rarely used
any more. The second model is used on some palmtop computers and embedded
systems. The third model was used by early personal computers (e.g., running MS-
DOS), where the portion of the system in the ROM is called the BIOS (Basic Input
Output System).
RTOS KERNEL: Memory(4)
• Introduction Participation of User space programs with kernel for
• Structure of RTOS services and as a central pool of memory for
specialized applications.
• Components of RTOS
• RTOS Kernel
• Tasks
• Memory User Space memory
• Timers P1 P2
• I/O
• IPCs
• Device Drivers
• Expectations
• Examples M1 M2
Kernel Space Memory
μCOS-II – Microcontroller based operating System
Most applications for real-time systems are embedded. This means that the computer
is built into a system and is not seen by the user as being a computer.
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. The use
of a real-time kernel will generally simplify the design of
systems by allowing the application to be divided into
multiple tasks managed by the kernel.
A kernel will add overhead to your system because it requires
extra ROM (code space), additional RAM for the kernel data
structures but most importantly, each task requires its own
stack space which has a tendency to eat up RAM quite
quickly. A kernel will also consume CPU time (typically
between 2 and 5%).
μC/OS-II features:
Source Code:
ALL the source code for μC/OS-II. I went through a lot of efforts to provide you with a high quality
„product‟. You may not agree with some of the style constructs that I use but you should agree that the
code is both clean and very consistent. Many commercial real-time kernels are provided in source form
Portable:
Most of μC/OS-II is written in highly portable ANSI C, with target microprocessor specific code written
in assembly language. Assembly language is kept to a minimum to make μC/OS-II easy to port to other
processors.
μC/OS-II can run on most 8-bit, 16-bit, 32-bit or even 64-bit microprocessors or micro-controllers and,
DSPs. All the ports that currently exist for μC/OS can be easily converted to μC/OS-II in about an hour.
ROMable:
μC/OS-II was designed for embedded applications. This means that if you have the proper tool chain
(i.e. C compiler, assembler and linker/locator), you can embed μC/OS-II as part of a product.
Scalable:
I designed μC/OS-II so that you can use only the services that you need in your application. This means
that a product can have just a few of μC/OS-II‟s services while another product can have the full set of
features.
Preemptive:
μC/OS-II is a fully-preemptive real-time kernel. This means that μC/OS-II always runs the highest
priority task that is ready. Most commercial kernels are preemptive and μC/OS-II is comparable in
performance with many of them.
Multi-tasking:
μC/OS-II can manage up to 64 tasks, however, the current version of the software reserves eight (8) of these
tasks for system use. This leaves your application with up to 56 tasks. Each task has a unique priority assigned
to it which means that μC/OS-II cannot do round robin scheduling. There are thus 64 priority levels.
Deterministic:
Execution time of all μC/OS-II functions and services are deterministic. This means that you can always know
how much time μC/OS-II will take to execute a function or a service. Furthermore, except for one service,
execution time of all μC/OS-II services do not depend on the number of tasks running in your application.
Task stacks:
Each task requires its own stack, however, μC/OS-II allows each task to have a different stack size. This allows
you to reduce the amount of RAM needed in your application. With μC/OS-II‟s stack checking feature, you can
determine exactly how much stack space each task actually requires.
Services:
μC/OS-II provides a number of system services such as mailboxes, queues, semaphores, fixed-sized memory
partitions, time related functions, etc.
Interrupt Management:
Interrupts can suspend the execution of a task and, if a higher priority task is awakened as a result of the
interrupt, the highest priority task will run as soon as all nested interrupts complete. Interrupts can be nested up
to 255 levels deep.
Robust and reliable:
μC/OS-II is based on μC/OS which has been used in hundreds of commercial applications since 1992. μC/OS-II
uses the same core and most of the same functions as μC/OS yet offers more features.
Task & task state
A task, also called a thread, is a
simple program that thinks it has
the CPU all to itself. The design
process for a real-time
application involves splitting the
work to be done into tasks which
are responsible for a portion of
the problem.
Each task is assigned a priority,
its own set of CPU registers, and
its own stack area.
• Each task typically is an infinite loop that can be in any one of five states:
DORMANT, READY, RUNNING, WAITING FOR AN EVENT, or
INTERRUPTED (see Figure 2-3). The DORMANT state corresponds to a task
which resides in memory but has not been made available to the multitasking
kernel. A task is READY when it can execute but its priority is less than the
currently running task.
A task is RUNNING when it has control of the CPU. A task is WAITING FOR
AN EVENT when it requires the occurrence of an event (waiting for an I/O
operation to complete, a shared resource to be available, a timing pulse to occur,
time to expire etc.).
Finally, a task is INTERRUPTED when an interrupt has occurred and the CPU
is in the process of servicing the interrupt. Figure 2-3 also shows the functions
provided by μC/OS-II to make a task switch from one state to another.
Process control: Computer Aerospace:
Food processing peripherals: Flight management systems
Chemical plants Printers Weapons systems
Automotive: Terminals Jet engine controls
Engine controls Scanners Domestic:
Anti-lock braking systems Modems Microwave ovens
Office automation: Robots Dishwashers
FAX machines Washing machines
Copiers Thermostats
Resource Allocation in RTOS
Resource Allocation
The issues with scheduling applicable here.
Resources can be allocated in
Weighted Round Robin
Priority Based
Some resources are non preemptible
Example: semaphores
Priority inversion problem may occur if priority scheduling
is used
Priority Inversion Problem
Common in real-time kernels
Suppose task 1 has a higher priority than task 2
Also, task 2 has a higher priority than task 3
If mutual exclusion is used in accessing a shared resource,
priority inversion may occur
A Solution to Priority Inversion Problem
We can correct the problem by raising the priority of task 3
Just for the time it accesses the shared resource
After that, return to the original priority
What if task 3 finishes the access before being preempted by task 1?
incur overhead for nothing
A Better Solution to the Problem
Priority Inheritance
Automatically change the task priority when needed
The task that holds the resource will inherit the priority of the
task that waits for that resource until it releases the resource
Priority Inheritance Example
Assigning Task Priorities
Not trivial
In most systems, not all tasks are critical
Non-critical tasks are obviously low-priorities
Most real-time systems have a combination of soft and hard
requirements
RTOS KERNEL: Timer
Timer is software entity derived from hardware clock.
Timer provides mechanism to introduce task-delays and/or to
help synchronize and provide time off-course.
Watchdog Timers, Programmable Timers
Function :
- Get time
- Set time
- Time Delay(in system clk tick)
- Time Delay (In sec)
- Reset time
- RunAtExpiry
RTOS KERNEL:
Device Drivers(1)
• Introduction
• Structure of RTOS A piece of software that enables
• Components of RTOS devices connected to particular
• RTOS Kernel
• Tasks
processor, via various interfaces.
• Memory Controls, manages and configures
• Timers
devices connected to system.
• I/O
• IPCs
• Device Drivers
• Expectations
• Examples
RTOS KERNEL:
Device Drivers(2)
• Introduction
• Structure of RTOS
• Components of RTOS Client Drivers
• RTOS Kernel
• Tasks
• Memory
• Timers Protocol Layers
• I/O
• IPCs
• Device Drivers
• Expectations Host Controller Drivers
• Examples
Hardware