REAL TIME OPERATING SYSTEM

UNIT-5

OPERATING SYSTEM SERVICES : GOAL, MODES AND STRUCTURE Goal The OS Service Goal – Perfection and correctness during a service (i) Facilitating easy sharing of resources as per schedule and allocations─ No processing task or thread uses any resource until it has been allocated by the OS at a given instance Meaning of Resource of a system • Processor (s), memory, I/O • Devices, virtual devices, • System timer, software timers • Keypad, displays, printer and other such resources, which processes (tasks or threads) request from the OS. (ii) Facilitating easy implementation of the application program with the given system hardware through the system software (iii) Optimally scheduling the processes on one (or more CPUs if available) by providing an appropriate context switching mechanism (iv)Maximizing the system performance to let different processes (or tasks or threads) share the resources most efficiently with protection and without any security breach. (v) Providing management functions for the processes (tasks or threads), memory, file, physical and virtual devices and I/Os and for other functions for which it is designed (vi) Providing management and organisation functions for the I/Os, devices and files and file -like devices (vii) Providing interoperability of the application on different networks (viii) Providing a common set of interfaces that integrates various devices and applications through standard and open systems (ix) Providing easy interfacing and management functions for the network protocols and network (x) Providing portability of the application on different hardware configurations Processor in the system running in two modes Clock, called system clock. At every clock tick of the system-clock, there is system interrupt. On each system interrupt, the system time updates, the system context switches to the supervisory mode from user mode. After completing the supervisory functions in the OS, the system context switches back to user mode User mode User process─ permitted to run and use only a subset of functions and instructions in OS. Use of OS functions in user mode─ either by sending a message to the waiting process associated in the OS kernel space or by system call (calling an OS function). The use of hardware resources including memory is not permitted without OS making the call to the OS functions, called system call. User function call, which is not a system call, is not permitted to read and write into the protected memory allotted to the OS functions, data, stack and heap

[EEE-VVCET]

Page 1

REAL TIME OPERATING SYSTEM

UNIT-5

That protected memory space is also called kernel space. Hence execution of user functions calls is slower than the execution of the OS functions (on system call) due to need to spend time in first checking the access permission to the protected space Supervisory mode Also called kernel mode OS runs in protected mode the privileged functions and instructions in protected mode that are the privileged ones and the OS (more specifically, the kernel) is only one permitted to access the hardware resources and protected area memory Kernel space functions and processes execute faster than the user space functions and processes. Only a system call is permitted to read and write into the protected memory allotted to the OS functions, data, stack and heap TOP TO DOWN STRUCTURAL LAYERS  Software Application Programming Interface (API)  System software other than the one provided at the OS  OS Interface  OS  Hardware–OS Interface  Hardware • OS is the middle in-between layer between the application software and system hardware Top to down Structural Layers Kernel  Process, memory and IO managers are essential components of a kernel  Kernel may include file and device management functions as part of the kernel in a given OS  Kernel in certain OSes is without File and Device management functions as part of the kernel in the given OS and any other needed functions other than process, memory and IO device managers, which are essential components of a kernel are not provided for at the kernel Process Management Kernel Services in an OS  Creation to deletion of Processes  Process structure maintenance  Processing resource requests  Scheduling Processes  Inter process Communication (IPC) (communication between Tasks, ISRs, OS functions) Memory Management Kernel Services in an OS  Allocation and de-allocation between Tasks, ISRs, OS functions

[EEE-VVCET]

Page 2

REAL TIME OPERATING SYSTEM

UNIT-5

Kernel Services in an OS  File Management  Device Management,  Device Drivers  I/O Management  Interrupts Control (by handling ISR) Mechanism PROCESS MANAGEMENT Process creation Step 1: At the reset of the processor. in a computer system, an OS is initialized first─ enabling the use of the OS functions, which includes the function to create the processes Step 2: Using OS process creation function, a process, which can be called initial process, is created. Step 3: OS started and that calls the initial process to run. Step 4: When the initial process runs, it creates subsequent processes. Processes can be created hierarchically. OS schedules the threads and provide for context switching between the threads (or tasks). Means defining the resources for the process and address spaces (memory blocks) for the created process, its stack, its data and its heap and placing the process initial information at a PCB Creation of a process Means defining the resources for the process and address spaces (memory blocks) for the created process, its stack, its data and its heap and placing the process initial information at a PCB PCB (i) Context (ii) Process stack pointer (iii) Current state [Is it created, activated or spawned? Is it running? Is it blocked?] (iv) Addresses that are allocated and that are presently in use (v) Pointer for the parent process (vi) Pointer to a list of daughter processes. (vii) Pointer to a list of resources, which are usable (consumed) only once. For examples, input data, memory buffer or pipe, mailbox message, semaphore (viii) Pointer to a list of resources, which are usable (consumed) only once (ix) Pointer to queue of messages. (x) Pointer to Access-permissions descriptor (xi) ID

[EEE-VVCET]

Page 3

REAL TIME OPERATING SYSTEM

UNIT-5

OS_Task_Create ( ) function  OS function creates a process using OS_Task_Create ( ) function Task_Send_Card_Info in the mai  Task_Send_Card_Info task creates two other tasks, Task_Send_Port_Output and Task_Read_Port_Input.  OS then controls the context switching between the processes OS function first creates the Display_process. Display_process creates─  Display_Time_DateThread  Display_BatteryThread  Display_SignalThread  Display_ProfileThread  Display_MessageThread  Display_Call StatusThread  Display_MenuThread Message Passing by process running in user mode  Generates and puts (sends) a message  OS lets the requested resource (for example, input from a device or from a queue) use or run an OS service function (for example, define a delay period after which process needs to be run again).  A message can be sent for the OS to let the LCD display be used by a task or thread for sending the output.  An ISR sends a message to a waiting thread to start on return from the ISR System call by process running in user mode  Call to a function defined at the OS.  For example, OSTaskCreate ( )─ to create a task.  First an SWI instruction is issued to trap the processor and switch to supervisory mode.  OS then executes a function like a library function  Processor on finishing the instructions of a called function, the processor again switches back to user mode and lets the calling process run further Process manager (i) makes it feasible to let for a process to sequentially execute or block when needing a resource and to resume when it becomes available, (ii) implements the logical link to the resource manager for resources management (including scheduling of process on the CPU), (iii) allows specific resources sharing between specified processes only, (iv) allocates the resources as per the resource allocation- mechanism of the system and (iv) manages the processes and resources of the given system.

[EEE-VVCET]

Page 4

REAL TIME OPERATING SYSTEM

UNIT-5

Timer Functions  Real time clock─ system clock, on each tick SysClkIntr interrupts  Based on each SysClkIntr interrupts─ there are number of OS timer functions OS_TICK_PER_SEC─ to set the system clock ticks and hence SysClkIntr interrupts per s • OSTickInit ( )─ to initiate system clock Ticks • OS TimeDelay ( )─ to delay the process making call by a fixed number of system clock ticks specified in argument • OSTimeDelay-Resume ( )─ to resume a delayed process specified in the argument • OSTimeSet ( )─ to set the counts of system clock ticks • OSTimeGet ( ) ─ to read the counts of system clock ticks to find the time interval from the previous read or write of the counts • OSSemPend (semVal, twait, *semErr)─ towait for a semaphore release • OSMboxPend (semVal, twait, *mboxErr) ─ to wait for a message in mailbox (wait for • message pointed not Null) SysClkIntr service routine call the OS functions (i) to increment system time and (ii) to find the new messages or IPCs, which the OS event control blocks received from the system call for the IPC functions, (iii) call the OS function as per the message or system call (iv) Then OS either selects the same task or selects new task or thread [by preemption in case of preemptive scheduling and switches the context to the new one, and Then after return from the interrupt the new task runs from the code, which was blocked from running Event Functions • Wait for only one event (semaphore or mailbox-message posting event) • Event related OS functions can wait for number of events before initiating an action or wait for any of the predefined set of events • Events for wait can be from differenttasks or the ISRs • Some OSes support and some don’t support event functions for a group of event OSEventCreate ( )  Creates an event register, which has a set of 8 or 16 or 32 flag-bits  Event register is for defining the information of occurrences of the events in an event register  Event register is for clearing the defined occurrences of the events in an event register  Each bit corresponds to an event flag OS Event Register flag-bits  Flag = 1 means occurrence of an event in an event register  Flag = 0 means an event in an event group has not occurred  A subset of flags defines an event-group

[EEE-VVCET]

Page 5

REAL TIME OPERATING SYSTEM

UNIT-5

 For example, a 16-bit register can be divided into four groups. Group 0 is from bit 0 to bit 3, group 1 from bit 4 to bit 7, Group 2 is from bit 8 to bit 11 and group 3 from bit 12 to bit 15  OSEventQuery ( )─ to query an event register to find the event register existence and its contents.  OSEventDelete ( ) ─ delete the event register  SET (event_flag) to set one of the bits at the event register  Event flag in the register can be set by an ISR or Task using SET (event_flag) Function  CLEAR (eventFlag) clears the flag in the event register.  An event flag can be cleared by an ISR or Task  WAIT_ALL function─ task waits for the occurrences of setting all the event flags in a group. [Wait till AND operation between all flags in the group equals true.]  WAIT_ANY function─ task waits for the occurrences of setting at least one event flag setting in a group. [Wait till OR operation between all flags in the group equals true. Memory Management Functions 1. 2. 3. 4. 5. 6. 7. 8. 9. Memory allocation When a process is created, the memory manager allocates the memory addresses (blocks) to it by mapping the process address space. Threads of a process share the memory space of the process Memory Management after Initial Allocation Memory manager of the OS─ secure, robust and well protected. No memory leaks and stack overflows Memory leaks means attempts to write in the memory block not allocated to a process or data structure. Stack overflow means that the stack exceeding the allocated memory block(s)

Memory Managing Strategy for a system  Fixed-blocks allocation  Dynamic -blocks Allocation  Dynamic Page-Allocation  Dynamic Data memory Allocation Memory Managing Strategy for a system  Dynamic address-relocation  Multiprocessor Memory Allocation  Memory Protection to OS functions Memory allocation in RTOSes  RTOS may disable the support to the dynamic block allocation, MMU support to dynamic page allocation and dynamic binding as this increases the latency of servicing the tasks and ISRs.  RTOS may not support to memory protection of the OS functions, as this increases the latency of servicing the tasks and ISRs.  User functions are then can run in kernel space and run like kernel functions  RTOS may provide for disabling of the support to memory protection among the tasks as this increases the memory requirement for each task

[EEE-VVCET]

Page 6

REAL TIME OPERATING SYSTEM

UNIT-5

Memory Manager functions (i) use of memory address space by a process, (ii) specific mechanisms to share the memory space and (iii) specific mechanisms to restrict sharing of a given memory space (iv) optimization of the access periods of a memory by using an hierarchy of memory (caches, primary and external secondary magnetic and optical memories). (v) Remember that the access periods are in the following increasing order: caches, primary and external secondary magnetic and then or optical. Fragmented not continuous memory addresses in two blocks of a process  Time is spent in first locating next free memory address before allocating that to the process.  A standard memory allocation scheme is to scan a linked list of indeterminate length to find a suitable free memory block.  When one allotted block of memory is deallocated, the time is spent in first locating next allocated memory block before deallocating that to the process.  The time for allocation and de-allocation of the memory and blocks are variable (not deterministic) when the block sizes are variable and when the memory is fragmented.  In RTOS, this leads to unpredicatble task Performance Device Management Functions Device Driver ISRs  Number of device driver ISRs in a system,  Each device or device function having s a separate driver, which is as per its hardware  Software that manages the device drivers of each device  Provides and executes the modules for managing the devices and their drivers ISRs.  Effectively operates and adopts appropriate strategy for obtaining optimal performance for the devices.  Coordinates between application-process, driver and device-controller.  Process sends a request to the driver by an interrupt; and the driver provides the actions by executing an ISR.  Device manager polls the requests at thedevices and the actions occur as per their priorities.  Manages IO Interrupts (requests) queues.  Creates an appropriate kernel interface and API and that activates the control register specific actions of the device. [Activates device controller through the API and kernel interface.]  Manages the physical as well as virtual devices like the pipes and sockets through a common strategy.

Device management has three standard approaches Three types of device drivers: (i) Programmed I/Os by polling from each device its the service need from each device. (ii) Interrupt(s) from the device drivers device- ISR and (iii) Device uses DMA operation used by the devices to access the memory. Most common is the use of device driver ISRs
[EEE-VVCET] Page 7

REAL TIME OPERATING SYSTEM

UNIT-5

Device Manager Functions  Device Detection and Addition  Device Deletion  Device Allocation and  Registration  Detaching and Deregistration Device Manager Functions  Restricting Device to a specific process  Device Sharing  Device control  Device Access Management  Device Buffer Management  Device Queue, Circular-queue or blocks of queues Management Device Manager Functions  Device drivers updating and upload of new device-functions  Backup and restoration Device Types  char devices and  block devices Set of Command Functions for the Device Management Commands for Device  create  open  write  read  ioctl  close and  delete ioctl Command for Device (i) Accessing specific partition information (ii) Defining commands and control functions of device registers (iii) IO channel control ISR functions  intlock ( ) to disable device-interrupts systems,  intUnlock ( ) to enable device-interrupts,  intConnect ( ) to connect a C function to an interrupt vector  Interrupt vector address for a device ISR points to its specified C function.  intContext ( ) finds whether interrupt is called when an ISR was in execution UNIX Device driver functions Facilitates that for devices and files have an analogous implementation as far as possible.  open ( ),

[EEE-VVCET]

Page 8

REAL TIME OPERATING SYSTEM

UNIT-5

 close ( ),  read ( ),  write ( ) functions analogous to a file open, close, read and write functions. APIs and kernel interfaces in BSD (Berkley sockets for devices)  open,  close,  read  write in-kernel commands  (i) select ( ) to check whther read/write will succeed and then select  (ii) ioctl ( )  (iii) stop ( ) to cancel the output activity from the device.  (iv) strategy ( ) to permit a block read or write or character read or write File System Organization and Implementation File  a named entity on a magnetic disc, or optical disc, or system memory or memory stick contains has the data, characters and text OSes differing abstractions of a file i) A file may be a named entity that is a structured record named entity as on a disk, which has having random access in the system. ii) May be a structured record on a RAM analogous to a disk and may also be either called separately called as ‘RAM disk’ or simply ,simply, as a ‘file’ itself (virtual device). (iii) May be an unstructured record of bits or bytes. (iv) A file device may be a pipe -like device File organization in a system File is organized in a way according to a file system, which has set of command functions for operations on the file Standard set of interfaces  Should a file having integers differ from a file having bytes?  Should a file having bytes differ from file having characters?  Due to the differing approaches to device and file management interfaces, the development of a set of standard interfaces must.  Then only then can systems can be portable. Two type of file systems─ Block File System Block File System. Its application generates records to be saved into the memory.  First structured into a suitable format and then translated into block-streams.  A file pointer (record) points to a block from the start to the end of the file.

[EEE-VVCET]

Page 9

REAL TIME OPERATING SYSTEM

UNIT-5

Byte Stream File-System Its application generates record stream.  Stream are to be saved into the memory.  These are first structured into a suitable format and then translated into byte-stream.  A file pointer (byte index) points to a byte from the start index = 0 to N-1 in a file of N bytes POSIX  A standard set of interfaces.  File operations are as the operations on a linear sequence of bytes  POSIX stands for Portable Operating System Interface IEEE standard for coding the programs when using the multiple threads.  The X after I is because of the interfaces being similar to ones in UNIX like.  It is according to the definitions at A T & T UNIX System V Interface. Set of Command Functions in the POSIX File System  open ( )  write ( ) in the byte stream at the present pointer position  read ( ) from the byte stream present pointer position  lseek (List seek) or set the file pointer in the byte stream  fcntl ( )  close () File descriptor─ fd  An integer, which returns on opening a file and which points to a data structure. File describing data structure  Identity  Creator or Owner  State  Locks and Protection fields  file Info  Sharing Permission  Count  Storing Media Details I/O ports  Subsystems of OS device management system─ UART access sub system and the parallel port access sub system .  They are used by drivers to communicate with the many devices that use them  I/O instructions depend on the hardware platform.  I/O systems differ in different OSes

[EEE-VVCET]

Page 10

REAL TIME OPERATING SYSTEM

UNIT-5

I/O Subsystem in a Typical I/O System at in an OS  Application  IO Basic functions  IO device driver functions  Device Hardware or Port or IO InterfaceCard OSes differing IO operations  Traditional OSes Synchronous IO operations─ at a certain fixed data transfer rates.  RTOSes Asynchronous IO operations ─ at the variable data transfer rates.  Are at a certain fixed data transfer rates.  Therefore, a task (process) blocks tills till completion of the IO.  For example, a write function, write ( ) for 1 kB data transfer to a buffer.  Are at a certain fixed data transfer rates.  Therefore, a task (process) blocks tills till completion of the IO.  For example, a write function, write ( ) for 1 kB data transfer to a buffer. Synchronous IO operations  Synchronous IO operation means once synchronous IO initiates, the data transfer will block the task till 1 kB data gets transferred to the buffer.  Similarly, read ( ) once initiated blocks the task till 1 kB is read Variable data transfer rates.  Permits that a process of high priority to run nd should not block during the IOs. INTERRUPT ROUTINES IN RTOS ENVIRONMENT AND HANDLING OF INTERRUPT SOURCE CALL 1. INTERRUPT ROUTINES IN RTOS ISRs in RTOSes  ISRs have the higher priorities over the RTOS functions and the tasks.  An ISR should not wait for a semaphore, mailbox message or queue message  An ISR should not also wait for mutex else it has to wait for other critical section code to finish before the critical codes in the ISR can run.  Only the IPC accept function for these events (semaphore, mailbox, queue) can be used, not the post function

RTOSes  Three alternative ways systems to respond to hardware source calls from the interrupts

[EEE-VVCET]

Page 11

REAL TIME OPERATING SYSTEM

UNIT-5

2. Direct Call to an ISR by an Interrupting Source and ISR sending an ISR enter message to OS

 On an interrupt, the process running at the CPU is interrupted  ISR corresponding to that source starts executing.  A hardware source calls an ISR directly.  The ISR just sends an ISR enter message to the RTOS. ISR enter message is to inform the RTOS that an ISR has taken control of the CPU ISR IPC messages and Exit message  ISR code can send into a mailbox or message queue but the task waiting for a mailbox or message queue does not start before the return from the ISR  When ISR finishes, it send s Exit message to OS  On return from ISR by retrieving saved context, The RTOS later on returns to the interrupted process (task) or reschedules the processes (tasks).  RTOS action depends on the event-messages, whether the task waiting for the event message from the ISR is a task of higher priority than the interrupted task on the interrupt Event Message (IPC) from the ISR  On certain RTOSes, there may be a function OSISRSemPost ( ).

[EEE-VVCET]

Page 12

REAL TIME OPERATING SYSTEM

UNIT-5

Multiple ISRs Nesting  Each ISR low priority sends on high priority interrupt the ISR interrupt message (ISM) to the OS to facilitate return to it on the finishing and return from the higher priority interrupt.  Nesting means when an inter upt source call of higher priority, for example, SysClkIntr occurs, then the control is passed to higher priority and on return from the higher priority the lower priority ISR starts executing.  Each ISR on letting a higher priority interrupt call sends the ISM to the RTOS.  Common stack for the ISR nested calls, similar to the nested function calls. 3. RTOS first interrupting on an interrupt, then RTOS calling the corresponding ISR

 On interrupt of a task, say, k-th task, the RTOS first gets itself the hardware source call and initiates the corresponding ISR after saving the present processor status (or context)  Then the ISR during execution then can post one or more outputs for the events and messages into the mailboxes or queues.  The ISR must be short and it must simply puts post the messages for another task.  This task runs the remaining codes whenever it is scheduled.  RTOS schedules only the tasks (processes) and switches the contexts between the tasks only.  ISR executes only during a temporary suspension of a task. Mobile PDA device example  Each device event has the codes for an ISR, which executes only on scheduling it by the RTOS and provided an interrupt is pending for its service.  Assume that using an RTOS, the touch screen ISR, ISR_TouchScreen has been created using a function OS_ISR_Create ( ).  The ISR can share the memory heap with other ISRs.  A function, IntConnect connects the touch screen event with the event identifier in an interrupt handler, ISR_handler.

[EEE-VVCET]

Page 13

REAL TIME OPERATING SYSTEM

UNIT-5

 When a touch screen event occur on tap at the screen to select icon or menu the OS sends signal on behalf of the ISR_handler to the waiting ISR_TouchScreen.  ISR_TouchScreen runs on an interrupt call message  ISR_TouchScreen executes as per its priority, IST_TouchScreenPriority among the other pending ISRs before it starts Executing  Before return from the ISR_TouchScreen, it sends a message to kernel using a function OS_eventPost ( ) or OS_ISR_Exit ( ) just before the end of the codes in the ISR_TouchScreen 4. RTOS first interrupting on interrupt, then RTOS calling the corresponding ISR, the ISR sending messages to priority queue of Interrupt Service threads by Temporary Suspension of a scheduled Task

 An RTOS can provide for two levels of interrupt service routines, a fast level ISR,FLISR and a slow level ISR (SLISR).  The FLISR can also be called hardware interrupt ISR and the SLISR as software interrupt ISR.  FLISR is called just the ISR in RTOS Windows CE The SLISR is called interrupt service thread (IST) in Windows CE. ISR sending messages to priority queue of Interrupt Service threads  The use of FLISR reduces the interrupt latency (waiting period) for an interrupt service and jitter (worst case and best case latencies difference) for an interrupt service.  An IST functions as deferred procedure call(DPC) of the ISR. An i-th interrupt service thread (IST) is a thread to service an i-th interrupt source call.

[EEE-VVCET]

Page 14

REAL TIME OPERATING SYSTEM

UNIT-5

Windows NT  Priority level of interrupts always higher than the user-thread priorities. [Threads are also assigned priorities.]  Only very critical operations of ISR are performed and the remaining processing passed to a DPC or IST.  DPCs executes ass priority FIFOs.LS  Even very low priority task ISR and DPC can preempt a real time process.  DPCs run in FIFO mode. therefore, a DPC of the very low priority ISR may not release a resource. [For example, DPC of network IO or keypad interrupt] Real Time  A real time is the time which continuously increments at regular intervals after the start of the system and time for all the activities at difference instances take that time as a reference in the system. RTOS  A real time operating system (RTOS) is multitasking operation system for the applications with hard or soft real time constraints  Real-time constraint means constraint on occurance of an event and system expected response and latency to the event. Basic OS Functions  Process Management,  Resources Management,  Device Management,  I/O Devices subsystems  Network Devices and subsystems Management Process Priorities Allocation  User level priorities allocation, called static priority allocation or real-time priority allocation is permitted.  The real time priorities are higher than the dynamically allocated priorities to the OS functions and the idle priority allotted to low priority threads.  The idle priority thread or task is one which runs when no other high priority ones running. Process Management by Preemption  RTOS kernel preempts a lower priority process when a message or event for that was waiting is obtained for the higher priority process.  The RTOS kernel has the preemption points at the end of the critical code and therefore the RTOS can be preempted at those points by a real time high priority task.  Only small sections in the RTOS functions are non-preemptive Process Priorities Management by priority Inheritance  Priorities Inheritance enables a shared resource in low priority task, for example, LCD display, be used by high priority task first.

[EEE-VVCET]

Page 15

REAL TIME OPERATING SYSTEM

UNIT-5

 An intermediate priority task will not preempt the low priority task when it is locked to run the critical shared resource or code for the high priority task.  Priority sealing in place of priority inheritance option can also be used for a specific system. Process Predictability  A predictable timing behavior of the system and a predictable task-synchronization with minimum jitter (difference between best case latency and worst case latency) Memory Management by Protection  In RTOS threads can run in kernel space.  The real time performance becomes high. However, then a thread can access the kernel codes, stack and data memory space, and this could lead to unprotected kernel code  Either disabling use of MMU and virtual memory or using memory locks.  Memory locking stops page swapping between physical memory and disk disabled. This makes RTOS task latencies predictable and reduces jitter (time between worst case latency and best case latencies for a task or thread). Memory Allocation  In RTOS, the memory allocation is fast and there are , fixed length memory block allocationt and system takes predictable time for allocation Scheduling and Interrupt-latency control functions  Real time Task-Scheduling and Interruptlatency control and uses of the timers and system clocks Timer Functions and Time Management  Provides for timer functions. There is time allocation and de-allocation to attain best utilization efficiency in given timing constraints Asynchronous IO Functions  Permits asynchronous IOs, which means IOs without blocking a task IPC Synchronization  Synchronization of tasks with IPCs (Semaphores, mailboxes, message queues, pipes, sockets and RPCs) Spin Locks  Spin locks for critical section handling Hard and soft real time operability  Hard real-time and soft real-time operations Time Slicing  Time-slicing of the processes execution of those processes which have equal priority Basic Design using an Real Time
[EEE-VVCET] Page 16

REAL TIME OPERATING SYSTEM

UNIT-5

Operating System RTOS  An embedded system with a single CPU can run only one process at an instance.  The process at any instance may either be an ISR, or kernel function or task  Provides running the user threads in kernel space so that they execute fast.  Provides effective handling of the ISRs, device drivers, ISTs, tasks or threads  Disabling and enabling of interrupts in user mode critical section code  Provides memory allocation and deallocation functions in fixed time and blocks of memory  Provides for effectively scheduling and running and blocking of the tasks in cases of number of many tasks  I/O Management with devices, files, mailboxes, pipes and sockets becomes simple using an RTOS  provides for the uses of Semaphore (s) by the tasks or for the shared resources (cCritical sections) in a task or OS functions  Effective management of the multiple states of the CPU and, internal and external physical or virtual devices Hard and Soft Real Time Design Considerations Hard real time  Hard real time means strict about adherence to each task deadline. When an event occurs, it should be serviced within the predictable time at all times in a given hard real time system.  The preemption period for the hard real time task in worst case should be less than a few MICROsECOND.  A hard RT RTOS is one, which has predictable performance with no deadline miss, even in case of sporadic tasks (sudden bursts of occurrence of events requiring attention).  Automobile engine control system and anti lock brake are the examples of hard real time systems Hard real time system design  Provision of asynchronous IOs  Provision of locks or spin locks  Predictions of interrupt latencies and context switching latencies of the tasks  Predictability is achieved by writing all functions which execute always take the same predefined time intervals in case of varying rates of occurrences of the events. Example of hard real time system  video transmission, each picture frame and audio must be transferred at fixed rate Soft real time system  One in which deadlines are mostly met.  Soft real time means that only the precedence and sequence for the task operations are defined, interrupt latencies and context switching latencies are small but there can be few deviations between expected latencies of the tasks and observed time constraints and a few deadline misses are accepted Soft real time task  The preemption period for the soft real time task in worst case may be about a few ms.  Mobile phone, digital cameras and orchestra playing robots are examples of soft real time systems.

[EEE-VVCET]

Page 17

REAL TIME OPERATING SYSTEM

UNIT-5

Memory Optimization  Compact code without effect on performance  Code means code compiled and assembled executable in the given system  Compact code also reduces the total number of CPU cycles, and thus, the total energy requirements Using Compressed data structures  Use compressed data structure─ provided de-compression algorithm plus compressed data structures combined together take less memory in the system compared to the case when only un compressed data structures are used . Appropriate Data type Declarations  Use unsigned bytes especially within the for-loops and while loops for a short and a short for an integer, if possible, to optimise memory use system.  Avoid if possible the use of 'long' integers and ‘double’ precision floating point values especially within the for-loops and while loops Power Optimization  Saving power and energy requirement for a given set of codes, while finishing instructions in the scheduled time-slot to standby and Stop Modes  Wait and Stop instructions and operation in power-down mode.  One way to do this is to cleverly incorporate into the software the Wait and Stop instructions.  For example, a program can be such that it reduces the brightness level of the LCD panel so that it takes less power when the system is used in fully lighted room. [A sensor senses the light level at specific intervals] Stop instructions  Mobile phone auto-switch off the LCD lights when not using for 5 or 10 or 20 s.  A call attend mode can be switched off if there is not talk for over a minute Current Requirements  (i) 75 mA when the processor plus the external memories and chips are in running state  (ii) 50 mA─ when only the processor Running  Disable use of certain structural units of the processor—for example, caches—when not necessary and to keep in disconnected state those structure units that are not needed during a particular software-portion execution, for example timers or IO units Reduce Circuit Glitches  In a CMOS circuit, power dissipates only at the instance of change in input.  Therefore, unnecessary glitches and frequent input changes increase power dissipation.  VLSI circuit designs optimized to eliminate all removable glitches, thereby eliminating any frequent input changes

[EEE-VVCET]

Page 18

REAL TIME OPERATING SYSTEM

UNIT-5

Cooperative Scheduling in the cyclic order  Each task cooperate to let the running task finish  Cooperative means that each task cooperates to let the a running one finish.  None of the tasks does block in-between anywhere during the ready to finish states.  The service is in the cyclic order Worst-case latency  Same for every task  Tworst = {(sti + eti )1 + (sti + eti )2 +...+ (sti + eti )N-1 + (sti + eti )N} + tISR.  tISR is the sum of all execution times for the ISRs  For an i-th task, switching time from one task to another be is sti and task execution time be is eti  i = 1, 2, …, N 1 , N, when number of tasks = N

[EEE-VVCET]

Page 19

REAL TIME OPERATING SYSTEM

UNIT-5

Cooperative Scheduling of Ready Tasks in List Cooperative Scheduling in the order in which a task is initiated on interrupt  None of the tasks does block in-between anywhere during the ready to finish states.  The service is in the order in which a task is initiated on interrupt. Worst-case latency  Same for every task in the ready list  Tworst = {(dti + sti + eti )1 + (dti + sti + eti )2 +...+ (dti + sti + eti )n-1 + (dti + sti + eti )n} + tISR.  tISR is the sum of all execution times for the ISRs  For an i-th task, let the event detection time with when an event is brought into a list be is dti , switching time from one task to another be is sti and task execution time be is eti
[EEE-VVCET] Page 20

REAL TIME OPERATING SYSTEM

UNIT-5

 i = 1, 2, …, n 1 , n

Cooperative Scheduling of Ready Tasks Using an Ordered List as per precedence Constraints Cooperative Scheduling in the order of Ready Tasks using an Ordered List as per priority precedence  Scheduler using a priority parameter, taskPriority does the ordering of list of the tasks─ ordering according to the precedence of the interrupt sources and tasks.  The scheduler first executes only the first task at the ordered list, and the total, equals the to period taken by the first task on at the list. It is deleted from the list after the first task is executed and the next task becomes the first. Cooperative Scheduling in the order of Ready Tasks using an Ordered List as per priority precedence  The insertions and deletions for forming the ordered list are made only at the beginning of the cycle for each list. Worst-case latency  Not Same for every task. Varies from (dti + sti + eti ) p(m)} + Tisr to {(dti + sti + eti )p1 + (dti + sti + eti ) p2 +...+ (dti + sti + eti ) p(m-1) + (dti + sti + eti ) p(m)} + tISR.  tISR is the sum of all execution times for the ISRs  For an i-th task, let the event detection time with when an event is brought into a list be is dti , switching time from one task to another be is sti and task execution time be is eti

[EEE-VVCET]

Page 21

REAL TIME OPERATING SYSTEM

UNIT-5

 i = 1, 2, …, m 1 , m; m is number of ISRs and tasks in the list

[EEE-VVCET]

Page 22

REAL TIME OPERATING SYSTEM

UNIT-5

Example of ACVM  First the coins inserted by the user are read, then the chocolate delivers, and then display task displays ‘thank you, visit again’ message.  Each task cooperates with other to finish.  The precedence of tasks in the ready list─ reading coins is highest, then of chocolate delivery and display for the ordered list of the ready tasks. Task Cyclic Scheduling of Periodic TasksCommon scheduling models  Cooperative Scheduling of ready tasks in a circular queue. It closely relates to function queue scheduling.  Cooperative Scheduling with Precedence Constraints  Cyclic scheduling of periodic tasks and Round Robin Time Slicing Scheduling of equal priority tasks  Preemptive Scheduling  Scheduling using 'Earliest Deadline First' (EDF) Precedence Time Periodic Scheduling in the cyclic order  Assume periodically occurring three tasks  Let in time-frames allotted to the first task, the task executes at t1, t1 + Tcycle, t1+ 2  Tcycle, .., second task frames at t2, t2 + Tcycle, t2+ 2  Tcycle and third task at t3, t3 + Tcycle, t3+ 2  Tcycle, … . Time Period Scheduling in the Periodic tasks  Start of a time frame is the scheduling point for the next task in the cycle.  Tcycle is the cycle for repeating cycle of execution of tasks in order 1, 2 and 3 and equals start of task 1 time frame to end of task 3 frame.  Tcycle is period after which each task time frame allotted to that repeats Case : tcycle = N Sum of the maximum times for each task  Then each task is executed once and finishes in one cycle itself.  When a task finishes the execution before the maximum time it can takes, there is a waiting period in-between period between two cycles.  The worst-case latency for any task is then N  Sum of the maximum times for each task. A task may periodically need execution. A task period for the its need of required repeat execution of a task is an integral multiple of tcycle.

[EEE-VVCET]

Page 23

REAL TIME OPERATING SYSTEM

UNIT-5

Example of Video and audio signals  Signals reaching at the ports in a multimedia system and processed  The video frames reach at the rate of 25 in one second.  The cyclic scheduler is used in this case to process video and audio with Tcycle = 40 ms or in multiples of 40 ms. Common scheduling models  Cooperative Scheduling of ready tasks in a circular queue. It closely relates to function queue scheduling.  Cooperative Scheduling with Precedence Constraints  Cyclic scheduling of periodic tasks and Round Robin Time Slicing Scheduling of equal priority tasks  Preemptive Scheduling  Scheduling using 'Earliest Deadline First' (EDF) precedence.  Rate Monotonic Scheduling using ‘higher rate of events occurrence First’ precedence  Fixed Times Scheduling  Scheduling of Periodic, sporadic and aperiodic Tasks  Advanced scheduling algorithms using the probabilistic Timed Petri nets (Stochastic) or Multi Thread Graph for the multiprocessors and complex distributed systems. Round Robin Time Slice Scheduling of Equal Priority Tasks  Round robin means that each ready task runs turn by in turn only in a cyclic queue for a limited time slice.  Widely used model in traditional OS.  Round robin is a hybrid model of clock-driven model (for example cyclic model) as well as event driven (for example, preemptive)  A real time system responds to the event within a bound time limit and within an explicit time.

[EEE-VVCET]

Page 24

REAL TIME OPERATING SYSTEM

UNIT-5

Case : Tcycle = N  Tslice  Same for every task = Tcycle  Tcycle ={Tslice )}N + tISR.  tISR is the sum of all execution times for the ISRs  For an i-th task, switching time from one task to another be is st and task execution time be is et  Number of tasks = N Worst-case latency  Same for every task in the ready list  Tworst = {N (Tslice)} + tISR.  tISR is the sum of all execution times for the ISRs  i = 1, 2, …, N 1 , N VoIP Tasks Example  Assume a VoIP [Voice Over IP.] router.  It routes the packets to N destinations from N sources.  It has N calls to route.  Each of N tasks is allotted from a time slice and is cyclically executed for routing packet from a source to its destination Round Robin  Case 1: Then each task is executed once and finishes in one cycle itself.  When a task finishes the execution before the maximum time it can takes, there is a waiting period in-between period between two cycles.  The worst-case latency for any task is then N  tslice. A task may periodically need execution. A task The period for the its need of required repeat execution of a task is an integral multiple of tslice.

[EEE-VVCET]

Page 25

REAL TIME OPERATING SYSTEM

UNIT-5

Case 2: Alternative model strategy  Case 2: Certain tasks are executed more than once and do not finish in one cycle  Decomposition of a task that takes the abnormally long time to be executed.  The decomposition is into two or four or more tasks.  Then one set of tasks (or the odd numbered tasks) can run in one time slice, t'slice and the another set of tasks (or the even numbered tasks) in another time slice, t''slice. Decomposition of the long time taking task into a number of sequential states  Decomposition of the long time taking task into a number of sequential states or a number of node-places and transitions as in finite state machine. (FSM).  Then its one of its states or transitions runs in the first cycle, the next state in the second cycle and so on.  This task then reduces the response times of the remaining tasks that are executed after a state change. Preemptive Scheduling Model Difficulties in cooperative and cyclic scheduling of tasks  Cooperative schedulers schedule such that each ready task cooperates to let the running one finish.  However, a difficulty in case of the cooperative scheduling is that a long execution time of a low- priority task lets a high priority task waits at least until that that finishes Difficulties in cooperative and cyclic scheduling of tasks  Difficulty when the cooperative scheduler is cyclic but without a predefined tslice─ Assume that an interrupt for service from first task occurs just at the beginning of the second task. The first task service waits till all other remaining listed or queued tasks finish.  Worst case latency equals the sum of execution times of all tasks Preemptive Scheduling of tasks  OS schedules such that higher priority task, when ready, preempts a lower priority by blocking  Solves the problem of large worst case latency for high priority tasks.

[EEE-VVCET]

Page 26

REAL TIME OPERATING SYSTEM

UNIT-5

RTOS Preemptive Scheduling  Processes execute such that scheduler provides for preemption of lower priority process by higher priority process.  Assume priority of task_1 > task_2> task_3 > task_4…. > task N  Each task has an infinite loop from start (Idle state) up to finish.  Task 1 last instruction points to the next pointed address, *next. In case of the infinite loop, *next points to the same task 1 start.

[EEE-VVCET]

Page 27

REAL TIME OPERATING SYSTEM

UNIT-5

Worst-case latency  Not Same for every task  Highest priority task latency smallest  Lowest priority task latency highest Worst-case latency  Different for different tasks in the ready list  Tworst = {(dti + sti + eti )1 + (dti + sti + eti )2+...+ (dti + sti + eti )p-1 + (dti + sti + eti )p} + tISR.  tISR is the sum of all execution times for the ISRs  For an i-th task, let the event detection time with when an event is brought into a list be is dti ,

[EEE-VVCET]

Page 28

REAL TIME OPERATING SYSTEM

UNIT-5

switching time from one task to another be is sti and task execution time be is eti  i = 1, 2, …, p 1 when number of higher priority tasks = p 1 for the pth task. ISRs Handling  Hardware polls to determine whether an ISR with a higher priority ISR than the present one needs the service at the end of an instruction during execution of an ISR, if yes, then the higher priority ISR is executed. An infinite loop in each task  Each task design is like as an independent program, in an infinite loop between the task ready place and the finish place.  The task does not return to the scheduler, as a function does.  Within the loop, the actions and transitions are according to the events or flags or tokens. When priority of task_1 > task_2 > task_3  (1) At RTOS start, scheduler sends a message (Task_Switch_Flag) to task 1 to go to un-blocked state and run, and thus highest priority task 1 runs at start.  (2) When task 1 blocks due to need of some input or wait for IPC or delay for certain period, a message (Task_Switch_Flag) will be sent to RTOS, task 1 context saves and the RTOS now sends a message (Task_Switch_Flag) to task 2 to go to unblocked state and run.  (3) Task 2 now runs on retrieving the context of task 2. When it blocks due to need of some input or wait for IPC or delay for certain period, a message (Task_Switch_Flag) will be sent to RTOS, task 2 context saves and an RTOS message (Task_Switch_Flag) makes the task 3 in unblocked state. Task 3 will run now after retrieving the context of task 3.  (4) If during running of task 3, either task 2 or task 1 becomes ready with the required input or IPC or delay period is over, task 3 is preempted, a message (Task_Switch_Flag) will be sent to RTOS, task 3 context saves, and task 1, and if task 1 not ready, then task 2 runs after retrieving the context of task 2.  (5) A message (Task_Switch_Flag) is sent to RTOS after task 2 blocks due to wait of IPC or need of sum input and task 2 context saves and task 1 if ready then task 1 runs on retrieving the context of task 1  (6) task 1 if not ready then task 3 runs on retrieving the context of task 3  (7) Task 1 when ready to run preempts tasks 2 and 3, and Task 2 when ready to run preempts task 3

Specifying timeout for waiting for the token or event • Specify timeout for waiting for the token or event. • An advantage of using timeout intervals while designing task codes is that worstcase latency estimation is possible.

[EEE-VVCET]

Page 29

REAL TIME OPERATING SYSTEM

UNIT-5

• There is deterministic latency of each tasks • Another advantage of using the timeouts is the error reporting and handling • Timeouts provide a way to let the RTOS run even the preempted lowest priority task in needed instances and necessary cases. Critical Section Handling Critical Section Service by disabling and enabling interrupts  Critical section is a section in a system call (OS function), where there is no pre-emption by tasks.  A disable interrupts function can be used at beginning of critical section and enable interrupts function executed at exit from the critical section to prevent preemption by tasks as well as ISRs.

Disabling and enabling preemption by other processes by using lock ( ) and unlock ( ) Critical Section Service by lock ( ) and unlock ( ) in a Preemptive Scheduler  A lock function can be used at beginning of critical section and an unlock function executed at exit from the critical section. RTOS COS-II lock ( ) and unlock ( )  RTOS COS-II provides a function OSSchedLock ( ) to lock scheduling and hence locks preemption by other task waiting to proceed further for taking the lock ( )  OSSchedUnlock ( ) unlocks scheduling and hence unlocks preemption by other task waiting to proceed further after executing lock ( )

[EEE-VVCET]

Page 30

REAL TIME OPERATING SYSTEM

UNIT-5

Taking and releasing semaphore (mutex) by processes by using semTake( ) and semGive ( ) Critical Section Service by semTake ( ) and semGive ( ) in a Preemptive Scheduler  A mutex semaphore can be used.  Take the mutex at critical section 1 start  Release the mutex at critical section end  Same mutex is then taken and released by another critical section 2 when the access to the section is permitted after taking semaphore at an instance Petri net concept based model  Petri net concept based model which models and helps in designing the codes for a task  The model shows places by the circles and transitions by the rectangles.

Petri net model in Figure  (i) Each task is in idle state (or at idleTaskPlace) to start with, and a token to the RTOS is taskSwitchFlag = reset.  (ii) Let us consider the task_J_Idle place, which is currently has of highest priority among the ready tasks.  When the RTOS creates task, task_J, the place, task_J_Idle undergoes a transition to the ready state (or to readyTaskPlace), task_J_Ready place.  The RTOS initiates idle to ready transition by executing a function, task create ( ).

[EEE-VVCET]

Page 31

REAL TIME OPERATING SYSTEM

UNIT-5

 For the present case it is done by executing a function, task_J_create ( ).  A transition from the idle state of the task is fired as follows.  RTOS sends two tokens, RTOS_CREATE Event and taskJSwitchFlag. The output token from the transition is taskSwitchFlag = true. (iii) When after task J finishes, the RTOS sends a RTOS_DELETE event (a token) the task, it returns to the task_J_Idle place and its corresponding taskJSwitchFlag resets. (iv) At task_J_Ready place, the scheduler takes the priority parameter into account. If the current task current happens to be of highest priority, the scheduler sets two tokens, taskJSwitchFlag = true (sends a token) and highest Priority Event = true, for the transition to the running task J place, task_J_Running. The scheduler also resets and sends the tokens, task switch flags, for all other tasks that are of lesser priority. This is because the system has only one CPU to process at an instant (v) From the task_J_Running place, the transition to the task_J_Ready place will be fired when the task finish flag sets (vi) At task_J_Running place, the codes of the switched task J are executed. (vii) At the runningTaskPlace, the transition for preempting will be fired when RTOS sends a token, suspendEvent. Another enabling token if present, is time_out_event will also fire the transition. An enabling token for both situations is the semaphore release flag, which must be set. Semaphore release flag is sets on finishing the codes of task J critical-sections. On firing, the next place is task_J_Blocked. Blocking is in two situations., One situation is of preemption. It happens is when the suspendEvent occurs on a call at the runningTaskPlace asking the RTOS to suspend the running. Another situation is a time-out of an SWT, which that associates with the running task place (viii) On a resumeEvent (a token from RTOS) the transition to task_J_Running place occurs (ix) At the task_J_Running place, there is another transition that fires so that the task J is at back at to the to task_J_Running place when the RTOS sends a token, take_Semaphore_Event for to asking the task J to take the semaphore (x) There can be none or one or several sections taking and releasing semaphore or message. RTOS during the execution of a section, the RTOS resets the semaphore release flag and sets the take semaphore event token

Models for Performance Measures Three types of tasks for finding performance  Scheduler must take into account (aperiodic, periodic and sporadic) separately.  (i) An aperiodic task needs to be run only once.  (ii) A periodic task needs to run after the fixed periods and it that must be executed before its next preemption is needed.  (iii) A sporadic task needs to be checked for run after a minimum time period of its occurrence. Predictably response to the event and minimum interrupt latency as Performance Measures  An RTOS should quickly and predictably respond to the event.  It should minimum interrupt latency and fast context switching latency Three Models for Performance Measures  (i) Ratio of the sum of latencies of the tasks and Interrupt with respect to the sum of the execution times.  (ii) CPU load for how much time CPU not idle

[EEE-VVCET]

Page 32

REAL TIME OPERATING SYSTEM

UNIT-5

 (iii) Worst-Case Execution time with respect to mean execution time. Interrupt latencies as Performance Metric  Interrupt and task execution latencies with respect to the sum of the execution times must be very small  There must be fast context switching. CPU Load as Performance Metric  Each task gives a load to the CPU that equals the task execution time divided by the task period  CPU load or system load estimation in the case of multitasking is as follows. Suppose there are m tasks. For the multiple tasks, the sum of the CPU loads for all the tasks and ISRs should be less than 1 CPU Load  CPU load equal to 0.1 (10%)─ means the CPU is underutilized and spends its 90% time in a waiting mode.  Since the executions times can vary or and the task periods vary, the CPU loads can also vary CPU Load  CPU load equal to 0.1 (10%)─ means the CPU is underutilized and spends its 90% time in a waiting mode.  Since the executions times can vary or and the task periods vary, the CPU loads can also varySporadic Task Model Performance Metric  Ttotal = Total length of periods for which sporadic tasks occur  e = Total Task Execution Time  Tav = Mean periods between the sporadic occurrences  Tmin = Minimum Period between the sporadic occurrences Sporadic Task Model Performance Metric  Ttotal = Total length of periods for which sporadic tasks occur  e = Total Task Execution Time  Tav = Mean periods between the sporadic occurrences  Tmin = Minimum Period between the sporadic occurrences Sporadic Task Model Performance Metric  Worst-Case Execution-time performance metric, p is measured calculated as follows for a tasks worst case of a task in a model.  p = p worst= (e * Ttotal / Tav )/ (e * Ttotal / Tmin).  Because average rate of occurrence of sporadic task = (Ttotal / Tav) and maximum rate of sporadic task burst = Ttotal / Tmin.

[EEE-VVCET]

Page 33

REAL TIME OPERATING SYSTEM

UNIT-5

OS SECURITY ISSUES Protection Mechanism  OS should provide protection mechanisms and implement a system administrator (s) defined security Flexibility to of change  when needed to fulfill the need requirements of all the processes.  For example, a process has control of 32 memory blocks at an instance and the OS configured the system accordingly. t  Later when more processes are created, this can be reconfigured. Controlled resource sharing  Controlling read and write of the resources and parameters by user processes.  For example, some resources write only for a process and some read only for a set of processes  Another example, memory buffer to which one process writes at an instant till that buffer is emptied by other process Confinement Mechanism  Mechanism that restricts sharing of parameters to a set of processes only Security Policy (Strategy)  Rules for authorizing access to the OS, system and information.  A policy example is that a communication system may having a policy of peer-topeer communication (connection establishment preceding the data packets flow). Authentication Mechanism  External authentication mechanism for the user and a mechanism meant to prevent an application run unless the user registers and the system administrator (software) authorizes  Internal authentication for the process, and the process should not appear (impersonate) as some like other processes.  User authentication can become difficult if the user disseminates password passwords or other authentication methods Authorization  User or process (s) allowed to use the system resources as per the security policy Encryption  A tool to change information to make it unusable by any other user or process unless without the appropriate key is used for deciphering it. Kernel of an RTOS • Used for real-time programming features to meet hard and soft real time constraints, • Provides for preemption points at kernel, user controlled dynamic priority changes, fixed memory blocks,
[EEE-VVCET] Page 34

REAL TIME OPERATING SYSTEM

UNIT-5

asynchronous IOs, user processes in kernel space and other functions for a system.

RTOS features in general _ Basic kernel functions and scheduling: Preemptive or Preemptive plus time slicing _ Support to Limited Number of tasks and threads _ Task priorities and Inter Service Threads priorities definitions _ Priority Inheritance feature or option of priority ceiling feature

[EEE-VVCET]

Page 35

REAL TIME OPERATING SYSTEM

UNIT-5

_ Task synchronization and IPC functions _ Support to task and threads running in kernel space _ IDE consisting of editor, platform builder, GUI and graphics software, compiler, debugging and host target support tools _ Device Imaging tool and device drivers _ Clock, time and timer functions, _ Support to POSIX, _ Asynchronous IOs, _ Fixed memory blocks allocation and deallocation system, _ Support to different file systems and flash memory systems TCP/IP protocols, network and buses protocols, _ Development environment with Java _ Componentization (reusable modules for different functions), which leads to small footprint (small of size of RTOS codes placed in ROM image) _ Support to number of processor architectures, such as INTEL, ARM, Philips, … Host and Target Based Development Approach _ . A host machine (Computer) for example, a PC uses a general purpose OS, for example, Windows or Unix for system development. The target connects by a network protocol for example TCP/IP during the development phase. The developed codes and the target RTOS functions first connect a target. The target with downloaded codes finally disconnects and contains a small size footprint of RTOS. For example, the target does not download host machine resident compiler, cross compiler, editor for programs, simulation and debugging programs, and MMU support Self Host Based Development Approach _ Same system with full RTOS is used for development on which the application will be running. This also does not require cross compilation. When application codes are ready, the required RTOS function codes and application codes are downloaded into the ROM of the target board Introduction to Embedded Software Development Process and Tools 1. Development Process and Hardware─ Software Development Process • Consists of cycles of editing-testingdebugging. • Processor and hardware part once chosen remains fixed, the application software codes have to be perfected by a number of runs and tests. Cost of developing a final targeted system _ While the cost of the processor is quite small, the cost of developing a final targeted system is quite high

[EEE-VVCET]

Page 36

REAL TIME OPERATING SYSTEM

UNIT-5

_ Needs a larger time frame than the hardware circuit design

Software Tools _ Software Development Lit (SDK) _ Source-code Engineering Software _ RTOS _ Integrated Development Environment _ Prototyper _ Editor _ Interpreter

[EEE-VVCET]

Page 37

REAL TIME OPERATING SYSTEM

UNIT-5

_ Compiler _ Assembler _ Cross Assembler _ Testing and debugging tools _ Locator

Typical tool Features _ Comprehension, _ Navigation and browsing, _ Editing, _ Debugging, _ Configuring (disabling and enabling specific C++ features) _ Compiling _ Searches and lists the definitions, symbols, hierarchy of the classes, and class inheritance trees _ Symbols include the class members _ Searches and lists the dependencies of symbols and defined symbols, variables and functions _ Monitors, enables and disables the implementation virtual functions. _ Finds the full effect of any code change on the source code. _ Searches and lists the dependencies and hierarchy of included header files. Navigates to and fro─ _ between the implementation and symbol declaration. _ between the overridden and overriding methods. Browses through _ information regarding instantiation (object creation) of a class. _ encapsulation of variables among the members _ public, private and protected visibility of the members. _ object component relationships _ Automatically removes error- prone and unused tasks. _ Provides easy and automated search and replacement Integrated Development Environment (IDE) IDE Consists of • Simulators • editors, • compilers, • assemblers, etc.

[EEE-VVCET]

Page 38

REAL TIME OPERATING SYSTEM

UNIT-5

• emulators • logic analyzers • EPROM/EEPROM application codes burner. • Provides an integrated development Environment _ Facility for defining a processor family as well as defining its version. _ Includes source code engineering tools that incorporate the editor, compiler for C and embedded C++, _ Assembler, linker, locator, logic analyser, stethoscope, and help to use _ Optimizes the use of memory

Provides Windows on the screen for the detailed information of ─ _ source code part with labels and symbolic arguments, _ registers as the execution continues,

[EEE-VVCET]

Page 39

REAL TIME OPERATING SYSTEM

UNIT-5

_ status of peripheral devices, _ status of RAM and ports, _ status of stack and program flow as it Continues _ Verifies the performance of a target system that an emulator built into the development system, which remains independent of a particular targeted system, _ Includes a logic analyzer for up to 256 or 512 transactions on the address and data buses after triggering _ Simulates on a host system (PC), the hardware unit like emulator, peripherals, and I/O devices. _ Supports conditional and unconditional breakpoints. _ Debug by single stepping. _ Facilitate for synchronizing the internal peripherals _ Facility of a user-definable assembler to support a new version or type of processor. _ Provision of a multi-user environment. _ Design process divisibility into a number of sub parts. _ Each programmer assigned independent but linked tasks _ tasks, queues, semaphores and IPC Objects RTA in IDE _ Real-Time Analysis (RTA) suite profiles the code coverage and locates runtime errors. IDE Example _ IDE from Keil µVision 2 with RTX51 for 8051 family of microcontrollers _ IDE from Keil µVision 3 RTX51 for ARM family of processors and Microcontrollers Host-Target System Development Approach _ During development process, a host system is used _ Then locating and burning the codes in the target board. _ Target board hardware and software later copied to get the final embedded system _ Final system function exactly as the one tested and debugged and finalized during the development process Host system at PC or workstation or laptop _ High performance processor with caches, large RAM memory _ ROMBIOS (read only memory basic input-output system) _ very large memory on disk _ keyboard _ display monitor _ mice _ network connection _ Program development kit for a high level language program or IDE _ Host processor compiler and cross compiler _ Cross assembler Program Development Tool Kit _ Program development tool kit or IDE _ Editor─ used for writing C codes or assembly mnemonics or C++ or Java or Visual C++ using the keyboard of the host system (PC) for entering the program.

[EEE-VVCET]

Page 40

REAL TIME OPERATING SYSTEM

UNIT-5

_ Using GUIs for allowing the entry, addition, deletion, insert, appending previously written lines or files, merging record and files at the specific positions. _ Create source file that stores the edited file. _ File given an appropriate name by the programmer _ Can use previously created files _ Can also integrate the various source files. _ Can save different versions of the source files.

Target system differs from a final system _ Target system interfaces with the computer as well works as a standalone system _ In target system might be repeated downloading of the codes during the development phase. • Target system copy made that later on functions as embedded system • Designer later on simply copies it into final system or product. • Final system may employ ROM in place of flash, EEPROM or EPROM in embedded system.

[EEE-VVCET]

Page 41

REAL TIME OPERATING SYSTEM

UNIT-5

Linking and Locating Software

Linker _ Links the compiled codes of application software, object codes from library and OS kernel functions. _ Linking necessitates because of the number of codes to be linked for the final binary file. Linking Necessity _ For example, standard codes for to program a delay task, must link with the assembled codes. _ The delay code sequential from a beginning address. _ The assembly software codes also sequential from another beginning address. _ Both the codes have to at the distinct addresses as well as at the available addresses in the system. Linker links these Linked binary file _ After linking, re-allocation of the sequences of placing the codes before actually placement of the codes in the Memory _ Linked file in binary for run on a computer commonly known as executable file or simply '.exe' file. Loader _ Program loaded in a computer RAM. _ Loader program performs the task of reallocating the codes after finding the physical memory addresses available at a given instant _ Loader a part of the operating system and places codes into the memory after reading the '.exe' file. _ Step necessary because the available memory addresses may not start from 0x0000, and binary codes have to be loaded at the different addresses during thae run. • Loader finds the appropriate start address. • In a computer, after the loader loads into a section of RAM and after loading the program ready to run

[EEE-VVCET]

Page 42

REAL TIME OPERATING SYSTEM

UNIT-5

Locator _ When the code embeds into ROM or flash, a system design process is locating these codes as a ROM image. _ Codes are permanently placed at the actually available addresses in the ROM. _ Embedded systems─ no separate program to keep track of the available addresses at different times during the running, as in a computer

Next step after linking─ use of a locator for the program codes and data in place of loader _ The locator is specified by the programmer as per available addresses at the RAM and ROM in target. _ Programmer defines the available addresses in embedded systems for loading to load and creating files for permanently locating the codes using a device programmer _ Uses cross-assembler output, a memory allocation map and provides the locator program output file. _ Locator program output is in the Intel hex file or Motorola S- record format. _ Uses the cross compile codes in different cross-compiled segments for (i)instructions, (ii) initialized values and addresses (iii) constant strings (iv) uninitialized data. _ Locates the I/O tasks and hardware device driver codes at the unchanged addresses. These are as per the interfacing circuit between the system buses and ports or devices.

[EEE-VVCET]

Page 43

REAL TIME OPERATING SYSTEM

UNIT-5

[EEE-VVCET]

Page 44

REAL TIME OPERATING SYSTEM

UNIT-5

[EEE-VVCET]

Page 45

REAL TIME OPERATING SYSTEM

UNIT-5

Getting Embedded Software into the Target System using Device Programmer Device programmer _ also called laboratory programmer _ A programming system for a device _ Device selectable _ Device may be a PROM or EPROM chip or a flash or a unit in a microcontroller or PLA, GAL or PLC. _ Selected device inserts into a socket _ Programmed (burned the codes) by transfer of the bytes for each address using the software at the HOS

Software of device programmer _ Runs at a host system _ The system interconnects with the socket and device programmer circuit usually through a serial port (UART or USB). _ Running at the host uses an input file containing the from the locator software output records _ File reflects the final design and has a boot program plus the compressed record, which the processor decompresses before the embedded system processor starts execution. _ Bootstrap program is the program to start up a system. _ An IDE incorporates the device programmer within it Burning _ A process that places the codes. _ Codes downloaded, according to ROM image (locator output) _ Burning done in the laboratory using a device programmer into an erased EPROM or EEPROM or PROM or Flash

[EEE-VVCET]

Page 46

REAL TIME OPERATING SYSTEM

UNIT-5

Programming Method of the Device Programmer _ A device cell array (at the address defined by A0 to A19 signals) stores the ‘0’s as per 0s at D0 to D7 when a strobe pulse of a few microseconds duration applied in the presence of a high voltage of 12V by the device programmer circuit. Programming Steps of the Device Programmer (i) Applies the A0 to A19 bits as needed at a selected address input of the array of cells. (ii) Applies as inputs, the D0 to D7 bits that are meant for that address (iii) Applies a high voltage to make programming feasible for the needed duration in microseconds. (iv) Applies a programming pulse for a sufficient duration to cause fusing of the desired links in the array, to convert a '1' to '0'. (v) Switches off high voltage (vi) Applies a next higher address than the previous one. (vii) Repeats the above steps (ii) to (iv) for writing (converting) the logic states of the D0 to D7 bits at the current instance at the new address, and (viii) Continues till a cell array at the last desired address programmed. Two approaches for the embedded system design device programmer (1) When the software development cycle ends then the cycle begins for the process of integrating the software into the hardware at the time when a system is designed. (2) Both cycles concurrently proceed when co-designing a time critical sophisticated system Software Hardware Tradeoff _ It is possible that certain subsystems in hardware (microcontroller), IO memory accesses, real-time clock, system clock, pulse width modulation, timer and serial communication are also implemented by the software _ A serial communication real-time clock and timers featuring microcontroller may cost more than the microprocessor with external memory and a software implementation. _ Hardware implementations provide advantage of processing speed Hardware implementation advantages (i) Reduced memory for the program. (ii) Reduced number of chips but at an increased cost. (iii) Simple coding for the device drivers. (iv) Internally embedded codes, which are more secure than at the external ROM (v) Energy dissipation can be controlled by controlling the clock rate and voltage Software implementation advantages (i) Easier to change when new hardware versions become available. (ii) Programmability for complex operations. (iii) Faster development time. (iv) Modularity and portability. (v) Use of standard software engineering, modeling and RTOS tools. (vi) Faster speed of operation of complex functions with high-speed microprocessors. (vii) Less cost for simple systems.

[EEE-VVCET]

Page 47

REAL TIME OPERATING SYSTEM

UNIT-5

Units to be choosen _ Processor ASIP or ASSP _ Multiple processors _ System-on-Chip _ Memory _ Other Hardware Units of System _ Buses _ Software Language _ RTOS (real-time programming OS) _ Code generation tools _ Tools for finally embedding the software into binary image Embedded System Processors Choice _ Processor Less System _ System with Microprocessor or Microcontroller or DSP _ System with Single purpose processor or ASSP in VLSI or FPGA

[EEE-VVCET]

Page 48

REAL TIME OPERATING SYSTEM

UNIT-5

Factors and Needed Features Taken into Consideration _ When the 32-bit system, 16kB+ on chip memory and need of cache, memory management unit or SIMD or MIMD or DSP instructions arise, we use a microprocessor or DSP. _ Video game, voice recognition and image-filtering systems− need a DSP. _ Microcontroller provides the advantage of on-chip memories and subsystems like the timers Factors for On-Chip Feature _ 8 bit or 16 bit or 32 bit ALU _ Cache, _ Memory Management Unit or _ DSP calculations _ Intensive computations at fast rate _ Total external and internal Memory up to or more than 64 kB _ Internal RAM _ Internal ROM/EPROM/EEPROM _ Flash _ Timer 1, 2 or 3 _ Watchdog Timer _ Serial Peripheral Interface Full duplex _ Serial Synchronous Communication Interface (SI) Half Duplex _ Serial UART _ Input Captures and Out-compares _ PWM _ Single or multi-channel ADC with or without programmable Voltage reference (single or dual reference) _ DMA Controller _ Power Dissipation Processor Sensitive _ Can have memory mapped IOs or IO mapped IOs. _ IO instructions are processor sensitive. _ Fixed point ALU only or Floating-point operations preetn _ Provision for execution of SIMD (single instruction multiple data) and VLIW (very large instruction word) instructions. _ Programming of the modules needing SIMD and VLIW instructions is handled differently in different processors. _ Assembly language− sometimes facilitate an optimal use of the processor’s special features and instructions. _ Advanced processors− usually provide the compiler or optimizing compiler sub-unit to obviate need for programming in assembly. Memory Sensitive _ Real-time programming model and algorithm used by a programmer depend on memory available and processor performance. _ Memory address of IO device registers, buffers, control-registers and vector addresses for the interrupt sources or source groups are prefixed in a microcontroller. _ Programming for these takes into account the addresses. _ Same addresses must be allotted for these by the RTOS. _ Memory-sensitive programs need to be optimized for the memory use by skillful programming for example, ARM Thumb® instruction set use

[EEE-VVCET]

Page 49

REAL TIME OPERATING SYSTEM

UNIT-5

ALLOCATION OF ADDRESSES TO MEMORY _ Program segments and device addresses _ Different sets and different structures of data at the memory _ Device, Internal Devices and I/O devices Addresses and Device Drivers Porting Issues _ Porting issues of OS _ I/O instructions _ Interrupt Servicing Routines _ Data types _ Interface specific data types _ Byte order _ Data Alignment _ Linked Lists _ Memory Page Size _ Time Intervals

Performance Metrics _ Performance Modeling for metric _ System Performance Index as Performance Metric _ Multiprocessor system performance as Performance Metric _ MFLOPs and DMIPS (Dhrystone/s) as Performance Indices as Performance Metrics _ Buffer Requirement, IO performance and Bandwidth Requirement as Performance Metrics Performance Accelerators _ Conversion of CDFGs into DFGs for example by using loop flattening (loops are converted to straight program flows) and using look-up tables instead of control condition tests to decide a program flow path _ Reusing the used arrays in memory, appropriate variable selection, appropriate memory allocation and de-allocation strategy • Using stacks as data structure when feasible in-place of queue and using queue in place of list, whenever feasible. _ Computing slowest cycle first and examining the possibilities of its speed-up. _ Code such that more words are fetched from ROM as a byte than the multibyte words Testing on Host Machine Host and Target Test Systems During Development Process • Two systems with different CPUs or microcontroller and hardware architecture. • One system─ host, generally PC or laptop or workstation. • Other system ─target, actual hardware for the embedded system under development

[EEE-VVCET]

Page 50

REAL TIME OPERATING SYSTEM

UNIT-5

Host and Target _ Target independent and target dependent code. _ Code has two parts: hardware independent code and hardware dependent code. _ Port and devices─ have fixed addresses on hardware Host _ Testing and debugging at each stage as well as at the final stage when the modules are put together. _ Test at initial stages─ at the host _ Host─ used to test hardware independent codes. _ Host ─ also used to run simulator _ Used to test hardware independent codes. _ Target ─ also used to run monitor

Testing Steps at Host Machine _ 1. Initial Tests─ each module or segment at initial stage itself and on host itself _ 2. Test data─ all possible combinations of data designed and taken as test data _ 3. Exception condition tests ─ all possible exceptions for the test _ 4. Tests-1: hardware independent code _ 5. Tests-2:scaffold software, software running on host the target dependent codes and which have same start of code and port and device addresses as at the hardware. _ Instructions– given from file or keyboard inputs. _ Outputs–at host’s LCD display and saves at File _ 6. Test Interrupt Service routines hardware independent part– sections of interrupt service routines are called, which are hardware independent and tested _ 7. Test Interrupt Service routines hardware dependent part _ 8. Timer tests─ Hardware dependent code timing functions, clock tick set, counts get, counts put, delay _ 9. Assert-Macro tests─ insert the codes in the program that check whether a condition or a parameter actually turns true or false. _ If it turns false─ the program stops. _ Use the assert macro at different critical places in the application program

[EEE-VVCET]

Page 51

REAL TIME OPERATING SYSTEM

UNIT-5

Simulator

Simulator • Uses knowledge of target processor or microcontroller, and target system architecture on the host processor. • First does cross compilation of the codes and place these into host system RAM. • Behavior of target system processor registers simulated

[EEE-VVCET]

Page 52

REAL TIME OPERATING SYSTEM

UNIT-5

• Uses linker and locator to port the cross compiled codes in RAM and functions like the code that would have run at the actual target system. • Simulates hardware units like emulator, peripherals, network and input-output devices on a host (PC (or workstation or laptop). • A simulator remains independent of a particular targeted system • Results expected from codes at target system RAM, peripherals, network and input-output devices obtained at the host system RAM • Helps in the development of the system before the final target system is ready with only a PC as the tool for development. • Simulators readily available for different processors and processing devices employing embedded systems Simulator Features _ Defines the processor or processing device family as well as its various versions for the target system. _ Monitors the detailed information of a source code part with labels and symbolic arguments as the execution goes on for each single step. _ Provides the detailed information of the status of RAM and ports (simulated) of the defined target system as the execution goes on for each single step. _ Provides the detailed information of the status of peripheral devices (simulated, assumed to be attached) with the defined system. _ Provides the detailed information of the registers as the execution goes on for each single step or for each single module. Monitors system response and determines throughput. _ The windows on the screen providing details _ Detailed information of the status of stack, devices and ports (simulated) of the defined microcontroller system _ Program flow trace as the execution continues. _ Trace─ the output of contents of program counter versus the processor registers. _ Trace of application software means an output of chosen variables in a function of stepping sequence _ Helps the window on the screen to provide the detailed meaning of the present command. _ Monitors the detailed information of the simulator commands as these are entered from the keyboard or selected from the menu _ Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints. _ Breakpoints and the trace together are the important testing and debugging tool. _ Facilitates synchronizing the internal peripherals and delays. _ Employs RTOS scheduler that preempts task. _ Simulates the inputs from the interrupts, the timers, ports and peripherals. So it tests the codes for these. _ Provides network driver and device driver support Simulator Possible Inabilities _ May not resolve timing issues and hardware dependent problems _ Processor speed at target processor may not be adequately mapped with the host for calculating time responses and calculating output instances and throughputs at the target. _ May not be able to take into account portability problems. _ For example, target system may have 8-bit data bus between RAM and unpipelined processor and host may be having pipelined processor and 32-bit bus

[EEE-VVCET]

Page 53

REAL TIME OPERATING SYSTEM

UNIT-5

_ A simulator may fail to show a bug from shared data as it arises from an interrupt in some particular situation only. _ For example, a long word in four registers loaded partly, and exactly at that moment the interrupt occurred. _ May not be able to simulate the ASICs and IP(s), embedded at the target system _ ASIC or IP core manufacturer may provide an alternative debugging tool _ ICE for the processor ARM7 or ARM9 emulates the ARM functions on host processor and system. Laboratory Tools

Hardware Diagnostic Laboratory Tools Hardware Diagnostic Laboratory Tools • Volt-Ohm meter─ useful for checking the power supply voltage at source and voltage levels at chips power input pins, and port pins initial at start and final voltage levels after the software run, checking broken connections, improper ground connections, and burnout resistances and diodes. • LED test ─ useful for testing port outputs and when using port conditions 1 or 0 for debugging a particular set of conditions Hardware Diagnostic Laboratory Tool • Logic Probe • Oscilloscope • Logic Analyser • Bit Rate meter • ICE • System Monitor Codes Use of Logic Probe • Simplest hardware test device. • Handheld pen like device with LEDs – Glows green for ‘1’ and red for ‘0’ • Important tool when studying the long port-delay effects (>1s). • Delay program tests the presence of system clock ticks Uses of Oscilloscope • Screen to display two signal voltages as a function of time • Displays analog as well as digital signals as a function of time • Noise detection tool • Mal-function detection of a sudden transitions between '0' and '1' states during a period. Uses of Logic Analyser • A powerful hardware tool for checking multiple lines carrying address, data and control bits, IO buses, ports, peripherals and clock. • Recognizes only discrete voltage conditions, '1' and '0'. • Collects, stores and tracks multiple signals and bus transactions simultaneously and successively. • Reads multiple input lines (24 or 48) and later displays, using this tool, each transaction on each of these on computer monitor (screen) observed

[EEE-VVCET]

Page 54

REAL TIME OPERATING SYSTEM

UNIT-5

• Also shows states on the horizontal axis instead of time in its state mode of display. • Displays the logic states of a particular line as a function of ‘0’ and ‘1’ on another line. • Catches intermittent bugs • Does not help on a program halt due to a bug. • Does not show processor register and memory contents, if the processor uses caches then a bus examination alone may not help. • Cannot modify the memory contents and input parameters and study their effects [simulator needed as that helps in studying these effects]

Logic Analyzer two modes of functioning _ One mode─ to show time on x-axis, and logic states of the clock signal, bus signals and other signals on y – axis. _ Second mode ─ to give address, data bus and other signal states from a trigger point to examine illegal opcodes, access in protected address space and other states as a function of a reference state. Use of Bit rate meter • A measuring device that finds numbers of ‘1’s and ‘0’ in the preselected time spans. • Measures throughput. • can estimate bits ‘1’s and ‘0’s in a test message and then use bit rate meter to find whether that matches with the message. DEVELOPMENT PROCESSES USING ICE

Using an Emulator or ICE • A circuit for emulating target system remains independent of a particular targeted system and processor • Emulator or ICE provides great flexibility and ease for developing various applications on a single system in place of testing that multiple targeted systems.

[EEE-VVCET]

Page 55

REAL TIME OPERATING SYSTEM

UNIT-5

Emulator _ Emulates MCU inputs from sensors _ Emulates controlled outputs for the peripheral interfaces/systems _ Emulates target MCU IOs and socket to connect externally MCU ICE • Means In-Circuit Emulator • Interface COM port of a computer • Emulates target MCU IOs • ICE socket connects MCU externally • Uses computer developed object files and hex files for the MCU • Uses debugger at the computer developed files for the MCU application Difference in Emulator and ICE • Emulator uses the circuit consisting of the microcontroller or processor itself. The emulator emulates the target system with extended memory and with codes downloading ability during the edit-testdebug cycles.

[EEE-VVCET]

Page 56

REAL TIME OPERATING SYSTEM

UNIT-5

• ROM Emulator emulates only a ROM. • ICE uses another circuit with a card that connects to target processor (or circuit) through a socket. Back support hardware package and ICE Subunits _ Interface circuit _ Socket _ External Memory _ Emulator-board display unit _ Twenty-keys pad _ Registers _ Connectors Target _ Target system keyboard _ Target system driver circuit _ Monitor codes Development processes using Monitor

Target Monitor • Computer (PC) interface commands • Command interpreter • Application codes down loaded from PC • Data System Monitor functions _ Monitor loads the application codes, also used for corrections in codes and then test the system. _ A command for download can download a new application codes into the monitor. _ A command for reset the program restarts the program. _ Monitor loads the application (in hex-file) from developing system (at host) that can also be modified later to correct the codes.

[EEE-VVCET]

Page 57

REAL TIME OPERATING SYSTEM

UNIT-5

_ A part of the monitor runs on host system. _ Debug monitor codes are downloaded along with the locator binary image. _ A write and a read command is used to correct or examine the codes at the memory addresses of the system _ Monitor controls (inserts, removes, modifies) breakpoints as per command from debugger. _ A breakpoint partitions the program into separate segments. When a program segment runs, then there is pause at breakpoint, then test the result observed after the run and examined, and then next segment is run. _ Breakpoints enable program test running between the different program segments. • To have controlled execution of instructions, application loading and codes correction _ Monitor controls (as per command from debugger) the execution of application at full speed, as well as by single stepping during debug phase. Target Commands • Download into monitor • Define Execution start address • Define Single step execute • Define Full speed execute • Set breakpoints • Reset breakpoints • Send selected codes/ IOs info for computer display Use of System Monitor Codes for Debugging • Downloaded codes in ICE may run a 'Power On Self Test' (POST) program on bootstrapping. • A ROM may also have a debug monitor. • GNU debugger gdb, - a downloadable freeware - may also provide the debug monitor codes for the system

[EEE-VVCET]

Page 58

Sign up to vote on this title
UsefulNot useful