Embedded Systems Assignment 2: Ajay Margad 1MS08EC138
Embedded Systems Assignment 2: Ajay Margad 1MS08EC138
ASSIGNMENT 2
Question 1: EXPLAIN WITH AN EXAMPLE HOW THE ROUNDROBIN ARCHITECTURE WORKS.WHERE IS IT NOT SUITABLE
The code in gure is the prototype for round-robin, the simplest imaginable architecture. There are no interrupts. The main loop simply checks each of the I/O devices in turn and service any that need service. This is marvelously simple architecture - no interrupts, no shared data, and no latency concerns and therefore always an attractive potential architecture, as long as you can get away with it. Simple as it is, the round-robin architecture is adequate for some jobs. Consider, for example, a digital multi meter such as the one shown in gure A digital multimedia measures electrical resistance, current, and potential in units of ohms, amps and volts, each in several dierent ranges. A typical multi meter has two probes that the user touches to two points on the circuit to be measured, a digital display, and a big rotary switch thats selects which measurements and changes the display to reect the most recent measurement. Possible pseudo-code for a multi meter is as shown in gure each time around its loop; it checks the position of the rotary switch and then branches to code to make the appropriate measurement, to format its results, and to write the results to the display. Even a very modest microprocessor can go around this loop many times each second. Round-robin works well for this system because there are only three I/O devices, no particularly lengthy processing, and no tight response requirements. The microprocessor can read the hardware that actually makes the measurements at any time. The display can be written to at whatever speed is convenient for the microprocessor. When the user changes the position of the rotary switch, hes unlikely to notice the few fractions of a second it takes for the microprocessor to get around loop. The round-robin architecture is adequate to meet all of these requirements, and its simplicity makes it very attractive choice for this system. Unfortunately, the round-robin architecture has only one advantage over other architectures - simplicity - where as it has a number of problems that make it inadequate for many systems: If any one device needs response in less time than it takes the microprocessor to get around the main loop in the worst-case scenario, then the system wont work. In gure 5.1., for example, if devise Z can wait no longer than 7 milliseconds for service, and if the pieces of code that service devices A and B take 5 milliseconds each, then the processor wont always get to device Z quickly enough. Now you can squeeze just a little more out of the round-robin architecture by testing device A, device B and devise Z, but there is a limit to how much of this you can do. The world is full of I/O devices that need fairly rapid service: serial ports, network ports, push buttons, etc. Even if none of the required response times are absolute deadlines, the system may not work well if there Is any lengthy processing to do. For example, if any one of the cases in gure 5.3 were to take, say ,3 seconds, then the systems response to the rotary switch may be as bad as 3 seconds. This may not quite meet the denition of not working but it would probably not be a system that anyone would be proud to ship. This architecture is fragile. Even if you manage to tune it up so that the AJAY MARGAD 1MS08EC138 ii
ASSIGNMENT 2
microprocessor gets around the loop quickly enough to satisfy the entire requirement may break everything. Because of these shortcomings, round-robin architecture is probably suitable only for very simple devices such as digital watches and microwave ovens and possibly not even for those.
iii
ASSIGNMENT 2
Question 2:WHAT ARE THE 2 RULES THAT THE INTERRUPT ROUTINES IN RTOS ENVIRONMENT MUST FOLLOW THAT DO NOT APPLY TO A TASK CODES? ILLUSTRATE, WITH EXAMPLES.WHAT HAPPENS WHEN EACH RULE IS VIOLATED.
Rule 1: An interrupt routine must not call any RTOS function that might
iv
ASSIGNMENT 2
block the caller. Therefore, interrupt routines must not get semaphores, read from queue or mailboxes that might be empty, wait for events, and so on. If an interrupt routine calls an RTOS function gets blocked, then, in addition to the interrupt routine, the task that was running when the interrupt occurred will be blocked, even if that task is the highest-priority task. Also, most interrupt routines must run to completion to reset the hardware to be ready for the next interrupt. As we can see from gure 7.14 how interrupt routine should work but in actual case what would really happen is shown in gure 7.15 (Rule 1)
Rule 2: An interrupt routine must not call any RTOS function that might cause the RTOS to switch task unless the RTOS knows that an interrupt routine, and not a task, is executing. This means that interrupt routine may not write to mailboxes or queue on which tasks may be waiting, set events, release semaphores, and so onunless the RTOS knows it is an interrupt routine breaks this rule, the RTOS might switch control away from the interrupt routine to run another task, and the interrupt routine may not complete for a long time, blocking at least all lower-priority interrupt and possibly all interrupts. As we can see from gure 7.16 how interrupt routine should work but in actual case what would really happen is shown in gure 7.17 (Rule 2)
ASSIGNMENT 2
Question 3:What are the 3 dierent states of task in RTOS? How the state of each task is tracked? The basic building block of software written under an RTOS is the TASK. Under most RTOSs a task is simply a subroutine. Each task in an RTOS is always in one of the three states: Running Ready Blocked 1. Running : which means that the microprocessor is executing the instructions that make up this task. Unless yours is a multiprocessor system, there is only one microprocessor, and hence only one task that is in the running state at any given time.
vi
ASSIGNMENT 2
2. Ready : which means that some other task is in the running state but that this task has things that it could do if the microprocessor becomes available. Any number of tasks can be in this state. 3. Blocked : which means that this task hasnt got anything to do right now, even if the microprocessor becomes available. Tasks get into this state because they are waiting for some external event. For example, a task that handles data coming in from a network will have nothing to do when there is no data. A task that responds to the user when he presses a button has nothing to do until the user presses the button. Any number of tasks can be in this state as well. The other task states included among the oerings are suspended, pended, waiting, dormant, and delayed.The transition among the three task states is shown below:
Question 4:What is a reentrant function? Give the 3 rules to decide reentrant functions Reentrant functions are functions that can be called by more than one task and that will always work correctly, even if the RTOS switches from one task to another in the middle of executing the function. Three rules are applied to decide if a function is reentrant or not, they are: 1. A reentrant function may not use variables in a non-atomic way unless they are stored on the stack of the task that called the function or are otherwise the private variables of that task. 2. A reentrant function may not call any other functions that are not themselves reentrant. 3. A reentrant function may not use the hardware in a non-atomic way.
Question 5:What is an event? Give the 3 standard features of an event AJAY MARGAD 1MS08EC138 vii
ASSIGNMENT 2
Management of events is another service RTOSs oer within the system. An event is essentially a Boolean ag that tasks can set or reset and that other tasks can wait for. For example, when the user pulls the trigger on the cordless bar-code scanner, the task that turns on the laser scanning mechanism and tries to recognize the bar-code must start. Events provide an easy way to do this: the interrupt routine that runs when the user pulls the trigger sets an event for which the scanning task is waiting. Some of the standard features of events are: 1. More than one task can block waiting for the same event, and the RTOS will unblock all of them (and run them in priority order) when the event occurs. For example, if the radio task needs to start warming up the radio when the user pulls the trigger, then that task can also wait on the trigger-pull event. 2. RTOSs typically form groups of events, and tasks can wait for any subset of events within the group. For example, an event indicating that the user pressed a key on the scanner keypad might be in the same group with the trigger-pull event. If the radio task needs to wake up both for a key and for the trigger, it can do that. The scanning task will wake up only for the trigger event. 3. Dierent RTOSs deal in dierent ways with the issue of resetting an event after it has occurred and tasks that were waiting for it have been unblocked. Some RTOSs reset events automatically; if the trigger-pull event is not reset, for example, then tasks that need to wait for the event to be set will never again wait.
Question 6:Illustrate with suitable examples, the problems of priority inversion and deadly embrace PRIORITY INVERSION Whenever one task takes a semaphore, every other task that subsequently wants that semaphore has to wait until the semaphore is released. If one task takes the semaphore and then holds it for too long, other tasks may miss real-time deadlines. A particularly perverse instance of this problem can arise if the RTOS switches from a low-priority task (say TASK C) to a medium-priority task (say TASK B) after TASK C have taken a semaphore. A high-priority task (say TASK A) that wants the semaphore then has to wait until TASK B gives up the microprocessor: TASK C cant release the semaphore until it gets the microprocessor back. No matter how carefully you code TASK C, TASK B can prevent TASK C from releasing the semaphore and can thereby hold up TASK A indenitely. This problem is called priority inversion. Some RTOSs resolve this problem with priority inheritance they temporarily boost the priority of TASK C to that of TASK A whenever TASK C holds the semaphore and TASK A is waiting for it.
viii
ASSIGNMENT 2
DEADLY EMBRACE The gure below illustrates the problem of deadly embrace. The functions ajsmrsv and ajsmrls are from an RTOS called AMX. The function ajsmrsv reserves a semaphore, and the function ajsmrls releases the semaphore. The two additional parameters to ajsmrsv are time-out and priority information and are not relevant. Task1 and Task2 operate on variables a and b after getting permission to use them by getting semaphores hSemaphoreA and hSemaphoreB. Deadly Embrace Example:
int a; int b; AMXID hSemaphoreA; AMXID hSemaphoreB; void vTask1 (void) ajsmrsv (hSemaphoreA, 0, 0); ajsmrsv (hSemaphoreB, 0, 0); a=b; ajsmrls (hSemaphoreB); ajsmrls (hSemaphoreA); void vTask2 (void) ajsmrsv (hSemaphoreB, 0, 0); ajsmrsv (hSemaphoreA, 0, 0); b=a; ajsmrls (hSemaphoreA); ajsmrls (hSemaphoreB);
ix
ASSIGNMENT 2
From the above code, if vTask1 calls ajsmrsv to get hSemaphoreA, but before it can call ajsmrsv to get hSemaphoreB, the RTOS stops it and runs vTask2. The task vTask2 now calls ajsmrsv and gets hSemaphoreB. When vTask2 then calls ajsmrsv to get hSemaphoreA, it blocks, because another task (vTask1) already has that semaphore. The RTOS will now switch back to vTASK1, which now calls ajsmrsv to get hSemaphoreB. Since vTask2 has hSemaphoreB, however, vTask1 now also blocks. There is no escape from this for either task, since both are now blocked waiting for the semaphore that the other has. This phenomenon is known has deadly embrace. Question 7:With the help of timing signals, explain how disabling of interrupts aects system response for the following case. Disable interrupts for 125 micro sec for task code to use a pair of temperature variables it shares with ISR that reads temperatures from hardware and writes them into variables. Disable interrupts for 250 micro sec for task code to get time accurately from variables it shares with ISR that responds to timer interrupt. A special signal recieved from another processor shall be responded with 625 micro sec If in the above case, microprocessor is replaced with another having exactly half speed, will the system meet the deadline? Interrupts are disabled in our hypthetical system for at most 250 micro sec at a time. The interrupt routine needs 300 micro sec, for a total, worst case time of 550 micro sec, within the 625 micro sec limit
ASSIGNMENT 2
Note that the interrupt will never be delayed for 375 micro sec, the sum of the two periods of time during which interrupts are disabled. If the hardware asserts the inter processor interrupt signal while the system has disabled interrupts in order to read the time, then in at most 250 micro sec the system will re enable the interrupts, and the microprocessor will jump to the interrupt routine. The fact that the system might at some other time disable the interrupts for another period of time is irrelevant. There is no way to enable and then disable interrupts so fast that the microprocessor will not service the pending interrupts. However, to cut costs, the hardware group proposes to replace the microprocessor with one that runs only half as fast. The processing time are doubled, interrupts are disabled for twice as long, the ISR takes twice as long, but the 625 micro sec deadline remains the same. The system will not meet its deadline. Interrupts will be disabled for upto 500 micro sec at a time, and the ISR needs 600 micro sec to do this work.The total of these two is 1100 micro sec , much longer than the 625 micro sec deadline. Question 8:Explain RTOS architecture with an algorithm. The dierence that Real-Time Operating System Architecture and the other architectures The necessary signalling between the interrupt routines and the task code is handled by the real-time operating system. No loop in code decides what needs to be done next. Code inside the realtime operating system decides which of the task code functions should run. The real-time operating system knows about the various task-code subroutines and will run whichever of them is more urgent. The real-time operating system can suspend one task subroutine in the middle of its processing in order to run other.
xi
ASSIGNMENT 2
The rst two of the dierences are mostly programming convenience. The last one is substantial: systems using the real-time-operating-system architecture can control task code response as well as interrupt routine response. The possible priority level code is shown below.
xii
ASSIGNMENT 2
A side eect of this scheduling mechanism is that the systems response will be relatively stable, even when the code is change. The response times for the task code function in the round-robin architectures and in the function queuq architecture depend upon the length of the various task code suroutines, evan lower-priority ones. When we change ay subroutine, we potentially cahnge response times throught the system architecture, changes to to lower-priority functions do not generally eect the response of the higher-priority functions. Another advantage of using this architecture is that its widely available for purchase. By buying RTOS we get immediate solutions to some of the problems and get a useful debugging tools as well. Question 9:What are semaphores? Explain the structure and use of binary semaphores for data protection. Semaphores are tools to the problems where RTOS causes a new class of shared-data problems by switching the microprocessor from task to task and, like interrupts, changing the ow of execution. Semaphore is explained with a train example. In the olden days, the railroad barons discovered that it was for business if their train ran into one another. Their solution to this problem was to use signals called Semaphores. As shown in the gure below the rst train enters the pictured section of track, the semaphore behind it automatically lowers. When a second train arrives, the engineer notes the lowered semaphore, and he stops and waits for the semaphores to rise. When the rst train leaves that section of track, the semaphore rises, and the engineer on the second train knows that it is safe to proceed on. There is no possibility of the second train running into rst train. The general idea of the semaphores in an RTOS is similar to the idea of a railroad semaphore
xiii
ASSIGNMENT 2
A typical RTOS binary semaphore works like this: tasks can call two RTOS function, Take Semaphore and Release Semaphore. If one task has called take Semaphore to take the and has not called Release Semaphore to release it, then any other taks that calls Take Semaphore will block until the rst task calls Release Semaphore. Only one task can have a semaphore at a time.
xiv
ASSIGNMENT 2
Before the levels task (vCalculateTanklevels ) updates the data in the structure, it calls Take Semaphore to take (lower) the semaphore. If the user presses a button while the levels task is modyfying the data and still has the semaphore, then the following sequence of events occurs: 1. The RTOS will switch to the button task,just as before, moving the levels task to ready. 2. When the button task tries to get the semaphore by calling Take Semaphore, it will block because the levels task already the semaphore. 3. The RTOS will then look around for another task to run and will notice that the levels task is still ready. With the button task blocked, the levels task will get to run until it releases the semaphore. 4. When the levels task releases the semaphore by calling Release Semaphore, the button task will no longer be blocked, and the RTOS will switch back to it. Question 10:Explain interrupt handling procedure,context switch-
xv
ASSIGNMENT 2
ing and critical section. Interrupt handling procedure: When the microprocessor detects that a signal attached to one of itd interrupt request pins is asserted, it stops executing the sequence of its instructions it was executing, saves on the stack the address of the instruction that would have been next, and jumps to an interrupt routine. Interrupt routines are subroutines that you write, subroutines that do whatever needs to be done when the interrupt comes from the serial port chip and that chip has received a character from the serial port chip and that chip has received a character from the serial port chip and put it into memory. Typically, interrupts routines also must do some miscellaneous housekeeping chores, such as resetting the interrupts-detecting hardware within the microprocessor to be ready for the microprocessor to be ready for the next interrupt.
Context Switching After the hardware mechanisms have determined which interrupt to handle and have acknowledged the interrupt, the current instruction stream is halted and a context switch is performed, a process in which the master processor switches from executing the current instruction stream to another set of instructions. This alternate set of instructions being executed as the result of an interrupt is the interrupt service routine (ISR) or interrupt handler. An ISR is simply a fast, short program that is executed when an interrupt is triggered. The specic ISR executed for a particular interrupt depends on whether a non vectored or vectored scheme is in place. In the case of a non vectored interrupt, a memory location contains the start of an ISR that the PC (program counter) or some similar mechanism branches to for all non vectored interrupts. The ISR code then
xvi
ASSIGNMENT 2
determines the source of the interrupt and provides the appropriate processing. In a vectored scheme, typically an interrupt vector table contains the address of the ISR. The steps involved in an interrupt context switch include stopping the current programs execution of instructions, saving the context information (registers, the PC or similar mechanism that indicates where the processor should jump back to after executing the ISR) onto a stack, either dedicated or shared with other system software, and perhaps the disabling of other interrupts. After the master processor nishes executing the ISR, it context switches back to the original instruction stream that had been interrupted, using the context information as a guide. The interrupt services provided by device driver code, based upon the mechanisms discussed above, include enabling/disabling interrupts through an interrupt control register on the master CPU or the disabling of the interrupt controller, connecting the ISRs to the interrupt table, providing interrupt levels and vector numbers to peripherals, providing address and control data to corresponding registers, and so on. Additional services implemented in interrupt access drivers include the locking unlocking of interrupts, and the implementation of the actual ISRs. The pseudo code in the following example shows interrupt-handling initialization and access drivers that act as the basis of interrupt services (in the CPM and SIU) on the MPC860. Critical Section While accessing shared data as a means to communicate is a simple approach, the major issue of race conditions can arise. A race condition occurs when a process that is accessing shared variables is preempted before completing a modication access, thus aecting the integrity of shared variables. To counter this issue, portions of processes that access shared data, called critical sections A set of instructions that must be atomic for the system to work properly is oftenly called critical section. A part of the program is said to be atomic if it cannot be interrupted. A more precise way to look the shared-data problem is that it is the problem that arises when an interrupt routine and the task code share data, and the task code uses the shared data in a way that is not atomic. When we disable interrupts around the lines of the task code that use the shared data, we have made that collection of lines atomic, and we have therefore solved the shared-data problem. Sometimes we use the word atomic to mean not that part of the program cannot be interrupted by anything that might mess up the data it is using. From the perspective of the shared-data problem the nuclear reactor program need only disable the interrupts that reads in the temperatures. If other interrupts that reads in temperatures.If other interrupts change other data the time of the day, water pressures, steam pressures, etc.-while the task code is working with the temperatures,that will cause no problem.
xvii
ASSIGNMENT 2
Question 11:What is interrupt latency? Explain the factors aecting it. Interrupt latency refers to the amount of time it takes a system to respond to an interrupt. It is nothing but how fast does my system respond to each interrupt. Factors aecting interrupt latency are: 1. The longest period of time during which that interrupt is disabled. 2. The period of time it takes to execute any interrupt routines for interrupts that are of higher priority than the one in question. 3. How long it takes the microprocessor yo stop what it is doing, do the necessary bookkeeping, and start executing instructions within the interrupt routine. 4. How long it takes the interrupt routine to save the context and then do enough work that what it has accomplished counts as a response.
xviii
ASSIGNMENT 2
However dierent people include dierent combinations of the above factors when they calculate interrupt latency.among 4 above factors factor 3 can found by looking in the microprocessor documentation provided by the manufacturer. The other 3 items can found in one of two ways.First , we can write the code and measure how long it takes to execute. Second, you can count the instructions of various types and look up in the microprocessors documentation how long each type of instruction takes. The later technique works reasonably ell for the smaller microprocessor, since the time it takes to do each instruction is deterministic, and the manufacturer can provide the data. It works far less well for microprocessors that cache instructions ahead of time;with these microprocessors,how long an instruction takes depends critically upon whether the instruction was already in the cache and often upon several other unknowable factors as well. Question 12:What are the disadvantages of using large number of tasks? The disadvantages of using a large number of tasks are: 1. More data sharing among tasks:With more tasks, there is more data shared among two or more tasks. This may well translate into requirements for more semaphores, and hence into more microprocessor time lost handling the semaphores and into more semaphore-related bugs. 2. More communication : With more tasks, there is more requirement to pass messages from one task to another through pipes, mailboxes, queues, and so on. This will also translate into more microprocessor time and more chances for bugs . 3. More memory : Each task requires a stack; thus, with more tasks (and hence more stacks),we need more memory, at least for stack space, and perhaps for inter task messages as well. 4. More task switching : Each time the RTOS switches tasks, a certain amount of microprocessor time is wasted saving the context of the task that is stopping and restoring the context of the task that is about to run. Others things being equal, a design with more tasks will probably lead to a system in which the RTOS switches tasks more often and therefore a system with less throughput. 5. More calls to RTOS : More tasks means more calls to the RTOS. Calling more functions can add up a lot of processing overhead.
Question 13:Explain the methods to save code space and methods to save power In embedded system, there may be shortage of code space, or data space or both. They are not interchangeable, since code must be stored in ROM and data in RAM. AJAY MARGAD 1MS08EC138 xix
ASSIGNMENT 2
methods to save code space Should make sure that two functions are not doing the same thing. Make sure that development tools arent sabotaging. Calling memcpy might cause the tools to drag in memmove, memset, strcpy , strncpy, strset, even if those functions are not used. The manual that come with tools should indicate this. RTOS should be congured to use only those functions that are needed. Should look at the assembly language listings created by the cross-complier to see if certain of the C statements translate into huge numbers of instructions. Static variables should be used instead of variables on the stack. Many microprocessor can read and write static variables using fewer instructions than they do for stack variables. If one of these microprocessors is used, space is saved by declaring local variables to be static. If 8-bit processor is used, char variables should be used instead of int variable. If all else fails, a lot of space ca be saved-at the cost of a lot of headaches-by writing the code in assembly language. methods to save power Some embedded systems run on battery power, and for these systems, battery life is often a big issue. The primary method for preserving battery power is to turn o parts or all of the system including microprocessor whenever possible. Most embedded systems have at least one-power saving mode. Software can typically put the microprocessor into one of those modes with a special instruction or by writing value to a control register within the microprocessor . The modes are named such as sleep mode, low-power mode, idle mode, standby mode, and so on. 1. Common Power-Saving Mode(1) Stop executing instructions, stop peripherals, stop clock circuit-saves lot of power. Requires restarting software because microprocessor is reset. Software must gure out if it just started or is restarting. Static RAM uses little power-No need of stopping. 2. Common Power-Saving Mode(2) Stop executing instructions, peripherals continue to operate-saves less power. No special hardware required. No need of restarting software . DMA continues to send data to UART. AJAY MARGAD 1MS08EC138 xx
ASSIGNMENT 2
Timers continue to run, interrupt microprocessor, etc. 3. Common Power-Saving Mode(3) Turn of the entire system, power consumption=0. User turns it back on when needed. Examples-Cordless bar-code scanner, software needs to turn system o.
Question 14:Explain the need for interrupts Suppose a peripheral intermittently receives data, which must be serviced by the processor. There are two methods of servicing viz Polling and Interrupts. Polling-The processor can poll the peripheral regularly to see if data has arrived, this method is wasteful. Interrupts-The peripheral can interrupt the processor whenever it has data, this method is ecient as it saves CPU time to greater extent. It requires an extra pin/pins:Int, if Int is 1, processor suspends current program, jumps to an Interrupt Service Routine(ISR). Essentially, polling of the interrupt pin is built-into the hardware. So no extra time is required to poll the interrupt pin. Events taking place when a processor is interrupted are: Microprocessor detects interrupt request (IRQ) signal is asserted Stops executing the instructions Saves on stack the address of next instruction Jumps to interrupt service routine (ISR) and executes it Returns from ISR Pops address from stack Continues execution of next instruction The code below shows a microprocessor responding to an interrupt.
xxi
ASSIGNMENT 2
Question 15:Describe the function of a scheduler with a task state transition diagram. A part of the RTOS called the scheduler keeps track of the state of each task and decides which task should go into the running state. Unlike the scheduler in windows or Unix, the scheduler in most RTOS are entirely simpleminded about which task should get the processor; they look at priorities programmer assign to the task, and among the tasks that are not in the blocked state, the one with highest priority runs, and the rest of them wait in the ready state. The scheduler will not ddle with task priorities; if a high priority task has hogs the microprocessor for a long time while lower priority task are waiting in the ready state, thats too bad. The lower priority tasks just have to wait; the scheduler assumes that programmer knew what he/she was doing when he/she set the task priorities. Figure below shows the transition among the three task states. The word block means move into the blocked state, run means move into running state or be in the running state, and switch means change which task is in the running state. The gure is self explanatory, but there are few consequences: A task will only block because it decides for itself that it has run out of things to do. Other tasks in the system or the scheduler cannot decide for a task that it needs to wait for something. As a consequence of this, a task has to be running just before it is blocked; it has to execute the instruction that gure out that theres nothing more to do. While a task in blocked, it never gets the microprocessor. Therefore, an interrupt routine or some other task in the system must be able to signal that whatever the task was waiting for has happened. Otherwise, the task will be blocked forever. The shuing of tasks between the ready and running states is entirely the work of the scheduler. Tasks can block themselves and tasks and interrupt routines can move other task from the blocked states to the ready state, but the scheduler has control over the running state.
xxii
ASSIGNMENT 2
xxiii