CSE 522 Realtime Embedded Systems Computer Science Engineering
CSE 522 Real-time Embedded Systems Computer Science & Engineering Department Arizona State University Tempe, AZ 85287 Dr. Yann-Hang Lee yhlee@asu. edu (480) 727 -7507
Real-time Embedded Systems q Embedded system v the software and hardware component that is an essential part of another system q Real-time system v provide well-timed A/D computation Reference input A/D v deadlines, jitters, Controller Control-raw computation D/A Plant actuator periodicity v temporal dependency sensor 2
Embedded Systems -- Examples 3
Emerging Embedded Systems 4
Hardware Platform q Organization v buses to connect components – PCI, ISA, PC 104+ memory q Package v standard chips on PC v processor + ASIC v SOC I/O CPU (microprocessor) I/O Timer I/O 5
SW Development for RT ES q To write the control software for a smart washer initialization v initialize v read keypad or control knob v read sensors v take an action q System current state v state transition diagram v external triggers via external trigger? ISR: to set/clear events Take actions polling or ISR q If there are multiple triggers and external conditions – single or multiple control loops Change system state 6
Periodic Tasks q Invoke computation periodically v Adjust pressure valves at a 20 Hz rate Task initialization (set up periodic timer interrupts) Task initialization start_time=time( ) wait for the interrupt event computation Sleep(period ( time( ) -start_time) ) 7
SW Development for RT ES q In the example of smart washer v Never-ending in a single control loop v Single execution threat and one address space v Event triggering and state transitions v Small memory footprint q What are missing: v no concurrency (real-world events occur in parallel) v no explicit timing control (let’s add a timer) v difficult to develop and maintain large embedded systems – verifiable, reusable, and maintainable 8
RT ES vs. General Software q Multi-tasking for concurrent events q Machine dependence and portability q Software abstraction, modular design v information hiding, OO, separate compilation, reusable v a sorting procedure -- function, input, output specification q Control timing v predictable actions in response to external stimuli v deadline (absolute or relative), and jitter q Resource constraints and sharing v CPU time, stack, memory, and bandwidth q Scheduling 9
Timing Constraints and Multi-threading q Given input x 1 at time t 1, produce output y 1 at time t 2 q Non-deterministic operation, Time-dependent behavior, and race condition v difficult to model, analyze, test, and re-produce. q Example: NASA Pathfinder spacecraft v Total system resets in Mars Pathfinder v An overrun of data collection task a priority inversion in mutex semaphore failure of communication task a system reset. v Took 18 hours to reproduce the failure in a lab replica the problem became obvious and a fix was installed 10
Trends of RT Embedded Systems Applications q Wide-spreading, distributed, connected, and heterogeneous q Mission and safety critical q High-end consumer products v cell phone, HDTV, home network, PDA, GPS, appliances q Quality of the products v portable/reusable, reliable/dependable, interoperable, predictable (schedulable), and secured q Software extensive q A new S-class Mercedes-Benz v over 20 million lines of code v nearly as many ECUs as the new Airbus A 380 (excluding the plane's in-flight entertainment system). 11
Embedded System Development q Need a real-time (embedded) operating system ? q Need a development and test environment ? v Use the host to edit, compile, and build application programs, and configure the target v At the target embedded system, use tools to load, execute, debug, and monitor (performance and timing) Development workstation Embedded systems (Workstation, embedded system development tools) Simulated signal source (workstation, interface cards), & test harness Ethernet 12
From Source to Executable q Compiler, linker, and loader q In ELF: executable, relocatable, shared library, and core v information for relocation, symbol, debugging v linker resolves symbol reference q Link script or link command file v assigns absolute memory addresses (program area, static data, bss, stack, vector table, etc. ) q Startup code to disable interrupts, initialize stack, data, zero uninitialized data area, and call main(). asm ld cc 13
Real-time Operating System q Use the computer hardware efficiently q To manage system resource through v system calls -- issued by tasks v interrupts -- timer and external events q Typical requirements v Support for scheduling of real-time tasks and interrupt handlers v Inter-process communication v I/O support -- driver v User control of system resource -- memory and file system q Thread or process for task execution: v smallest execution units that can be scheduled v lives in a virtual, insulated environment v uses or owns system resources 14
Real-time Operating System q Functions: v task management, Ø scheduling, dispatcher Ø communication (pipe, queue) Ø synchronization (semaphore, event) External interrupt Timer interrupt System calls (trap) memory management v time management v device driver v interrupt service v Interrupt dispatch Interrupt service Time service & events Scheduling & dispatcher Task execution Services (create thread, sleep, notify, send, …) kernel 15
RTOS Structures q Small, fast, proprietary kernels q Monolithic kernels that contains all services q Component-based kernels or micro-kernel v contain the minimal services v small (10 K bytes) and modular v configurable by selecting components to compose a kernel q RT extensions (to extend Unix or Windows) v Why -- richer environment, more functionality, familiar interfaces v Compliant kernel (Lynx. OS) -- Takes an existing RTOS and make it execute other UNIX binaries v Dual kernels– add an RTOS kernel between the hardware and the OS. (RTLinux) v OS kernel modifications – use patches to make Linux kernel more deterministic (Real-time Linux distributions) 16
RTOS vs. OS q Often used as a control device in a dedicated application q Well-defined fixed-time constraints v The system allows access to sensitive resources with defined response times. Ø interrupt latency and time for context switch v worst-case and average response times q Requirements of RTOS v predictable (? ? ) v upper bounds for system calls and memory usage v configuration of memory layout and kernel data structures v fine grain interrupt control 17
Task Management in vx. Works executing Execution pending Ready ready delayed Blocked q Task structure: v task control block -- task. Init() suspended Ø priority(initial and inherited), stack frame, task current state, Ø entry point, processor states (program counter, registers) Ø callback function (hook) pointers for OS events q Create and initialization v task. Init, task. Activate, task. Spawn v task_id = task. Spawn (name, priority, options, stacksize, main, arg 1, …, arg 10); q Task control and deletion: task. Delay (nanosleep), task. Suspend, task. Resume, task. Restart, exit, task. Delete 18
Scheduling Mechanism q Priority-driven and round-robin with timeslicing v task. Priority. Set (tid, priority), kernel. Time. Slice v task. Lock, task. Unlock -- disable and enable scheduling (preemption) v 0 (highest) to 255 (lowest) in vx. Works 19
Shared Code and Reentrancy q A single copy of code is invoked by different concurrent tasks must reentrant v pure code v variables in task stack (parameters) v guarded global and static variables (with semaphore or task. Lock) v variables in task content (task. Var. Add) task. One ( ) {. . . my. Func ( ); . . . } task. Two ( ) {. . . my. Func ( ); . . . } my. Func ( ) {. . } 20
Inter-task Communication q Shared memory v vx. Works has all tasks in a single address space Ø simple and unprotected Ø direct access as long as the address is known q Message queue -v multiple senders and receivers v msg. QCreate( ), msg. QDelete( ), msg. QReceive( ) Ø status = msg. QSend(msg. QId, buffer, n. Bytes, timeout, priority ) v queue size, message size, timeout parameters v msg_pri_normal -- to be added to the queue tail v msg_pri_urgent -- to be added to the queue head v ISR cannot read a message queue v mq_notify( ) in POSIX -- notification to a single task when a new message arrives at an empty queue 21
Inter-task Communication q Pipe -- virtual I/O, built on top of msg. Q v pipe. Dev. Create (name, n. Messages, n. Bytes) -- create a named pipe in the global file descriptor table v open, read, write, and ioctl routines for device control v select( ) -- wait for input from multiple pipes (with a timeout) q Network Inter-task communication v Socket and RPC of vx. Works -- compatible with BSD 4. 3 Unix q Signals (for asynchronous events) v between tasks and ISR -- to execute signal handler of a task v bind a handler to a signal, send a signal (kill(tid, signo)), signal masks v sigqueue( ) in POSIX v sig. Init( ), sigqueue. Init( ) 22
Signals q To register a handler -- signal (signo, sig. Handler) void sig. Handler ( int sig, int code, struct sigcontext * p. Sig. Ctx); q Exception: issues a signal to the running task v if no signal handler, suspend the task v hardware dependent v return with exit(), task. Restart(), longjump() signal normal program {. . } sig. Handler {. . } 23
Synchronization and Mutual Exclusion q Semaphores in vx. Works: v binary v mutual exclusion -- addresses inheritance, deletion safety and recursion v counting q Routines: sem. BCreate( ), sem. MCreate( ), …, sem. Delete( ) ü sem. Take( ), sem. Give( ), sem. Flush( ) (broadcasting) q Semaphore id, queue type (SEM_Q_PRIORITY or SEM_Q_FIFO), and timeout on waiting ü ü SEM_ID sem = sem. BCreate (SEM_Q_PRIORITY, SEM_FULL); sem. Take(sem, WAIT_FOREVER); . . . sem. Give(sem); q Synchronozation: v ISR calls sem. Give( ) to signal an event v task calls sem. Take( ) to wait for the event 24
Synchronization and Mutual Exclusion q Mutual Exclusive -- restriction: v can be given by the task took it (owns it) v cannot be given from an ISR v no flush q Priority inheritance: set flag = SEM_Q_PRIORITY | SEM_INVERSION_SAFE q Deletion Safety: delete a task while it is holding a semaphore v SEM_DELETE_SAFE: protect from deletion q Recursion: (task ownership count) v take a semaphore more than once by the task that owns it v released when it is given the same number of times q POSIX semaphore (counting) v unnamed -- malloc a semaphore struct and use * to operate v named --open a semaphore in OS, shared among processes 25
Interrupt Service Routines (1) q Interrupt service routines (ISRs) run outside of any task’s context. Thus they involves no task context switch. q int. Connect ( ) -- to install user-defined ISR_routine v If int. Connect() is used for Power. PC, it is not needed to explicitly disable the current interrupt source and do interrupt acknowledgement. handler wrapper Save registers set up stack check interrupt source (vector) invoke routine restore registers and stack exit user ISR_routine ( ) {. . . . } int. Connect(INUM_TOIVEC(some. Int. Num), ISR_routine, some. Val); 26
Interrupt Service Routines (2) q Interrupt stack -- a suitable size of maximum interrupt nesting depth q Whenever the architecture allows it, all ISRs use the same interrupt stack v The stack is allocated as system starts up v Must be large enough to handle the worst case q Limitations to ISRs v ISR should not be blocked Ø don’t take a semaphore (malloc() and free() takes a semaphore), giving semaphore however is permitted Ø don’t perform I/O via vx. Works drivers that can get blocked v ISRs cannot call printf() to output message to console, please use log. Msg() and other functions defined in log. Lib 27
Interrupt Service Routines (3) q Interrupt-to-task communications v Interrupt events usually propagate to task-level code. v The following techniques can be used to communicate from ISRs to task-level code Ø Shared memory and ring buffers. ISRs can share variables, Ø Ø buffers, and ring buffers with task level code Semaphores. Giving semaphores is permitted Message queues. ISR can send messages to message queues for tasks to receive Pipes. ISRs can write messages to pipes that tasks can read Signals. ISRs can signal tasks, causing asynchronous scheduling of their signal handlers 28
Timer and Clock q Clock tick q Watchdog timer in vx. Works -- mantained by the system clock ISR v wd. Create( ), wd. Delete( ), wd. Start( ), wd. Cancel( ) v Typically invokes a callback function when the delay is expired (at the interrupt level of the system clock) q real-time clock -q POSIX timer v create, set and delete a timer that signals tasks when goes off q Delay a period: v task. Delay( ) in vx. Work v nanosleep( ) in POSIX 29
Device Driver q Purpose: v a well defined and consistent interface to handle requests for device operations v isolate device-specific code in the drivers q A software interface to hardware devices v resides in kernel or user spaces q Classification Ø character device (terminal) Ø block (disk) -- with buffer cache Ø network Ø pseudodevice OS specific code I/O class specific code device driver Hardware specific code q When to call a device driver Ø configuration, I/O operations, and interrupt I/O adapters 30
Interaction with I/O Devices q Polling -v Read status until the device is ready, and then read/write data q Check flags which are set by ISR – v Interrupts when a new input arrives or the device completes an output operation v If the flag is set, proceed to do the I/O operation q Use driver – v Build input/output buffers in the driver v If an new input arrives, ISR reads the data and saves in the buffer (if a write is completed, ISR triggers the next write if the output buffer is not empty) v Application reads from (or write to) the corresponding buffer 31
Structure of Device Driver 0 1 2 3 File descriptor table Device list (of device descriptors) “/tty 0/” 1 “/pty 0/” 1 “/xx 1/” 3 Devicedependent data Driver table (function pointers) 32
Board Support Package q Most of RTOS’s are independent of the particular target board. q The board-specific code for initializing and managing a board’s hardware is called the BSP. The BSP provides RTOS with standard hardware interface functions which allow it to run on a board. Hardware-Independent Software Tools - Applications I/O System vx. Works Libraries TCP/IP File Systems Hardware-Dependent Software wind Kernel SCSI Driver SCSI Controller BSP Hardware Clock Timer Serial Controller Network Driver Ethernet Controller 33
Remote Target Boot Process q Basic initialization code exits in ROM. v This code can initialize the serial port or ethernet controller v allows the user to set the target parameters like the name of kernel image , target IP address, host IP address etc needed initially to pull over the kernel image into target. v It can perform TFTP and other serial port transfers. 34
Boot ROM q Target’s boot ROM code executes on power up. q The boot ROM code containing a bootloader: v Allows setting of boot parameter. v Downloading & executing kernel image. q Default Boot ROM’s does not contain the Vx. Works system. v Replace board manufacturer’s ROMs with vx. Works bootloader v Downloads Vx. Works into target memory via the network (TFTP) or serial port v Starts executing Vx. Works. 35
Boot Sequence q vx. Works boot sequence rom. Init. s : rom. Init() Disables interrupts, puts the boot type on the stack, clears caches boot. Init. c : rom. Start() The text and data segments are copied from ROM to RAM usr. Config. c and boot. Config. c : usr. Init() Cache initialization, zeroing out the system bss segment, initializing interrupt vectors and initializing system hardware to a quiescent state Libcuptoolvx. a : kernel. Init() usr. Cofig. c and boot. Config. c : usr. Root() Initiates the multitasking environment: disables round-robin mode, creates an interrupt stack, creates root stack and TCB Initializes the I/O system, installs drivers, creates devices, and then sets up the network as configured in config. All. h and config. h 36
- Slides: 36