You are on page 1of 35

Embedded System

Embedded Systems:
Electronics system that contains processor (uP/uC/DSP/ASIP etc.) and peripherals which is configured to perform specific dedicated application

G P Computer System:
contains general purpose (GP) microprocessor, primary & secondary memories, keyboards, printer, scanner, monitor etc.

Software embeds in ROM and not accessible to the user

Mostly designed for time constrained applications (real time systems)

Programmed for GP applications that includes word processing, accounting, scientific computing, email, multimedia, database system etc.

either independent system or a part of larger system.

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

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 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

(2) Memories :

(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.

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

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 overall performance is slightly degraded, job execution has value even if completed late Often described quantitatively in terms of usefulness function as a function of the 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

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

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 and synchronization (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

RTOS

Context of process and context switching a process can create one or more other processes (referred to as child processes) and these processes in turn can create child processes to form process tree. When process is created, RTOS allocates memory space and instantiates data 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 parent and 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 address space of same process. Have their own PC, stack and registers which are private and never shared Advantages:- reduces context switching overhead, multiple control points in a process, improves responsiveness

RTOS

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 of f1. 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

Reentrant Functions:

A reentrant function 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

Consider strtoupper function where global variable buffer used by multiple processes.

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).

RTOS

According to OS kernel features, following explains 3 alternatives found in 3 RTOSs for responding and synchronizing the ISR call (1) Interrupt source calls ISR directly and ISR does complete servicing. It merely send a message to RTOS (2) RTOS Kernel intercepts the interrupt call and initiate corresponding ISR after saving context. ISR send message(s) to RTOS for initiating processes. Now kernel schedules and runs processes according to messages sent by ISR. RTOS only schedules process and ISR runs during suspension of processes. (3) RTOS treats ISR as a process. After interrupt call, RTOS calls ISR process after saving context. The ISR merely sends IPC containing parameters needed by RTOS. Then RTOS initiates and executes the processes 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

Function:- (i) routine for performing actions as per parameter passed to it and may be called from process, ISR or another function (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

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 slack means missed deadline)

[A] Non Preemptive Task(Process) scheduling:


(1)Round Robin (Circular Queue):

Processes are executed sequentially from ready linked list RTOS keeps track of currently executing process. It updates linked list upon insertion and removal of a process. New process is inserted at the end of linked 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

(2) Round Robin with Priority based Ready List

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

(3) Round Robin Scheduling with Time Slicing:


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 Tslot it is blocked (suspended) until it get its turn in the next time slice

Tslice is fixed whereas Tslot is variable If process finishes before Tslot there is waiting period Disadv. Of Non-Preemptive: Long execution of low priority tasks make high priority task to wait long Difficult to meet deadlines

Scheduling Algorithms
[B] Preemptive Scheduling:

Process may be blocked at any instant to allow higher priority task to run. This is called preemption. In preemptive scheduling, Priorities are assigned to processes using various 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: Scheduler should not block any process running in critical region

Example :- A scheduler is invoked every 1 unit of time and selects process from ready queue to run. (a) How processes are scheduled with Least Slack Time first policy ? (b) How the processes are scheduled with Shortest Run time first policy? (c) Find total time spent in wait by all process, total no. of context switches and no. of deadline missed for each scheduling. In case of tie, following criteria would be used in that order (i) process already running should be preferred over others (ii) process with earlier deadline should be 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 by P0=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 waiting process >to ensure proper scheduling using Round Robin, circular selection of processes from ready queue is required

Periodic Process (Task) model

Periodic Processes (Tasks) are executed repetitively with period pi and execution time ei where i is 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 ik being the kth thread in process Pi LCM of all pi for i=1,2,3, . . . . . n is called hyper period H The ratio ui=ei/pi the 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 ri must complete Di units of time after ri; where Di is relative deadline. If is not Di specified, period of the process would be considered as deadline.

Periodic Scheduling
Periodic Scheduling of Process (Taslk):

In general, Periodic threads of process i can be represented as 4-tuple (ri,pi,ei,Di) where ri phase of 1ST thread, pi period, ei execution time and Di relative deadline. For example P1= (1,12,4,6) is periodic task whose 1st job is released at time 1 and must complete at time 7. The second job is ready at time 13 and must be 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) 3 and execution time 2. Some algorithms for periodic scheduling are: Dynamic priority => EDF, Least Slack Time First, Shortest Remaining Runtime First Fixed Priority => Rate Monotonic (RM), Deadline Monotonic (DM)

Periodic Scheduling

i1 , i2 . . . are threads of process Pi For P1, relative deadline is 6 for each threads. Therefore absolute deadline for 11, 12, 13 . . are 7, 17, 27, . . .

Rate Monotonic (RM) Scheduling


Very popular fixed priority scheduling policy for most medium scale RTOS Assigns priority base on frequency of periodic task i.e. smaller the period higher 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/n 1), 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 periods p1<p2<p3 <pn then priority of tasks P1>P2>P3 > . >Pn The task Pi meets its first deadline only if ei + [k=1 to i-1 (pi/pk) x ek ] pi

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 to handles 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 also created that contain info such as message queue ID, permission, messages currently in queue, size of each message, process ID of last message written/ 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

IPC

Receive (buf) => read msg. from top of the queue and store in buf Send (id1, m1) => write message m1 in queue intended for recipient process id1 Query () => retrieves info such as msg. queue size, queue empty or not Delete() => deletes msg. queue

IPC
PIPES:

An IPC between two given interconnected processes using unidirectional anonymous 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 the pipe server. A process that connects to a pipe is a pipe client. One process writes information to the pipe, then the other process reads the information from the pipe

Resource Access Control

Global variables are often shared between ISR process and main process. As shown sharing of variable Temp causes 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)

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 boolean Semaphore 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 =0 would not help much

Resource Access Control


P (wait) & V (signal) 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 of sem_1 must be atomic in P and V functions

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 for n processes in general?

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 its turn Avoids busy waiting even if rate of execution differs among processes. For example, long delay in non-critical section P1 will not hinder the progress of P0

You might also like