Professional Documents
Culture Documents
Module3 Qing Li
Module3 Qing Li
Module3 Qing Li
Anoop Thomas
Contents
Introduction – Basics of OS & Real Time Systems
RTOS vs GPOS
RTOS Components
Scheduler & Scheduling Algorithms
RTOS – Advantages & Dis-advantages
Tasks & Data
Semaphores, Message Queues, Mailboxes & Pipes
Timer Functions & Events
Memory Management & Interrupt Routines
System Concepts
3
Embedded Operating Systems
• An "embedded system" is any computer system or computing
device
• That performs a dedicated function or
• Is designed for use with a specific embedded software application.
• Embedded systems may use a
• ROM-based operating system or
• A disk-based system, like a PC.
• But an embedded system is not usable as a commercially viable
substitute for general purpose computers or devices.
4
What makes a good Embedded OS?
• Modular
• Different functions of OS can be kept in different modules; Can be
used whenever necessary
• Eg- Networking module, MMU module etc
• Scalable
• Scaling up or down; May be memory
• Configurable
• Configure according to user requirement
• Small footprint
• Refers to memory; Requires only few memory to run a program
• CPU support
• Flexible with many processors
• Device drivers
• Software that makes an OS understand the device connected
externally to it; Good embedded OS should have drivers inbuilt
5
Real Time Systems
• Failed System
• System that can’t satisfy one or more of the requirements stipulated in
the formal system specification 6
What is Real Time?
-Donald Gillies
7
What is Real Time?
8
Real Time Systems (cont..)
• Reactive Systems
• Scheduling is driven by ongoing interaction with environment
• Eg- Fire Control System
• Embedded Systems
• Found in a system that is not itself a computer
• Eg- Automobiles – Fuel injection, Airbag Deployment, Braking etc
9
When is a system Real Time?
• Can be argued that all practical systems are real time systems
• All are Real Time
• Grade processing at the end of a semester
• Monthly payroll run
• Aircraft data processing
• Nuclear reactors
• Reservation Systems – Airline, Railways
• Doesn’t have to process data in μsec to be considered real time –
Must have response times that are constrained
• Based on timing constraints:
• Hard and Soft Real Time Systems
10
Soft Real Time Systems
11
Hard Real Time Systems
12
13
Brief History of Operating Systems
14
16
Similarities – RTOS and GPOS
• Level of multitasking
• Software and hardware resource management
• Provision of underlying OS services to applications
• Abstracting the hardware from the software application
17
GPOS VS RTOS
A GPOS is used for systems/applications that are not time
critical. Example:- Windows, Linux, Unix etc. An RTOS is used
for time critical systems. Example:- VxWorks, uCos etc
18
Differences - RTOS and Desktop OS
• Determinism
• Known upper bounds for
• Time taken by the kernel to react when an external event has occurred
• Kernel provides predictable schedules and timers for applications
• "Deterministic" timing means that OS consume only known and
expected amounts of time. RTOS have their worst case latency
defined. Latency is not of a concern for General Purpose OS
• Responsiveness
• How quickly the OS can transfer the execution to the interrupt
service routine (ISR) and execute the routine?
• The effect of interrupt nesting: servicing a higher priority
interrupt delays the lower priority interrupt handling?
19
• User Control
• RTOS usually allows fine-grained control over the system to
make meeting RT requirements easier
• Task scheduler: fixed task execution timings
• Memory manager: switch off VM/swap/caches for easier
predictability of execution times
• Reliability
• Often run critical tasks that might cost lots of money or even
human lives in case of failure
• Simpler the kernel, easier it is to inspect for bugs
20
• Task Scheduling -
• General purpose operating systems
• optimized to run a variety of applications and processes
simultaneously,
• thereby ensuring that all tasks receive at least some
processing time.
• low-priority tasks may have their priority boosted above
other higher priority tasks, which the designer may not
want.
21
• Task Scheduling -
•However, RTOS uses
• priority-based preemptive scheduling, which allows high-
priority threads to meet their deadlines consistently.
• All system calls are deterministic, implying time bounded
operation for all operations and ISRs.
• This is important for embedded systems where delay could
cause a safety hazard.
•The scheduling in RTOS is time based. In case of
General purpose OS, like Windows/Linux, scheduling is
process based.
22
•Fail – Safe Operation
• If/when an error occurs, some sensible way to recover from
it(no general approach exists, entirely application dependent)
• Stability
• If a deadline error occurs, try to execute the most important
real-time tasks anyways
23
Differences – RTOS and GPOS
24
Used in embedded systems
25
Defining a RTOS
26
High Level View of an RTOS
27
Kernel
• In some applications , an RTOS comprises only a kernel, which
is the core supervisory software that
• Provides minimal logic,
• Scheduling, and
• Resource-Management algorithms.
• A file system,
28
RTOS Kernel – Components
• Scheduler
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 preemptive scheduling.
• Objects
Special kernel constructs that help developers create applications for
real time embedded systems.
Common kernel objects include tasks, semaphores, and message
queues.
• Services
Operations that the kernel performs on an object or, generally
operations such as timing, interrupt handling, and resource
management. 29
Common Components in a RTOS
Kernel
30
Scheduler
31
• Schedulable Entity
• Multitasking
• Context Switch
• Task Control Block
• Dispatcher
Schedulable Entities
• Kernel object that can compete for execution time on a system
based on pre-defined scheduling algorithm
• Tasks and Processes
• A task is an independent thread of execution that contains a
sequence of independently schedulable instructions
32
Multitasking
33
Context Switch
• Each task has its own context, which is the state of the
CPU registers required each time it is scheduled to run.
34
Task Control Block
• Every time a new task is created, the kernel also creates
and maintains an associated task control block(TCB)
• TCBs are system data structures that the kernel uses to
maintain task specific information
• When a task is running, its context is highly dynamic
• This dynamic context is maintained in the TCB
• When the task is not running, its context is frozen
within the TCB, to be restored the next time the task
runs.
35
Key Characteristics of an RTOS
• Reliability
• Predictability
• Performance
• Compactness
• Scalability
36
Task, Process & Threads
• Task is a generic term that refers to an
activity carried out by software that occurs
independently from other activities in the
system.
• Tasks that are separate executing
programs are called processes
• Tasks that execute in the context of a
single program are called threads.
• Smallest sequence of programmed instructions
that can be managed independently by
a scheduler.
37
Task Concept
38
Task States
• Running:
• Instructions are being executed
• If it is not a multiprocessor system, there is only one microprocessor
Only one task i.e., running at any given time.
• Ready:
• The task is waiting to be assigned to run state by the scheduler.
• Any number of tasks can be in this state
• Blocked:
• The task is waiting for some event to occur
• Any number of tasks can be in this state
39
Task States
40
Scheduler
• Keeps track of the state of each task and decides which
task should go into the running state.
• Looks for priority among the tasks that are not in the
blocked state.
• One with highest priority runs and others remain in the
ready state.
• Switching between ready and running states is entirely
the function of scheduler
41
Task Scheduling
43
If one task is running and another higher priority
task unblocks, does the task i.e., running gets
stopped and moves to ready state right away???
44
Pre-emptive or Non Pre-emptive
RTOS
• Preemptive OS - Stops a lower priority task as soon as a
higher priority task enters the ready state
• Non-preemptive process - Continue executing the
current running process until it blocks regardless of the
priorities of the other ready processes
45
Example –Tank Monitoring
System
46
Uses for tasks
47
Uses for tasks
48
Sample Code
49
Responding to a button under an
RTOS
50
Tasks and Data
51
Data in an RTOS based RT system
52
Tasks and Data
• RTOS typically has its own private data structures Not
available to any of the tasks
• Data variables can be shared among tasks Easy to move data
from one task to another.
• Two tasks in the same module in which the variables are declared
• Make the variable public in one of the task and make them ‘extern’
in the other
53
Sharing data among RTOS tasks
struct
{
long lTankLevel;
long lTimeUpdated;
} tankdata[MAX_TANKS];
/* button task */
void vRespondToButton (void) /* high priority */
{
int i;
while (TRUE)
{
{
!! Block until user pushes a button
i = !! ID of button pressed
printf (“\nTIME: %d LEVEL: %d,
tankdata[ i ].lTimeUpdated,
tankdata[ i ].lTankLevel);
}
} 54
Sharing data among RTOS tasks
/* levels task */
void vCalculateTankLevels (void) /* low priority */
{ int i = 0;
while (TRUE)
{
!! Read levels of floats in tank i
!! Do some calculations
/* store the result */
tankdata[ i ].lTimeUpdated = !! Current time
/* between these two instructions is a bad place for a task switch */
tankdata[ i ].lTankLevel = !! Result of calculation
!! Figure out which tank to do next
i = !! Something new
}
} 55
Shared Data Problems
56
Tasks that can Share Code
void task1 (void)
{
.
.
vCountErrors (9);
.
.
}
void task2 (void)
{
.
.
vCountErrors (11);
.
}
57
Why this code fails??
58
Problems with Shared Data
59
Semaphores
60
Semaphores
61
Semaphore Functions
• Binary Semaphores
• Two functions, one to set the semaphore to disable other tasks, and
the other to release the semaphore to other tasks.
• Many names in use:
• Lower and raise
• p and v
62
Sample Code
63
Sample Code
64
Execution Flow with Semaphores
65
Execution Flow with Semaphores
66
Initialize Semaphores
67
Multiple Semaphores
• Using a single semaphore is impractical
• Most RTOS’s allow multiple semaphores
• It is up to the programmer to allocate different semaphores to different
data items
• Advantages
Whenever a task takes a semaphore, it slows down the response of any task
that needs the same semaphore.
In a s/m with only 1 semaphore,
o if the lowest priority task takes the semaphore to change data in a shared
array
o Higher priority task might block waiting for that semaphore
70
Semaphore Variants
Binary Semaphore
Counting Semaphores
Semaphores that allow more than one task at a time
The maximum number of tasks is determines through the
initialization of the semaphore
Mutex
Semaphores that automatically deals with priority inversion
problem 71
Counting Semaphore
72
Mutex
73
Many mutex implementations also support recursive locking , which allows the task
that owns the mutex to acquire it multiple times in the locked state.
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.
A recursive mutex allows nested attempts to lock the mutex to succeed, rather than
cause deadlock ,which is a condition in which two or more tasks are blocked and are
waiting on mutually locked resources.
In this example, a lock count tracks the two states of a mutex (0 for unlocked and 1
for locked), as well as the number of times it has been recursively locked (lock
count > 1).
In other implementations, a mutex might maintain two counts: a binary value to
track its state, and a separate lock count to track the number of times it has been
acquired in the lock state by the task that owns it.
The count used for the mutex tracks the number of times that the task owning the
mutex has locked or unlocked the mutex.
Additionally, the count for the mutex is always unbounded, which allows multiple
recursive accesses.
Task Deletion Safety - MUTEX
76
wait-and-signal synchronization
multiple-task wait-and-signal synchronization
credit-tracking synchronization
single shared-resource-access synchronization
recursive shared-resource-access synchronization
multiple shared-resource-access synchronization.
Message Queues
80
Message Queues- Components
81
Message Queues- States
82
Queues (cont..)
• Writing into queue If queue is full and task tries to add some
value into it
• Error message to be printed telling that write operation failed (or)
• Block the task until some other task reads data from the queue and
creates some space
• Reading from a queue Read from the queue if there is any data
• Return an error code if data is not present (or)
• Blocks your task if queue is empty
83
Message Queue Contents & Storage
84
Contents
temperature value from a sensor
bitmap to draw on a display
text message to print to an LCD
keyboard event
data packet to send over the network
Storage
One kernel might use a system pool, in which the messages
of all queues are stored in one large shared area of memory.
Another kernel might use separate memory areas, called
private buffers, for each message queue.
Message Queue Operations
85
87
Pipe Components
88
Pipe FSM
89
Typical Pipe Operations
90