Você está na página 1de 12

Machine Design Machine Design

Agenda

 (ES1) software development so far


Introduction to Advanced Embedded  The limitations of your current examples.
Systems (The Course)  Challenges: concurrency, real-time & resource
sharing.
 Advanced ES software
 Embedded & Mechatronics Systems
 Concurrency & multitasking
 Real-Time Systems
 Partial solution: Operating systems
 Final solution: Real-time operating
systems
 Resource sharing (optional)
 Conclusion
Mechatronics Lab 1 Mechatronics Lab 2

Machine Design Machine Design

Your (ES1) programs so far …


(ES1) software development so far You were asked to do examples such as:

 The EVK1100 is equipped with three push


buttons and 6 LEDs. Turn on one LED when a
push button is pressed

 Read the value of the photoresistor and turns


on all LEDs when there is low light shining on
the photoresistor (covered by the hand), and
turns off all LEDs when it’s lighter.

 Configure a PWM channel, for a given


frequency and duty cycle. Every 5 seconds,
read the PWM value and print it out to the
display.

Mechatronics Lab 3 Mechatronics Lab 4

Machine Design Machine Design

Your (ES1) programs so far … But what if …?

 You can potentially handle more  You are to execute these activities within
advanced functionality. the one program?
 How can you do all these things concurrently
(at the same time)?
 Yet, the program internal structure is
 How can you change the same LEDs based on
simply a single sequence of actions: both (1) the push buttons, (2) as well as the
While (1) { photoresistor?
1. Sample  How can you print different information on the
2. Compute
same display?
3. Actuate
4. State update
} Requirement1: Concurrency / Multitasking
Requirement2: Resource sharing

Mechatronics Lab 5 Mechatronics Lab 6

1
Machine Design Machine Design

How you might have dealt with


Even more, what if …?
concurrency?
 You need to ensure timing guarantees
 Of a certain task, irrespective of the other  Solution1  Solution2
tasks being executed.
 You need to ensure that the LEDs should lit no While(1) { While(1) {
later than 5 ms after the button is pressed. 1. Sample1 1. Sample1
2. Compute1 2. Sample2
3. Output1 3. Compute1
4. Sample2 4. Compute2
5. Compute2 5. Output1
6. Output2 6. Output2
} }
Requirement3: Real-Time
Is this a scalable solution?
How well can you manage this software?
Mechatronics Lab 7 Mechatronics Lab 8

Machine Design Machine Design

How you might have dealt with How you might have dealt with real-
concurrency? time requirements?

 Other solutions  You can try to make the execution time


 Use interrupts (event & time triggers) from sample to actuate as short as
 Deploy on a distributed computer system (with possible?
or without communication network) While (1) {
 Deploy on a multicore processor 1. Sample
2. Compute
3. Actuate
4. State update
}

Is it enough to make the


execution as short as possible?

Mechatronics Lab 9 Mechatronics Lab 10

Machine Design Machine Design

But cannot solve all problems ... The answer is … ES2


 Timing requirements.  A sneak-preview in this lecture
 How can you guarantee that you can execute your task
within X time units?
 Concurrency.
 How can you fairly & predictably share the timing
between multiple tasks.
Partial Answer
 Timing requirements with Concurrency. Operating systems
 How can you guarantee that you can execute your
task within X time units, given that other independent Complete Answer
tasks need also to run?! Real-time Operating Systems
 Resource sharing.
 How can you make sure 2 tasks can light the same
LED predictably?
 How can you make sure 2 tasks can print out
information on the display in a controlled way.

• Need to solve them systematically


• Why re-invent the wheel?
Mechatronics Lab 11 Mechatronics Lab 12

2
Machine Design Machine Design

But first, an introduction to …


Advanced ES software:
 Advanced ES software Embedded & Mechatronics Systems
 Embedded & Mechatronics Systems
 Concurrency & multitasking
 Real-Time Systems

Mechatronics Lab 13 Mechatronics Lab 14

Machine Design Machine Design

A mechatronic module: Scania


Embedded & Mechatronics Systems
diesel engine and controller
Domestic
robot
Pet
Car
Component

ECU connectors
Medical on top of the ECU

Tough Environment
Tight integration
Robot Real-time
Dependability
Cowbot

Combustion Engine ECU tasks: control of engine, fan, alternator, engine brake,
engine turbo, and the EGR valve + CAN communication, + diagnostics, …
Mechatronics Lab 15 Mechatronics Lab 16

Machine Design Machine Design

Embedded & Mechatronics Systems Typical activities in embedded systems

 An Embedded system typically requires a number of


activities to be carried out!

 Activity examples:
 Human-machine interface
 Controllers
Communication

Actuators  Time-triggered activities (such as control loops, etc.)


 Event-triggered activities (communication, interrupts, etc.)
Computer Mecha-  Diagnostics and supervision
Control  Communication (for example via CAN)
software nics
Sensors  Common characteristics of these activities
 A mixture of timing requirements (Time- & event- triggered
activities)
 Different modes of operation
 Diagnostics
 Configurability (on-line parameter change, software upgrade)
 Connectivity (for example diagnostics via GSM)

Leading to the need to support concurrent and


real-time programming
Mechatronics Lab 17 Mechatronics Lab 18

3
Machine Design Machine Design

A real-life example and analogy of


Advanced ES software: concurrency (& scheduling)
Concurrency & multitasking

• Task control block: Task state, priority and variables


• Context switching
• Scheduling

Mechatronics Lab 19 Mechatronics Lab 20

Machine Design Machine Design

A real-life example and analogy of


Push-button exercise
concurrency (& scheduling)
You are at home and deeply involved in  Requirements:
1. Once a push-button is pressed, the corresponding led should be lit
preparing for the MF2042 exam! for 1s.
Suddenly the following things happen: 2. The corresponding unit should have a maximum load less than
50% over a full cycle
- The telephone is ringing. 3. Led status should be sent over the green bus to the LDI and
- Someone is knocking on the door. displayed in a meaningful way

- The alarm is ringing from the kitchen.


Design!
- You still have not fixed your troubling computer. • Event- or clock triggers
• One or more interrupts
Many activities … and only one Processor. • Background loop
 Scheduling! • Communication and
variables
Scheduling algorithm: FPS, EDF, FIFO, SJF, …
Managing task states, context switching, etc.

Mechatronics Lab 21 Mechatronics Lab 22

Machine Design Machine Design

Multiple activities and their


Concurrent Programming
realization as ”tasks”
 Definition, true and pseudo parallelism
Mapping activities into tasks
 Map all into one sequential task 1. Multiprogramming: on a single processor
2. Multiprocessing: on multiple processors with
 Map each into a separate task shared resources
 Or something in-between 3. Distributed processing: independent memories

Logical Concurrency Uniprocessor Concurrency

Context
Switch

Mechatronics Lab 23 Mechatronics Lab 24

4
Machine Design Machine Design

Definition of real-time
Advanced ES software:
Real-Time Systems Common definitions:
 A computer system is a real-time one if it
explicitly manages resources in order to meet
timing constraints
(Douglas Jensen, 1992)

 A real-time system is a system where the


correctness depends not only on the logical
result of computation but also on the time at
which the results are produced.
(Jack Stankovic, 1988).

 A system that is synchronous with the


interacting environment
Mechatronics Lab 25 Mechatronics Lab 26

Machine Design Machine Design

Real-time systems Hard vs. Soft real-time systems


Timing of actions is essential  Hard real-time
- Compare with juggling, air bag, engine control and
music  Timing and mission critical
 High reliability (predictability and determinism)
Age of data is essential
- Compare with juggling or a weather report: sample  Soft real-time
data, compute, actuate - when does the data cease to  Timing matters, but consequences are not
be valid?
critical.
 Notes:  Larger variations are allowed
- Different consequences depending on context!
- Different types of timing requirements
- Delays need to be controlled!
Can you think of examples of:
 Requirements on a real-time (computer) system
• Hard real-time systems?
(1) Sufficiently fast (processing, communication, ...) • Soft real-time systems?
(2) Predictable resource sharing and timing!

Mechatronics Lab 27 Mechatronics Lab 28

Machine Design Machine Design

Examples of real-time
Real-Time Computing Basics
activities/tasks
 Hard real-time activities/tasks:  Time: the correctness of the system
– Sensory data acquisition depends on both time and logic
– Detection of critical conditions
– Control output to actuator  Real: the internal time scale must
– Control of safety critical systems match the external time scale
 Real-time: ( real fast) predictable in
 Soft real-time activities/tasks: deterministic or probabilistic timing
– HMI requirements, i.e., the deadline
– Handling input data from the keyboard
– Displaying messages on the screen – Hard: missing deadline may cause
– GUI catastrophic or critical consequence
– Logging – Soft: meeting deadline is desirable, but not
critical

Mechatronics Lab 29 Mechatronics Lab 30

5
Machine Design Machine Design

Execution time – an important


parameter!
Factors affecting the execution time of a piece of
Partial solution: Operating systems
code:

 The number of and types of instructions in a


program.
 E.g. floating vs. fixed point computations.
 Data dependent selections and iterations in a
program.
 Varying execution time
 The compiler and linker libraries (other code)
used
 The hardware speed (CPU itself and memory
access)
 Pipelines & caches increase average throughput but
may cause a varying execution time - beware!
Thus in general: Cmin <= C <= Cmax
Mechatronics Lab 31 Mechatronics Lab 32

Machine Design Machine Design

What is an Operating System (OS)? Concurrent Programming using OS

 Definition  Scheduling of multi-tasks, and


 An operating system (OS) is software,  Management of memory, I/O, files, etc.
consisting of programs and data, that
runs on computers and manages the Application
computer hardware and provides
common services for efficient
programs
execution of various application
software. (Wikipedia, 2010) OS provides OS
services
 Example OS:
 Windows (XP, Vista, …)
 Linux Hardware is
 Unix Source:
http://en.wikipedia.org/wiki/Operating_system transparent
 Mac OS X
Mechatronics Lab 33 Mechatronics Lab 34

Machine Design Machine Design

Implementation without OS Scheduling on one CPU


 Pre-emption owing to scheduling method
 Background/foreground programming  Blocked by shared resource or to wait for a time period
 Foreground: creation
– Interrupt programming provided by the dispatch
microcontroller
– Fixed priority provided by hardware Ready Running
 Background: main function, while loop pre-empt
 Advantages: simple, efficient, small size
termination
 Drawbacks:
– Low level programming (interrupts, ports, Blocked/
Waiting
timers) Queue of ready
– Difficult to debug and re-allocate threads sorted by waiting queues
scheduling policy sorted by
– Complex scheduling policy

Mechatronics Lab 35 Mechatronics Lab 36

6
Machine Design Machine Design

Context Switch Effects of Schedules


creation ready running running
 Task A: starts 0, deadline 3, exec. time 2
ready
 Task B: starts 0, deadline 2, exec. time 1
A
Thread A OK
B
preemption
A
Thread B OK
termination B
dispatch running
A
Blocked
Bad
by var. B X
Mechatronics Lab 37 Mechatronics Lab 38

Machine Design Machine Design

Processes vs. Threads A Process Has


 A process is an executable instance of a  Code
program stored and operating in its own Stack
protected memory space. (Unit of allocation)  Data SP
 A thread is a stream of execution that may  Stack
share memory space with others. (Unit of
execution)  Execution context Heap
 Different methods of communication – Program counter (PC)
– Stack pointer (SP)
– Data registers Static Data

Code
PC
Global variable
OS
Mechatronics Lab 39 Mechatronics Lab 40

Machine Design Machine Design

A Thread Has
Final solution: Real-time operating
 Execution context SP(T2)
systems
Stack (T2)
– Program counter
(PC) Stack (T1)
SP(T1)
– Stack pointer (SP)
– Data registers Heap
 1 process has at least
1 thread
Static Data
 1 thread must belong PC(T2)
to 1 process Code (T2)
Code (T1)
PC(T1)

Mechatronics Lab 41 Mechatronics Lab 42

7
Machine Design Machine Design

Insufficiency of General Purpose


Real-Time OS
Computer Systems
 GP computers optimized for high-  Improvement on the limitations of GP
throughput on the average, but not computers
predictable  No DMA on the microcontroller or better
 Direct memory access (DMA) steals CPU control method
time  No cache on the microcontroller or
 Nondeterministic access time of cache consider cache effects on WCET
 Interrupts of I/O devices  Direct access to I/O devices
 Unknown blocking of shared resources  Time bounded access of shared
 Memory paging causes significant delay resources
 Uncontrollable queues in the kernel  Static memory allocation
(FIFO)  Flexible scheduling policies
Mechatronics Lab 43 Mechatronics Lab 44

Machine Design Machine Design

Real-Time Kernel Categories of RT Tasks


• A task is a thread or process
 Also called Microkernel • A job is an execution instance of a task
 Core part of an RTOS • Periodic, aperiodic, and sporadic (with minimal
 Supports concurrent threads and interval time)
scheduling
 Task communication and protection of
shared resources periodic
 Error detection and handling
job
I/O Memory Kernel aperiodic

Mechatronics Lab 45 Mechatronics Lab 46

Machine Design Machine Design

An Illustrating Example Real-Time Scheduling


Cruise Control App.
 Definition:
 assigning (temporal & spatial) processors
and resources (memory, I/O devices) to
tasks to complete all tasks under constraints
Cruise Cntr Sensor of Actuator of  Feasible schedule completes all tasks
Velocity Gas under constraints
 Schedulable task set has at least 1
ref_speed
Threads Processes of feasible schedule
1 Thread
Speed Process of
Control 2 Threads

Mechatronics Lab 47 Mechatronics Lab 48

8
Machine Design Machine Design

Scheduling Algorithm: Cyclic


Classification of Scheduling Algorithms
Executive
 Preemptive: running tasks can be  Old fashion
interrupted  Off line, static construction of an execution
 Non-preemptive: (More difficult) table
 Static: based on fixed parameters  With or without OS support
 Dynamic: based on dynamic parameters  Manual or optimization-based
 Off line: the execution of all tasks are  Example: A (exe=0.5, per.=2), B (2, 6)
determined before activation (as a table)  Analysis within a hyperperiod (LCM)
 On line: decisions are made at runtime
when the task set varies
 Optimal: minimize a “cost”, or no one is A
better than it
B 1 2 hyperperiod
 Heuristic: no guarantee of the optimality
0 2 4 6
Mechatronics Lab 49 Mechatronics Lab 50

Machine Design Machine Design

Scheduling Algorithm: Fixed-Priority


Pros and cons of Cyclic Executive
Scheduling
+ Very efficient implementation using  On line, preemptive, static
periodic timer interrupts and a dispatch  A task has a fixed priority
table  The scheduler dispatches the highest
+ Simple and relatively deterministic priority job (and may preempt a low
priority job)
- Manual partition of long tasks
 Predominant in RTOS
- Changes (e.g., new tasks, different
 Priorities are represented by integer
execution time) can cause complete values
reschedule
- Difficult to find a feasible schedule
highest Priority decreases
- Assumes a closed environment
- Periodic tasks only 1 2
Value increases
n
Mechatronics Lab 51 Mechatronics Lab 52

Machine Design Machine Design

Scheduling Algorithm: Rate Scheduling Algorithm: Dynamic-


Monotonic (RM) Scheduling Priority Scheduling
 Priority is proportional to rate  On line, preemptive, dynamic
 Optimal fixed-priority policy, for periodic
tasks that  Priorities are assigned to individual jobs
– are released at the beginning of a period and dynamically
must complete within the period
– are independent  The scheduler dispatches the highest
– have fixed computation time (or upperbound, priority job
WCET), less than the period
 Example A (0.5, 1), B (1, 2)  Slightly higher computation overhead
 Not available in most commercial RTOS

A A X
B B
0 2 0 2
Mechatronics Lab 53 Mechatronics Lab 54

9
Machine Design Machine Design

Scheduling Algorithm: Earliest


Deadline First (EDF)
Resource Sharing (optional)
 Priorities are assigned inversely
proportional to the absolute deadlines of
the active jobs
 Under the same assumption for RM, n
periodic tasks are schedulable if and only
if
U=C1/T1 + … Cn/Tn ≤ 1
 Optimal among ALL preemptive scheduling
algorithms

B
0 2
Mechatronics Lab 55 Mechatronics Lab 56

Machine Design Machine Design

Unprotected Resource Sharing Unprotected Resource Sharing


 A resource is any soft-/hard-ware entity
used by a thread to advance its execution  Critical section is not atomic
 Concurrent tasks are pre-emptive
What is the final value of n?  Unpredictable value (corrupted data)
Thread A Thread B
Thread A Thread B
… … R1 a1 b1 R2
n:=n+1 n:=n-1 a2 b2
n=5
… … n=5
R1+1 a3 b3 R2-1

Critical region (section): a sequence of statements accessing


b1, b2, b3
the shared resource n=6
a1, a2 a3
Mechatronics Lab 57 Mechatronics Lab 58

Machine Design Machine Design

Importance of Mutual Exclusion How to Ensure Mutual Exclusion

 The resource is shared by at least two  Disallow pre-emption (by disabling


preemptive threads interrupts or limiting preemption level)
 Critical region may be shared global  Serialize resource access by separating
variable, non-reentrant code, devices the threads that access the same
 The operations of the critical region is mutually exclusive resource (via offline
not atomic (must allow interleaving) scheduling)
 Unpredictable, difficult to debug  Utilize OS supported “protection
 Need mutual exclusion to protect a techniques”: semaphores, message
shared resource from concurrent access queues, etc.
 The protected resource is mutually
exclusive resource
Mechatronics Lab 59 Mechatronics Lab 60

10
Machine Design Machine Design

An Old Fashioned Approach A Naïve Approach


 Use a Boolean free
 Disallow ALL pre-emption  A new shared resource created!
 Negative effect to other important interrupts  Both threads may find (free==1)

Thread A Thread B Thread A Thread B


… … … free …
disable disable while (!free); while (!free);
interrupts; interrupts;
free=0; free=0;
n:=n+1; n:=n-1;
n n:=n+1 n n:=n-1;
enable interrupts; enable interrupts;
free=1; free=1;
… …
… …
Mechatronics Lab 61 Mechatronics Lab 62

Machine Design Machine Design

How to Improve It? Semaphore

 Checking and locking should be atomic  Semaphores: (Sec. 4.2)


 Replace the inefficient polling with “blocking”  Invented by Dijkstra in 1965
and “awakening” mechanism  Common in OS
 Many variants. We are using binary semaphores
only in this course and Rubus OS
Thread A Thread B
 Adopt the improvements
… free …  Typical system calls:
 Lock(S) or Wait(S): lock the resource. If it is
Atomic while (!free); while (!free); already locked, then wait (or is blocked)
free=0; free=0;  Unlock(S) or Signal(S): Unlock the resource, and
wake up all waiting (or blocked) threads
n:=n+1 n n:=n-1; Atomic
free=1; free=1;
… …
Mechatronics Lab 63 Mechatronics Lab 64

Machine Design Machine Design

Binary Semaphore Example of Using Semaphore


Semaphore status is managed by OS
 Two values: Free (1), Locked (0)
Thread A Thread B
 Must have an initial value
 Thread A calls Lock(s): …
s …
– If s is free (1), then s is locked (0) and A Lock(s); Lock(s);
continues n
n:=n+1 n:=n-1;
– If s is already locked (0), then s remains
locked and A is blocked Unlock(s); Unlock(s);
 Thread A calls Unlock(s): … …
– If s is free (1), then s remains free and A
continues Lock(s), B is blocked Unlock(s)
– If s is blocked (0), then s is free (1), A B
continues, and all threads blocked by s
becomes ready A
Lock(s) Unlock(s)
Mechatronics Lab 65 Mechatronics Lab 66

11
Machine Design Machine Design

Changing Thread States with Deadlock Caused by Shared


Semaphores Resources
creation
 Multiple threads “lock” each other and no
dispatching one can proceed
Ready Running  Deadlock occurs when each one (thread)
holds one resource (semaphore) and waits
pre-emption for the other one
 Priority inheritance cannot avoid it
 Starvation: a thread never gets CPU time
termination to execute, because of overload and
scheduling
Blocked/

A different thread
Waiting
Lock(s) when s is
called Unlock(s) already locked by
another thread
Mechatronics Lab 67 Mechatronics Lab 68

Machine Design Machine Design

Terms to keep in mind


Conclusion
 You have been introduced to
 Concurrency & concurrent programming
 Real-Time systems & real-time programming
 General Operating systems
 Real-time operating systems
 Real-Time Scheduling
 Resource sharing

Mechatronics Lab 69 Mechatronics Lab 70

12

Você também pode gostar