Você está na página 1de 45

Maths is not everything

Embedded Systems
6 - Operating Systems

Scheduling Real-Time requirements Inter-Process Communication


RMR2012

Operating systems - Anatomy

The operating system controls resources:


who gets the CPU; when I/O takes place; how much memory is allocated.
Scheduling filesystem I/O Mem. Mgt. Kernel hardware

Maths is not everything

RMR2012

Operating systems - Kernel

The most important resource is the CPU itself.


CPU access controlled by the scheduler Schedule policy executed by the dispatcher (processor queue) Events handled by interrupt Basic communication among tasks
dis pa

synch & comm

tc

he

Maths is not everything

RMR2012

t up rr g te in in andl h

Process state

A process can be in one of three gets states: CPU


executing on the CPU; ready to run; waiting for data.
Maths is not everything

executing
preempted

gets data and CPU needs data

gets data

ready
needs data

waiting

RMR2012

2008 Wayne Wolf

Operating system structure

OS needs to keep track of:


process priorities; scheduling state; process activation record.

Processes may be created:


2008 Wayne Wolf

statically before system starts; dynamically during execution.

Maths is not everything

RMR2012

Maths is not everything

Operating Systems Scheduling

RMR2012

Embedded vs. general-purpose scheduling

Workstations try to avoid starving processes of CPU access.


Fairness = access to CPU.

Embedded systems must meet deadlines.


Low-priority processes may not run for a long time.
User Programs User Program Operating Including Operating

Hardware

Hardware

Maths is not everything

2008 Wayne Wolf

System

System Components

RMR2012

Typical OS Conguration

Typical Embedded Conguration

Priority-driven scheduling

Each process has a priority. CPU goes to highest-priority process that is ready. Priorities determine scheduling policy:
xed priority;
Maths is not everything

RMR2012

2008 Wayne Wolf

time-varying priorities.

Priority-driven scheduling example

Rules:
each process has a xed priority (1 highest); highest-priority ready process gets CPU; process continues until done.
P2 ready t=0 P3 ready t=18 P1 ready t=15

P2
0
Maths is not everything

P1
10 20

P2
30 40

P3
50

time 60

2008 Wayne Wolf

P1: priority 1, execution time 10 P2: priority 2, execution time 30 P3: priority 3, execution time 20

RMR2012

The scheduling problem

Can we meet all deadlines?


Must be able to meet deadlines in all cases.

How much CPU horsepower do we need to meet our deadlines?


2008 Wayne Wolf

Maths is not everything

RMR2012

Process initiation disciplines

Periodic process: executes on (almost) every period. Aperiodic process: executes on demand. Analyzing aperiodic process sets is harder---must consider worst-case combinations of process activations.

Maths is not everything

RMR2012

2008 Wayne Wolf

Timing requirements on processes

Period: interval between process activations. Initiation interval: reciprocal of period. Initiation time: time at which process becomes ready.
Maths is not everything

RMR2012

2008 Wayne Wolf

Deadline: time at which process must finish.

Maths is not everything

Operating Systems Real-Time

RMR2012

What is a real-time system?

A real-time system is any information processing system which has to respond to externally generated input stimuli within a finite and specified period
the correctness depends not only on the logical result but also the time it was delivered failure to respond is as bad as the wrong response!
Maths is not everything

RMR2012

14

Example: a simple uid control system


Interface Pipe

Input flow reading

Flow meter

Processing

Maths is not everything

Output valve angle Time Computer

Valve

RMR2012

15

Timing violations

What happens if a process doesnt finish by its deadline?


Hard deadline: system fails if missed. Soft deadline: user may notice, but system doesnt necessarily fail.
2008 Wayne Wolf

Maths is not everything

RMR2012

A Typical Embedded System


Real-Time Clock Algorithms for Digital Control Engineering System

Interface

Data Logging

Remote Monitoring System

Database Data Retrieval and Display Display Devices

Maths is not everything

Operators Console

Operator Interface

Real-Time Computer

RMR2012

17

Characteristics of a RTS

Large and complex


vary from a few hundred lines of assembler or C to 20 million lines of Ada estimated for the Space Station Freedom

Concurrent control of separate system components


devices operate in parallel in the real-world; better to model this parallelism by concurrent entities in the program
Maths is not everything

Facilities to interact with special purpose hardware


need to be able to program devices in a reliable and abstract way

RMR2012

18

Characteristics of a RTS

Extreme reliability and safe


embedded systems typically control the environment in which they operate; failure to control can result in loss of life, damage to environment or economic loss

Guaranteed response times


Maths is not everything

we need to be able to predict with condence the worst case response times for systems; efciency is important but predictability is essential

RMR2012

19

Maths is not everything

Operating Systems Inter-Process Communication & Synchronization

RMR2012

Synchronisation and Communication The correct behaviour of a concurrent program depends on synchronisation and communication between its processes Synchronisation: the satisfaction of constraints on the
interleaving of the actions of processes (e.g. an action by one process only occurring after an action by another)

Communication: the passing of information from one


process to another
Concepts are linked since communication requires synchronisation, and synchronisation can be considered as contentless communication.
Maths is not everything

Data communication is usually based upon either shared variables or message passing.

RMR2012

21

Interprocess communication

Interprocess communication (IPC): OS provides mechanisms so that processes can pass data. Two types of semantics:
blocking: sending process waits for response;
Maths is not everything

RMR2012

2008 Wayne Wolf

non-blocking: sending process continues.

IPC styles

Shared memory:
processes have some memory in common; must cooperate to avoid destroying/missing messages.

Message passing:
processes send messages along a communication channel---no common address space.
Maths is not everything

RMR2012

2008 Wayne Wolf

Shared memory

Shared memory on a bus: memory

CPU 1

CPU 2

Maths is not everything

RMR2012

2008 Wayne Wolf

Race condition in shared memory

Problem when two CPUs try to write the same location:


CPU 1 reads ag and sees 0. CPU 2 reads ag and sees 0. CPU 1 sets ag to one and writes location. CPU 2 sets ag to one and overwrites location.
Maths is not everything

RMR2012

2008 Wayne Wolf

Atomic test-and-set

Problem can be solved with an atomic test-and-set:


single bus operation reads memory location, tests it, writes it.

ARM test-and-set provided by SWP:


ADR r0,SEMAPHORE
2008 Wayne Wolf
Maths is not everything

LDR r1,#1 GETFLAG SWP r1,r1,[r0] BNZ GETFLAG

RMR2012

Critical regions

Critical region: section of code that cannot be interrupted by another process. Examples:
writing shared memory; accessing I/O device.
Maths is not everything

RMR2012

2008 Wayne Wolf

Semaphores

Semaphore: OS primitive for controlling access to critical regions. Protocol:


Get access to semaphore with P(). Perform critical region operations.
Maths is not everything

RMR2012

2008 Wayne Wolf

Release semaphore with V().

Semaphores
A semaphore is a non-negative integer variable that apart from initialization can only be acted upon by two procedures P (or WAIT) and V (or SIGNAL) WAIT(S) If the value of S > 0 then decrement its value by one; otherwise delay the process until S > 0 (and then decrement its value). SIGNAL(S) Increment the value of S by one. WAIT and SIGNAL are atomic (indivisible).
Maths is not everything

Two processes both executing WAIT operations on the same semaphore cannot interfere with each other and cannot fail during the execution of a semaphore operation

RMR2012

29

Condition synchronisation

var consyn : semaphore (* init 0 *)

process P1; (* waiting process *) statement X; wait (consyn) statement Y; end P1;

process P2; (* signalling proc *) statement A; signal (consyn) statement B; end P2;

Maths is not everything

In what order will the statements execute?

RMR2012

30

Mutual Exclusion
(* mutual exclusion *) var mutex : semaphore; (* initially 1 *)

process P1; statement X wait (mutex); statement Y signal (mutex); statement Z end P1;

process P2; statement A; wait (mutex); statement B; signal (mutex); statement C; end P2;

Maths is not everything

In what order will the statements execute?

RMR2012

31

Deadlock

Two processes are deadlocked if each is holding a resource while waiting for a resource held by the other
type Sem is ...; X : Sem := 1; Y : Sem := 1; task A; task body A is begin ... Wait(X); Wait(Y); ... end A; task B; task body B is begin ... Wait(Y); Wait(X); ... end B;

Maths is not everything

RMR2012

32

Livelock

Two processes are livelocked if each is executing but neither is able to make progress.
type Flag is (Up, Down); Flag1 : Flag := Up; task A; task body A is begin ... while Flag1 = Up loop null; end loop; ... end A; task B; task body B is begin ... while Flag1 = Up loop null; end loop; ... end A;

Maths is not everything

RMR2012

33

Binary and quantity semaphores

A general semaphore is a non-negative integer;


its value can rise to any supported positive number

A binary semaphore (MUTEX) only takes the value 0 and 1; the signalling of a semaphore which has
the value 1 has no effect - the semaphore retains the value 1

A general semaphore can be implemented by two binary semaphores and an integer. With a quantity semaphore the amount to be decremented by WAIT (and incremented by SIGNAL) is given as a parameter; e.g. WAIT (S, i)

Maths is not everything

RMR2012

34

Example on the use of semaphores: Bounded Buffer


procedure Append(I : Integer) is begin Wait(Space_Available); Wait(Mutex; Buf(Top) := I; Top := Top+1 Signal(Mutex; Signal(Item_Available); end Append; procedure Take(I : out Integer) is begin Wait(Item_Available); Wait(Mutex); I := BUF(base); Base := Base+1; Signal(Mutex); Signal(Space_Available); end Take;

Maths is not everything

RMR2012

35

Process data dependencies

One process may not be able to start until another finishes. Data dependencies defined in a task graph.

P1

P2

P3 P4

Maths is not everything

RMR2012

2008 Wayne Wolf

Message-Based Communication and Synchronisation


Use of a single construct for both synchronisation and communication Three issues: the model of synchronisation, the method of process naming, the message structure

Process P1

Process P2 receive message

send message
Maths is not everything

RMR2012

time

time

Process Synchronisation using messages

Variations in the process synchronisation model arise from the semantics of the send operation Asynchronous (or no-wait) (e.g. POSIX)
Requires buffer space. What happens when the buffer is full?

Process P1 send message message


Maths is not everything

Process P2

receive message

RMR2012

time

time

Process Synchronisation using messages

Synchronous (e.g. CSP, occam2)


No buffer space required Known as a rendezvous
Process P1 send message blocked M Process P2

receive message

Maths is not everything

RMR2012

time

time

Process Synchronisation using messages


Remote invocation (e.g. Ada) Known as an extended rendezvous
The posting of a letter is an asynchronous send A telephone is a better analogy for synchronous communication

Process P1 send message blocked


Maths is not everything

Process P2

receive message

reply time time

RMR2012

Robot Arm Example


typedef enum {xplane, yplane, zplane} dimension;

void move_arm(int D, int P); #define DEFAULT_NBYTES 4 int nbytes = DEFAULT_NBYTES; #define MQ_XPLANE "/mq_xplane" #define MQ_YPLANE "/mq_yplane" #define MQ_ZPLANE "/mq_zplane" #define MODE . . . /* mode info /* names of message queues */ -- message queue name -- message queue name -- message queue name for mq_open */

Maths is not everything

RMR2012

41

Robot Arm Example


void controller(dimension dim) { int position, setting; mqd_t my_queue; /* message queue */ struct mq_attr ma; /*attributes */ char buf[DEFAULT_NBYTES]; ssiz_t len; position = 0; switch(dim) { /* open appropriate message queue */ case xplane: my_queue = MQ_OPEN(MQ_XPLANE,O_RDONLY,MODE,&ma); break; case yplane: my_queue = MQ_OPEN(MQ_YPLANE,...); break; case zplane: my_queue = MQ_OPEN(MQ_ZPLANE,...); break; default: return; } while (1) { /* read message */ len = mq_receive(my_queue, &buf[0], nbytes, null); setting = *((int *)(&buf[0])); position = position + setting; move_arm(dim, position); } }

Maths is not everything

RMR2012

42

Robot Arm Example

Now the main program which creates the controller processes and passes the appropriate coordinates to them:
void (*C)(dimension dim) = &controller; int main(int argc, char **argv) { mqd_t mq_xplane, mq_yplane, mq_zplane; struct mq_attr ma; /* queue attributes */ int xpid, ypid, zpid; char buf[DEFAULT_NBYTES]; /* set message queues attributes*/ ma.mq_flags = 0; /* No special behaviour */ ma.mq_maxmsg = 1; ma.mq_msgsize = nbytes; mq_xplane = MQ_OPEN(MQ_XPLANE, O_CREAT|O_EXCL, MODE, &ma); mq_yplane = ...; mq_zplane = ...;

Maths is not everything

RMR2012

43

Robot Arm Example


/* Duplicate the process to get three controllers */ switch (xpid = FORK()) { case 0: controller(xplane); exit(0); /* child */ default: /* parent */ switch (ypid = FORK()) { case 0: controller(yplane); exit(0); default: /* parent */ switch (zpid = FORK()) { case 0: controller(zplane); exit(0); default: /* parent */ break; } } } while (1) { /* set up buffer to transmit each co-ordinate to the controllers, for example */ MQ_SEND(mq_xplane, &buf[0], nbytes, 0); }

Maths is not everything

RMR2012

44

Message passing

Message passing on a network:

CPU 1 message
2008 Wayne Wolf
Maths is not everything

CPU 2 message message

RMR2012