ppt1_rtos (1)
TRANSCRIPT
-
7/30/2019 ppt1_rtos (1)
1/35
Embedded System
Embedded Systems:
Electronics system that containsprocessor (uP/uC/DSP/ASIP etc.)and peripherals which isconfigured to perform specificdedicated application
Software embeds in ROM andnot accessible to the user
Mostly designed for timeconstrained applications (real timesystems)
either independent system or apart of larger system.
G P Computer System:
contains general purpose (GP)microprocessor, primary &
secondary memories, keyboards,
printer, scanner, monitor etc.
Programmed for GP applicationsthat includes word processing,
accounting, scientific computing,
email, multimedia, database system
etc.
user does have access to
software and decides which OS to
run and which application to launch.
## Small scale, medium scale and sophisticated Embedded System
-
7/30/2019 ppt1_rtos (1)
2/35
Elements of embedded systems
(1) Processors : Microprocessors : e.g.68HCxxx, 80x86, SPARC, PowerPC
Microcontrollers : 68HC11xx, 8051, PIC series, ARM series DSP : TMS series, SHARC
ASSP/ASIP : processor with hardwired logic customized to application
(2) Memories : ROM variants : application programs, code for RTOS, codes for booting,
initializing, initial input data and strings, pointers of service routines
RAM (int. & ext.) : variables during program run, I/O buffers Cache : copies of inst. and data in advance, intermediate results for fast
processing
(3) Built-in Modules : Serial/Parallel ports, ADC/DAC, PWM, Watchdog timer, RTC etc.
(4) I/O :
Inputs => keyboard, sensor circuits, comm. network interface etc. Outputs=> LED, LCD, Alarm, actuators, comm. network interface etc.
-
7/30/2019 ppt1_rtos (1)
3/35
Example (Telegraph) :
Network Data may be out of order, lost or arrive twice
Other computers on Network also want to print
Need to provide status of printer to computers
It has to work with different type of printer
It need to respond quickly and keep track of time
Aspects :throughput, response, handling uncommon events,debugablility
-
7/30/2019 ppt1_rtos (1)
4/35
Real Time System
system wherein execution of jobs (or tasks) are time constrained
Release time, response time, deadlines
Hard and Soft Real time System: Hard -> miss of deadline is fatal fault, consequences may be disastrous
Soft -> occasional misses of deadline will not do serious harm, only overallperformance is slightly degraded, job execution has value even if completedlate
Often described quantitatively in terms ofusefulness function as a function ofthe tardiness of job
Tardiness = lateness of job = completion time - deadline
Plot is a guide for selection type of scheduling to be used that best suits
-
7/30/2019 ppt1_rtos (1)
5/35
Validation > for Hard RTS, validation of all constraints (worst case) is must
> for Soft RTS, only demo of jobs meeting avg. case is suffice
Example of Hard RTS :- industrial process control, flight control
Example of Soft RTS :- Telephone system (delay in call setup not much
objectionable), multimedia (quality is not much affected if few frames, say 2
or 3, per minute are late or lost)
In soft RTS, since timing constraints are relaxed
we have more design options
we can make system better in other aspects
we can make system cost-effective
Performance measures for soft RTS : miss rate:% of tasks that are executed late (missed deadlines)
loss rate:% of tasks that are discarded (not executed at all)
invalid rate = miss rate + loss rate
We need to minimize invalid rate
-
7/30/2019 ppt1_rtos (1)
6/35
RTOS
When RTOS is needed? When not?
RTOS is platform for embedded system that performs various system tasks
such as handling system call, scheduling, inter process communication andsynchronization (IPC), interrupt handling, servicing timers etc.
Central concept in OS is process which is an abstraction of running program
Process (or Task ) : Process is an action of execution of the program. Application software can be
defined as consisting of the processes
Process Status :- ready, running, blocked, terminated, sleeping
-
7/30/2019 ppt1_rtos (1)
7/35
RTOS
Context of process and context switching
a process can create one or more other processes (referred to as childprocesses)and these processes in turn can create child processes to formprocess tree.
When process is created, RTOS allocates memory space and instantiatesdata structure called Process Control Block (PCB)
PCB :-Context (Program status word, SP, PC & other CPU registers value),process ID, Current state, pointers to queue of messages, pointers to parentand daughter process, pointer to list of resources, pointer to access
permission descriptor for sharing resources globally and with other process User mode (application) and Kernel mode (RTOS) processes
No synchronization among processes without OS kernel
Threads : Threads are subunits of a process which may execute simultaneously
Process may contain multiple threads. All threads of a process run in addressspace of same process.
Have their own PC, stack and registers which are private and never shared
Advantages:-reduces context switching overhead, multiple control points ina process, improves responsiveness
-
7/30/2019 ppt1_rtos (1)
8/35
RTOS
-
7/30/2019 ppt1_rtos (1)
9/35
RTOS
Basic OS Functions:
[1] System Call : Application accesses kernel data and code via system calls
Upon receiving call, RTOS saves context of calling process and
switched kernel mode
it then executes the API function and switches back to user mode
[2] Servicing Interrupts : independent call from either h/w or s/w whose scheduling is controlled
either by ISR process instructions or RTOS
If ISR happens in non-reentrant function f1 and if ISR also contains call
to f1 then it modifies shared variables off1. When f1 is resumed, it runs
with modified variables which leads to unpredictable result. To avoid this
ISR must call only reentrant function.
Latency: sum of (i) time to process current instruction, flush the pipeline,
read interrupt vector & jump to handler part of OS kernel (ii) time kernel
takes to disable interrupts (iii) time required to complete service routine
of higher-priority interrupt if any (iv) time to save context of interrupted
process (v) time the kernel takes to start ISR
-
7/30/2019 ppt1_rtos (1)
10/35
Reentrant Funct ion s:
A reentrantfunction is one that can be used by more than one process
concurrently without fear of data corruption. A reentrant function can be
interrupted at any time and resumed at a later time without loss of data. A function or routine is described as reentrant if it can be safely called again
before its previous invocation has been completed (i.e. it can be safely
executed concurrently).
Any function called within ISR should be reentrant
Only static and global variable affects re-entrance
Reentrant function forces compiler to allocate separate memory dynamically
for each instance of call and allows more than one task (process) to use it
concurrently without fear of data corruption
A reentrant function:
Does not hold static data over successive calls
Does not return a pointer to static data; all data is provided by the caller
of the function
Ensures protection of global shared data
Must not call any non-reentrant functions
-
7/30/2019 ppt1_rtos (1)
11/35
Considerst r toupperfunction where global variable buffer used by multiple
processes.
-
7/30/2019 ppt1_rtos (1)
12/35
1st Solution => The function is made reentrant by dynamically allocating
memory (using malloc) for buffer for every invocation of function.
2nd Solution => caller must provide the storage for input strings (in_str) and
output string (out_str).
-
7/30/2019 ppt1_rtos (1)
13/35
RTOS
According to OS kernel features, following explains 3 alternatives foundin 3 RTOSs for responding and synchronizing the ISR call
(1) Interrupt source calls ISR directly and ISR does complete servicing. Itmerely send a message to RTOS
(2) RTOS Kernel intercepts the interruptcall and initiate correspondingISR after saving context. ISR send message(s) to RTOS for initiatingprocesses. Now kernel schedules and runs processes according tomessages sent by ISR. RTOS only schedules process and ISR runsduring suspension of processes.
(3) RTOS treats ISR as a process. After interrupt call, RTOS calls ISRprocess after saving context. The ISR merely sends IPC containingparameters needed by RTOS. Then RTOS initiates and executes theprocesses and one of them is ISR
[3]Scheduling: Scheduler is a Part of RTOS kernel that schedules processes and allocates
resources to them according to scheduling policy
Preemptive and Non preemptive/Cooperative scheduling
online (run time) and offline (pre- run time) scheduling
Fixed priority and dynamic priority based scheduling
-
7/30/2019 ppt1_rtos (1)
14/35
Funct ion:-(i) routine for performing actions as per parameter
passed to it and may be called from process, ISR or anotherfunction (nesting) (ii) synchronization among functions without OS or
scheduler
Process:-(i) independent entity scheduled/controlled by RTOS (ii)
each process has distinct stack for saving context and distinct
memory block for storing PCB (iii) no synchronization among the
processes without OS kernel
Each process runs sequentially but executions of multiple processes
can be interleaved called multiprocessing
-
7/30/2019 ppt1_rtos (1)
15/35
Scheduling Algorithms
Timing parameters:
Release time: an instant the process is ready for execution Execution (run) time : time period to complete process execution
Absolute deadline (d) : an instant by which process must finish
Slack time = (d-t)remaining run time of process at time t
= deadline estimated completion time (negative slackmeans missed deadline)
-
7/30/2019 ppt1_rtos (1)
16/35
[A] Non Preemptive Task(Process) scheduling:
(1)Round Rob in (Circu lar Queue):
Processes are executed sequentially from ready linked list
RTOS keeps track of currently executing process. It updates linked list uponinsertion and removal of a process. New process is inserted at the end oflinked list
Circular FIFO buffer can be used to form ready list of processes
New process is inserted before the currently running one (last in circular list)
Simple architecture : no interrupts, no shared data, no latency concerns.
Attractive option for some jobs
-
7/30/2019 ppt1_rtos (1)
17/35
(2) Round Rob in w ith Prior i ty based Ready Lis t
Processes in ready queue are ordered as per their priority but executed in turn
(circularly) from ordered list
Scheduling is still non-preemptive as no process is preempted by any other
Time to execute all processes in ready queue is termed as one cycle
The processes are ordered based on priority at the beginning of every cycle.
Process is allowed to run till the end of execution
-
7/30/2019 ppt1_rtos (1)
18/35
(3) Round Rob in Schedul ing w ith Time Sl icing:
RTOS defines a time slot for each process for its execution Tslot
In a single schedule cycle ( time slice Tslice) processes are taken sequentially
If process doesnt finish in Tslotit is blocked (suspended) until it get its turn inthe next time slice
Tsliceis fixed whereas Tslot is variable
If process finishes before Tslot there is waiting period
Disadv. Of Non -Preemptiv e:
Long execution of low priority tasks make high priority task to wait long
Difficult to meet deadlines
-
7/30/2019 ppt1_rtos (1)
19/35
Scheduling Algorithms
[B] Preemptive Scheduling:
Process may be blocked at any instant to allow higher priority task torun. This is called preemption.
In preemptive scheduling, Priorities are assigned to processes usingvarious criteria.
Following scheduling algorithms are commonly used
Shortest Remaining Runtime First
Priorities are assigned such that shorter the execution time,
higher the priority
Earliest Deadline First (EDF)
Earlier the deadline, higher the priority Least Slack time First (LSF) or Least Laxity First (LLF)
Smaller the slack, higher the priority
Note:Schedulershould not blockany process running in critical region
-
7/30/2019 ppt1_rtos (1)
20/35
Example :- A scheduler is invoked every 1 unit of time and selects process fromready queue to run. (a) How processes are scheduled with Least Slack Time firstpolicy ? (b) How the processes are scheduled with Shortest Run time firstpolicy?(c) Find total time spent in wait by all process, total no. of context switches andno. of deadline missed for each scheduling.
In case of tie, following criteria would be used in that order (i) process alreadyrunning should be preferred over others (ii) process with earlier deadline shouldbe selected (iii) processes should be scheduled in Round robin fashion
Ans:
Slacktime = deadline - t- time remaining to finish process at t
The slack time of processes when they became ready (released) is given byP0=18 (at t=0), P1=4 (at t=10), P2=19 (at t=4) and for P3=5 (at t=5).
>slack time of running process remains constant while it decreases for waitingprocess
>to ensure proper scheduling using Round Robin, circular selection of processesfrom ready queue is required
-
7/30/2019 ppt1_rtos (1)
21/35
-
7/30/2019 ppt1_rtos (1)
22/35
-
7/30/2019 ppt1_rtos (1)
23/35
-
7/30/2019 ppt1_rtos (1)
24/35
Periodic Process (Task) model
Periodic Processes (Tasks) are executed repetitively with periodpi
and execution time ei where iis process number
Assume that process needs to execute only one thread in a period
Threads (jobs) of a process Pi are refereed to as i1, i2, . . . being
ikbeing the kth thread in process Pi
LCM of allpifor i=1,2,3, . . . . . n is called hyper period H The ratio ui=ei/pithe utilization of the process (task) Pi is equal to
fraction of time of a processor is kept busy
The total utilization U of all the processes in the system is the sum of
utilizations of individual process in it
1ST thread of process Pi released at release time rimust completeDiunits of time afterri; where Diis relative deadline. If is not Dispecified, period of the process would be considered as deadline.
-
7/30/2019 ppt1_rtos (1)
25/35
Periodic Scheduling
Periodic Schedul ing of Process (Taslk):
In general, Periodic threads of process ican be represented as 4-tuple(ri,pi,ei,Di) whereri phase of 1ST thread, p i period, ei execution timeand Di relative deadline.
For example P1= (1,12,4,6) is periodic task whose 1st job is released at time1 and must complete at time 7. The second job is ready at time 13 and mustbe completed by 19 and so on.
Some element of 4-tuple may be omitted for simplicity. For example
(12,4,6) => has zero phase (i.e. ri=0)
(12,4) => has ri=0 & Di=0. Here period becomes deadline for thread
e.g. P1(3,2) :- threads of process P1 are periodic with period (deadline) 3and execution time 2.
Some algorithms for periodic scheduling are:
Dynamic priority => EDF, Least Slack Time First, Shortest RemainingRuntime First
Fixed Priority => Rate Monotonic (RM), Deadline Monotonic (DM)
-
7/30/2019 ppt1_rtos (1)
26/35
Periodic Scheduling
i1
, i2
. . . are threads of process Pi
For P1, relative deadline is 6 for each threads. Therefore absolutedeadline for11,12,13 . . are 7, 17, 27, . . .
-
7/30/2019 ppt1_rtos (1)
27/35
Rate Mono tonic (RM) Schedu l ing
Very popular fixed priority scheduling policy for most medium scale RTOS
Assigns priority base on frequency of periodic task i.e. smaller the periodhigher the priority
A set of processes is schedulable under RM algorithm with following
requirements
(1) Necessary Condition:
U = [i=1 to n ei/pi] 1(2) Sufficient condition:
U n (21/n1), here as n , U ln(2) or U 0.69 (for n ) Lehoczky proposed schedulability test for Any Phase:- a set of task (P1,P2,
. . . Pn) is schedulable in RM technique under any phase if the tasks meet
their respective first deadline in zero phasing.Let the periodsp1 . >Pn
The task Pi meets its first deadline only if
ei+ [k=1 to i-1 (pi/pk)xek] pi
-
7/30/2019 ppt1_rtos (1)
28/35
Inter Process Communication (IPC)
Processes exchange data and control info through IPC mechanism
IPC ensures that exchange occur at right time and under right condition
IPC methods: (1) Signal (ii) message queue (iii) pipe
Signals: Signals are used to signal asynchronous events to one or more processes
Signals have no inherent relative priorities, signals take min. CPU time
Process may ignore signals, except those meant for stop/kill process
If a process dont block signals, it choose to handle them or allows kernel tohandles them
Used in exception handling, error reporting
Message Queue: A process may create its own message queue
When message Queue is created, corresponding data structure is alsocreated that contain info such as message queue ID, permission, messagescurrently in queue, size of each message, process ID of last messagewritten/ read, time of last message written/read etc.
process-to-process and process-to-ISR communication
pointers to messages queue for reading and writing messages
-
7/30/2019 ppt1_rtos (1)
29/35
IPC
Receive (buf) => read msg. from top of the queue and store in buf
Send (id1, m1) => write message m1 in queue intended for recipientprocess id1
Query () => retrieves info such as msg. queue size, queue empty or not
Delete() => deletes msg. queue
-
7/30/2019 ppt1_rtos (1)
30/35
IPC
PIPES:
An IPC between two given interconnected processes using unidirectionalanonymous pipe or uni/bi directional named pipes
Pipe is kernel buffer for info transfer, used cyclically, stream oriented
Unlike msg. queue, pipe mechanism does not preserve message boundary
Unidirectional /bidirectional pipe
Example : Client/Server communication: The process that creates a pipe is
thepipe server. A process that connects to a pipe is apipe client. Oneprocess writes information to the pipe, then the other process reads theinformation from the pipe
-
7/30/2019 ppt1_rtos (1)
31/35
Resource Access Control
Global variables are often shared between ISR process and main process. As
shown sharing of variable Tempcauses race condition and leads to hazards.
Without proper locking (a mutex), the code cannot be race free
Solution : disable all interrupts, writing sensitive part of process in critical
section (region)of memory which is protected by lock
Lock (semaphore) ensures that shared resource is acquired by only one
process at a time. It makes critical region atomic (uninterruptible). Each share
resource has its own lock (semaphore)
-
7/30/2019 ppt1_rtos (1)
32/35
Resource Access Control
Semaphore :-acts as lock to protect critical region, process takes
semaphore from RTOS before executing critical section codes
Boolean Semaphore (mutex):
facilitates mutually exclusive access to shared resources using booleanSemaphore flag sem_f
Each process does test before set action
What if process is preempted between test and set? => multiple process may
enter critical region (race condition)
Testing again and again before setting sem_f =0would not help much
R A C t l
-
7/30/2019 ppt1_rtos (1)
33/35
Resource Access Control
P (wait) & V (sig nal) Semaphore: Before entering CS, process executes P or wait function to acquire lock
After executing CS, process executes V or signal function to release lock
Changing and testing ofsem_1must be atomic in P and V functions
-
7/30/2019 ppt1_rtos (1)
34/35
Resource Access Control
Taking Turn :
Turn variable keeps track of which process can enter in critical region Strict alteration in execution
Not good if frequency one process is much faster than other. Process has to
wait long (busy waiting problem or starvation)
What will be algorithm forn processes in general?
-
7/30/2019 ppt1_rtos (1)
35/35
Resource Access Control
Petersons Algorithm:
Uses two variables: (1)flag => who is interested (2)turn => whose turn it is
Process enters to CS only if other processes are not interested and if it is itsturn
Avoids busy waiting even if rate of execution differs among processes. Forexample, long delay in non-critical section P1 will not hinder the progress ofP0