0% found this document useful (0 votes)
5 views62 pages

ES Module 5

this consists of notes related to embedded system module 5

Uploaded by

REKHA R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views62 pages

ES Module 5

this consists of notes related to embedded system module 5

Uploaded by

REKHA R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 5

REAL-TIME OPERATING SYSTEMS

OS SERVICES

Goal:
The OS goals are perfection and correctness to achieve the following:

1. Facilitating easy sharing of resources as per schedule and allocations. Resources mean
processor(s), memory, I/Os, devices, virtual devices (e.g., pipes, sockets).system timer,
keyboard, displays, printer and other such resources, which processes (tasks or threads)
request from the OS. No processing task or thread uses any resource until it has been
allocated by the OS at a given instance.
2. Facilitating easy implementation of the application-program with the given system-
hardware. An application programmer for a system can use the OS functions that are
provided in given OS without having to write the codes for the services (functions) that
follow.
3. Optimally scheduling the processes on one (or more CPUs if available) and providing an
appropriate context-switching mechanism.
4. Maximizing the system performance to let different processes (tasks or threads) share the
resources most efficiently with protection and without any security breach. Examples of
security breach are tasks obtaining illegal access to other task-data directly without
system calls, overflow of the stacks into memory and overlaying of PCBs at the
memory.
5. Providing management and functions for the processes memory. Devices and I/Os and
other functions.
6. Providing management and organization function for the devices files and virtual devices
and I/Os.
7. Providing easy interfacing and management function for the network protocol and
networking.
8. Providing portability of application on different hardware configurations.
9. Providing interoprobability of application on different networks.
10. Providing a common set of interface that integrates various device applications through
the standard and open systems.

The OS goals are perfection, correctness, portability, imperability and providing a common
set of interfaces for the system, and orderly access and control when managing the
processes.

[Link]. of ECE, BGSIT 1


MODULE 5
User and Supervisory Mode Structure
• When using an OS, the processor in the system runs in two modes. There is clock,
called system clock. At every tick of the clock, there is an interrupt. On interrupt, the
system time updates, the system context switches to the supervisory mode from the
user mode. After completing the supervisory (kernel-space) functions, the system
context switches back to the user mode.
1. User mode: The user process is permitted to run and use only a subset of
functions and instructions in OS. This is done in the user mode either by sending
a message to a waiting process associated with the OS kernel or by initiating a
system call (call by an OS function. The use of hardware resources including
memory is not permitted without making the call to the OS functions. The OS
calls the resources by system call. User function call is distinct from a system
call, and is not permitted to read and write into the protected memory allotted to
the OS functions, data, stack and heap. This protected memory space is also
called kernel space. Hence execution of user functions calls is slower than the
execution of the OS functions (which run on system call. This is because of the
protected access to memory by the functions running in user-space.
2. Supervisory mode: The OS runs the privileged functions and instructions in the
protected mode and the OS (more specifically, the kernel) only accesses the
hardware resources and the protected area memory. [The term kernel means
nucleus. In the supervisory mode the kernel codes run in protected mode. Only a
system-call is permitted to read and write into the protected memory allotted to
the OS functions, data, stack and heap. The kernel space functions execute faster
than the user-space functions.

[Link]. of ECE, BGSIT 2


MODULE 5
Structure:
A system can be assumed to have a structure as per Table 1.

Table 1 Layered Model of the System

Kernel:
• The OS is the middle layer between the application software and system hardware. An
OS includes some or all of the following structural units.
1. Kernel with file management and device management as part of the kernel in the
given OS.
2. Kernel without file management and device management as part of the kernel in
the given OS and any other needed function not provided for at the kernel.
• The kernel is the basic structural unit of any OS in which the memory space of the
functions, data and stack are protected from access by any call other than the system-
call.
• Table 2 gives the functions (services) in the kernel, they are as per the OS design.
• The kernel has management functions for processes, resources, ISRs, ISTs, files,
device drivers and 10 subsystems and network subsystems.

[Link]. of ECE, BGSIT 3


MODULE 5
TABLE 2 Kernel Services in an operating system (OS)

[Link]. of ECE, BGSIT 4


MODULE 5
PROCESS MANGEMENT:
Process Creation:
• At reset of processer in a computer system, an OS is initialized first, and then a
process, which can be called initial process, is created initialization of OS.
• Then the OS is started and that runs an initial process.
• Processes can be created hierarchically.
• The initial process creates subsequent processes OS schedules the processes and
provides for context switching between the processes and threads.
• Creation of a process means specifying the resources for the process and address
success (monitory blocks) for the created process, stack, data and heap and placing
the processional information at PCB.
• The process manager allocates a PCB (or TCB in case tsk represents a process) when
it creates the process and later manages it.
• The other OS units can send the manages the queries for the process when repaired.
PCB is process descriptors used by the process manager.
• A PCB or TCB describes the following
1. Content Processor status word, PC. SP and other CPU registers at the instant of
the best instruction run executed when the process was left and the processor
switched to another process
2. Process stock pointer
3. Current store: Is it created, activated or spawned? Is it running? By it blocked?
(Spawn means create and activate)
4. Addresses that are allocated and that are presently in use.
5. Pointer for the parent process in case there exists a hierarchy of the processes.
6. Painter to a list of daughter processes (processes lower in the hierarchy)
7. Painter a list of resources, which are usable (consumed) only once. For example
input, memory buffer or pipe, mailbox message, semaphore (there may be
producers and consume of these resource
8. Pointer to a list of resource type usable more than once: A resource type example
is a memory block another example is a 10 port. Each resource type will have a
count of these types. For example, the number of memory blocks or number of I0
ports
9. Pointer to queue of messages. It is considered as a special case of resources that
are usable once. It is because messages from the OS also queue up to be
controlled by a process.
10. Pointer to access permissions descriptor for sharing a set of resources globally,
and with another process.
11. ID by which identification is made by the process manager.

[Link]. of ECE, BGSIT 5


MODULE 5
Management of the Created Processes:
• A process (or thread or task) is considered a unit in which sequential running is
feasible only under the control of an OS, with each process having an independent
control block (descriptor of the process at an instant).
• Process manager is a unit of the OS that is the entity responsible for controlling a
process execution.
• Process management enables process creation, activation, running, blocking,
resumption, deactivation and deletion.
• A process manager facilitates the following.
o Each process of a multiple process (or multitasking or multithreading) system
is executed such that a process state can switch from one to another.
o A process does the following sequential execution of the states: 'created",
"ready or activate", "spawn' (means create and activate), "running", "blocked'
or 'suspended", "resumed and finished' and 'ready' after finish' (when there is
an infinite loop in a process) and finally deleted'. Blocking and resuming can
take Place several times in a long process. The different OSes make the
provisions for possible states between creation and deletion differently.
• The LCD display can be used only by one task or thread at an instance. A running
process requests by two methods, which are listed in Table.3.
• The process manager
i. makes it feasible for processes sequentially (or concurrently) execute or block
when needing a resource and to resume when it becomes available;
ii. implements logical link to the resource manager for resources management
(including scheduling of processes on the CPU);
iii. allows specific resources sharing between specified processes only:
iv. allocates the resources
v. as per the resource allocation mechanism of the system and
vi. manages the processes and resources of the given system.

Table 3 Request for a Resource or Operating System (OS) Service by a Running Process

[Link]. of ECE, BGSIT 6


MODULE 5
Timer Functions:
• A real-time clock (hardware timer timeout) in the system interrupts the system with
each tick, which occurs a number of times in 1 second. An interrupt on a tick can be
called SysC1kIntr (system real-time clock timer interrupts). An OS provides a number
of OS timer functions. These functions use SysCikinir interrupts on the clock ticks.
The periodic SysCikintr interrupts on this tick is used by the system to switch to the
supervisory mode from the user mode on every tick.
• The following are the steps.
1. Before servicing of SysCIkIntr, the context of presently running task or thread
saves on the TCB data structure.
2. SysC1kIntr service routine calls the OS.
3. The OS finds the new messages or IPCs, which are received from the system call
by the OS event control blocks for IPC functions.
4. The OS either selects the same task or selects a new task or thread [by pre-emption
in case of pre-emptive scheduling] and switches the context to the new one.
5. After return from the interrupt, the new task runs from the code, which was
blocked from running earlier.
• Each OS has a function for defining the OS ticks per second, which defines
generation of the SysC1kIntr interrupts and which in turn provides the timer functions
of the OS. The function thus defines the SysCIkintr interrupt intervals after initiating
the ticks. The functions thus also define the period after which the system calls the
ISR on the SysCikintr interrupts and switches to the OS supervisory mode functions
listed before.
• The number of ticks if made large. Then the frequent running of the OS codes to be
run on SysCikIntr interrupt takes place because the context switching to the
supervisory mode takes place too frequently. The number of ticks, if made small, the
total time spent on SysCikIntr interrupts per second reduces, but then system time
accuracy for the OS timer functions becomes small.
• Table 4 gives the example of RTOS timer functions and the actions on calling
functions.
Table 4 Exemplary Timer Functions

Example 3:

(a) # define OS TICK PER SEC 100/µCOS-II function to define the number of ticks per
second = 100 before the beginning of main () and initiating of OS by OSInit () function/. (b)
[Link]. of ECE, BGSIT 7
MODULE 5
OSTickInit ()/icons-II function to initiate the defined number of ticks per second after the
beginning of the first task and creation of all the tasks to which the context will be switched
by the OS on the tick. It initiates SysC1kIntr interrupts every 10 MS as OS ticks/s = 100 "/.

Event Functions:
• In case of IPC, there is waiting for only one semaphore post event or mailbox
message-posting event. Provisioning of event functions in an OS offers an advantage
that there can be wait for more than one event and the events can also be from the
different tasks or ISRs.
• The queue messages can be from the different tasks or ISRs. Queues can offer the
same advantage that there can be wait for more than one messages. However, the OS
functions for queue execute in more time than the event-functions. Same OS supports
and some do not support event functions. The event-functions enable OS actions after
a group of events. The OS event functions can be understood as follows: There is an
event register. It has 8 or 16 or 32 event-flags, which form the groups. Each bit of the
group in the register corresponds to one event flag in a set of flags.
• An event register creates using an OS function. OS EventCreate (). An event register
can be divided into groups, each group assigned to different tasks. For example, a 16-
bit register can be divided into four groups. Group 0 is from bit 0 to bit 3. group I
from bit 4 to bit 7. Group 2 is from bit 8 to bit 11 and group 3 is from bit 12 to bit 15.
An OS function, OSEventQuery() queries an event register to find the event register
existence and its contents. An event register deletes using an OS function,
OSEventDelete ().
• Each event sets one of the bits at the event register using the SET (event Flag)
function. Event flag in the register can be set by an ISR or task. CLEAR (event Flag)
cigars the flag in the event register. An event flag can be cleared by an ISR or task.
• A task can use the WAIT ALL function for the occurrences of setting all the event
flags in a group. [Wait till AND operation between all flags in the group equals to
true. The task can use WAIT ANY function for an occurrence of setting of any of the
event flags in the group. [Wait till OR operation between all flags in the group equals
to true.]

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

• The memory manager of the OS has to be secure, robust and well protected. There
must be control such that there are no memory leaks and stack overflows Memory
leaks mean attempts to write in the memory block not allocated to a process or data
structure. Stack overflow means that the stack exceeds the allocated memory block(s)
when there is no provision for additional stack space. Table 5 gives memory-
management strategy.

[Link]. of ECE, BGSIT 8


MODULE 5
Example 4:
An OS provides for dynamic memory allocation and de-allocation functions. Dynamic
memory allocation is used for creating memory address space for a buffer or a messages
queue or some other purpose during execution of a task. Dynamic memory de-allocation is
used for freeing the memory taken up for the buffer during execution of the task.
Consider fragmented physical memory allocations. Fragmented means that memory
addresses in two variable-size blocks of a process are not continuous. When a block of
memory address is allocated, the time is spent in first locating the next free memory address
before allocating that to the process. A standard memory allocation scheme scans a linked
list of indeterminate length to find a suitable free memory block. When one allotted block of
memory is de-allocated, the time is spent in first locating the next allocated memory block
before de-allocating 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 unpredictable task-performance (run-
time).

RTOS UCOS-II provides for memory partitioning. A task must create a memory partition
or several memory partitions by using function OSMemCreate (). Then the task is
permitted to use the partition or partitions. A partition has several memory blocks. A task
gets a memory block or blocks from the partition by using function OSMemGet (). A task
releases a memory block or blocks to the partition by using function OSMemPut ().
Therefore, the task consists of several fixed size memory blocks. The fixed size memory
blocks allocation and de-allocation time takes fixed time (deterministic). Therefore, it leads
to a predictable task-performance.

Table 5 Memory Managing Strategy for a System

Managing Strategy Explanation


Fixed blocks allocation Memory address space is divided into blocks with processes
having small address spaces getting a lesser number of blocks and
processes with big address spaces getting a larger number of
blocks.
Dynamic blocks Memory address space is divided into fixed blocks as above and
allocation then later the memory manager later allocates variable size blocks
(in units of say 64 or 256 bytes) dynamically allocated from a free
(unused) list of memory blocks description table at the different
computation phases of project.
Dynamic page Memory has fixed sized blocks called pages and the memory
allocation manager MMU (memory management units) allocates the pages
dynamically with a page descriptor table.
Dynamic data memory The manager allocates memory dynamically to different data
allocation structures like the nodes of a list, queues and stacks.

Dynamic address The manager dynamically allocates the addresses initially bound
relocation to the relative addresses. It adds the relative address to address
with relocation register. The memory manager now dynamically
changes only the contents of relocation register. It also takes into
account a limit-defining register so that the relocated addresses are
within the limit of available addresses. This is also called run-time
dynamic address binding.

[Link]. of ECE, BGSIT 9


MODULE 5
Multiprocessor memory The memory adopts an allocation strategy either shared with tight
allocation coupling between two or more processors or shared with loose
coupling or multisegmented allocations

Memory protection to Memory protection to the OS functions means that the system call
OS functions (call to an OS unction) and function call in user space are distinct.
The OS function code. Data and stack are in the protected memory
area. It means that when a user function call attempts to write or
read in the exclusive memory space allocated to the OS functions,
it is blocked and the system generates an error. The memory of
kernel functions is distinct and can be addressed only by the
systems calls. The memory space is called kernel space.
Memory protection Memory protection to the tasks means that a task function call
among the tasks cannot attempt to write or read in the exclusive area of memory
space allocated to another task. The protection increases the
memory requirement for each task and also the execution. time of
the code of the task.

• The memory manager manages the following:


i. use of memory address space by a process.
ii. specific mechanisms to share the memory space.
iii. specific mechanisms to restrict sharing of a given memory space and
iv. Optimization of the access periods of a memory by using an hierarchy of memories
(caches, primary and external secondary magnetic and optical memories).
Remember that the access periods are in the following increasing order: caches,
primary and external secondary magnetic and then optical.

The memory manager allocates memory to the processes and manages it with appropriate
protection. There may be static and dynamic allocations of memory. The manager
optimizes the memory needs and memory utilization. An RTOS may disable the support to
the dynamic block allocation, MMU support to the dynamic. Page allocation and dynamic
binding as this increases the latency of servicing the tasks and ISRs. An RTOS may or may
not support memory protection in order to reduce the latency and memory needs of the
processes.

DEVICE, FILE AND IO SUBSYSTEMS MANAGEMENT


Device Management

• There are number of device drive ISRs for each device in a system, each driver-
function of a device (e.g. open, close, read) calls a separate ISR. Device manages
(inside or outside the kernel space) is the software that manages these for all. When
device driver functions are a part of the OS (inside or outside the kernel space), the
device manager effectively operates and adopts appropriate strategy for obtaining
optimal performance for the devices.
• The manager coordinates between application process, driver and device controller. A
process sends a request to the driver functions by an interrupt using SWI: and the
driver provides the actions on calling and executing the ISR. The device manager

[Link]. of ECE, BGSIT 10


MODULE 5
polls the requests at the devices and the actions occur as per their priorities. The
device manager manages IO interrupt (requests) queues. The device manager creates
an appropriate kernel interface and API, and that activates the control register-specific
actions of the device. The device controller is activated through the API and kernel
interface. An OS device manager provides and executes the modules for managing the
devices and their driver ISRs.
1. It manages the physical as well as virtual devices like the pipes and sockets
through a common strategy.
2. Device management has three standard approaches to three types of device
drivers:
i) programmed I/Os by polling the service need from each device:
ii) interrupt(s) from the device driver ISR and
iii) DMA operation used by the devices to access the memory. Most common is
the use of device driver ISRs.
3. A device manager has the functions given in Table 6.

Table 6 Functions of a Device Manager

Function Actions
Device detection and Provides the codes for detecting the presence of various
addition devices, then adding(initializing, configuring and testing)
them for the use of OS device driver functions. A
manager can provide for tracking the hardware inventory
(list of devices present in the system and connected to the
system).

Device deletion Provides the codes for denying the device resources.

Device allocation and Allocates and registers the port fit may be a register or
registration memory) addresses for the various devices at distinctly
different addresses and also includes codes for detecting
any collision between them.

Detaching and Detaches and deregisters the port (it may be a register or
deregistration memory) addresses for the various devices at distinctly
different addresses and also includes codes for detecting
any collision between existing addresses in case of
addresses reallocation to the remaining attached
(registered) devices.
Restricting device to a Restricts a device access to one process(task) only, at an
specific process instant.
Device sharing Permits sharing of access of a device to the set of
processes, but to one process (task) at an instant.
Device control A manager can also provide for remote control of the
devices from the remote server at the service provider.
(For example, mobile devices with server at the service
provider)
Device access management (i) sequential access, (ii) random access, (iii) semi-
random access. (iv) serial communication may be by
UART or USB, and (v) 4 (or more) serial bits in parallel

[Link]. of ECE, BGSIT 11


MODULE 5
during IOs (for example, SDIO). The device manager
provides the necessary interface.

Device buffer management Device hardware may merely have a single byte buffer, or
double buffer or 8-byte buffer. A device buffer manager
uses a memory manager to buffer the I/O data streams
from the device that sends the data and manages
computations without wait while the buffer receives the
data at a slow rate. Also used are the multiple buffers and
producer-consumer-type bounded buffers.
Device queue. circular- Device IO data streams from the device can be organized
queue or blocks of queue as the queues, circular queues and blocks of queues.
management

Device driver A manager manages the device drivers. A device driver


or a software driver is the software for interface with the
device hardware through the buses on the one hand and
for interface with the OS and application on other hand.
The software commands for read and write enables the
read and write functions through the ISRs called by using
the SWIs. The interface software to OS enables the
creation, connection, binding, opening and closing of the
device.
Device drivers updating and A manager can also provide for updating the driver
uploading of new device software from the Internet and uploading the new device
functions functions, which become available at a later date.

Backup and restoration A manager can also provide for the backup and
restoration for drivers.

Table 7 gives the set of OS command functions for a device.

Table 7 Set of Command Functions for Device Management

Commands Action(s)
create and open create is for creating and open is for creating (if not
created earlier) and configuring and initializing the
device.
write Write into the device buffer or send output from the
device and advance the pointer (cursor).

read Read from the device buffer or read input from the
device and advance the pointer (cursor).

ioctl Specified device configured for specific functions and


given specific close and delete parameters.

Close and delete close is for de-registering the device from the system
and delete is for close (if not closed earlier) and
detaching the device.

[Link]. of ECE, BGSIT 12


MODULE 5
The ioctl () has three arguments for the device-specific parameters.

1. First argument: Defines the chosen device and its functions by passing as argument,
the device descriptor (a number),
2. Second argument: Defines the control option or use option for the IO device. Network
devices control by defining baud rate or other parameters. Its use is as per function
defined as a second argument. Controlled device will be according to the first
argument.
3. Third argument: Values needed by the defined function are at the third argument.

Example 5:
Status ioctl (fd. FIOBAUDRATE. 19.200) is an instruction in RTOS VxWorks. The fd is the
device descriptor (an integer returned when the device is opened) and FIOBAUDRATE is a
pointer for IO baud rate function that takes value of baud rate = 19.200 from third argument.
This configures the device for operation at the 19.200-baud rate.

• A device driver ISR uses several OS functions. Examples are as follows: intlock() to
disable interrupts system, intUnlock () to enable interrupts intConnect() to connect a
C function to an interrupt vector (the interrupt vector address for a device ISR points
to a specific C function). Function intContext () finds whether interrupt is called when
an ISR was in execution.
• UNIX OS makes it feasible for devices and files to have an analogous implementation
as far as possible. A device has open (), close (), read(), write() functions analogous to
a file open, close, read and write functions. APIs and kernel interfaces in BSD
(Berkley sockets for devices) UNIX are open. [Link] and write. The following are
the in-kernel commands: (i) select. which is to first check whether a read or write will
succeed. (ii) ioctl to transfer driver-specific information to the device driver. (iii) stop
to cancel the output activity from the device. (iv) strategy to permit a block mad or
write or character read or write.

The device manager initializes controls and drives the physical and virtual devices of the
system. The main classes of devices are char devices and block devices. Device driver
functions may be similar to file functions, open, read. I seek, write and close.

File System Organization and Implementation


• A tile isa named entity on a magnetic disk, optical disk or system memory. A file
contains the data, characters and texts. It may also have a mix of these. Each OS may
have differing abstractions of a file.
i. A file may be named entity that is a structured record as on a disk having
random access in the system.
ii. A file may be unstructured record on a RAM analogous to a disk and may also
be either separately called RAM disk or Simply, a file (virtual device).
iii. A file may be an unstructured record of bits or bytes.
iv. A file device may he a pipe-like device.
• It is necessary to organize the files in a systematic way and to have a set of command
functions. Table 8.8 eves these functions for POSIX file system.

Table 8 Set of Command Functions in the Portable Operating System Interface (POSIX) File
System

[Link]. of ECE, BGSIT 13


MODULE 5
Command in POSIX Action(s)
open Function for creating the file

write Writing the file

trad Reading the file

seek List seek or set the file Setting the pointer for the appropriate place in the file for the
pointer next read of write

close Closing the file.

• Should a file having integers differ from a file having bytes? Should a file having
bytes differ from a file having characters? Due to the differing approaches to device
and file management interfaces, the development of a set of standard interfaces
becomes must. Only then can systems he portable. A standard set of interfaces is
called POSIX. from IEEE POSIX stands for portable operating system interface
standard for coding programs when using the multiple threads. The X after I is
because of the interfaces being similar to the ones in Unix. It is according to the
definitions at the AT & T UNIX System V Interface. POSIX defines the functions:
open, close. cad, write, Iseek and fentl. Function Iseek is to move the pointer position
in the byte stream. Function fent is for ile control. The POSIX standard for file
operations are as the operations on a finear sequence of bytes.
• Window NT assumes a file as the named entity for a record of bytes placed
sequentially and the OS has the command functions, createFile, ReadFile. WriteFile
and SetFilePointer, and CloseHandle for creating a file. reading a file, writing a file
and setting the file pointer from the present to a new location. A file in Unix has
open(1, close ), read (), write () functions analogoes to a device,open, close, read and
write functions. The BSD Unix interface differs slightly from Unix.

There are two types of file systems

1. Block file system. Its a Its application n generates records to be saved into the
memory. These are first structured f the file. from the start to the end of the file
pointer (byte index) points to a byte from the start index=0 to N-I in a file of N bytes,
Just as each process has a processor descriptor (PCB); a file system has a data
structure, called file descriptor into a suitable format and then translated into block
streams. A file pointer (record) points to a block
2. Byte stream file system. Its application generates record streams. These streams are to
be saved into are first t structured into a suitable format and then translated into byte
streams. A the memory. These are (Table 8.9). The structure differs from one file
manager to another. File descriptor, fd. for a file is an integer, which returns on
opening a file. fd points to the data structure of the file. fd is usable till the closing of
the file.

Table 9 Data Structure of File Descriptor in a Typical File System

File Descriptor Meaning


[Link]. of ECE, BGSIT 14
MODULE 5
Identity Name by which a file is identified in the application.

Creator or owner Process or program by which it was created


State A state can be closed, archived (saved), "open executing
file or "open file for additions”
Locks and protection fields O_RDWR file opens with read and write permissions,
O_RDONLY file opens with read only permissions. O
WRONLY file opens with write only permissions
File info Current length, when created, when last modified, when
last accessed
Sharing permission Can be shared for execution, reading or writing
Count Number of directories referring to it
Storing media details Blocks transferable per access.

I/O Subsystems:
1/O ports are the subsystems of OS device management systems. Drivers communicate with
the many devices that use them. I/O instructions depend on the hardware platform. I/O
systems differ in different OSes. Subsystems of a typical 10 system are as given in Table 10.

There are two types of IO operations-synchronous and asynchronous. There may be separate
functions for synchronous and asynchronous operations in an RTOS. In case of traditional
OS. Only synchronous IOs may be supported.

Synchronous IO operations are at certain fixed data transfer rates. Therefore, a task (process)
blocks tills till completion of the 10. For example, a write function, write() for 1 kB data
transfer to a buffer. Synchronous IO operation means once synchronous 10 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.

Table 10 Input/Output (I/0) Subsystem in a Typical I/0 System in an Operating System (OS)

Subsystems
Action(s) and Layers between the Subsystems
Hierarchy
Application An application having an I/O system. There may also be a
sublayer between the application and I/O basic functions

I0 basic functions These are device-independent OS functions, for example.


file system functions for read and write, buffered 10 or file
(block) read and write functions. There may also be a
sublayer between the basic I/O functions and I/O device-
driver function.
I0 device driver These are device-dependent OS functions. A driver may
functions interface with a set of library functions, for example, for
serial communication
Device hardware or port Serial device or network.
or IO interface card

[Link]. of ECE, BGSIT 15


MODULE 5
Asynchronous IO operations are at the variable data transfer rates. It provisions for a process
priority not blocked during the IOS.

Example 6:

POSIX has the following asynchronous functions: aio_read () and aio_write for the
asynchronous read and write in an I/O system. Therefore, an aio_read () and aio_write () do
not block the task till completion of the 10. ain_list() is to initiate a list of certain maximum
asynchronous I/O port requests. ain_error (). aio_cancel, aio suspend are functions for
asynchronous 10 error status retrieval and for cancelling and suspending I/O operations,
respectively. Suspension is till the next port device interruption or till a timed out aio_return
returns the status of completed operations.

I/O subsystems are an important part of OS services. Examples are the UART access and the
parallel port access. There are synchronous and asynchronous 10s. A task gets blocked during
the synchronous IOs, for example, fread() or write (). RTOSes support asynchronous IOs. for
example, aio read() and aio_write also in order to not to block a task during the IOs.

Interrupt Routines in RTOS Environment and Handling of Interrupt Source


Calls:
• In a system, the ISRs should function as following.
1. ISRs have higher priorities over the OS functions and the application tasks. An ISR
does not wait for a semaphore, mailbox message or queue message.
2. An ISR does 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 accept function for
these events can be used.
• There are three alternative systems for the OSes to respond to the hardware source
calls from the interrupts. Figure 1(a-c) show the three systems. The following sections
explain the three alternative systems in three
• OSes for responding to a hardware source call on interrupts.

[Link]. of ECE, BGSIT 16


MODULE 5

Fig. 1 (a), (b), (c) Three alternative systems in three real-time operating systems for
responding to a hardware source call on interrupts

Direct Call to an ISR by an Interrupting Source and ISR Sending an ISR


Enter Message:
• Figure 1(a) shows the steps. On an interrupt, the process running at the CPU is
interrupted and the ISR corresponding to that source starts executing (step 1). A
hardware source calls an ISR directly. The ISR just sends an ISR enter message to the
OS (step 2)
• OS is simply sent an ISR enter message (ISM) from the ISR in step 2. Later the ISR
code can send into a mailbox or message queue (step 3) but the task waiting for the
mailbox or message queue does not start before the return from the ISR (step 4). The
ISR enter message in step 2 is to inform the OS that an ISR has taken Control of the
CPU. The ISR continues execution of the codes needed for the interrupt service till the
ISR exit message is sent just before the return (step 4).

[Link]. of ECE, BGSIT 17


MODULE 5

Fig. 1 (a), (b), (c) Three alternative systems in three real-time operating systems for
responding to a hardware source call on interrupts

• There are two functions, ISR and OS functions, in two memory blocks. An i-th
interrupt source causes ith ISR, ISR_i to execute. The routine sends an ISR enter
message to the OS. The message is stored at the memory allotted for OS messages.
When the ISR finishes, it sends ISR exit to the OS and there is return and either there is
the execution of interrupted process (task) or rescheduling of the processes (tasks). OS
action depends on the event messages, whether the task waiting far the event is a task of
higher priority than the interrupted task at the interrupt.
• On certain OS, there may be a function OSISRSemPost (). The ISR semaphore is a
special semaphore. which OSISRSemPost () posts and on return from the OS to be
taken by the calling ISR itself. OS ensures that OSISRSemPost executing ISR is
returned after any system call from the ISR.

Example 9

Consider the RTOS COS-II. Assume that a microcontroller has a hardware timer, which is
programmed to interrupt every 10 ms. The microcontroller on timer interrupt calls and PC
changes to an ISR vector address. ISR_Timer_Addr. At ISR_Timer_Addr. there is a routine
ISR Timer for servicing the timer interrupt. ISR_Timer first executes OSIntEnter () just after
the start of ISR_Timer is called. ISR Timer then executes OSIntExit () before the return code.

The OSIntEnter() sends the message to the RTOS that there should be context-switch and
return from the ISR only after any system call is made by the ISR or until the OSIntExit ()
executes in the ISR code. Any task waiting for the post of semaphore or mailbox message or
queue message should not start on execution of the post function within the ISR or in any
other task or ISR. RTOS schedules that later on return from ISR.

The multiple ISRs may be nested and each ISR of low priority sends high priority ISR
interrupt message(ISM) to the OS to facilitate return to it on the completion and return from
the higher priority interrupt. Nesting means when an interrupt source call of higher priority,
for example, system real-time clock interrupt SysC1kIntr) occurs, then the control is passed
to higher priority SysC1kIntr and on return from the higher priority the lower priority ISRS
[Link]. of ECE, BGSIT 18
MODULE 5
or tasks starts executing. The number of ISRs can be nested with execution order in sequence
to their priorities. Each ISR on letting a higher priority interrupt call sends the ISM (step 4)to
the RTOS.

There is common stack for the ISR nested calls, similar to the nested function calls.

RTOS First Interrupting on an Interrupt, then OS Calling the Corresponding ISR

• Figure 1 (b) shows the steps. On interrupt of a task. say. k-th task. the OS first gets the
hardware source call step 1) and initiates the corresponding ISR after saving the
present process status (or context) (step 2). The called ISR (step 3) during execution
then can post one or more outputs (step 4) for the events and messages into the
mailboxes or queues
• Assume that there are the routine (i-th ISR) and two processes (OS and j-th task) in
three memory blocks other than the interrupted k-th task. An i-th interrupt source
causes the OS to get the notice of that. then after step 1 it finishes the critical code till
the pre-emption point and calls the i-th ISR ISR executes (step 3) after saving the e
context (step 2) onto a stack. The preemption point is the last instruction of the critical
part of the presently running OS function, after which the ISR being of highest
priority is called. The ISR in step 4 can past the event or mailbox message(s) to the
OS for initiating the j-th task or k-th task after the return (step 5) from the ISR and
after retrieving the j-th or k-th task context.
• The events or mailbox messages are stored at the memory allotted for OS messages.
The OS initiates the j-th task (if is of higher priority than the interrupted task k) or
runs the interrupted task k
• The ISR must be short and it must simply post the messages for another task. This
task runs the remaining codes whenever it is scheduled (according to priorities). OS
schedules only the tasks (processes) and switches the contexts between the tasks only.
ISR executes only during a temporary suspension of a task.
• OS may provide for nesting or an OS may provide for the ISRs such that the OS
initiates running of the ISR calls from a priority ordered FIFO.
• The system priorities are ISRS and then tasks (or ISTs). IST is just a task initiated on
signal or message from an ISR (for example, task j in above example).

Example 10

Each device event has the codes for an ISR, which executes only on scheduling by the RTOS
and provided an interrupt is pending for its service. Consider mobile PDA device example.
The 5 steps for the interrupt servicing by first interrupting the RTOS process are as follows:

Assume that using RTOS. 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.

Let a touch screen event occur, which means the user of the mobile device taps the screen at
a select icon or menu (step 1). After saving context of current process (step 2) the OS sends
the signal on behalf of the ISR handler to the initiate ISR_TouchScreen (step 3). An interrupt
service thread or a Task TouchScreen Input IST_TouchScreen waits using a function OS
[Link]. of ECE, BGSIT 19
MODULE 5
eventPend () for message (an object, such as semaphore, mailbox or queue message) (step 4)
from the ISR_TouchScreen. The IST executes as per its priority Task or IST
_TouchScreenPriority among the other pending ISTs or tasks before it starts executing.

Before return from the ISR_TouchScreen, it sends a message to the kerel using a OS
ISR_Exit() just before the end of the codes in the ISR_TouchScreen (step 5). The
ISR_TouchScreen can be restarted on the next interrupt event and gets ready for the next
hardware event of tap on the screen.

RTOS First Interrupting on an Interrupt, then RTOS Initiating the ISR and then an
ISR

An RTOS can provide for two levels of ISRs, a fast-level ISR. FLISR and a slow-level ISR
(SLISR). The FLISK 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. 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 a deferred procedure call (DPC) of the ISR. An i-th IST is a thread to
function interrupt source call.

Figure 1(c) shows seven steps on the interrupt. On interrupt, the RTOS first gets the hardware
source call 1) and initiates the corresponding ISR after finishing the critical section and
reaching the pre (step) emption point and then saving the processor status (or context) (step
2). The ISR executes the device- and platform-dependent code (step 3). The ISR at the start
can mask (disable) further pre-emption from the same or other hardware sources. The ISR
during execution then can send one or more outputs for the events and messages into the
mailboxes or queues for the ISTS (step 4). The IST executes the device and platform-
independent code. The ISR just before the end, unmasks (enable) further pre-emption from
the same or other hardware sources (step 5).

There are the ISRs and number of ISTS, RTOS and tasks in the memory blocks other than the
interrupted task. Any interrupt source causes the RTOS to get the notice of that, then
completes the critical code till the pre-emption point and calls the ISR. ISR executes after
saving the context onto a stack. The ISR can post message(s) into the FIFO for the IST(s)
after recognizing the interrupt source and its priority. The ISTs jn the FIFO that have received
the messages from the ISR(s) executes (step 6) as per their priorities on return (step 5) from
the ISR. The ISR has the highest priority and pre-empts all pending ISTs and tasks.

When no ISR or IST is pending execution in the FIFO. the interrupted task runs on return
(step7).

The ISRs must be short, run critical and necessary codes only, and then they must simply
send the initiate all or messages to ISTs into t FIFO. It is the IST. which runs the remaining
codes as per the priority-bused schedule. The system priorities are in order of ISRS, ISTs and
tasks. The ISTs are SLISRS running device independent codes as per the device priorities on
signals (SWIs) from the ISR The ISTs run in the kernel space.

The ISTs do not lead to priority inversion and have the priority inheritance mechanism.

[Link]. of ECE, BGSIT 20


MODULE 5
RTOS schedules the ISTS and tasks (processes) and switches the contexts between the ISTS
and tasks

Example 11
Consider Mac OS X. The Mac OS X is RTOS for the mobile device, for example, iPod. An
interrupt handler first receives the primary interrupt and then it generates a software
interrupt known as a secondary interrupt. The secondary software interrupt is sent to initiate
an IST.
The OS does not receive the actual interrupt but the low level process intercepts the interrupt.
It calls a low-level (hardware level) ISR, LISR. It resets the pending interrupt bit in the device
interrupt controller and calls a device-specific ISR, say, DISR, The DISR, posts a message to
an IST, specific to the device. The message notifies to the IST, that an interrupt has occurred,
and then the DISR, returns to LISR. LISR resets another pending interrupt bit in the device
interrupt controller and calls the another device-specific ISR. say, DISR
When no further interrupts are pending, the OS control returns to the currently executing
thread. which was interrupted and when the OS passed control to the LISR.
The IST, are scheduled by the OS. the IST, finds that the SWI has occurred, it starts and run
he codes. ISTs run as if a thread is running.

An RTOS uses one of the three strategies on interrupt calls: (i) an ISR servicing directly
after merely informing the RTOS at the start of ISR: (ii) kernel intercepting the call and
calling the corresponding SRs and tasks, RTOS kernel schedules only the tasks (processes)
and ISR executes only during a temporary suspension of the task by the RTOS: (iii) kernel
intercepting the call and calling the ISR. Which initiates and queues the calls into a
priority FIFO, The ISR signals the SWs for the ISTs. The RTOS kernel schedules the ISTs
as priority queue and then tasks processes as per the priority queue.

REAL-TIME OPERATING SYSTEMS


RTOS is multitasking OS for the applications needing meeting of time deadlines and
functioning in real e constraints. Real-time constraint means constraint on time interval
between occurrence of an event and system-expected response to the event. RTOS-software
has the OS services listed in Table 11. These enable design of software for a large number of
embedded systems.

An RTOS is an OS for response time-controlled and event-controlled processes. The


processes have predictable latencies. An RTOS is an OS for the systems having the real
timing constraints and deadlines the tasks, ISTs and ISRs.

Table 11 Real-Time Operating System (RTOS) Services

Function Activities
Basic 05 functions Process management, resources management, device
management, I/O devices subsystems and network devices and
subsystems management.
Process priorities User-level priorities allocation, called static priority allocation or
management: real time priority allocation is permitted. The real-time priorities
priority allocation 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 are running.

[Link]. of ECE, BGSIT 21


MODULE 5
Process The RTOS kernel preempts a lower priority process when a
management: message or event for which it is waiting to run a higher priority
preemption process takes place. 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 Priorities inheritance enables a shared resource in low priority
management: task, for example, LCD display, be used by high priority task
priorityinheritance first. An intermediate priority task will not pre-empt the low
priority task when it is locked to run the critical shared resource
or code for the high priority task Priority seating in place of
priority inheritance option can also be used for a specific system.
Process predictability A predictable timing behaviour of the system and a predictable
task synchronization with minimum jitter (difference between
best-case and worst-case latencies).
Memory In RTOS threads of application program can run in kernel space.
management The real-time performance becomes high. However, then a
protection thread can access the kernel codes, stack and data memory
space, and this could lead to unprotected kernel code.
Memory Memory management is by either disabling the use of MMU and
managementMMU virtual memory or by using memory locks. Memory locking
stops the page. swapping between the physical memory and disk
when MMU is disabled. This makes RTOS task latencies
predictable and reduces jitter (time between worst-case and best-
case latencies for a task or thread).
Memory allocation In RTOS, the memory allocation is fast when there are fixed
length memory block allocations. First speed of allocation is
important (Example 8.6)
RTOS scheduling und Real-time task scheduling and interrupt latency control and use
interrupt latency of timers and system clocks.
controlfunctions
Timer functions Provides for timer functions. There is time allocation and de-
andtime allocation to attain efficiency in given timing constraints
management
Asynchronous 10 Permits asynchronous 10s, which means 10s without blocking a
functions Time task.
slicing
IPC Synchronization of tasks with IPCs (semaphores, mailboxes,
synchronization message queues, pipes, sockets and RPCs).
functions
Time slicing Time slicing of the execution of processes which have equal
priority.
Hard and soft real- Hard real-time and soft real-time operations.
timeoperability

[Link]. of ECE, BGSIT 22


MODULE 5

Basic Design Using an 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, kernel function or task. An RTOS use in embedded
system facilities the following,

1. An RTOS provides running the user threads in kernel space so that they execute fast.
2. An RTOS provides effective handling of the ISRs, device drivers, ISTs, tasks or
threads and the disabling and enabling of interrupts in the user mode critical section
codes. A critical section means a section of codes or a resource or codes that must run
without blocking. One critical section is when there is a shared data or resource with
the other routines or tasks. RTOS provides for effective handling of such a situation.
3. An RTOS provides memory allocation and de-allocation function in fixed time and
blocks of memory and restricting the memory accesses only for the stack and other
critical memory block.
4. An RTOS provides the effectively scheduling and running and blocking of the tasks
in cases.
5. I/O management with devices, files, mailboxes, pipes and sockets becomes simple
using an RTOS and RTOS provides for the use of message queue and mailbox, pipes,
sockets and other IPC functions. RTOS provides for the use of semaphore(s) by tasks
or for the shared resources (critical sections) in a task or OS functions.
6. Effective management of the multiple states of the CPU and internal and external
physical or virtual devices. Assume that the following actions are concurrently
needed in an application.
I. Physical devices timer, UART and keyboard have issued the interrupts and the
service routines are to be executed.
II. A file is taken as a virtual device. The file also must be opened with its pointer to
its first record.
III. A physical timer is to configure its control register.
IV. Another timer gets a count input from the system clock.
V. A virtual device, a file, gets the inputs for writing onto it.
VI. A timer states changes on timer and generates a need for its service.
VII. A file states changes on transfer of all needed records to it.
VIII. A timer executes a service routine on timeout.
IX. A file needs execution of a function, close{} by effectively using a common
method to handle these needs, the RTOS solves all the problems.

[Link]. of ECE, BGSIT 23


MODULE 5
Design Principles:
Following are the design principles when using an RTOS to design an embedded system.

Design with the ISRs and Tasks:

• The embedded system hardware source call generated interrupts. On interrupt, if the
interrupt is not masked (disabled) the interrupt saves the current process (a task or
thread or OS function) context on a stack and executes the ISR corresponding to that
interrupt. It is done by an RTOS by one of the three methods by a given RTOS
environment. Interrupts are masked by disable interrupt command and unmasked by
enable interrupt commands.
• The ISR can only post (send) the messages for the RTOS and parameters for the tasks.
No ISR instruction should block any task. Therefore, the ISR should not use mutex
locks and should not use OS pending function for the IPCs. Only an RTOS initiates
the actions according to the ISR- posted signals.
• Semaphores, queues, mailboxes and pipes and the RTOS control states of the tasks
and interaction with the tasks. The variables and task-switching flags must always be
under the RTOS control. No ISR instruction should wait for using the messages. The
ISR should execute the codes that should not wait for actions by the RTOS and tasks.
• RTOS provides for nesting of ISRs. This means that running ISR can be interrupted
by a higher priority interrupt and the higher priority ISR starts executing, blocking the
running of low priority ISR, when the high priority interrupt service completes and
there is return to the low priority interrupt after retrieving the saved context from the
stack for the low priority interrupt. A task can wait and take the messages (IPCs) and
post (send) the messages using the system cells. A task or ISR should not call another
task or ISR. Each ISR or task has to be under the control of the RTOS. Such an
attempt should generate an error.
Each ISR Design Consisting of Shorter Code:

• As ISRs have higher priorities over the task, the code should be made short so that the
tasks do not wait longer to execute. A design principle is that the ISR code should be
optimally short and the detailed computations be given to an IST or task by posting
the message or parameters for that. The frequent posting of the messages by the IPC
functions from the ISRs should be avoided. When there are frequent interrupts from
the same source, then the messages can be first put in the buffer on each interrupt and
when the buffer is sufficiently filled, the IPC message can be posted for ready buffer.
This is because if the buffer is not used and the IPC messages are posted frequently by
making system calls, OSMsgQPost ( ) functions, there will be frequent context
switches and hence wastage of time.

[Link]. of ECE, BGSIT 24


MODULE 5
Design with Using Interrupt Service Threads are Interrupt Service tasks :

• In certain RTOSses, servicing the interrupts, there are two levels, fast level ISRs and
slow level ISTs, the priorities are first for the ISRs, then for the ISTs and then the task
the ISRs post the messages for the ISTs and do the detailed computations. If RTOS is
providing for only one level, then use the tasks as ISTs.

Design each Task with an Infinite Loop from Start (Idle State) up to Finish (Last State):

• Each task has a while loop which never terminates. A task waits for an IPC or signal
to start. Tee task, which gets the signal runs or takes the IPC for which it is waiting,
runs from the point where it was blocked or pre-empted. In pre-emptive scheduler, the
high priority task can be delayed for some period to let the priority task execute.

Design in the Form of Tasks for the Better and Predictable Response Time Control:

• The RTOS provides the control over the response time of different task. The different
tasks are assigned different priorities and those tasks which system needs to execute
with faster response are separated out. For example, in a mobile phone device there is
need for faster response to the phone call receiving task then the user key input. In
digital camera the task for recording the image needs faster response then the task for
downloading the image on a computer through USB port.

Design in the Form of Tasks for a Modular Design :

• System of multiple tasks makes the design modular. The tasks provide modular
design. For example, in a mobile phone device we consider the user key input and
display as separate task. When the display size changes and new display hardware is
introduced, only the codes for the display tasks and resource and data sharing tasks
and ISRs need to be modified.
• When a new functionality is introduced in the system, the user key input task and new
functionality associated task need to be modified.

Design in the Form of Tasks for Data Encapsulation:

System of multiple task encapsulates the code and data of one task from the other.

Design with Taking Care of the Time Spent in the System Calls:

• The expected time in general depends on the specific target processor of the imbedded
system and the memory access times. However in order to provide the relative
magnitude of the time taken for the basic actions at a pre-emptive schedular, a new
parameter is defined. It defines the time taken for an action by an RTOS schedular in
terms of an assumed scaling parameter, S. S emphasizes the relative magnitudes of
execution times the for various actions in a typical RTOS.
• Let time taken for the simplest instruction be tmin. The minimum time is when the
semaphores P and V are assigned certain initial values, true or false. Let S be defined
in units of Ts, the Ts and tminsa depend on a specific target processor of the
embedded system and the memory access time.
• The RTOS create ( ) function to create a task takes longer CPU time then writing in to
a queue and reading form the queue and using a semaphore takes the least. Therefore,

[Link]. of ECE, BGSIT 25


MODULE 5
a design should create all the tasks at the beginning, even before the start of the tick of
the system clock.
• As queue takes longer time then the semaphore, use semaphores if it suffices.
• As signals takes the least time among the IPCs, use signals for the most urgent IPCs
(e.g. error reporting by the throwing the exceptions).

Use Appropriate Precedence Assignment Strategy and Use Pre-emption in Place of Time
Slicing:

• The task of higher priority pre-empts the low priority tasks and ISRs pre-empt the
tasks. Therefore, an appropriate precedence is chosen. The ISRs have higher priorities
over the ISTs and tasks. A mode of scheduling the tasks is assigning them equal
priorities and allotting time slice for round robin mode. Time slicing is done in certain
specific cases, for example in a network router when it is routing the packets of
multiple clients.

Avoid Task Deletion:

• Create tasks at start up only and avoid creating and deleting tasks later. The only
advantage of deleting is the availability of additional memory space. Suppose a task is
deleted by an OSTaskDelete ( ) Function. Now a situation can be that a task is waiting
for a semaphore (to let other task finish the critical section) or is waiting for a queue
(or mail box) message for a pointer at the RTOS, and the pointer is for a message to
the task that has been deleted. A prolonged blockage or a deadly embrace or a
deadlock will then occur. An RTOS may not provide protection for this situation
Certain RTOS provide an option to make a semaphore deletion safe.

Use Idle CPU Time for Internal Function:

• Often, the CPU may not be running any task. All tasks may be waiting for pre-
emption (for transition from ready place to running place). The CPU at that instant
may associate the RTOS for the following. Read the internal queue. Manage the
memory. Search for a free block of memory. Delete or dispatch a task. Perform the
internal and IPC functions.

Design with Memory Allocation and De-allocation by the Task:

• If memory allocation and de-allocation are done by task the number of RTOS
functions is reduced. The reduced interrupt latency periods as execution of these
functions takes significant time by RTOS where as the RTOS pre-empts a task.
Further, if fixed sized memory blocks are allocated, then the predictability of time
taken in memory allocation is there.

Design with Taking Care of the Shared Resource or Data among the Tasks:

• The ISR should be like a function or should take care of problem from the shared
resources or data such as buffer or global variables. Disabling of running of other task
for a longer period increases worst case interrupt latency periods for all the interrupts.
While executing the critical section codes. If possible, instead of disabling the
interrupts only the task switching flag changes should be used. It is done by using
semaphore. Thus, only the pre-emption by RTOS should be prevented. Disabling pre-

[Link]. of ECE, BGSIT 26


MODULE 5
emption may be better than disabling interrupts. However, both increase worst case
interrupt latencies. Resource locking using the mutex semaphore or spin locks may be
better than disabling perceptions of interrupts. A task should take the mutex
semaphore only during a short period in which the critical section alone is executed
and shared resources( such as the display device driver) . Spin locks can also be used
in case critical section code is short and executes in time less than the IPC and context
switching time.

Design with Hierarchical and Scalable Limited RTOS Functions:

• Use an RTOS, which is hierarchical as well as scalable so that has only the needed
function or at the ported sections of kernel. This is because the pre-emption
scheduling increases the interrupt latency periods because of the time spent in context
switching and saving and retrieving pointers for the RTOS functions like memory
allocation, and IPCs. The functions for the memory management, file system
functions, IPC (e.g., pipe, signal, socked and RPC) are provided outside the kernel in
a hierarchical and scalable RTOS. MMU is disabled for predictive response time of
the tasks. Hierarchical RTOS means the RTOS functions portable after extending and
interfacing other functions abilities and configuring for specific processor and set of
devices. Scalable RTOS means portable into for system ROM image after the limited
RTOS functions in the kernel space as per the application needs. For example, if
queue and pipe functions are not required in embedded system design, then these
functions are not ported in scalable RTOS.

Encapsulation Using the Semaphores and Queues:


Semaphores, queues and messages should not be globally shared variables, and each should
be shared between a set of tasks only and encapsulated from the rest.

Semaphores:

A semaphores encapsulates the data during a critical section or encapsulates a buffer from a
reading task or writing into the buffer by multiple tasks concurrently. Example 15 gives
another example.

Queues:

A queue can be used to encapsulate the messages to a task at an instance from the multiple
from the multiple tasks. Assume that a display task is posted a menu for display on a touch
screen in a PDA. Multiple tasks can post the messages into the queue for display. When one
tasks is posting the messages and these messages are displayed, another task should be
blocked from posting the messages.

We can write a task, which takes the input messages from other tasks and posts these
messages to the displayed task only after querying whether the queue is empty.

[Link]. of ECE, BGSIT 27


MODULE 5
Hard Real-Time Considerations:
Hard real time means strict adherence to each task deadline. We an event occurs, it should be
serviced within the predictable at all times in a given hard real-time system. The preemption
period for the hard real-time task in a worst case should be less than a few microseconds. A
hard RTOS is one, which has predictable performance with no deadlines miss , even in case
of sporadic tasks (sudden bursts of occurrence of events requiring attention). Automobiles
engine control system and antilock brake are the examples of hard real-time systems.

Hard real-time systems provide for the following.

1. Disabling of all other interrupts of lower priority when running the hard realtime
tasks.
2. Preemption of higher priority task by lower priority tasks.
3. Some critical code in the assembly to meet the real time constraint (deadline) fast.
4. Task running in kernel space. This saves the time required to first check whether
access is outside the memory space allocated to kernel functions.
5. Provision of asynchronous IOs.
6. Provision of spin locks.
7. Predictions of interrupt latencies and context switching latencies of the tasks. This is
achieved by writing all functions which on execution always take the same time
intervals in case of varying rates of occurrences of the events.
8. Response in all the time slots for the given events in the system and thus providing the
guaranteed task deadlines even in case of sporadic and a periodic tasks. Sporadic tasks
means tasks executed on the sudden bursts of the corresponding events at high rates,
and a periodic tasks mean tasks having no definite period of event occurrence.

A soft real time is 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 a few deviations between expected latencies of
the tasks and observed time constraints and a few deadline misses are accepted. The
preemption period for the soft real time task in a worst case may be about a few milliseconds.
Mobile phone, digital cameras and orchestra playing robots are of soft real time systems.

Saving of memory and power:

Methods of saving and optimizing the memory space:

Following are the methods.

1. Use compressed data structure provided the de-compression algorithm plus compressed
data structure combined together take less memory in the compared with the case when
only unpacked data structure is used.
2. Make the codes compact and fitted in small memory areas without affecting the code
performance. This is called memory optimization. Code means code compiled and
assembled executable in the given system. It also reduces the total amount of CPU
cycles, and thus, the total energy requirements.
3. Use declaration as unsigned byte, especially within the for and while loops, if there is a
variable, which always has value between 0 and 255. When using data structures, limit
the maximum size of the queues, lists and stacks size to 256. Byte arithmetic takes less
time than integer arithmetic. Follow a rule that uses unsigned bytes especially within
[Link]. of ECE, BGSIT 28
MODULE 5
the for and while loops for a short integer if possible, to optimize use of the RAM and
ROM available in the system. Avoid if possible the use of ‘long’ integers and ‘double’
precision floating point value bytes especially within the for and while loops.
4. Avoid use of library functions if a simpler coding is possible. Library functions are the
general functions. use of general function need more memory in several cases. Follow a
rule that avoids use of library functions in case a generalized function is expected to
take more memory especially when is coding is simple.
5. Configure the RTOS functions. For example, if queues are not needed the RTOS queue
functions are not ported in the ROM image. Use a configurable, scalable, hierarchical
RTOS which will help the ROM mage to execute the needed function at the kernel.
6. Optimize the RAM use for the stacks. It is done by three methods: (i) reducing the
number of tasks that interact with the OS, (ii) reducing the number of nested calls and
call at best one more function from a function (one function calling another function
and that calling the third and so on means nested calls), (iii) optimize the number of
tasks. (Less number of tasks are to be brought first into an initiated task list and there
are the frequent interactions with the OS and context savings and retrievals stack on
context switching, thus giving more memory and time overheads.) This optimizes the
use of the stack. As a rule reduce the use of frequent function calls and nested calls and
thus reduce the time and RAM memory needed for the stacks, respectively.
7. Optimize the allocation of stacks. A method is that allocated stack areas on allocation
are filled with the specific bytes or specific set of bytes. Then find that in worst cases of
running of the embedded system, how many filled bytes do not change. Then reduce
the allocated stack spaces by rewriting the task, buffer and other memory creation
codes.
8. In case the software design can be made fast with the instruction set of the target
processor, the assembly codes be used. This also allows the efficient use of memory.
The device-driver programs in the assembly especially provide efficiency due to the
need to use the bit set-reset instructions for the control and status registers. Only a few
assembly codes for using the device I/O port addresses control and status registers are
needed. The best use is made of available features for the given applications. Assembly
coding also helps in coding for atomic operations. A modifier register can be used in
the C program for fast access to a frequently used variable. If portAdata is frequently
employed, it is used as follows, 'register unsigned byte portAdata'. The modifier
register directs the compiler to place portAdata in a general purpose register of the
processor. As a rule, use the assembly codes for simple functions like configuring the
device control register port addresses and bit manipulations if the instruction set is
clearly understood. Use assembly codes for the atomic operations for increment and
addition. Use modifier 'register’ in C program for a frequently used variable.
9. Calling a function causes context saving on a memory stack and on return the context is
retrieved. This involves time and can increase the worst-case interrupt latency. There is
a modifier inline. When the inline modifier is used, the compiler inserts the actual
codes at all the places where these operators are used. This reduces the time and stack
overheads in the function call and return. But, this is at the cost of more ROM being
needed for the codes. If used, it increases the size of the program but gives a faster
speed. Using the modifier directs the compiler to put the codes for the function (in curly
braces) instead of calling that function. As a rule, use inline modifies for all frequently
used small sets of codes in the function or the operator overloading functions if the
ROM is available in the system. A vacant ROM memory is an unused resource. Why
[Link]. of ECE, BGSIT 29
MODULE 5
not use it for reducing the worst-case interrupt latencies by eliminating the time taken
in the frequent save and retrieval of the program context?
10. When a variable is declared static, the processor accesses with less number of
instructions than from the stack. As long as shared data problem does not arise ,the use
of static(global) variables can be Optimized. These are not used as the arguments for
passing the values. A good function is one that has no arguments to be passed. The
passed values are saved on the stacks in case of interrupt services calls and other
function calls. Besides obviating the need for repeated declarations, the use of global
variables thus reduce the worst-Case interrupt latency and the time and stack overheads
in the function call and return. But this is at the cost of the codes for eliminating shared
data problem, As a rule, use static (global ) variables if shared data problems are
tackled and use static variables in case it needs saving frequently on the stack.
11. Combine two functions if possible. For example, the search functions for finding
pointers t a list item and pointers of previous list items combine into one. If present is
false the pointer of the previous list item retrieves the one that has the item. As a rule,
combine whenever feasible two functions of more of less similar codes.
12. Use if feasible, alternatives to the switch-case statements, a table of pointers to the
functions. This saves the processor time in deciding which set of statements to execute
in place of performing the conditional tests all down a chain.
13. When using C++, configure the compiler for not permitting the multiinheritance,
templates, exceptional handling, new style casts, virtual base classes and namespaces.
As a rule, for using C++, use the classes without multiple inheritance, without template,
with run- time identification and with throw able exceptions.
14. When using Java, use the J2ME and configure the device classes. As a rule, us J2ME
with device configurations when programming small-devices code in Java.

Methods of Saving and Optimizing the Power Needs:

Following are the methods of power saving.

Switch to standby and stop modes:

An embedded system has to perform tasks continuously from powerup may also be left in
power-ON state; therefore, power saving during execution is important. A microcontroller
used in the embedded system must provide for executing 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 a
fully lighted room. A sensor senses the light level at specific intervals.

An embedded system may need to be run continuously, without being switched off; the
system design, therefore, is constrained by the need to limit power dissipation while it is
running. Total power consumption by the system in running , waiting, and idle states should
also be limited. A program can provide for auto-switch over the standby mode in the case
System is not used within a specified time interval and stop mode when the s5 or 10 or 20
seconds. A call attend mode can be switched off if there is no talk for over a minute.

The current needed at any instant in the processor for an embedded system depends on the
state and mode of the processor. The following are the typical values in six states of the
processor.

[Link]. of ECE, BGSIT 30


MODULE 5
1. 50mA when only the processor is running; that is, the processor is executing
instructions.
2. 75 mA when the processor plus the external memories and chips are in a running
state; that is, fetching and execution are both in progress.
3. 15uA when only the processor is in the stop state; that is, fetching and execution have
both stopped and the clock has been disabled from all structural units of the processor.
4. 15uA when the processors plus the external memories and chips are in the stop state ;
that is, fetching and execution have both stopped and the clock disabled from all
system units.
5. 5mA when only the processors is in the waiting state; that is, fetching and execution
have both stopped but the clock has not been disabled from the structural units of the
processor, such as timers.
6. 10 mA when the processor, the external memories and the chips are in the waiting
state. Waiting state now means that fetching and execution have both stopped; but the
clock has not been disabled from the structural units of the processor and the external
IO units and dynamic RAM refreshing also has not stopped.

Disable cache mode:

Yet another method is disable use of certain structural units of the processor - for example,
caches - when not necessary and to keep in disconnected state those structure nit needed
during a particular software portion execution, for example, timers or IO units. The software
designer should enable the use of caches in a processor by an appropriate instruction, to
obtain greater performance during run of a section of a program, while simultaneously
disabling the remaining sections in order to reduce the power dissipation and minimize the
system energy requirement. Hardware designers should select a processor with multiway
cache units so that only that part of a cache unit gets activated that has the data necessary to
execute a subset of instructions. This also reduces power dissipation.

Reduce circuits glitches:

In a CMOS circuit, power dissipates only at the instance of change in input . Therefore,
unnecessary glitches and frequent input change increase power dissipation. VLSI circuit
design have a unique way of avoiding power dissipation. A circuit design is made such that it
eliminates all removable glitches, thereby eliminating any frequent input changes.

Low-voltage operation modes:

Another is too operate the system at the lowest voltage levels in the idle state by selecting
power-down mode in that state.

1) The processor goes into a stop state when it receives a ‘stop’ instruction. The stop state
also occurs in the following conditions:
i. On disabling the clock inputs to the processor.
ii. On stopping the external clock circuit functions.
iii. On the processor operating in auto-shutdown mode. When in the stop state, the
processor disconnects with the buses (buses become in tri-state). The stop state can
change to a running state. The transition to the running state is either because of a
user interrupt or because of the periodically occurring wake-up interrupts.
2) The processor goes into a waiting state either on receiving

[Link]. of ECE, BGSIT 31


MODULE 5
i. an instruction for Wait, which slows or disables the clock inputs to some of the
processor units including ALU, or
ii. when an external clock circuit becomes non-functional. The timers are still operating
in the waiting state. The waiting state changes to running state when either (i) An
interrupt occurs or (ii) a reset signals.
3) Power dissipation reduces typically by 2.5 uW per 100 kHz reduced clock rate. So
reduction 8000 kHz to l00 kHz reduces power dissipation by about 200 uW, which is
nearly similar to when the clock is non-functional. [Remember, the total power
dissipated (energy required) may not reduce. This is because on reducing the clock rate
the computations will take a longer time at the lower clock rate and the total energy
required equals the power dissipation per second multiplied by the time]. The power
25uW is typically the residual dissipation needed to operate the timers and few other
units. By operating the clock at lower frequency or during the power-down mode of the
processor, the advantages are as follows:
i. heat generation reduces.
ii. Radiofrequency interferences also then reduces due to reduced power dissipation
within the gates.[Radiated RF (radiofrequency) power depends on the RF current
inside a gate, which reduces due to increase in ’ON’ state resistance between the
drain and channel when there is reduced heat generation.]
4) Low – voltage systems are built using LVCMOS(low-voltage CMOS) gates and
LVTTL(low-voltage TTL). Use of 3.3V,2.5V,1.8V and 1.5V systems and IO interfaces
other than the conventional 5V systems results in significantly reduced power-
consumption and can be advantageously used in the following cases.
i. In portable or hand-held devices such as cellular phone (compared with 5V,a CMOS
circuit power dissipation reduces by half, ~(3.3/5)^2, in 3.3V operation. This also
increases the time intervals needed for recharging the battery by a factors of two).
ii. In a system with smaller overall geometry, the low-voltage system processors and
IO circuits generate lesser heat and thus can be packed into a smaller space.

RTOS Task Scheduling Models, Interrupt Latency and Response Times of the
Tasks As Performance Metrics
Following are the common scheduling models used by schedulers.

1. Cooperative scheduling of ready tasks in a circular queue. It closely relates to function


queue scheduling.
2. Cooperative scheduling with precedence constraints.
3. Cyclic and round robin (time slicing) scheduling.
4. Preemptive scheduling.
5. Scheduling using ‘earliest deadline first’ (EDF) precedence.
6. Rate monotonic scheduling using ‘higher rate of events occurrence First’ precedence.
7. Fixed times scheduling.
8. Scheduling of periodic, sporadic and aperiodic tasks.
9. Advanced scheduling algorithms using the probabilistic timed Petri nets (stochastic)or
multithread graphs. These are suitable for multiprocessor and for complex distributed
systems.
10. An RTOS commonly executes the codes for the multiple tasks as priority-based
preemptive scheduler.

[Link]. of ECE, BGSIT 32


MODULE 5
Cooperative Scheduling Model

First consider a scheduling by a cooperative scheduler function by a simple example.


Consider an embedded system - an automatic washing machine. The system can be
partitioned into multiple tasks. First three tasks are task A1, task A2,and task A3 in a set of
tasks A1 to AN. Fig 2(a) shows the first three tasks of the multiple process embedded
software. The scheduler first starts the tasks A1 waiting loop and waits for the message A1
from task A1.
1. Tasks A1: The task is to reset the system and switch on the power if the door of the
machine is closed and the power switch pressed once and released to start the
system. Task 1 waiting loop terminates after detection of two events-
(i) door closed and
(ii) power switch pressed by the [Link] the end,task 1 sets a flag
start_F,which is a message A1 to schedule task A2 to start executing
[Link] message can be sent using semaphore function
OSSemPost(start_F).
2. Task A2: The scheduler waits for the message A1 for start_F [Link] waiting can
be using semaphore function OSSemPend(Start_F).If start_F posting event occurs at
task 1,the task 2 starts.A bit is set to signal water into the wash tank and repeatedly
checks for the water [Link] the water level is adequate the flag water-stage_F is
set,which is a message A2 to schedule task A3 to start executing [Link] message
can be sent using semaphore function OSSemPost(water-stage1_F).
3. Task A3: The scheduler waits for the message A2 for the stage1_F [Link]
waiting can be by using semaphore function OSSemPend (water-stage1_F).If water-
stage1_F posting event occurs at task 2 the task 3 waits ends and starts. A bit is set to
stop water inlet and another bit sets to start the wash tank motor. Then a flag, motor-
stage1_F is set, which is a message A3, to the schedule the next task to start
executing code. This message can be sent using semaphore function OSSemPost
(motor- stage_F).

• Figure 2(b) shows the cooperative scheduling model. Figure 2(c) shows the task
program contexts at various instances. Task A1 context has a pointer for task A1,
ADDR_A1. Task A2 context has a pointer for task A2, ADDR_A2. Task A3 context
has a pointer for task A3, ADDR_A3.

[Link]. of ECE, BGSIT 33


MODULE 5

Fig 2: (a) First three task in set of tasks A1 to AN into which the embedded software is
broken for the example in the text (b) Cyclic scheduling (c) Message from the schedule and
task program contexts at various instances in washing machine tasks

The Cooperative Scheduling Of Ready Tasks List:

• Figure 3(a) shows a scheduler in which the scheduler inserts into a list the ready for
sequential execution in cooperative model. Program counter PC changes whenever the
CPU starts executing another process. Figure 3(b) shows how the PC changes on
switch to another context. The scheduler switches the context such that there is
sequential execution of different tasks, which the scheduler calls from the list one by
one in a circular queue.
• Cooperative means that each ready task cooperates to let a running one finish. None of
the tasks does a block anywhere during the ready to finish states. The services in the
order in which a task is initiated on interrupt and placed in ready list. We can say that
the task priority parameter sets as per its position in the queue.
• Worst-case latency is the same for each task. It is ttotal. It is time-period of the circular
[Link] longer the queue, the greater is the [Link] a task is running ,all other ready
tasks must wait. For an i-th task,let the event detection time when an event is brought
into a list be dti,switching time from one task to another be sti and task execution time
be eti. Then if there are n tasks in the ready list,the worst-case latency with scheduling
when including the ISRs execution times will be:

T worst ={(dti + sti+eti)1 +(dti+sti+eti)2+….+(dti+sti+eti)n-1+(dti+sti+eti)n}+tISR=ttotal+tISR.

• Here the tISR is the sum of all execution times for the ISRs. Remember, the Tworst
should always be less than the deadline,td for any of the task in the list.

[Link]. of ECE, BGSIT 34


MODULE 5

Figure 3 (a)An OS scheduling in which the scheduler inserts into a list the ready task for a
sequential execution in a cooperative mode (b) PC assignments at different times, when the
scheduler calls the tasks one by one in the circular queue from the list

The Cooperative Scheduling of Ready Tasks Using an Ordered list as per precedence
constraints:

Figure (a) shows a cooperative priority-based scheduling of the ISRs executed in


the first layer (top-right side) and priority-based ready tasks at an ordered list executed in
the second layer(bottom-left),[Link] 4(b) shows the PC switch at different
times,when the scheduler calls the ISRs and the corresponding tasks at an ordered list one
by one. The scheduler using a priority parameter,taskPriority,does the ordering of list of
the tasks.
The scheduler first executes only the first task at the ordered list,and the ttotal , equals
the period taken by the first task on [Link] is deleted from the list after the first task is
executed and the next task becomes the [Link] insertions and deletions for forming the
ordered list are made only at the beginning of each list.
At the first layer, an ISR has a set of short codes that have to be executed [Link]
ISRs run in the first layer(top-right in figure)according to their assigned [Link] sends a
flag(s) or token(s) and its priority parameter for the task to be initiated(serviced).This task
inserts into the ready task [Link] is a block anywhere from the start to
[Link],however,the next start of scheduling is among the ready tasks that run in turn
only from a priority-wise ordered [Link] ordering to the precedence of the interrupt
sources and tasks.
Let pem be the priority of that tasks which has the maximum execution [Link] worst-
case latencies for the highest priority and lowest priority tasks will now vary from:
{(dt i+ sti + eti)pem + tISR}
[Link]. of ECE, BGSIT 35
MODULE 5
to {(dti + sti +eti)p1 + (dti + sti + eti)p2 +….+(dti + sti + eti)pm-1 + (dti + sti + eti)pm + tISR}.
Here, p1,p2,………pm-1 are the priorities of tasks in the ordered list. Also
p1>p2>…>pm . With this scheduler, it is easier, but not granted, to meet requirement that
Tworst should be < Td for each task and interrupt source. The programmer assigns the
lowest Td task a highest priority.

Fig. 4: (a) cooperative priority-based scheduling of the interrupt service routines(ISRs)


executed in the first layer(top-right side) and priority-based ready tasks at an ordered list
executed in the second layer (bottom-left) (b) Program counter assignments at different
times on the scheduler calls to the ISRs and the corresponding tasks.
Cyclic and Robin with Time Slicing Scheduling Models:

Cyclic Scheduling AN OS scheduler can let the system schedule the various tasks in real
time as follows: Let us assume that we have periodically occurring three tasks, the need for
their service arises after periodically. Let the time-frames be allotted to the first task, the
task executes at t1, t1 +Tcycle , t1 + 2 x Tcycle , …….second task frames at t2, t2 + Tcycle,
t2 + 2 x Tcycle and the third task at t3, t3 + T, t3 + 2’Tcycle,…… . Start of a time frame is
the scheduling point for the next task in the cycle. Tcycle is the cycle for repeating the 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 the period after which each the task time frame allotted to that repeats.

[Link]. of ECE, BGSIT 36


MODULE 5

Each of the N tasks in a cyclic scheduler completes in its allotted time frame when the time
frame size is based on the deadline. A cyclic scheduler is clock-driven and is useful for the
periodic tasks. It repeats the schedule decided after computation based on the period of
occurrences of task instance. Each task has the same priority for execution in the cyclic
mode.

Round Robin Time Slicing Scheduling


• A task may not complete in its allotted time frame. Round Robin means that each
ready task runs in turn only in a cyclic queue for a limited time slice Tslice . Tslice =
Tcycle / N, where N = number of tasks. It is a widely used model in traditional OS.
Round Robin is a hybrid model of the clock-driven model( e.g., cyclic model) as well
as event-driven (e.g., preemptive). A the time- constrained tasks in the round robin
mode can be understood by a simple example.
• Suppose after every 20 ms, there is a stream of coded messages reaching at port A of
an embedded system, it is then decrypted and retransmitted to the port after encoding
each decrypted message. The multiple processes consist of five tasks: C1, C2, C3, C4
and C5, as follows:
1. Task C1: Check for a message at port A every 20 ms.
2. Task C2: Read port A and put the message in a message queue.
3. Task C3: Decrypt the message from the message queue.
4. Task C4: Encode the message from the queue.
5. Task C5: Transmit the encoded message from the queue to port B.

Figure 5(a) The tasks C1 to C5 round robin (b) Task program contexts at five instances in
the round robin(time slice)scheduling scheduler for C1 to C5 with Tslice = 4ms.

[Link]. of ECE, BGSIT 37


MODULE 5
• Figure 5(a) shows five tasks, C1 to C5, that are to be scheduled. Figure 5 (b)shows the
five contexts in five time schedules, between 0 and 4ms, 4 and 8ms, 8 and 12ms, 12 and
16ms and 16 and 20ms, respectively. Let OS initiate C1 to [Link] there be slice-clock
tick interrupts at each 4 ms. Task C1 is scheduled by OS to bring it to the running state
from its blocked state as timer triggers an event. If it is known that after every 20 ms a
byte reaches port A, a timer interrupt triggers an event every [Link] C1 runs within
4 ms, and C2 starts running.

• Figure 5(b) shows at different time slices the real-time schedules, process contexts and
saved contexts.

1. At the first instance (first row)the context is C1 and task C1 is running.


2. At the second instance(second row) after 4 ms, the OS switches the context to
[Link] C1 is finished,C2 is running .As task C1 is finished ,nothing is saved on
the task C1 stack.
3. At the third instance(third row),the OS switches the context to C3 on next timer
interrupt, which occurred after 8 ms from the start of task [Link] C1 is
finished,C2 is blocked and C3 is running context C2 is saved on task C2 stack
because C2 is in blocked state.
4. At the fourth instance(fourth row),the OS switches the context to C4 on timer
interrupt, which occurred after 12 ms from the start of task [Link] C1 is
finished,C2 and C3 are blocked and C4 is running. Contexts C2,C3 and C4 are at
the tasks C2 and C3 stacks, respectively.
5. At the fifth instance(fourth row),the OS switches the context to C5 on next timer
interrupt which occurred after 16 ms from the start of task [Link] C1 is
finished ,C2,C3 and C4 are blocked and C5 is running. Contexts C2,C3 and C4
are at the tasks C2,C3 and C4 stacks, respectively.
6. On a timer interrupt at the end of 20 ms, the OS switches the context to C1 .As
task C5 is finished ,only the contexts C2,C3 and C4 remain at the stack. Task C1
is running as per its schedule.

• Figure 5(a) The tasks C1 to C5 round robin (b) Task program contexts at five instances
in the round robin(time slice)scheduling scheduler for C1 to C5 with Tslice = 4ms.

[Link]. of ECE, BGSIT 38


MODULE 5

Figure 6: (a) The Programming Model for the cooperative time-sliced scheduling of the task
(b) The program counter assignments on the scheduler call to tasks at two consecutive time slice.

• When a p-th task has high execution time,etp,the worst-case latency of the lowest
priority task can exceed its deadline. To overcome this problem, it is better than the OS
defines a lower time slice for each task. Each task has codes in an infinite loop. Cyclic
scheduling with time slicing is simple and there is no insertion or deletion into the
queue or list. Figure 6(a) shows a programming model for cyclic time-sliced round
robin [Link] 6(b) shows PC on context switches when the scheduler call to
tasks at two consecutive time [Link] task is allocated a maximum time interval =
tslice/N, where tslice is the timer after which a timer (with the OS)interrupts and
initiates a new cycle.
• The OS completes the execution of all ready tasks in one cycle within a time
slice,N*tslice in this mode,Let Tworst be the sum of the maximum times for all the
tasks if there are N tasks in [Link],when tslice> or = Tworst ,the Tworst equals:

{(dti+sti+eti)+(dti+sti+eti)+…..+(dti+sti+eti)+(dti+sti+eti)}+tISR.

• If N*tslice equals the sum of the maximum times for each task,then each task is
executed once and finishes in one cycle [Link] a task finishes the execution before
the maximum time it can take,there is a waiting period between the two [Link]
worst-case latency for any task is N*tslice.A task may periodically need execution .
• The period for the required repeat execution of a task is an integral multiple of
[Link] each task to run only once,the N*tslice should also be less that the greatest
common factor of all the task periods.
• The estimation of response time for each task is easy in time slice cyclic round robin
[Link] a K-th [Link] task responds within its task period plus the sum
of the maximum times taken during a time slice from the task 1 to task(k-1).The
response time of the m-th task at the end of the list is the maximum.
• An alternative model strategy can be the decomposition of a task that takes an
abnormally long time to be [Link] decomposition is into two or four or more
[Link] one set of tasks(or the odd numbered tasks) can run into slice,tslice and
another set of tasks(or the even-numbered tasks)in another time slice,tslice.
• Another alternative strategy can be the decomposition of the long time-taking task into
a number of sequential states or a number of node places and transitions as in the
[Link] one of its states or transitions runs in the first cycle,the next state in the
second cycle and so [Link] task then reduces the response times of the remaining tasks
that are executed after a state.
[Link]. of ECE, BGSIT 39
MODULE 5
Pre-emptive Scheduling Model:
• Cooperative schedulers schedule such that each ready task cooperates to let the running
one finish. However, a disadvantage of the cooperative scheduler is that a long
execution time of a low-priority task makes a high-priority task wait at least until it
finishes.
• There is a further disadvantage if the cooperative scheduler is cyclic but without a
predefined tslice. Assume that an interrupt for service from the 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.
• The time-slicing scheduler is simpler in design and extremely valuable in many
applications where there is a need to use the resources of the embedded systems
sequentially, or none of the tasks has a shorter deadline than the tslice or tcycle.
• Round robin scheduler also give appropriate time slice to let a task finish with the
allotted time frame. Now consider the problem with round robin.
• Let there be N tasks from task 1 to task N and let the assigned order of priority for
interrupt servicing be from 1(highest)to N(lowest).Assume now that an interrupt occurs
in the time-slicing scheduling just after the cycle starts. It means task 1 misses by a
flick the chance of running from start to finish as task i will not get serviced till the
cycle up to task N finishes or till the defined period tslice expires.
• Can the higher-priority task preempt a lower priority by blocking it? If yes, then this
can solve the problem of large worst case latency for high priority tasks. The hardware
polls to determine whether an ISR or task with a higher priority than the present one
needs service at the end of an instruction during execution. If yes, then the higher
priority ISR or task is executed. Similarly, the RTOS preemptive scheduler can block a
running task at the end of an instruction by a message to the task and let the one with
the higher priority take control of the CPU.
• Now consider a preemptive scheduler by a simple example. Suppose there is a stream
of coded message reaching at port A of an embedded system. It then decrypts and re-
transmits to port B after encoding each decrypted message.
• Figure 7(a) shows the tasks for the multiple processes of this application. Five
processes are executed at five tasks,B1,B2,B3,B4 and [Link] consider preemptive
scheduling by a scheduler function by another example. Consider an embedded system
for reading a port A input and decrypting the input data, encoding it and sending it to
another port B output .The system can be partitioned into multiple tasks. Five tasks are
task B1, B2, B3, B4 and [Link] 7(a) shows the assigned functions to the task and
ISR. The order of priorities is as follows.
1. Task B1:Check for a message at port A.
2. TaskB2:Read port A.
3. TaskB3:Decrypt the message.
4. TaskB5:Transmit the encoded message to the port.
• Figure 7(b) gives the symbols used to show the preemptive scheduler actions shown in
figure 7(c).A higher priority task takes control from a lower priority task. A higher
priority task switches into the running state after blocking the low priority task. The
context saves on the preemption. Figure 7(c) shows the following.

[Link]. of ECE, BGSIT 40


MODULE 5
1. At the first instance(first row)the context is B3 and task B3 is running.
2. At the second instance(second row)the context switches to B1 as context B3 saves
on interrupt at port A and task B1 is of highest [Link] task B1 is in a
running state and task B3 is in a blocked [Link] B3 is at the task B3 stack.
3. At the third instance(third row) the context switches to B2 on interrupt ,which
occurs only after task B1 [Link] B1 is in a finished state,B2 in a running
state and task B3 is still in the blocked [Link] B3 is still at the task B3
stack.
4. At the fourth instance (fourth row)context B3 is retrieved and the context switches
to [Link] B1 and B2,both of higher priorities than B3,are [Link] B1 and
B2 are in finished [Link] B3 blocked state changes to running state and B3 is
now in a running state.
5. At the fifth instance(fifth row)the context switches to [Link] B1,B2 and B3,all
of higher priorities than B4,are [Link] B1,B2 and B3,are in the finished
states.B4 is now in a running state.
6. At the sixth instance(sixth row)the context switches to [Link] B1,B2,B3 and
B4, all of higher priorities than B5,are [Link] B1,B2,B3 and B4, are in the
finished states.B5 is now in a running state.
7. At the seventh instance(seventh row)the context switches to B1 as context B5 is
saved on interrupt at port A,and task B1 is of highest [Link] task B1 is in a
running state and task B5 is in a blocked [Link] B5 is at task B5 stack.
8. At the eighth instance(eighth row)the context switches to B2 on interrupt,which
occurs only after task B1 [Link] B1 is in a finished state,B2 in a running
state and task B5 is still in the blocked [Link] B5 is still at the task B5
stack.
9. At the last instance (last row)the context is B3 and task B3 is [Link] tasks
B1 and B2 are in finished state.

[Link]. of ECE, BGSIT 41


MODULE 5

Fig 7 (a) First five tasks B1 to B5 (b)The symbols used for the states in a preemptive
scheduling (c) The task program contexts at the various instances.

• RTOS manages the processes and provides for preemption of lower priority process by
higher priority process. Let the priority of task_1>task_2>task_3>task_4……>task N.
Figure 8(a) shows the preemptive scheduling of N tasks. figure 8(a) also shows the
context switching whenever the process switches from a task to the RTOS to a task.
Figure 8(b) shows PC assignments on the scheduler call to pre-empt task 2 when the
priority of task_1>task_2>task_3.
• Each task has an infinite loop from start(idle state)up to finish(refer to task 1, task 2,
and task N,three boxes at the bottom of this figure).Last instruction of task 1 points to
the next pointed address,*[Link] case of the infinite loop,*next points to the same task
1 [Link] is unlike a cooperative scheduler, where it signals the next task execution to
the OS and OS now initiates and runs the next task in the ready list.

[Link]. of ECE, BGSIT 42


MODULE 5

Figure 8(a) Preemptive scheduling of the tasks (b) Program Counter assignments on a scheduler call
to preempt task 2. Priority of task_1> task_2> task_3

• In a preemptive scheduler, there is an RTOS message during the running of task 2 to


preempt the task 2. Figure 8(a) shows the sequence markings(1),(2),and (3) and figure
8(b)shows program counter assignment. Their meanings are as follows. In step 1,task 2
is run. The higher priority task 1 is initiated as follows:
1. Task 2blocks and sends a message to the RTOS(step 2)
2. The RTOS now sends a message to task 1 to go to the unblocked state and
run(step3).
• After task 1 blocks then RTOS makes the task 2 in the unblocked state. Task 2 now
[Link] task 2 blocks then RTOS makes task 3 in the unblocked state. Task 3 will
run now.
• Each task design is like an independent program, in an infinite loop between the task
ready place and the running task 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. The context switching may also occur on an ISR call.
• We can define timeout for waiting for the token or event. An advantage of using time
out intervals while designing task codes is that worst-case latency estimation is
possible. Any task’s worst-case latency is the sum of the tISR and the intervals of all
other tasks are of higher priority. Another advantage of using the using the time outs is
the error reporting and handling by the RTOS. Timeouts provide a way to let the RTOS
run even the lowest priority task in necessary cases.
• Whenever the preemption event takes place, a task switching(a task place transition to
its running place)becomes necessary, and the scheduler searches for the highest priority
task at that instance. That task only is switched to the running place by the scheduler
.Switching occurs when a taskSwitchFlag is sent to the highest priority task and not to
the task that was running previously.
• How can the context switching intervals reduce?The context switching intervals are
reduced by the static declaration of the variables, as the static variables are RAM-
resident variables and do not save on the stack on a function [Link] this is the
case,on a call the PC and few must-save registers are [Link] switching now does
not lead to additional stack-saving overheads.
• The conditions in which an event (token),the preemptionEvent ,is generated for task to
undergo transition from the running place to the ready place are as follows.

[Link]. of ECE, BGSIT 43


MODULE 5
1. The preemption even takes place when an interrupt occurs and just before the
return from the interrupt, there is a service call to the RTOS by the ISR. On this
call to the RTOS, a token, the preemption Event, is set. The task then undergoes
transaction to the place, readyTaskPlace, and runs only when asked by the
scheduler (by sending taskSwitchFlag).
2. Each RTOS uses a system clock ticked by a SysClkIntr interrupt. The preemption
event takes place when the SysClkIntr interrupt (real-time clock-driven software
timer interrupt) occurs at the RTOS. On this event RTOS takes control of the
processor and checks whether it should let currently executing task continue or to
preempt it to make a way for the higher priority task. This event makes another
higher priority task ready to run, on the switch of the flag to the latter.
3. The preemption event takes place when any call to RTOS occurs to enter the
critical section or for sending the task message (outputs) to the RTOS, and if
another higher priority task then needs to be serviced (take control of the CPU)
(now the preemption is before entering the critical section).

Critical Section Service by a Preemptive Scheduler:


• Critical section is a section in a system call (OS function), when there is no
preemption by either ISRs or higher priority tasks. Critical section is also a section in
task to prevent preemption. A lock function executes before beginning of critical
section and an unlock function executes at exit from the critical section.
• Assume that a task I is waiting for a critical section resource,and task J is using a
kernel lock at an instance because of the system call for lock by another task [Link]
task J executes unlock function,the task I waiting for lock will run.
• Assume that context switching time is large,for example,I ms,while the critical section
resource is required by the task for much shorter duration,then kernel lock is an
inefficient mechanism to lock a critical section.A spin lock can be used to protect the
critical section resource as follows.
• Assume that task J is being provided the critical section resource through spin
lock,Slock .Assume that task I need the critical section resource at instance [Link] spin
lock concept provides a busy wait loop for [Link] I goes at ti into a busy wait loop for
the spin lock,[Link] soon as J releases the slock,the Ii gets the critical resource
without spenting time for the context switch.
• An implementation of the spin lock in a task can be by a try. The high priority task
tries the lock by a wait loop for the lock for a define time twait, else the task un-
blocks.
• Another implementation of the spin lock can be by trying two or four wait loops for
the lock with successive decrements in the time twait to 0,after which the task UN-
blocks. After the unblocking ,the task will run critical section code without the
context switch unlike the case when mute x is used to block or UN-block a critical
section.
• A lock function alternative is executing by taking a mute x and lock by releasing the
mute [Link] implementation is by an instruction that disables a specific interrupt
at the beginning of a critical section and enables the specific interrupt at the end of the
critical section.
• Two task may have two sections that share the data or resource and only one section
must [Link] the critical section,a task waits for mute x semaphore from the

[Link]. of ECE, BGSIT 44


MODULE 5
scheduler and releases the mute x semaphore at the exit from the critical
[Link] for priority inheritance permits critical section service by a pre-
emptive scheduler without priority inversion.
• Can work be done without the semaphores and/or mute x for the critical sections?
Yes,one strategy is the disabling and enabling the [Link] disabling of a
preemption means disabling only the task switching flags,or their passing to the task
when using shared data and enabling the task switching flags to change and pass again
after [Link] it should then be ensured that all the ISRs are the reentrant
[Link] strategy could be use of resources locking semaphore,mute x for
spin-lock.

Model for Critical Section Service by a Preemptive Scheduler:

Fig 9 The Petri net model for the task with a preemptive scheduler and one critical section
where it takes a semaphore and release on critical section over

Fig 9 Shows a Petri net concept-based model which models ans helps in designing the codes
for a task that has a critical section in its [Link] figure shows places by the circles and
transitions by the [Link] following are the places and transitions.

1. Each task is in the idle state to start with, and a token to the RTOS is
taskSwitchFlag=rest.
2. Consider the task_J_Idle place, which currently has highest priority among the ready
tasks. When the RTOS creates task-J, the place task_J_Idle undergoes a transition to the
ready state, task_J_Ready [Link] RTOS initiates idle to ready transition 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.

[Link]. of ECE, BGSIT 45


MODULE 5
3. When after task J finishes, the RTOS sens an RTOS_DELETE event to the task, it
returns to task_J_Idle place and its corresponding taskJSwitchFlag resets.
4. At task_J_Ready place, the scheduler task the priority parameter into [Link] the
current task happens to be of the highest priority, the scheduler sets two sections,
taskJSwitchFlag=true and highest Priority Event=true, for the transition to the running
task J place, task_J_Running. The scheduler also resets and sends tokens, task switch
flags, for all other tasks that are of lesser priority. This is because the system has one
CPU to process at an instant.
5. From the task_J_Running place, the transition to the task_J_Ready place will be fired
when the task finish flag sets.
6. At task_J_Running place, the codes of the switched task J are executed.
7. At the runningTaskPlace, the transition for preempting will be fired when RTOS sends
a token,suspendEvent. Another enabling token if present, time_out_event also fire the
transition. An enabling token for both situations is the semaphore release flag, which
must be set. Semaphore release flag is set 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 preemptive. It happens 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 that associate with the running task place.
8. On a resumeEvent the transition to tadk_J_Running place occurs(refer to the right-side
middle transition, which is between the three transitions that are shows in the figure).
9. At the task_J_Running place, there is another transition that fires so that the task J is
back at the task_J_Running place when the RTOS sends a token,
take_Semaphore_Event to ask the task J to take the semaphore(the RTOS sets the
semaphore request flag, take_Semaphore_Event; it resets semaphore release flag; it
directs task J to run [Link] not block).
10. There can be none or one or several critical [Link] the execution of a critical
section, the RTOS resets the semaphore release flag and set the task semaphore event
toke.

Earliest Deadline First (EDF) Precedence and Rate Monotonic Schedulers


(RMS) Models:
• The event-driven schedules are required for real-time scheduling in case of a number of
tasks being large or in case of aperiodic or sporadic tasks. Aperiodic task is one in
which the period of occurrence is not known because it may be known when an event
can occur. For example, an event of receiving a phone call is aperiodic event. Sporadic
task periods of bursts when the task events occur.
• A deadline is the period in which a task must finish. A task, which has a least deadline
that is which has little time left for completion, must be scheduled first. This algorithm
of the scheduler is known as EDF algorithm.

EDF Precedence:
• When a task becomes ready, its will be considered at a scheduling point. The scheduler
does not assign any priority. It computes the deadline left at a scheduling point.
Scheduling point is an instance at which the scheduler blocks the running task and re-
computes the deadlines and runs the EDF algorithm and finds the task to be run.
• An EDF algorithm can also maintain a priority queue based on the computation when
the new task inserts. When the number of tasks becomes large, the computation
complexity increases for insertion into the queue. Another EDF algorithm can also

[Link]. of ECE, BGSIT 46


MODULE 5
maintain two or more priority queues based on the relative deadlines and the scheduler
inserts the new task into one of the queues.

Precedence Assignment in the Scheduling Algorithms:


• The best strategy is one,which is based on EDF precedence. Precedence is made the
highest for a task that corresponds to an interrupt source, which occurs at earlist and
which deadline will finish the earliest.
• How is the precedence assigned in the case of variable CPU loads for the different
tasks and variable EDFs? One method as follows.
• Let t1 be the instance when task I needs preemptive the first time and t2 be the next
instance. A task with minimum (t2-t1) is inserted at the top of the task priority list. It is
assigned the highest precedence. The list is dynamically ordered according to (t2-t1).
• First, there is a deterministic or static assignment of the precedence in advanced
scheduling algorithms. It means first there is RMS. Later on the scheduler dynamically
assigns and fixes the time out delays afresh, and assigns the precedence as per the EDF.
The need for the dynamic assignment arises due to the sporadic tasks ans the distributed
or multiprocessor indeterminate environment.
• Resource sharing among the tasks creates a problem. The algorithm has to ensure that
none of them misses the deadline.
• A task occurring at a higher rate should then get higher precedence in case of periodic
tasks. Assume that the data is being received from multiple channels and some channel
receive data at a faster rate than the others. A scheduler uses rate monotonic algorithm
(RMA) to schedule the task in this case.

Rate Monotonic Scheduler:


• RMS computes the priorities,p,from the rate of occurrence of the tasks. The i-th task
priority,pi is proportional to (1/ti) where ti is the period of the occurrence of the task
event. RMA gives an advantage over EDF because most RTOSes have provisions for
priority assignment. Higher-priority tasks always get executed.
• RMA disadvantage is that it does not support aperiodic and sporadic tasks. When a
burst occurs, even due to higher rate of arriving of the sporadic task in the burst period,
It cannot be assigned high priority. The aperiodic and sporadic tasks can be assigned
the tickets by aperiodic and sporadic servers in the scheduler. Ticket means the periods
in which the events from them will be scheduled.
• RMA disadvantage is that a task may have long periods, but can be very critical. It will
be assigned least priority. A solution is to divide the very critical task into two or more
task to raise their allocated priority by the RMA.

Fixed (Static) Real-Time Scheduling Model:


• The slice-time scheduling method is a special case of ‘fixed real-time scheduling’.
Every task is allotted fixed schedules to run. Let there be m tasks and m real-time clock
interrupts, the scheduler can thus assign each task a fixed schedule. Each task
undergoes a ready place to running place transition on the timeouts of the
corresponding timer. The OS is supposed to define hard real-time schedules for each
task.
• A scheduler is said to be using a fixed-time scheduling method when the schedule is
static and deterministic. The working environment is unaltered when processes are

[Link]. of ECE, BGSIT 47


MODULE 5
schedule on the single CPU of the system. Schedules are deterministic as the worst-case
latencies for all the interrupts and the tasks are predeterminable. The OS scheduler can
thus schedule each task at fixed times so that none misses its deadline(this is when the
worst-case latency of each task is less then its deadline for its service). The ‘no deadline
miss’ advantage is feasible only in deterministic situations. Coding for the tasks are
such that execution times do not vary under the different inputs or different conditions.
• Schedules once defined remain static in a fixed-time scheduler. Fixed schedules can be
defined by one of the three methods.
1. Simulated annealing method. Here the different schedules can be fixed and the
performance simulated. Now, schedules for the tasks are gradually incremented
by changing the interrupt timer settings( using a corresponding OS function) till
the simulation result shows that none is missing its deadline.
2. Heuristic method. Here, reasoning are past experience helps to define and fix the
schedules.
3. Dynamic programming model. This is as follows:a specific running program first
determines the schedules for each task and then the timer interrupt loads the timer
settings from the outputs from the program.
• If the scheduler cannot fix the schedules, it is a non-deterministic situation. An example
is a situation in which a message for a task is expected in a network, from another
system and the minimum and maximum periods for receiving it are unknown. Another
example is when the inputs for a task are expected from another system and the
minimum and maximum periods when the inputs will be received are not known.
• A dynamic scheduling model is as follows:the software design may be such that
priorities can be rescheduled and fixed time redefined when a message are error
message is received during the run.

Latency and Deadlines as Performance Metric in Scheduling Models for


Periodic, Sporadic and Aperiodic Tasks:
• An RTOS should quickly and predictably respond to the event. It should have
minimum interrupt latency and fast context switching latency.
• Different models have been proposed for measuring performances. Three performance
metrics are as follows.
1. Ratio of the sum of interrupt latencies with respect to the sum of the execution
times.
2. CPU load.
3. Worst-case execution time with respect to the mean execution time.
• ‘Interrupt latencies’ in varies task models can be used for evaluating performance
metrics. The latencies for varies tasks scheduling models. The CPU load is another way
to look at the performance. Worst-case performance calculation for a sporadic task is
explained in. ‘Refer Real Time Systems’ by Jane [Link], Pearson Education, 2000,
for details of many models available for evaluating the performances.

[Link]. of ECE, BGSIT 48


MODULE 5
CPU Load as Performance Metric:
• Each task gives a load to the CPU that equals the task execution time divided by the
task period. [Task period means period allocated for a task.] Recall In_AOut_B intra
network of example 4.1. Receiver port A expects another character before 172micro
sec. Task period is 172micro sec. If the task execution time is also 172micro Sec, the
CPU load for this task is 1(100%). The task execution time when a character is received
must be less than 172micro sec. The maximum load of the CPU is 1(less than 100%).
• The 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. The time outs and fixed-time limit definitions for
the tasks reduce the CPU load for the higher-priority tasks so that even the lower-
priority tasks can be run before the deadlines. What does it mean when the sum of the
CPU loads equal to 0.1(10%)? It means that the CPU is underutilized and spends 90%
of its time in a waiting mode. As the execution times and the task period vary, the CPU
loads can also vary.
• When a task needs to run only once, then it is aperiodic(one shot) in an application.
Scheduling of the task that need to run periodically with the fixed periods can be
periodic and can be done with a CPU load very close to 1. An example of a periodic
task is as follows. There may be inputs at a port with predetermined periods, and the
inputs are in succession without any gap.
• When a task cannot be schedule at fixed periods, its schedule is called sporadic. For
example, if a task is expected to receive inputs at variable time gaps, then the task
schedule is sporadic. An example is packets from the routers in a network. The variable
time gap must be within defined limits.
• A preemptive scheduler must take into account three types of tasks(aperiodic, periodic
and sporadic) separately.
1. An aperiodic task needs to be preempted only once.
2. A periodic task needs to be preempted after the fixed periods and ot must be
executed before its next preemption is needed.
3. A sporadic task needs to be checked for preemption after a minimum time period
of its occurrence. Usually, the strategy employed by the software designer is to
keep the CPU load between (0.7+-0.25) for sporadic tasks.

Sporadic Task Model Performance Metric:


• Let us consider the following parameters.
• Ttotal is the total length of the periods for which sporadic tasks occur; e is the total task
execution time; Tav is the mean periods between the sporadic occurrences; Tmin is the
minimum period between the sporadic occurrences.
• Worst-case execution time performance metric, p is calculated as follows for the worst-
case of a task in a model.

p = pworst = (e*Ttotal/Tav) / (e*Ttotal/Tmin).


• It is because the average rate of occurrence of sporadic task is (Ttotal/Tav) and the
maximum rate of sporadic task burst is Ttotal/Tmin.

OS Security Issues:
• When a doctor has to dispense to multiple patients, protection of the patients from any
confusion in the medication becomes imperative. When an OS has to supervise multiple
processes and their access to the resources, protection of memory and resources from
any unauthorized writes into the PCB or resources, or mix up of accesses of one by
another becomes imperative. The OS security issue is a critical issue.

[Link]. of ECE, BGSIT 49


MODULE 5
• Each process determines whether it has a control of a system resource exclusively or
whether it is isolated from the other processes, or whether it shares a resources common
to a set of processes. For example, a file or memory blocks of a file will have exclusive
control over a process and a free memory space will have the access to all the
[Link] OS then configures when a resource is isolated from one process and a
resource is shared with a defined set of processes.
• The OS should also have the flexibility to change this configuration when needed, to
fulfil the requirements of all the processes. For example, a process has control of 32
memory blocks at an instance and the OS configures the system accordingly. Later
when more processes are created,this can be reconfigured.
• The OS should provide protection mechanisms and implement a system
administrator(s)-defined security policy. For example, a system administrator can
define the use of resources to the registered and authorized users(and hence their
processes).
• What about issues of an application changing the OS configuration? The OS needs a
protection mechanism for [Link] application software programmer can find a hole in
the protection mechanism and gain an unauthorised access. Thus the implementation of
protection mechanisms and enforcement of security policy for resources is a
challenging issue before any OS software designer. The network environment
complicates this issue.
Table13 gives the various activities for implementing important security functions.
Table13 Important Security Functions.

[Link]. of ECE, BGSIT 50


MODULE 5
Introduction to Embedded Software Development Process and Tools
Development Process and Hardware-Software:
• Figure10(a) shows the development process of an embedded system and Figure 10(b)
edit-test-debug cycle. During implementation phase of the development process.
There are cycles of editing-testing-debugging during the development phases. Whereas
the processor part once chosen remains fixed, the application software codes have to be
perfected by a number of runs and tests. Whereas the cost of the processor is quite
small, the cost of developing a final targeted system is quite high and needs a larger
time frame than the hardware circuit design.

Figure 10 (a) Development process of an embedded system (b) Edit-test-debug cycle during
the implementation phase of the development process
The developer uses four main approaches to the edit-test-debug cycles.

1. An IDE or prototype tool.


2. A simulator without any hardware.
3. Processor only at the target system and uses an in-between ICE (in-circuit-emulator).
4. Target system at the last stage.

Software Tools:

• The tools are required for the application software high-level language programming.
Also required are the RTOS, testing debugging, assembly language programming (for
implementing the device-driver functions and system integration tools. Table 14 lists
the software tools in software and hardware embedded system. Table 14 Software
Modules and Tools for implementation of an Embedded System

Table 14 Software Modules and Tools for implementation of an Embedded System

[Link]. of ECE, BGSIT 51


MODULE 5

Software tools are used to develop software for designing an embedded system. Sophisticated
tools-Integrated development environment and prototype development tools are needed for
integrated development of system software and hardware. The testing and debugging tools
are needed for testing and debugging.

[Link]. of ECE, BGSIT 52


MODULE 5
Source Code Engineering Tool

• A source code engineering tool is of great help for source code development, compiling
and cross-compiling. The tools are commercially available for embedded C/C++ code
engineering, testing and debugging. The features of a typical tool are comprehension,
navigation and browsing, editing, debugging, configuring (disabling and enabling the
C++ features) and compiling. A tool for C and C++is SNIFF+. It is from WindRiver
Systems. A version, SNIFF+ PRO has full SNIFF+ code as well as debug module.
• Main features of the tool are as follows:
1. It searches and lists the definitions, symbols, hierarchy of the classes and class
inheritance trees. [The symbols include the class members. A tree is a data
structure. A data structure tree has a root. From n the roots, the branches emerge
and from the branches more branches emerge. On the branches, finally there are
the leaves (terminating nodes).]
2. It searches and lists the dependencies of symbols and defined symbols, variables,
functions (methods)and other symbols.
3. It monitors, enables and disables the implementation virtual functions. Use of
virtual functions is for dynamic run -time binding.
4. It finds the complete effect of any code change on the source code.
5. It searches and lists the dependencies and hierarchy of the included header files.
6. It navigates to and fro between the implementation and symbol declaration.
7. It navigates to. In a daughter class with the same name and number and types of
arguments as in the parent class. Over-ridden method is the method of the parent
class, which has been redefined at the daughter class.)
8. It browses through information regarding instantiation (object creation) of a class.
9. It browses through the encapsulation of variables among the members and
browses through the public, private and protected visibility of the members.
10. It browses through object component relationships.
11. It automatically removes error-prone and unused tasks.
12. It provides easy and automated search and replacement.
• The embedded software programmer for sophisticated applications uses a source code
engineering tool for program coding, profiling, testing and debugging of embedded
system software.

Integrated Development Environment (IDE)


• DE consists of simulators with editors, compilers, assemblers, etc., emulators, logic
analysers and EPROMA EEPROM application codes burner. An IDE must have the
following features.
1. It has a facility for defining a processor family as well as defining its version. It
has source code engineering tools which incorporate the editor, compiler for ,
embedded C++ assembler, linker, locator, logic analyser, stethoscope and 'Help'.
2. It has the facility of a user-definable assembler to support new version or type of
processor. Provides a multiuser environment.
3. The design process divides into number of subparts. Each programmer is assigned
independent but linked tasks.
4. It simulates hardware unit-like emulator. Peripherals and I/O devices on a host
system (PC). It supports conditional and unconditional breakpoints. It provides

[Link]. of ECE, BGSIT 53


MODULE 5
test-vectors. A test-vector is program-path for the controlled flow of the program
used during testing phase and later removed or disabled on completing that phase.
5. It debugs by single stepping. It has the facility for synchronizing the internal
peripherals.
6. It provides Windows on the screen. These provide the detailed information of the
source code part with labels and symbolic arguments, the registers as the
execution continues, the detailed information of the status of peripheral devices,
status of RAM and ports, and the status of stack and program flow as it continues.
7. It verifies the performance of a target system. It has an emulator built into the
development system that remains independent of a particular targeted system,
plus a logic analyser for up to 256 or 512transactions on the address and data
buses after triggering.
• An IDE tool is from WindRiver Systems and that employs VxWorks RTOS. An
architectural feature is dynamic linking and incrementally loading the object modules'
into the target system. Exemplary target processor families that are supported are
PowerPC, Intel, Motorola. Pentiums, MIPS and ARM/Strong ARM. It helps in
prototype development and tests the prototype applications. There is a text editor with
GNU C/C++ compilers. Debugging is performed at three levels, source code-level. task-
level (scheduling, IPCs and interrupts study) and domain-level. It includes VxSim,
stethoscope and trace scope. Figure 11(a) and (b) show simple and sophisticated IDE,
respectively.
• An IDE (u Vision 2) is from keil software Inc. with RTX51 RTOS for 8051 target
processor families. Another IDE keil µVision 3 is for ARM family of processors and
microcontrollers. It has cross-compiler, source-level debugger, object browser, monitor
for run-time behaviour, event-to-event viewing. The object browser browses the
applications behaviour overtime. It graphically displays the RTOS tasks, queues.
semaphores and IPC objects. A real-time analysis (RTA) suite profiles the code
coverage and locates run-time errors. It optimizes the use of the memory.

[Link]. of ECE, BGSIT 54


MODULE 5

Figure 11 (a) Simple Integrated development environment (IDE) (b) Sophisticated IDE

HOST AND TARGET MACHINES

• During the development process, a host system is used before locating and burning
the codes in the target board. The target board hardware and software is later copied
to get the final embedded system, which will function exactly as the one tested and
debugged and finalized during the development process.

Using a Host System

Host system is a PC or workstation or laptop. It has the following hardware.

1. High-performance processor with caches


2. Large RAM memory
3. ROMBIOS (read only memory basic input-output system)
4. Very large memory on disk
5. Keyboard
6. Display monitor
7. Mice
8. Network connection

It a full-fledged computer. It has software tools (Table 11 and must include the following:

1. Program development kit for a high-level language program or IDE.


2. Host processor compiler and cross complier.
3. Cross-assembler.

[Link]. of ECE, BGSIT 55


MODULE 5
Program Development Tool Kit:

• Program development tool kit or IDE has an editor. The editor is used for writing C
codes or assembly mnemonics or C ++ or Java Visual C++ using the keyboard of the
host system (PC) for entering the program. Using GUIS, it allows the addition, deletion,
insert, appending previously and files at written lines or files, merging record and files
at the specific positions. It creates a source file that positions in creates a sour stores the
edited file. It also has an appropriate name (given by the programmer). It can use
previously created files and can also integrate the various source files. It can save
different versions of the source files. Program development kit or IDE has the code
generation tools (assembler. compiler. loader and linker).
• A high-level language is machine-independent. It will have an expression like X = X +
2.3 or X=2* Y +V*Z+ 19 and so on. When we use a high-level language C. a tool is
needed for obtaining the machine codes a target system. The programmer writes the
mnemonics or C program. using the editor. The mice and keyboard combinations of the
host system (PC) or host system are for entering the program codes. Each language
needs a compiler. The codes may not be executable using an interpreter.
1. An interpreter does expression-by -expression (line-by-line) translation to the
machine-executable codes.
2. A compiler uses the complete set of the expressions. It may also include the
expressions from the library routines; that is standard tailor-made programs. Whereas
an interpreter helps in on-line execution of the codes, a compiler helps in the off-line
programming for obtaining the executable machine codes later. The C programs are
used with an interpreter as well as with a compiler. A cross-compiler is a compiler
that created binary executable files for the for target system processor.
3. An assembly language program has the mnemonics that are machine-dependent.
Example of a mnemonic is SBC A. Ox0B. It means an instruction, which subtracts,
along with the previous'carry', the A register of the processor with the hexadecimal
number Ox0B. An assembly mnemonic is specific to a processor or microcontroller. It
is according to the instructions provided in the instruction set. The assembly
mnemonics needs an interpreter to translate into the machine codes that are executed
on a specific processing device.
4. A dissembler translates the object codes into the mnemonics form of assembly
language. It helps in understanding the previously made object codes.
5. An assembler is a program that translates the assembly mnemonics into the binary
encodes and instructions, that is, into an executable file, called object file. It also
creates a list file that can be printed. The list file has address, source code (assembly
language mnemonic) and object codes in hexadecimal. The object file has addresses
that are to be allocated again during actual run of the assembly language program. A
loader is a program that helps in this task by reallocating addresses before loading the
code and operands in the computer memory.
6. A linker links the needed object code files and library code files. This is before the
loader reallocates the addresses, and puts the codes at the physical addresses in the
memory, and the program runs. Loader performs the analogous functions on host
machine as the locator does on a target system in conjunction with a device
programmer.

[Link]. of ECE, BGSIT 56


MODULE 5
Cross-Compiler: C or C++ or visual C++ source files compile according to the native
including OS on which their binary image runs). Java classes compile as byte codes and are
therefore platform independent. A cross-compiler is a compiler that creates binary executable
files for the target system processor.

Cross-Assembler: It converts object codes or executable codes for a processor to other codes
for another processor and vice versa. The cross-assembler assembles the assembly codes of
the target processor as the assembly codes of the lets us use a processor of the host system
(PC) used in the system development. Later, it provides the object codes for the target
processor. These codes will be the ones actually needed in the finally developed system.

Code generation tools are used for creating and compiling at the host system. Then codes are
tested at the host system using simulators and number of latest software tools like profiler,
memory scope, stethoscope and memory and code coverage scope.

Target System:
• A target system has a processor. ROM memory for ROM image of the embedded
software, RAM for stack. temporary variables and memory buffers, peripherals and
interfaces. Figure 12(a) and (b) show simple and sophisticated target systems,
respectively. Some target systems have 8 or 16 MB flash memory and 64 MB SDRAM.
A target system may possess the RS232 as well as 10/100-base Ethernet connectivity or
USB port.

Figure 12 (a) Simple Target (b) Sophisticated target system

[Link]. of ECE, BGSIT 57


MODULE 5
• A target system differs from a final system. It interfaces with the computer as well
works as standalone system. There might be repeated downloading of the codes into it
during the development phase.
• The target. System or its copies simply work later as the embedded system. Consider
that a targeted system is under development. In the target system development phase,
say of outer, the codes of application software have to be written. These have to be
embedded in flash. These have be repeatedly written or modified and tested using
diagnostic, simulation and debugging tools, and embedded a final testing in an edit-test-
debug cycle shows it working according to specifications. The programmer it on simply
copies it into the final system or product. Also a final system may use a ROM in place
of flash1 the target system.
• An exemplary target system is a board that has an Philips LPC21xx processor (ARM
microcontroller). It is1C2100 evaluation board from Keil.
• Let us consider an exemplary sophisticated target system, Vx Works 5.4. It provides
run-time support by caleable RTOS support. Internet protocols support, POSIX library
support, file system and graphic supports. has a debugging agent. It has a back end
support package for a specific processor or microcontroller. The it get system connects
the simulator in parallel the host computer through a target server tool with ICE using
Ethernet or serial lines from the host computer.

Linking and Locating Software:


• Linker links the compiled codes of application software, object codes from library and
OS kernel. Linking is necessary because there are number of codes to be linked for
the final binary file. For example, there are standard codes to program a delay task for
which there is a reference in the assembly language program. The codes for the delay
must link with the assembled codes.
• The delay code is sequential from a certain beginning ides. The assembly software
code is also sequential from a certain beginning address. Both the codes are event at
the distinct and the available addresses in the system. A linker links these. The linked
file in binary for 'n on a computer is commonly known as executable file or simply
exe file.
• After linking, there has to be allocation of the sequences of placing the codes before
the actual placement of the codes in the memory. A program is loaded in a computer
RAM. The loader program performs the task of reallocating the codes finding the
physical memory addresses available at a given instant. The loader is a part of the OS
and aces codes into the memory after reading the exe file.
• This step is necessary because the available memory Addresses may not start from
0x0000, and binary codes have to be loaded at the different addresses during the n.
The loader finds the appropriate start address. In a computer, after the loader loads
into a section of RAM program are ready to run.
• When the code embeds into ROM or flash, a system design process locates these
codes as a ROM image. Codes are permanently placed at the actually available
addresses in flash-ROM. In embedded systems, ere is no separate program to keep
track of the available addresses at different times during the run as in a outer. In
embedded systems, therefore next step after linking is the use of a locator for the
program-codes d data in place of the loader.

[Link]. of ECE, BGSIT 58


MODULE 5
• The locator features are as follows.
1. The locator is specified by the programmer the available addresses at the RAM
and ROM in target. The programmer has to define the available addresses to load
and create files for permanently locating the codes using a device programmer.
2. It uses cross-assembler output, a memory allocation map and provides the locator
program output file. It is the final step of software design process for the
embedded system. Locator program output is in the Intel hex file or Motorola S-
record format. The locator uses the cross compile codes in different. Ross-
compiled segments for: (i) instructions, (ii) initialized values and addresses, (iii)
constant strings and (iv) un-initialized data.
3. The locator locates the I/O tasks and hardware device-driver codes at the
addresses without reallocation. This is because the port and device addresses for
these are fixed for a given system. These are as per the interfacing circuit between
the system buses and ports or devices.
4. The locator program reallocates the linked file and creates a file for permanent
location of codes in a standard format.
5. The file format may be Motorola S-record format or Intel hex file or any other
format.
• Figure 13 shows various software tools and chain of actions of linker at host and locator
in an embedded system.

Fig.13: Various software tools and chain of actions of linker at host and locator in an
embedded system

[Link]. of ECE, BGSIT 59


MODULE 5
Differences in Files, Addressing and Address Resolution Method
Table 15 Difference in files, addressing in Linker and locator

Locator Output File in Binary Image Motorola-S and Intel Hex Formats

Binary bit mapped (binary image) means bytes are sent in a sequence as per starting address
to the end address.

Motorola S-Record Format:

• Motorola S-record format is an industry standard for storing the locator file. Before its
use by the device programmer or ROM-mask programmer. It is called S-record because
it has first character as 'S' in each line. A line is as follows: first character is S, second
character is 2 (for specifying the record type), third and fourth characters are for a
hexadecimal number, say 14 (to specify that there are 20 bytes in that ne), the
remaining 40 characters (nibbles) divide as the address (3 bytes) and data (16 bytes)
and checksum +1 byte). Table 16 shows a typical S-record as a locator output and
device programmer input. It is left as an exercise to the reader to show that Add for line
6 in the record of Table 16 will be 0x000037.

Table 16 An Exemplary Motorola S-Record format

[Link]. of ECE, BGSIT 60


MODULE 5
Intel Hex File Format

• Intel hex file format is another industry standard for storing the locator file output,
before its use by the device programmer or ROM-mask programmer. A line is as
follows: first character (colon), second and third characters for data counts (assume =
10 in hexadecimal in case N d =16) in the line (address bytes, checksum byte and data
type bye excluded, only actual data bytes at the line, which are to be burned in ROM
are counted), fourth to seventh address (2 bytes), sixth and seventh as 0 and 0 to specify
data 28 ROM data and the remaining 32 characters as the data (16 bytes) and 2
characters for the checksum byte). Table 17 shows an Intel hex file, which corresponds
to the same data as at the Motorola S-record in Table 17 as a locator output and device
programmer input. It is left as an exercise to the reader to show that Add for line 6 in

Table 17 An Exemplary Intel Hex file format

Memory Map for coding a locator


• Figure 14(a) shows memory addresses needed in the case of Princeton architecture in
the system.
• Figure 14(b) shows memory addresses needed in the case of Harvard architecture.
These differ in following respect.
• Vectors and pointers, variables, program segments and memory blocks for data and
stacks have different addresses in the program in Princeton memory-architecture.
• Program segments and memory blocks for data and stacks have separate sets of
addresses in Harvard architecture. Control signals and read-write instructions are also
separate.
• The system memory allocation map is not only a reflection of addresses available to the
[Link], and the program segments and addresses available to the 10 devices,
but also reflects a description of the memory and 10 devices in the system hardware. It
maps guides to the actual presence of the various memories at the various units.
EPROM. PROM. ROM, EEPROM.
• Flash memory. SRAM RAM), DRAM (dynamic RAM) and 10 devices. It reflects
memory allocation for the programs, and data and 10 operations by the locator
program. It shows the memory blocks and ports (devices) at these addresses. Figure
14(a) and (b) show memory and I/O devices memory allocation map for the 68HC11

[Link]. of ECE, BGSIT 61


MODULE 5
(having memory-mapped 10 architecture), and for an IBM 80x86 6 PC) (having 10-
mapped 10 architecture). respectively.

Figure 14 (a) Memory Map (Princeton architecture) (b) Memory map (Architecture
architecture)

[Link]. of ECE, BGSIT 62

You might also like